Skip to content

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

Initial commit

Pancakefbb0b15cad4b
diff --git a/.env.example b/.env.example
new file mode 100644
index 000000000..aa3183e67
--- /dev/null
+++ b/.env.example
@@ -0,0 +1,103 @@
+# ============================================================================
+# AI-Tutor Environment Configuration
+# ============================================================================
+# Copy this file to .env and fill in your API keys and settings.
+# All API keys should be kept confidential and never committed to version control.
+# ============================================================================
+
+# ============================================================================
+# System Configuration
+# ============================================================================
+
+# Disable SSL certificate verification (set 'true' for self-signed certificates)
+# Use with caution in production environments
+DISABLE_SSL_VERIFY=false
+
+# ============================================================================
+# LLM (Large Language Model) Configuration
+# ============================================================================
+# Configure the main AI model used for reasoning, generation, and conversation.
+# Supports OpenAI-compatible APIs (OpenAI, Azure OpenAI, DeepSeek, Qwen, etc.)
+
+# LLM service provider type
+# Options: openai, azure_openai, ollama, lollms
+LLM_BINDING=openai
+
+# Model name for the LLM
+# Examples: gpt-4o, gpt-4o-mini, deepseek-chat, qwen-plus, claude-3-5-sonnet
+LLM_MODEL=
+
+# LLM API endpoint URL
+# OpenAI: https://api.openai.com/v1
+# Azure OpenAI: https://YOUR_RESOURCE.openai.azure.com
+# DeepSeek: https://api.deepseek.com
+# Alibaba Qwen: https://dashscope.aliyuncs.com/compatible-mode/v1
+LLM_BINDING_HOST=
+
+# LLM API authentication key
+LLM_BINDING_API_KEY=
+
+# ============================================================================
+# Embedding Model Configuration
+# ============================================================================
+# Configure the text embedding model used for semantic search and RAG.
+# Required for knowledge base functionality.
+
+# Embedding service provider type
+# Options: openai, azure_openai, ollama, lollms
+EMBEDDING_BINDING=openai
+
+# Embedding model name
+# Examples: text-embedding-3-large, text-embedding-3-small, text-embedding-ada-002
+EMBEDDING_MODEL=text-embedding-3-large
+
+# Embedding vector dimension
+# text-embedding-3-large: 3072 (default)
+# text-embedding-3-small: 1536
+# text-embedding-ada-002: 1536
+EMBEDDING_DIM=3072
+
+# Embedding API endpoint URL (same format as LLM_BINDING_HOST)
+EMBEDDING_BINDING_HOST=
+
+# Embedding API authentication key
+EMBEDDING_BINDING_API_KEY=
+
+# ============================================================================
+# TTS (Text-to-Speech) Configuration
+# ============================================================================
+# Configure voice synthesis for the Co-Writer narration feature.
+# Currently only supports Alibaba Cloud DashScope TTS service.
+
+# TTS model name
+# DashScope: qwen3-tts-flash (recommended), cosyvoice-v1
+TTS_MODEL=
+
+# TTS API endpoint URL
+# DashScope: https://dashscope.aliyuncs.com/api/v1
+TTS_URL=
+
+# TTS API authentication key (DashScope API Key)
+TTS_API_KEY=
+
+# Default TTS voice character
+# Options: Cherry (sweet female), Stella (intellectual female), Annie (lively female),
+# Cally (gentle female), Eva (elegant female), Bella (young female)
+TTS_VOICE=Cherry
+
+# ============================================================================
+# Web Search Configuration
+# ============================================================================
+# Configure external search APIs for research features.
+
+# Perplexity API key for web search functionality
+# Get your API key at: https://www.perplexity.ai/settings/api
+PERPLEXITY_API_KEY=
+
+# ============================================================================
+# Logging Configuration
+# ============================================================================
+
+# Log level for RAG tool module
+# Options: DEBUG, INFO, WARNING, ERROR
+RAG_TOOL_MODULE_LOG_LEVEL=INFO
diff --git a/.gitattributes b/.gitattributes
new file mode 100644
index 000000000..f8ff2b5de
--- /dev/null
+++ b/.gitattributes
@@ -0,0 +1 @@
+*.mp4 filter=lfs diff=lfs merge=lfs -text
diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml
new file mode 100644
index 000000000..13d6bcc27
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/bug_report.yml
@@ -0,0 +1,88 @@
+name: Bug Report
+description: File a bug report
+title: "[Bug]:"
+labels: ["bug", "triage"]
+
+body:
+ - type: checkboxes
+ id: existingcheck
+ attributes:
+ label: Do you need to file an issue?
+ description: Please help us manage our time by avoiding duplicates and common bugs with the steps below.
+ options:
+ - label: I have searched the existing issues and this bug is not already filed.
+ - label: I believe this is a legitimate bug, not just a question or feature request.
+ - type: textarea
+ id: description
+ attributes:
+ label: Describe the bug
+ description: A clear and concise description of what the bug is.
+ placeholder: What went wrong?
+ - type: textarea
+ id: reproduce
+ attributes:
+ label: Steps to reproduce
+ description: Steps to reproduce the behavior.
+ placeholder: |
+ 1. Go to '...'
+ 2. Click on '....'
+ 3. Scroll down to '....'
+ 4. See error
+ - type: textarea
+ id: expected_behavior
+ attributes:
+ label: Expected Behavior
+ description: A clear and concise description of what you expected to happen.
+ placeholder: What should have happened?
+ - type: dropdown
+ id: module
+ attributes:
+ label: Related Module
+ description: Which module is this bug related to?
+ options:
+ - Dashboard
+ - Knowledge Base Management
+ - Smart Solver
+ - Question Generator
+ - Deep Research
+ - Co-Writer
+ - Notebook
+ - Guided Learning
+ - Idea Generation
+ - API/Backend
+ - Frontend/Web
+ - Other
+ validations:
+ required: true
+ - type: textarea
+ id: configused
+ attributes:
+ label: Configuration Used
+ description: The AI-Tutor configuration used (if applicable).
+ placeholder: |
+ # Paste your config here or describe the settings
+ - type: textarea
+ id: screenshotslogs
+ attributes:
+ label: Logs and screenshots
+ description: If applicable, add screenshots and logs to help explain your problem.
+ placeholder: Add logs and screenshots here
+ - type: textarea
+ id: additional_information
+ attributes:
+ label: Additional Information
+ description: |
+ - AI-Tutor Version: e.g., v0.1.0
+ - Operating System: e.g., macOS 14.0, Windows 11, Ubuntu 22.04
+ - Python Version: e.g., 3.10.0
+ - Node.js Version: e.g., 18.17.0
+ - Browser (if applicable): e.g., Chrome 120, Firefox 121
+ - Related Issues: e.g., #1
+ - Any other relevant information.
+ value: |
+ - AI-Tutor Version:
+ - Operating System:
+ - Python Version:
+ - Node.js Version:
+ - Browser (if applicable):
+ - Related Issues:
diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml
new file mode 100644
index 000000000..3ba13e0ce
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/config.yml
@@ -0,0 +1 @@
+blank_issues_enabled: false
diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml
new file mode 100644
index 000000000..756d08c17
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/feature_request.yml
@@ -0,0 +1,52 @@
+name: Feature Request
+description: File a feature request
+labels: ["enhancement"]
+title: "[Feature Request]:"
+
+body:
+ - type: checkboxes
+ id: existingcheck
+ attributes:
+ label: Do you need to file a feature request?
+ description: Please help us manage our time by avoiding duplicates and common feature request with the steps below.
+ options:
+ - label: I have searched the existing feature request and this feature request is not already filed.
+ - label: I believe this is a legitimate feature request, not just a question or bug.
+ - type: textarea
+ id: feature_request_description
+ attributes:
+ label: Feature Request Description
+ description: A clear and concise description of the feature request you would like.
+ placeholder: What does this feature request add or improve?
+ - type: dropdown
+ id: module
+ attributes:
+ label: Related Module
+ description: Which module would this feature affect?
+ options:
+ - Dashboard
+ - Knowledge Base Management
+ - Smart Solver
+ - Question Generator
+ - Deep Research
+ - Co-Writer
+ - Notebook
+ - Guided Learning
+ - Idea Generation
+ - API/Backend
+ - Frontend/Web
+ - Other
+ validations:
+ required: true
+ - type: textarea
+ id: use_case
+ attributes:
+ label: Use Case
+ description: Describe the problem this feature would solve or the use case it would enable.
+ placeholder: What problem does this feature solve?
+ - type: textarea
+ id: additional_context
+ attributes:
+ label: Additional Context
+ description: Add any other context or screenshots about the feature request here.
+ placeholder: Any additional information, mockups, or examples
diff --git a/.github/ISSUE_TEMPLATE/question.yml b/.github/ISSUE_TEMPLATE/question.yml
new file mode 100644
index 000000000..a6f1eba83
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/question.yml
@@ -0,0 +1,47 @@
+name: Question
+description: Ask a general question
+labels: ["question"]
+title: "[Question]:"
+
+body:
+ - type: checkboxes
+ id: existingcheck
+ attributes:
+ label: Do you need to ask a question?
+ description: Please help us manage our time by avoiding duplicates and common questions with the steps below.
+ options:
+ - label: I have searched the existing questions and discussions and this question is not already answered.
+ - label: I believe this is a legitimate question, not just a bug or feature request.
+ - type: textarea
+ id: question
+ attributes:
+ label: Your Question
+ description: A clear and concise description of your question.
+ placeholder: What is your question?
+ - type: dropdown
+ id: module
+ attributes:
+ label: Related Module
+ description: Which module is your question related to?
+ options:
+ - Dashboard
+ - Knowledge Base Management
+ - Smart Solver
+ - Question Generator
+ - Deep Research
+ - Co-Writer
+ - Notebook
+ - Guided Learning
+ - Idea Generation
+ - API/Backend
+ - Frontend/Web
+ - Installation/Setup
+ - General
+ validations:
+ required: true
+ - type: textarea
+ id: context
+ attributes:
+ label: Additional Context
+ description: Provide any additional context or details that might help us understand your question better.
+ placeholder: Add any relevant information here (code snippets, error messages, configuration, etc.)
diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md
new file mode 100644
index 000000000..5f76a9562
--- /dev/null
+++ b/.github/pull_request_template.md
@@ -0,0 +1,54 @@
+<!--
+Thank you for contributing to AI-Tutor!
+
+Please make sure your pull request is ready for review before submitting.
+
+About this template
+
+This template assists contributors in providing a clear and concise description of their changes. Feel free to adjust it as needed.
+-->
+
+## Description
+
+[Briefly describe the changes made in this pull request.]
+
+## Related Issues
+
+[Reference any related issues or tasks addressed by this pull request.]
+- Closes #
+- Related to #
+
+## Changes Made
+
+[List the specific changes made in this pull request.]
+
+## Module(s) Affected
+
+- [ ] Dashboard
+- [ ] Knowledge Base Management
+- [ ] Smart Solver
+- [ ] Question Generator
+- [ ] Deep Research
+- [ ] Co-Writer
+- [ ] Notebook
+- [ ] Guided Learning
+- [ ] Idea Generation
+- [ ] API/Backend
+- [ ] Frontend/Web
+- [ ] Configuration
+- [ ] Documentation
+- [ ] Other: ___________
+
+## Checklist
+
+- [ ] Changes tested locally
+- [ ] Code follows project style guidelines
+- [ ] Self-review completed
+- [ ] Code reviewed
+- [ ] Documentation updated (if necessary)
+- [ ] No new warnings generated
+- [ ] Tests added/updated (if applicable)
+
+## Additional Notes
+
+[Add any additional notes or context for the reviewer(s).]
diff --git a/.github/workflows/linting.yaml b/.github/workflows/linting.yaml
new file mode 100644
index 000000000..9cc900dab
--- /dev/null
+++ b/.github/workflows/linting.yaml
@@ -0,0 +1,44 @@
+name: Linting and Formatting
+
+on:
+ push:
+ branches:
+ - main
+ - develop
+ pull_request:
+ branches:
+ - main
+ - develop
+
+jobs:
+ lint-and-format:
+ name: Linting and Formatting
+ runs-on: ubuntu-latest
+
+ steps:
+ - name: Checkout code
+ uses: actions/checkout@v6
+
+ - name: Set up Python
+ uses: actions/setup-python@v6
+ with:
+ python-version: '3.10'
+
+ - name: Set up Node.js
+ uses: actions/setup-node@v4
+ with:
+ node-version: '18'
+ cache: 'npm'
+ cache-dependency-path: web/package-lock.json
+
+ - name: Install Python dependencies
+ run: |
+ python -m pip install --upgrade pip
+ pip install pre-commit
+
+ - name: Install frontend dependencies
+ working-directory: ./web
+ run: npm ci
+
+ - name: Run pre-commit
+ run: pre-commit run --all-files --show-diff-on-failure
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 000000000..6dc0b6810
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,271 @@
+# ============================================
+# AI-Tutor Project .gitignore
+# ============================================
+
+# ============================================
+# User Generated Data and Outputs
+# ============================================
+# User data directory (migrated to data/user/)
+data/user/
+data/knowledge_bases/
+run_code_workspace/
+config/bench_config.yaml
+develop/
+src/agents/question/reference_papers/
+
+# ============================================
+# Python Related
+# ============================================
+# Bytecode cache
+__pycache__/
+**/__pycache__/
+*.py[cod]
+*$py.class
+*.so
+
+# Distribution/Packaging
+.Python
+build/
+develop-eggs/
+dist/
+downloads/
+eggs/
+.eggs/
+lib64/
+parts/
+sdist/
+var/
+wheels/
+*.egg-info/
+.installed.cfg
+*.egg
+MANIFEST
+
+# Virtual Environments
+.env
+*.env
+!.env.example
+env/
+venv/
+ENV/
+.venv/
+env.bak/
+venv.bak/
+
+# ============================================
+# Node.js and Frontend Build
+# ============================================
+# Node modules
+node_modules/
+**/node_modules/
+
+# Next.js build output
+.next/
+web/.next/
+out/
+web/out/
+
+# Frontend build artifacts
+dist/
+web/dist/
+build/
+web/build/
+
+# ============================================
+# Common Output and Cache Directories
+# ============================================
+# Output directories
+output/
+outputs/
+**/output/
+**/outputs/
+
+# Cache directories
+cache/
+**/cache/
+.cache/
+
+# Log files
+*.log
+
+# ============================================
+# IDE and Editors
+# ============================================
+# VSCode
+.vscode/
+.vscode/*
+!.vscode/settings.json
+!.vscode/tasks.json
+!.vscode/launch.json
+!.vscode/extensions.json
+
+# Cursor
+.cursor/
+
+# PyCharm / IntelliJ IDEA
+.idea/
+*.iml
+*.iws
+*.ipr
+
+# Sublime Text
+*.sublime-project
+*.sublime-workspace
+
+# Vim
+*.swp
+*.swo
+*~
+.netrwhist
+
+# Emacs
+*~
+\#*\#
+/.emacs.desktop
+/.emacs.desktop.lock
+*.elc
+auto-save-list
+tramp
+.\#*
+
+# ============================================
+# Operating System Files
+# ============================================
+# macOS
+.DS_Store
+.AppleDouble
+.LSOverride
+Icon
+._*
+.DocumentRevisions-V100
+.fseventsd
+.Spotlight-V100
+.TemporaryItems
+.Trashes
+.VolumeIcon.icns
+.com.apple.timemachine.donotpresent
+.AppleDB
+.AppleDesktop
+Network Trash Folder
+Temporary Items
+.apdisk
+
+# Windows
+Thumbs.db
+Thumbs.db:encryptable
+ehthumbs.db
+ehthumbs_vista.db
+*.stackdump
+[Dd]esktop.ini
+$RECYCLE.BIN/
+*.cab
+*.msi
+*.msix
+*.msm
+*.msp
+*.lnk
+
+# Linux
+*~
+.fuse_hidden*
+.directory
+.Trash-*
+.nfs*
+
+# ============================================
+# Temporary Files
+# ============================================
+*.tmp
+*.temp
+*.bak
+*.backup
+*.swp
+*.swo
+
+# ============================================
+# Testing and Coverage
+# ============================================
+.coverage
+.coverage.*
+htmlcov/
+.pytest_cache/
+.tox/
+nosetests.xml
+coverage.xml
+develop/
+
+# ============================================
+# Jupyter Notebook
+# ============================================
+.ipynb_checkpoints
+*.ipynb_checkpoints/
+
+# ============================================
+# Type Checking
+# ============================================
+# mypy
+.mypy_cache/
+.dmypy.json
+dmypy.json
+
+# Pyre type checker
+.pyre/
+
+# pytype static type analyzer
+.pytype/
+
+# ============================================
+# Other Python Tools
+# ============================================
+# Celery
+celerybeat-schedule
+celerybeat.pid
+
+# SageMath parsed files
+*.sage.py
+
+# Spyder project settings
+.spyderproject
+.spyproject
+
+# Rope project settings
+.ropeproject
+
+# mkdocs documentation
+/site
+
+# ============================================
+# Profiling
+# ============================================
+*.prof
+*.pstats
+
+# ============================================
+# Database Files
+# ============================================
+*.db
+*.sqlite
+*.sqlite3
+
+# ============================================
+# Compressed Files
+# ============================================
+*.zip
+*.tar
+*.tar.gz
+*.rar
+*.7z
+
+# ============================================
+# Reference Papers (large binary files)
+# ============================================
+# Keep structure but ignore large PDFs in reference_papers
+# question_agents/reference_papers/**/*.pdf
+
+# ============================================
+# Audio/Video Output (TTS generated)
+# ============================================
+*.mp3
+*.wav
+*.ogg
+!demo/*.mp4
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
new file mode 100644
index 000000000..58cd871c7
--- /dev/null
+++ b/.pre-commit-config.yaml
@@ -0,0 +1,105 @@
+# Pre-commit hooks configuration for AI-Tutor project
+# This configuration ensures code quality and consistency across the team
+#
+# Installation:
+# pip install pre-commit
+# pre-commit install
+#
+# Usage:
+# pre-commit run --all-files # Run on all files
+# git commit # Hooks run automatically on commit
+
+repos:
+ # ============================================
+ # General file checks
+ # ============================================
+ - repo: https://github.com/pre-commit/pre-commit-hooks
+ rev: v6.0.0
+ hooks:
+ # Remove trailing whitespace
+ - id: trailing-whitespace
+ args: [--markdown-linebreak-ext=md]
+ exclude: ^(.*\.min\.(js|css)|.*\.lock|.*\.log|.*\.pdf|.*\.zip|.*\.tar\.gz)
+
+ # Ensure files end with a newline
+ - id: end-of-file-fixer
+ exclude: ^(.*\.min\.(js|css)|.*\.lock|.*\.log|.*\.pdf|.*\.zip|.*\.tar\.gz)
+
+ # Check YAML files for syntax errors
+ - id: check-yaml
+ args: [--unsafe] # Allow custom tags in YAML
+
+ # Check JSON files for syntax errors
+ - id: check-json
+ exclude: ^(.*\.lock|.*\.log)
+
+ # Prevent committing large files
+ - id: check-added-large-files
+ args: [--maxkb=6144]
+
+ # Detect merge conflict markers
+ - id: check-merge-conflict
+
+ # Detect case conflicts in file names
+ - id: check-case-conflict
+
+ # Check for files that would conflict in case-insensitive filesystems
+ - id: check-toml
+
+ # ============================================
+ # Python code formatting and linting
+ # ============================================
+ # Note: 使用 ruff format 替代 black,避免格式化工具冲突
+ # ruff format 更快且与 ruff linter 配合更好
+ - repo: https://github.com/astral-sh/ruff-pre-commit
+ rev: v0.14.7
+ hooks:
+ # Ruff linting (只自动修复,不阻止提交)
+ - id: ruff
+ args: [--fix, --exit-zero]
+ files: ^(src/|scripts/).*\.py$
+ # --exit-zero: 即使有错误也不阻止提交,只自动修复
+
+ # Ruff import sorting (replaces isort)
+ - id: ruff-format
+ files: ^(src/|scripts/).*\.py$
+
+ # Note: python-check-docstring-first hook removed as it's not available
+ # Ruff already handles most code quality checks including import ordering
+
+ # ============================================
+ # Frontend code formatting and linting
+ # ============================================
+ # Note: ESLint 暂时禁用,因为 Next.js 项目通常有自己的 ESLint 配置
+ # 如果需要启用,可以取消下面的注释并配置 ESLint
+ # - repo: https://github.com/pre-commit/mirrors-eslint
+ # rev: v10.0.0-alpha.1
+ # hooks:
+ # - id: eslint
+ # files: ^web/.*\.(js|jsx|ts|tsx)$
+ # exclude: ^web/(node_modules|\.next|out|dist|build)/
+ # additional_dependencies:
+ # - eslint@^8.57.0
+ # - '@typescript-eslint/parser@^6.0.0'
+ # - '@typescript-eslint/eslint-plugin@^6.0.0'
+ # args: [--fix]
+
+ - repo: https://github.com/pre-commit/mirrors-prettier
+ rev: v4.0.0-alpha.8
+ hooks:
+ - id: prettier
+ files: ^web/.*\.(css|scss|json|jsonc|yaml|yml|md|graphql|html|ts|tsx|js|jsx)$
+ exclude: ^web/(node_modules|\.next|out|dist|build)/
+
+ # ============================================
+ # Security checks
+ # ============================================
+ - repo: https://github.com/Yelp/detect-secrets
+ rev: v1.5.0
+ hooks:
+ - id: detect-secrets
+ args: ['--baseline', '.secrets.baseline']
+ exclude: package-lock.json
+ # Only scan staged files for performance
+ pass_filenames: false
diff --git a/.secrets.baseline b/.secrets.baseline
new file mode 100644
index 000000000..62dfae8b2
--- /dev/null
+++ b/.secrets.baseline
@@ -0,0 +1,115 @@
+{
+ "version": "1.4.0",
+ "plugins_used": [
+ {
+ "name": "ArtifactoryDetector"
+ },
+ {
+ "name": "AWSKeyDetector"
+ },
+ {
+ "name": "AzureStorageKeyDetector"
+ },
+ {
+ "name": "Base64HighEntropyString",
+ "limit": 4.5
+ },
+ {
+ "name": "BasicAuthDetector"
+ },
+ {
+ "name": "CloudantDetector"
+ },
+ {
+ "name": "DiscordBotTokenDetector"
+ },
+ {
+ "name": "GitHubTokenDetector"
+ },
+ {
+ "name": "HexHighEntropyString",
+ "limit": 3.0
+ },
+ {
+ "name": "IbmCloudIamDetector"
+ },
+ {
+ "name": "IbmCosHmacDetector"
+ },
+ {
+ "name": "JwtTokenDetector"
+ },
+ {
+ "name": "KeywordDetector",
+ "keyword_exclude": ""
+ },
+ {
+ "name": "MailchimpDetector"
+ },
+ {
+ "name": "NpmDetector"
+ },
+ {
+ "name": "PrivateKeyDetector"
+ },
+ {
+ "name": "SendGridDetector"
+ },
+ {
+ "name": "SlackDetector"
+ },
+ {
+ "name": "SoftlayerDetector"
+ },
+ {
+ "name": "SquareOAuthDetector"
+ },
+ {
+ "name": "StripeDetector"
+ },
+ {
+ "name": "TwilioKeyDetector"
+ }
+ ],
+ "filters_used": [
+ {
+ "path": "detect_secrets.filters.allowlist.is_line_allowlisted"
+ },
+ {
+ "path": "detect_secrets.filters.common.is_baseline_file"
+ },
+ {
+ "path": "detect_secrets.filters.common.is_ignored_due_to_verification_policies",
+ "min_level": 2
+ },
+ {
+ "path": "detect_secrets.filters.heuristic.is_indirect_reference"
+ },
+ {
+ "path": "detect_secrets.filters.heuristic.is_likely_id_string"
+ },
+ {
+ "path": "detect_secrets.filters.heuristic.is_lock_file"
+ },
+ {
+ "path": "detect_secrets.filters.heuristic.is_not_alphanumeric_string"
+ },
+ {
+ "path": "detect_secrets.filters.heuristic.is_potential_uuid"
+ },
+ {
+ "path": "detect_secrets.filters.heuristic.is_prefixed_with_dollar_sign"
+ },
+ {
+ "path": "detect_secrets.filters.heuristic.is_sequential_string"
+ },
+ {
+ "path": "detect_secrets.filters.heuristic.is_swagger_file"
+ },
+ {
+ "path": "detect_secrets.filters.heuristic.is_templated_secret"
+ }
+ ],
+ "results": {},
+ "generated_at": "2024-01-01T00:00:00Z"
+}
diff --git a/Communication.md b/Communication.md
new file mode 100644
index 000000000..042649288
--- /dev/null
+++ b/Communication.md
@@ -0,0 +1,5 @@
+We provide QR codes for joining the HKUDS discussion groups on WeChat and Feishu.
+
+You can join by scanning the QR codes below:
+
+<img src="https://github.com/HKUDS/.github/blob/main/profile/QR.png" alt="WeChat QR Code" width="400"/>
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 000000000..0ad25db4b
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,661 @@
+ GNU AFFERO GENERAL PUBLIC LICENSE
+ Version 3, 19 November 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU Affero General Public License is a free, copyleft license for
+software and other kinds of works, specifically designed to ensure
+cooperation with the community in the case of network server software.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+our General Public Licenses are intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ Developers that use our General Public Licenses protect your rights
+with two steps: (1) assert copyright on the software, and (2) offer
+you this License which gives you legal permission to copy, distribute
+and/or modify the software.
+
+ A secondary benefit of defending all users' freedom is that
+improvements made in alternate versions of the program, if they
+receive widespread use, become available for other developers to
+incorporate. Many developers of free software are heartened and
+encouraged by the resulting cooperation. However, in the case of
+software used on network servers, this result may fail to come about.
+The GNU General Public License permits making a modified version and
+letting the public access it on a server without ever releasing its
+source code to the public.
+
+ The GNU Affero General Public License is designed specifically to
+ensure that, in such cases, the modified source code becomes available
+to the community. It requires the operator of a network server to
+provide the source code of the modified version running there to the
+users of that server. Therefore, public use of a modified version, on
+a publicly accessible server, gives the public access to the source
+code of the modified version.
+
+ An older license, called the Affero General Public License and
+published by Affero, was designed to accomplish similar goals. This is
+a different license, not a version of the Affero GPL, but Affero has
+released a new version of the Affero GPL which permits relicensing under
+this license.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU Affero General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Remote Network Interaction; Use with the GNU General Public License.
+
+ Notwithstanding any other provision of this License, if you modify the
+Program, your modified version must prominently offer all users
+interacting with it remotely through a computer network (if your version
+supports such interaction) an opportunity to receive the Corresponding
+Source of your version by providing access to the Corresponding Source
+from a network server at no charge, through some standard or customary
+means of facilitating copying of software. This Corresponding Source
+shall include the Corresponding Source for any work covered by version 3
+of the GNU General Public License that is incorporated pursuant to the
+following paragraph.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the work with which it is combined will remain governed by version
+3 of the GNU General Public License.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU Affero General Public License from time to time. Such new versions
+will be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU Affero General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU Affero General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU Affero General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the program's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU Affero General Public License as published
+ by the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Affero General Public License for more details.
+
+ You should have received a copy of the GNU Affero General Public License
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If your software can interact with users remotely through a computer
+network, you should also make sure that it provides a way for users to
+get its source. For example, if your program is a web application, its
+interface could display a "Source" link that leads users to an archive
+of the code. There are many ways you could offer source, and different
+solutions will be better for different programs; see section 13 for the
+specific requirements.
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU AGPL, see
+<https://www.gnu.org/licenses/>.
diff --git a/README.md b/README.md
index 5a3b76892..10a8563cb 100644
--- a/README.md
+++ b/README.md
@@ -1,2 +1,1355 @@
-# OpenTutor
-"OpenTutor: AI-Powered Personalized Learning Assistant"
+<div align="center">
+
+<img src="assets/logo-ver2.png" alt="OpenTutor Logo" width="150" style="border-radius: 15px;">
+
+# OpenTutor: Your Personal Learning Assistant
+
+[![Python](https://img.shields.io/badge/Python-3.10%2B-3776AB?style=flat-square&logo=python&logoColor=white)](https://www.python.org/downloads/)
+[![Next.js](https://img.shields.io/badge/Next.js-14-000000?style=flat-square&logo=next.js&logoColor=white)](https://nextjs.org/)
+[![FastAPI](https://img.shields.io/badge/FastAPI-0.100+-009688?style=flat-square&logo=fastapi&logoColor=white)](https://fastapi.tiangolo.com/)
+[![License](https://img.shields.io/badge/License-AGPL--3.0-blue?style=flat-square)](LICENSE)
+[![Feishu](https://img.shields.io/badge/Feishu-Group-blue?style=flat)](./Communication.md)
+[![WeChat](https://img.shields.io/badge/WeChat-Group-green?style=flat&logo=wechat)](./Communication.md)
+
+
+
+[**Quick Start**](#quick-start) · [**Core Modules**](#core-modules) · [**FAQ**](#faq)
+
+[🇨🇳 中文](assets/README/README_CN.md) · [🇯🇵 日本語](assets/README/README_JA.md) · [🇪🇸 Español](assets/README/README_ES.md) · [🇫🇷 Français](assets/README/README_FR.md) · [🇸🇦 العربية](assets/README/README_AR.md)
+
+</div>
+
+<div align="center">
+
+| ⚡ **Massive Document Knowledge Q&A** | 📈 **Interactive Learning Visualization** | <br>
+| 🧠 **Knowledge Reinforcement** | 🔬 **Deep Research & Idea Generation** |
+
+</div>
+
+---
+
+## Key Features of OpenTutor
+
+### 📚 Massive Document Knowledge Q&A
+• **Smart Knowledge Base**: Upload textbooks, research papers, technical manuals, and domain-specific documents. Build a comprehensive AI-powered knowledge repository for instant access.<br>
+• **Multi-Agent Problem Solving**: Dual-loop reasoning architecture with RAG, web search, paper search, and code execution—delivering step-by-step solutions with precise citations.
+
+### 🎨 Interactive Learning Visualization
+• **Knowledge Simplification & Explanations**: Transform complex concepts, knowledge, and algorithms into easy-to-understand visual aids, detailed step-by-step breakdowns, and engaging interactive demonstrations.<br>
+• **Personalized Q&A**: Context-aware conversations that adapt to your learning progress, with interactive pages and session-based knowledge tracking.
+
+### 🎯 Knowledge Reinforcement with Practice Problem Generator
+• **Intelligent Exercise Creation**: Generate targeted quizzes, practice problems, and customized assessments tailored to your current knowledge level and specific learning objectives.<br>
+• **Authentic Exam Simulation**: Upload reference exams to generate practice questions that perfectly match the original style, format, and difficulty—giving you realistic preparation for the actual test.
+
+### 🔍 Deep Research & Idea Generation
+• **Comprehensive Research & Literature Review**: Conduct in-depth topic exploration with systematic analysis. Identify patterns, connect related concepts across disciplines, and synthesize existing research findings.<br>
+• **Novel Insight Discovery**: Generate structured learning materials and uncover knowledge gaps. Identify promising new research directions through intelligent cross-domain knowledge synthesis.
+
+---
+
+<div align="center">
+ <img src="assets/figs/title_gradient.svg" alt="All-in-One Tutoring System" width="70%">
+</div>
+
+<!-- ━━━━━━━━━━━━━━━━ Core Learning Experience ━━━━━━━━━━━━━━━━ -->
+
+<table>
+<tr>
+<td width="50%" align="center" valign="top">
+
+<h3>📚 Massive Document Knowledge Q&A</h3>
+<a href="#problem-solving-agent">
+<img src="assets/gifs/solve.gif" width="100%">
+</a>
+<br>
+<sub>Document Q&A and Step-by-Step Problem Solving</sub>
+
+</td>
+<td width="50%" align="center" valign="top">
+
+<h3>🎨 Interactive Learning Visualization</h3>
+<a href="#guided-learning">
+<img src="assets/gifs/guided-learning.gif" width="100%">
+</a>
+<br>
+<sub>Interactive AI Learning with Knowledge Visual Explanations</sub>
+
+</td>
+</tr>
+</table>
+
+<!-- ━━━━━━━━━━━━━━━━ Practice & Reinforcement ━━━━━━━━━━━━━━━━ -->
+
+<h3 align="center">🎯 Knowledge Reinforcement</h3>
+
+<table>
+<tr>
+<td width="50%" valign="top" align="center">
+
+<a href="#question-generator">
+<img src="assets/gifs/question-1.gif" width="100%">
+</a>
+
+**Custom Questions**
+<sub>Auto-Validated Practice Questions with Instant Feedback</sub>
+
+</td>
+<td width="50%" valign="top" align="center">
+
+<a href="#question-generator">
+<img src="assets/gifs/question-2.gif" width="100%">
+</a>
+
+**Mimic Questions**
+<sub>Clone Exam Style for Authentic Practice</sub>
+
+</td>
+</tr>
+</table>
+
+<!-- ━━━━━━━━━━━━━━━━ Research & Creation ━━━━━━━━━━━━━━━━ -->
+
+<h3 align="center">🔍 Deep Research & Idea Generation</h3>
+
+<table>
+<tr>
+<td width="33%" align="center">
+
+<a href="#deep-research">
+<img src="assets/gifs/deepresearch.gif" width="100%">
+</a>
+
+**Deep Research**
+<sub>Web and Paper Search with Literature Review</sub>
+
+</td>
+<td width="33%" align="center">
+
+<a href="#idea-generation">
+<img src="assets/gifs/ideagen.gif" width="100%">
+</a>
+
+**Automated IdeaGen**
+<sub>Systematic Brainstorming and Concept Synthesis</sub>
+
+</td>
+<td width="33%" align="center">
+
+<a href="#co-writer">
+<img src="assets/gifs/co-writer.gif" width="100%">
+</a>
+
+**Interactive IdeaGen**
+<sub>RAG-powered Idea Generation with Multi-Source Insights</sub>
+
+</td>
+</tr>
+</table>
+
+<!-- ━━━━━━━━━━━━━━━━ Knowledge Infrastructure ━━━━━━━━━━━━━━━━ -->
+
+<h3 align="center">🏗️ All-in-One Knowledge System</h3>
+
+<table>
+<tr>
+<td width="50%" align="center">
+
+<a href="#dashboard--knowledge-base-management">
+<img src="assets/gifs/knowledge_bases.png" width="100%">
+</a>
+
+**Personal Knowledge Base**
+<sub>Build and Organize Your Own Knowledge Repository</sub>
+
+</td>
+<td width="50%" align="center">
+
+<a href="#notebook">
+<img src="assets/gifs/notebooks.png" width="100%">
+</a>
+
+**Personal Notebook**
+<sub>Your Contextual Memory for Learning Sessions</sub>
+
+</td>
+</tr>
+</table>
+
+<p align="center">
+ <sub>🌙 Use OpenTutor in <b>Dark Mode</b>!</sub>
+</p>
+
+---
+
+## 🏛️ OpenTutor's Framework
+
+<div align="center">
+<img src="assets/figs/full-pipe.png" alt="OpenTutor Full-Stack Workflow" width="100%">
+</div>
+
+### 💬 User Interface Layer
+• **Intuitive Interaction**: Simple bidirectional query-response flow for intuitive interaction.<br>
+• **Structured Output**: Structured response generation that organizes complex information into actionable outputs.
+
+### 🤖 Intelligent Agent Modules
+• **Problem Solving & Assessment**: Step-by-step problem solving and custom assessment generation.<br>
+• **Research & Learning**: Deep Research for topic exploration and Guided Learning with visualization.<br>
+• **Idea Generation**: Automated and interactive concept development with multi-source insights.
+
+### 🔧 Tool Integration Layer
+• **Information Retrieval**: RAG hybrid retrieval, real-time web search, and academic paper databases.<br>
+• **Processing & Analysis**: Python code execution, query item lookup, and PDF parsing for document analysis.
+
+### 🧠 Knowledge & Memory Foundation
+• **Knowledge Graph**: Entity-relation mapping for semantic connections and knowledge discovery.<br>
+• **Vector Store**: Embedding-based semantic search for intelligent content retrieval.<br>
+• **Memory System**: Session state management and citation tracking for contextual continuity.
+
+## 📋 Todo
+
+> 🌟 Star to follow our future updates!
+- [ ] Project-based learning
+- [ ] deepcoding from idea generation
+- [ ] Personalized memory
+
+## 🚀 Quick Start
+
+### Step 1: Clone Repository and Set Up Environment
+
+```bash
+# Clone the repository
+git clone https://github.com/HKUDS/OpenTutor.git
+cd OpenTutor
+
+# Set Up Virtual Environment (Choose One Option)
+
+# Option A: Using conda (Recommended)
+conda create -n aitutor python=3.10
+conda activate aitutor
+
+# Option B: Using venv
+python -m venv venv
+# On Windows:
+venv\Scripts\activate
+# On macOS/Linux:
+source venv/bin/activate
+```
+
+### Step 2: Install Dependencies
+
+Run the automated installation script to install all required dependencies:
+
+```bash
+# Recommended: Automated Installation
+bash scripts/install_all.sh
+
+# Alternative: Manual Installation
+python scripts/install_all.py
+
+# Or Install Dependencies Manually
+pip install -r requirements.txt
+npm install
+```
+
+### Step 3: Set Up Environment Variables
+
+Create a `.env` file in the project root directory based on `.env.example`:
+
+```bash
+# Copy from .env.example template (if exists)
+cp .env.example .env
+
+# Then edit .env file with your API keys:
+```
+
+### Step 4: Configure Ports and LLM Settings *(Optional)*
+
+By default, the application uses:
+- **Backend (FastAPI)**: `8001`
+- **Frontend (Next.js)**: `3782`
+
+You can modify these ports in `config/main.yaml` by editing the `server.backend_port` and `server.frontend_port` values.
+
+**LLM Configuration**: Agent settings for `temperature` and `max_tokens` are centralized in `config/agents.yaml`. Each module (guide, solve, research, question, ideagen, co_writer) has customizable parameters. See [Configuration Documentation](config/README.md) for details.
+
+### Step 5: Try Our Demos
+
+Experience the system quickly with two pre-built knowledge bases and a collection of challenging questions with usage examples.
+
+<details>
+<summary><b>Research Papers Collection</b> — 5 papers (20-50 pages each)</summary>
+
+A curated collection of 5 research papers from our lab covering RAG and Agent fields. This demo showcases broad knowledge coverage for research scenarios.
+
+**Used Papers**: [AI-Researcher](https://github.com/HKUDS/AI-Researcher) | [AutoAgent](https://github.com/HKUDS/AutoAgent) | [RAG-Anything](https://github.com/HKUDS/RAG-Anything) | [LightRAG](https://github.com/HKUDS/LightRAG) | [VideoRAG](https://github.com/HKUDS/VideoRAG)
+
+</details>
+
+<details>
+<summary><b>Data Science Textbook</b> — 8 chapters, 296 pages</summary>
+
+A comprehensive data science textbook with challenging content. This demo showcases **deep knowledge depth** for learning scenarios.
+
+**Book Link**: [Deep Representation Learning Book](https://ma-lab-berkeley.github.io/deep-representation-learning-book/)
+</details>
+
+<br>
+
+**Download and Setup:**
+
+1. Download the demo package: [Google Drive](https://drive.google.com/drive/folders/1iWwfZXiTuQKQqUYb5fGDZjLCeTUP6DA6?usp=sharing)
+2. Extract the compressed files directly into the `data/` directory
+3. Knowledge bases will be automatically available once you start the system
+
+> **Note:** Our knowledge bases use `text-embedding-3-large` with `dimensions = 3072`. Ensure your embeddings model has matching dimensions (3072) for compatibility.
+
+### Step 6: Launch the Application
+
+```bash
+# Activate virtual environment
+conda activate aitutor # or: source venv/bin/activate
+
+# Start web interface (frontend + backend)
+python scripts/start_web.py
+
+# Alternative: CLI interface only
+python scripts/start.py
+
+# Stop the service: Ctrl+C
+```
+
+### Step 7: Create Your Own Knowledge Base
+
+Create custom knowledge bases through the web interface with support for multiple file formats.
+
+1. **Access Knowledge Base**: Navigate to http://localhost:{frontend_port}/knowledge
+2. **Create New Base**: Click "New Knowledge Base"
+3. **Configure Settings**: Enter a unique name for your knowledge base
+4. **Upload Content**: Add single or multiple files for batch processing
+5. **Monitor Progress**: Track processing status in the terminal running `start_web.py`
+ - Large files may take several minutes to complete
+ - Knowledge base becomes available once processing finishes
+
+> **Tips:** Large files may require several minutes to process. Multiple files can be uploaded simultaneously for efficient batch processing.
+
+### Access URLs
+
+| Service | URL | Description |
+|:---:|:---|:---|
+| **Frontend** | http://localhost:{frontend_port} | Main web interface |
+| **API Docs** | http://localhost:{backend_port}/docs | Interactive API documentation |
+| **Health** | http://localhost:{backend_port}/api/v1/knowledge/health | System health check |
+
+---
+
+## 📂 Data Storage
+
+All user content and system data are stored in the `data/` directory:
+
+```
+data/
+├── knowledge_bases/ # Knowledge base storage
+└── user/ # User activity data
+ ├── solve/ # Problem solving results and artifacts
+ ├── question/ # Generated questions
+ ├── research/ # Research reports and cache
+ ├── co-writer/ # Interactive IdeaGen documents and audio files
+ ├── notebook/ # Notebook records and metadata
+ ├── guide/ # Guided learning sessions
+ ├── logs/ # System logs
+ └── run_code_workspace/ # Code execution workspace
+```
+
+Results are automatically saved during all activities. Directories are created automatically as needed.
+
+## 📦 Core Modules
+
+<details>
+<summary><b>🧠 Smart Solver</b></summary>
+
+<details>
+<summary><b>Architecture Diagram</b></summary>
+
+![Smart Solver Architecture](assets/figs/solve.png)
+
+</details>
+
+> **Intelligent problem-solving system** based on **Analysis Loop + Solve Loop** dual-loop architecture, supporting multi-mode reasoning and dynamic knowledge retrieval.
+
+**Core Features**
+
+| Feature | Description |
+|:---:|:---|
+| Dual-Loop Architecture | **Analysis Loop**: InvestigateAgent → NoteAgent<br>**Solve Loop**: PlanAgent → ManagerAgent → SolveAgent → CheckAgent → Format |
+| Multi-Agent Collaboration | Specialized agents: InvestigateAgent, NoteAgent, PlanAgent, ManagerAgent, SolveAgent, CheckAgent |
+| Real-time Streaming | WebSocket transmission with live reasoning process display |
+| Tool Integration | RAG (naive/hybrid), Web Search, Query Item, Code Execution |
+| Persistent Memory | JSON-based memory files for context preservation |
+| Citation Management | Structured citations with reference tracking |
+
+**Usage**
+
+1. Visit http://localhost:{frontend_port}/solver
+2. Select a knowledge base
+3. Enter your question, click "Solve"
+4. Watch the real-time reasoning process and final answer
+
+<details>
+<summary><b>Python API</b></summary>
+
+```python
+import asyncio
+from src.agents.solve import MainSolver
+
+async def main():
+ solver = MainSolver(kb_name="ai_textbook")
+ result = await solver.solve(
+ question="Calculate the linear convolution of x=[1,2,3] and h=[4,5]",
+ mode="auto"
+ )
+ print(result['formatted_solution'])
+
+asyncio.run(main())
+```
+
+</details>
+
+<details>
+<summary><b>Output Location</b></summary>
+
+```
+data/user/solve/solve_YYYYMMDD_HHMMSS/
+├── investigate_memory.json # Analysis Loop memory
+├── solve_chain.json # Solve Loop steps & tool records
+├── citation_memory.json # Citation management
+├── final_answer.md # Final solution (Markdown)
+├── performance_report.json # Performance monitoring
+└── artifacts/ # Code execution outputs
+```
+
+</details>
+
+</details>
+
+---
+
+<details>
+<summary><b>📝 Question Generator</b></summary>
+
+<details>
+<summary><b>Architecture Diagram</b></summary>
+
+![Question Generator Architecture](assets/figs/question-gen.png)
+
+</details>
+
+> **Dual-mode question generation system** supporting **custom knowledge-based generation** and **reference exam paper mimicking** with automatic validation.
+
+**Core Features**
+
+| Feature | Description |
+|:---:|:---|
+| Custom Mode | **Background Knowledge** → **Question Planning** → **Generation** → **Single-Pass Validation**<br>Analyzes question relevance without rejection logic |
+| Mimic Mode | **PDF Upload** → **MinerU Parsing** → **Question Extraction** → **Style Mimicking**<br>Generates questions based on reference exam structure |
+| ReAct Engine | QuestionGenerationAgent with autonomous decision-making (think → act → observe) |
+| Validation Analysis | Single-pass relevance analysis with `kb_coverage` and `extension_points` |
+| Question Types | Multiple choice, fill-in-the-blank, calculation, written response, etc. |
+| Batch Generation | Parallel processing with progress tracking |
+| Complete Persistence | All intermediate files saved (background knowledge, plan, individual results) |
+| Timestamped Output | Mimic mode creates batch folders: `mimic_YYYYMMDD_HHMMSS_{pdf_name}/` |
+
+**Usage**
+
+**Custom Mode:**
+1. Visit http://localhost:{frontend_port}/question
+2. Fill in requirements (topic, difficulty, question type, count)
+3. Click "Generate Questions"
+4. View generated questions with validation reports
+
+**Mimic Mode:**
+1. Visit http://localhost:{frontend_port}/question
+2. Switch to "Mimic Exam" tab
+3. Upload PDF or provide parsed exam directory
+4. Wait for parsing → extraction → generation
+5. View generated questions alongside original references
+
+<details>
+<summary><b>Python API</b></summary>
+
+**Custom Mode - Full Pipeline:**
+```python
+import asyncio
+from src.agents.question import AgentCoordinator
+
+async def main():
+ coordinator = AgentCoordinator(
+ kb_name="ai_textbook",
+ output_dir="data/user/question"
+ )
+
+ # Generate multiple questions from text requirement
+ result = await coordinator.generate_questions_custom(
+ requirement_text="Generate 3 medium-difficulty questions about deep learning basics",
+ difficulty="medium",
+ question_type="choice",
+ count=3
+ )
+
+ print(f"✅ Generated {result['completed']}/{result['requested']} questions")
+ for q in result['results']:
+ print(f"- Relevance: {q['validation']['relevance']}")
+
+asyncio.run(main())
+```
+
+**Mimic Mode - PDF Upload:**
+```python
+from src.agents.question.tools.exam_mimic import mimic_exam_questions
+
+result = await mimic_exam_questions(
+ pdf_path="exams/midterm.pdf",
+ kb_name="calculus",
+ output_dir="data/user/question/mimic_papers",
+ max_questions=5
+)
+
+print(f"✅ Generated {result['successful_generations']} questions")
+print(f"Output: {result['output_file']}")
+```
+
+</details>
+
+<details>
+<summary><b>Output Location</b></summary>
+
+**Custom Mode:**
+```
+data/user/question/custom_YYYYMMDD_HHMMSS/
+├── background_knowledge.json # RAG retrieval results
+├── question_plan.json # Question planning
+├── question_1_result.json # Individual question results
+├── question_2_result.json
+└── ...
+```
+
+**Mimic Mode:**
+```
+data/user/question/mimic_papers/
+└── mimic_YYYYMMDD_HHMMSS_{pdf_name}/
+ ├── {pdf_name}.pdf # Original PDF
+ ├── auto/{pdf_name}.md # MinerU parsed markdown
+ ├── {pdf_name}_YYYYMMDD_HHMMSS_questions.json # Extracted questions
+ └── {pdf_name}_YYYYMMDD_HHMMSS_generated_questions.json # Generated questions
+```
+
+</details>
+
+</details>
+
+---
+
+<details>
+<summary><b>🎓 Guided Learning</b></summary>
+
+<details>
+<summary><b>Architecture Diagram</b></summary>
+
+![Guided Learning Architecture](assets/figs/guide.png)
+
+</details>
+
+> **Personalized learning system** based on notebook content, automatically generating progressive learning paths through interactive pages and smart Q&A.
+
+**Core Features**
+
+| Feature | Description |
+|:---:|:---|
+| Multi-Agent Architecture | **LocateAgent**: Identifies 3-5 progressive knowledge points<br>**InteractiveAgent**: Converts to visual HTML pages<br>**ChatAgent**: Provides contextual Q&A<br>**SummaryAgent**: Generates learning summaries |
+| Smart Knowledge Location | Automatic analysis of notebook content |
+| Interactive Pages | HTML page generation with bug fixing |
+| Smart Q&A | Context-aware answers with explanations |
+| Progress Tracking | Real-time status with session persistence |
+| Cross-Notebook Support | Select records from multiple notebooks |
+
+**Usage Flow**
+
+1. **Select Notebook(s)** — Choose one or multiple notebooks (cross-notebook selection supported)
+2. **Generate Learning Plan** — LocateAgent identifies 3-5 core knowledge points
+3. **Start Learning** — InteractiveAgent generates HTML visualization
+4. **Learning Interaction** — Ask questions, click "Next" to proceed
+5. **Complete Learning** — SummaryAgent generates learning summary
+
+<details>
+<summary><b>Output Location</b></summary>
+
+```
+data/user/guide/
+└── session_{session_id}.json # Complete session state, knowledge points, chat history
+```
+
+</details>
+
+</details>
+
+---
+
+<details>
+<summary><b>✏️ Interactive IdeaGen (Co-Writer)</b></summary>
+
+<details>
+<summary><b>Architecture Diagram</b></summary>
+
+![Interactive IdeaGen Architecture](assets/figs/co-writer.png)
+
+</details>
+
+> **Intelligent Markdown editor** supporting AI-assisted writing, auto-annotation, and TTS narration.
+
+**Core Features**
+
+| Feature | Description |
+|:---:|:---|
+| Rich Text Editing | Full Markdown syntax support with live preview |
+| EditAgent | **Rewrite**: Custom instructions with optional RAG/web context<br>**Shorten**: Compress while preserving key information<br>**Expand**: Add details and context |
+| Auto-Annotation | Automatic key content identification and marking |
+| NarratorAgent | Script generation, TTS audio, multiple voices (Cherry, Stella, Annie, Cally, Eva, Bella) |
+| Context Enhancement | Optional RAG or web search for additional context |
+| Multi-Format Export | Markdown, PDF, etc. |
+
+**Usage**
+
+1. Visit http://localhost:{frontend_port}/co_writer
+2. Enter or paste text in the editor
+3. Use AI features: Rewrite, Shorten, Expand, Auto Mark, Narrate
+4. Export to Markdown or PDF
+
+<details>
+<summary><b>Output Location</b></summary>
+
+```
+data/user/co-writer/
+├── audio/ # TTS audio files
+│ └── {operation_id}.mp3
+├── tool_calls/ # Tool call history
+│ └── {operation_id}_{tool_type}.json
+└── history.json # Edit history
+```
+
+</details>
+
+</details>
+
+---
+
+<details>
+<summary><b>🔬 Deep Research</b></summary>
+
+<details>
+<summary><b>Architecture Diagram</b></summary>
+
+![Deep Research Architecture](assets/figs/deepresearch.png)
+
+</details>
+
+> **DR-in-KG** (Deep Research in Knowledge Graph) — A systematic deep research system based on **Dynamic Topic Queue** architecture, enabling multi-agent collaboration across three phases: **Planning → Researching → Reporting**.
+
+**Core Features**
+
+| Feature | Description |
+|:---:|:---|
+| Three-Phase Architecture | **Phase 1 (Planning)**: RephraseAgent (topic optimization) + DecomposeAgent (subtopic decomposition)<br>**Phase 2 (Researching)**: ManagerAgent (queue scheduling) + ResearchAgent (research decisions) + NoteAgent (info compression)<br>**Phase 3 (Reporting)**: Deduplication → Three-level outline generation → Report writing with citations |
+| Dynamic Topic Queue | Core scheduling system with TopicBlock state management: `PENDING → RESEARCHING → COMPLETED/FAILED`. Supports dynamic topic discovery during research |
+| Execution Modes | **Series Mode**: Sequential topic processing<br>**Parallel Mode**: Concurrent multi-topic processing with `AsyncCitationManagerWrapper` for thread-safe operations |
+| Multi-Tool Integration | **RAG** (hybrid/naive), **Query Item** (entity lookup), **Paper Search**, **Web Search**, **Code Execution** — dynamically selected by ResearchAgent |
+| Unified Citation System | Centralized CitationManager as single source of truth for citation ID generation, ref_number mapping, and deduplication |
+| Preset Configurations | **quick**: Fast research (1-2 subtopics, 1-2 iterations)<br>**medium/standard**: Balanced depth (5 subtopics, 4 iterations)<br>**deep**: Thorough research (8 subtopics, 7 iterations)<br>**auto**: Agent autonomously decides depth |
+
+**Citation System Architecture**
+
+The citation system follows a centralized design with CitationManager as the single source of truth:
+
+```
+┌─────────────────────────────────────────────────────────────────┐
+│ CitationManager │
+│ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │
+│ │ ID Generation │ │ ref_number Map │ │ Deduplication │ │
+│ │ PLAN-XX │ │ citation_id → │ │ (papers only) │ │
+│ │ CIT-X-XX │ │ ref_number │ │ │ │
+│ └────────┬────────┘ └────────┬────────┘ └────────┬────────┘ │
+└───────────┼────────────────────┼────────────────────┼───────────┘
+ │ │ │
+ ┌──────┴──────┐ ┌──────┴──────┐ ┌──────┴──────┐
+ │DecomposeAgent│ │ReportingAgent│ │ References │
+ │ ResearchAgent│ │ (inline [N]) │ │ Section │
+ │ NoteAgent │ └─────────────┘ └────────────┘
+ └─────────────┘
+```
+
+| Component | Description |
+|:---:|:---|
+| ID Format | **PLAN-XX** (planning stage RAG queries) + **CIT-X-XX** (research stage, X=block number) |
+| ref_number Mapping | Sequential 1-based numbers built from sorted citation IDs, with paper deduplication |
+| Inline Citations | Simple `[N]` format in LLM output, post-processed to clickable `[[N]](#ref-N)` links |
+| Citation Table | Clear reference table provided to LLM: `Cite as [1] → (RAG) query preview...` |
+| Post-processing | Automatic format conversion + validation to remove invalid citation references |
+| Parallel Safety | Thread-safe async methods (`get_next_citation_id_async`, `add_citation_async`) for concurrent execution |
+
+**Parallel Execution Architecture**
+
+When `execution_mode: "parallel"` is enabled, multiple topic blocks are researched concurrently:
+
+```
+┌─────────────────────────────────────────────────────────────────────────┐
+│ Parallel Research Execution │
+├─────────────────────────────────────────────────────────────────────────┤
+│ │
+│ DynamicTopicQueue AsyncCitationManagerWrapper │
+│ ┌─────────────────┐ ┌─────────────────────────┐ │
+│ │ Topic 1 (PENDING)│ ──┐ │ Thread-safe wrapper │ │
+│ │ Topic 2 (PENDING)│ ──┼──→ asyncio │ for CitationManager │ │
+│ │ Topic 3 (PENDING)│ ──┤ Semaphore │ │ │
+│ │ Topic 4 (PENDING)│ ──┤ (max=5) │ • get_next_citation_ │ │
+│ │ Topic 5 (PENDING)│ ──┘ │ id_async() │ │
+│ └─────────────────┘ │ • add_citation_async() │ │
+│ │ └───────────┬─────────────┘ │
+│ ▼ │ │
+│ ┌─────────────────────────────────────────────────────────────┐ │
+│ │ Concurrent ResearchAgent Tasks │ │
+│ │ ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐ │ │
+│ │ │ Task 1 │ │ Task 2 │ │ Task 3 │ │ Task 4 │ ... │ │
+│ │ │(Topic 1)│ │(Topic 2)│ │(Topic 3)│ │(Topic 4)│ │ │
+│ │ └────┬────┘ └────┬────┘ └────┬────┘ └────┬────┘ │ │
+│ │ │ │ │ │ │ │
+│ │ └────────────┴────────────┴────────────┘ │ │
+│ │ │ │ │
+│ │ ▼ │ │
+│ │ AsyncManagerAgentWrapper │ │
+│ │ (Thread-safe queue updates) │ │
+│ └─────────────────────────────────────────────────────────────┘ │
+│ │
+└─────────────────────────────────────────────────────────────────────────┘
+```
+
+| Component | Description |
+|:---:|:---|
+| `asyncio.Semaphore` | Limits concurrent tasks to `max_parallel_topics` (default: 5) |
+| `AsyncCitationManagerWrapper` | Wraps CitationManager with `asyncio.Lock()` for thread-safe ID generation |
+| `AsyncManagerAgentWrapper` | Ensures queue state updates are atomic across parallel tasks |
+| Real-time Progress | Live display of all active research tasks with status indicators |
+
+**Agent Responsibilities**
+
+| Agent | Phase | Responsibility |
+|:---:|:---:|:---|
+| RephraseAgent | Planning | Optimizes user input topic, supports multi-turn user interaction for refinement |
+| DecomposeAgent | Planning | Decomposes topic into subtopics with RAG context, obtains citation IDs from CitationManager |
+| ManagerAgent | Researching | Queue state management, task scheduling, dynamic topic addition |
+| ResearchAgent | Researching | Knowledge sufficiency check, query planning, tool selection, requests citation IDs before each tool call |
+| NoteAgent | Researching | Compresses raw tool outputs into summaries, creates ToolTraces with pre-assigned citation IDs |
+| ReportingAgent | Reporting | Builds citation map, generates three-level outline, writes report sections with citation tables, post-processes citations |
+
+**Report Generation Pipeline**
+
+```
+1. Build Citation Map → CitationManager.build_ref_number_map()
+2. Generate Outline → Three-level headings (H1 → H2 → H3)
+3. Write Sections → LLM uses [N] citations with provided citation table
+4. Post-process → Convert [N] → [[N]](#ref-N), validate references
+5. Generate References → Academic-style entries with collapsible source details
+```
+
+**Usage**
+
+1. Visit http://localhost:{frontend_port}/research
+2. Enter research topic
+3. Select research mode (quick/medium/deep/auto)
+4. Watch real-time progress with parallel/series execution
+5. View structured report with clickable inline citations
+6. Export as Markdown or PDF (with proper page splitting and Mermaid diagram support)
+
+<details>
+<summary><b>CLI</b></summary>
+
+```bash
+# Quick mode (fast research)
+python src/agents/research/main.py --topic "Deep Learning Basics" --preset quick
+
+# Medium mode (balanced)
+python src/agents/research/main.py --topic "Transformer Architecture" --preset medium
+
+# Deep mode (thorough research)
+python src/agents/research/main.py --topic "Graph Neural Networks" --preset deep
+
+# Auto mode (agent decides depth)
+python src/agents/research/main.py --topic "Reinforcement Learning" --preset auto
+```
+
+</details>
+
+<details>
+<summary><b>Python API</b></summary>
+
+```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 (main.yaml merged with any module-specific overrides)
+ config = load_config_with_main("research_config.yaml")
+ llm_config = get_llm_config()
+
+ # Create pipeline (agent parameters loaded from agents.yaml automatically)
+ pipeline = ResearchPipeline(
+ config=config,
+ api_key=llm_config["api_key"],
+ base_url=llm_config["base_url"],
+ kb_name="ai_textbook" # Optional: override knowledge base
+ )
+
+ # Run research
+ result = await pipeline.run(topic="Attention Mechanisms in Deep Learning")
+ print(f"Report saved to: {result['final_report_path']}")
+
+asyncio.run(main())
+```
+
+</details>
+
+<details>
+<summary><b>Output Location</b></summary>
+
+```
+data/user/research/
+├── reports/ # Final research reports
+│ ├── research_YYYYMMDD_HHMMSS.md # Markdown report with clickable citations [[N]](#ref-N)
+│ └── research_*_metadata.json # Research metadata and statistics
+└── cache/ # Research process cache
+ └── research_YYYYMMDD_HHMMSS/
+ ├── queue.json # DynamicTopicQueue state (TopicBlocks + ToolTraces)
+ ├── citations.json # Citation registry with ID counters and ref_number mapping
+ │ # - citations: {citation_id: citation_info}
+ │ # - counters: {plan_counter, block_counters}
+ ├── step1_planning.json # Planning phase results (subtopics + PLAN-XX citations)
+ ├── planning_progress.json # Planning progress events
+ ├── researching_progress.json # Researching progress events
+ ├── reporting_progress.json # Reporting progress events
+ ├── outline.json # Three-level report outline structure
+ └── token_cost_summary.json # Token usage statistics
+```
+
+**Citation File Structure** (`citations.json`):
+```json
+{
+ "research_id": "research_20241209_120000",
+ "citations": {
+ "PLAN-01": {"citation_id": "PLAN-01", "tool_type": "rag_hybrid", "query": "...", "summary": "..."},
+ "CIT-1-01": {"citation_id": "CIT-1-01", "tool_type": "paper_search", "papers": [...], ...}
+ },
+ "counters": {
+ "plan_counter": 2,
+ "block_counters": {"1": 3, "2": 2}
+ }
+}
+```
+
+</details>
+
+<details>
+<summary><b>Configuration Options</b></summary>
+
+Key configuration in `config/main.yaml` (research section) and `config/agents.yaml`:
+
+```yaml
+# config/agents.yaml - Agent LLM parameters
+research:
+ temperature: 0.5
+ max_tokens: 12000
+
+# config/main.yaml - Research settings
+research:
+ # Execution Mode
+ researching:
+ execution_mode: "parallel" # "series" or "parallel"
+ max_parallel_topics: 5 # Max concurrent topics
+ max_iterations: 5 # Max iterations per topic
+
+ # Tool Switches
+ enable_rag_hybrid: true # Hybrid RAG retrieval
+ enable_rag_naive: true # Basic RAG retrieval
+ enable_paper_search: true # Academic paper search
+ enable_web_search: true # Web search (also controlled by tools.web_search.enabled)
+ enable_run_code: true # Code execution
+
+ # Queue Limits
+ queue:
+ max_length: 5 # Maximum topics in queue
+
+ # Reporting
+ reporting:
+ enable_inline_citations: true # Enable clickable [N] citations in report
+
+ # Presets: quick, medium, deep, auto
+
+# Global tool switches in tools section
+tools:
+ web_search:
+ enabled: true # Global web search switch (higher priority)
+```
+
+</details>
+
+</details>
+
+---
+
+<details>
+<summary><b>💡 Automated IdeaGen</b></summary>
+
+<details>
+<summary><b>Architecture Diagram</b></summary>
+
+![Automated IdeaGen Architecture](assets/figs/ideagen.png)
+
+</details>
+
+> **Research idea generation system** that extracts knowledge points from notebook records and generates research ideas through multi-stage filtering.
+
+**Core Features**
+
+| Feature | Description |
+|:---:|:---|
+| MaterialOrganizerAgent | Extracts knowledge points from notebook records |
+| Multi-Stage Filtering | **Loose Filter** → **Explore Ideas** (5+ per point) → **Strict Filter** → **Generate Markdown** |
+| Idea Exploration | Innovative thinking from multiple dimensions |
+| Structured Output | Organized markdown with knowledge points and ideas |
+| Progress Callbacks | Real-time updates for each stage |
+
+**Usage**
+
+1. Visit http://localhost:{frontend_port}/ideagen
+2. Select a notebook with records
+3. Optionally provide user thoughts/preferences
+4. Click "Generate Ideas"
+5. View generated research ideas organized by knowledge points
+
+<details>
+<summary><b>Python API</b></summary>
+
+```python
+import asyncio
+from src.agents.ideagen import IdeaGenerationWorkflow, MaterialOrganizerAgent
+from src.core.core import get_llm_config
+
+async def main():
+ llm_config = get_llm_config()
+
+ # Step 1: Extract knowledge points from materials
+ organizer = MaterialOrganizerAgent(
+ api_key=llm_config["api_key"],
+ base_url=llm_config["base_url"]
+ )
+ knowledge_points = await organizer.extract_knowledge_points(
+ "Your learning materials or notebook content here"
+ )
+
+ # Step 2: Generate research ideas
+ workflow = IdeaGenerationWorkflow(
+ api_key=llm_config["api_key"],
+ base_url=llm_config["base_url"]
+ )
+ result = await workflow.process(knowledge_points)
+ print(result) # Markdown formatted research ideas
+
+asyncio.run(main())
+```
+
+</details>
+
+</details>
+
+---
+
+<details>
+<summary><b>📊 Dashboard + Knowledge Base Management</b></summary>
+
+> **Unified system entry** providing activity tracking, knowledge base management, and system status monitoring.
+
+**Key Features**
+
+| Feature | Description |
+|:---:|:---|
+| Activity Statistics | Recent solving/generation/research records |
+| Knowledge Base Overview | KB list, statistics, incremental updates |
+| Notebook Statistics | Notebook counts, record distribution |
+| Quick Actions | One-click access to all modules |
+
+**Usage**
+
+- **Web Interface**: Visit http://localhost:{frontend_port} to view system overview
+- **Create KB**: Click "New Knowledge Base", upload PDF/Markdown documents
+- **View Activity**: Check recent learning activities on Dashboard
+
+</details>
+
+---
+
+<details>
+<summary><b>📓 Notebook</b></summary>
+
+> **Unified learning record management**, connecting outputs from all modules to create a personalized learning knowledge base.
+
+**Core Features**
+
+| Feature | Description |
+|:---:|:---|
+| Multi-Notebook Management | Create, edit, delete notebooks |
+| Unified Record Storage | Integrate solving/generation/research/Interactive IdeaGen records |
+| Categorization Tags | Auto-categorize by type, knowledge base |
+| Custom Appearance | Color, icon personalization |
+
+**Usage**
+
+1. Visit http://localhost:{frontend_port}/notebook
+2. Create new notebook (set name, description, color, icon)
+3. After completing tasks in other modules, click "Add to Notebook"
+4. View and manage all records on the notebook page
+
+</details>
+
+---
+
+### 📖 Module Documentation
+
+<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>
+</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>
+</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">Interactive IdeaGen Module</a></td>
+<td align="center"><a href="src/agents/guide/README.md">Guide Module</a></td>
+</tr>
+<tr>
+<td align="center" colspan="4"><a href="src/agents/ideagen/README.md">Automated IdeaGen Module</a></td>
+</tr>
+</table>
+
+## ❓ FAQ
+
+<details>
+<summary><b>Backend fails to start?</b></summary>
+
+**Checklist**
+- Confirm Python version >= 3.10
+- Confirm all dependencies installed: `pip install -r requirements.txt`
+- Check if port 8001 is in use (configurable in `config/main.yaml`)
+- Check `.env` file configuration
+
+**Solutions**
+- **Change port**: Edit `config/main.yaml` server.backend_port
+- **Check logs**: Review terminal error messages
+
+</details>
+
+<details>
+<summary><b>Port occupied after Ctrl+C?</b></summary>
+
+**Problem**
+
+After pressing Ctrl+C during a running task (e.g., deep research), restarting shows "port already in use" error.
+
+**Cause**
+
+Ctrl+C sometimes only terminates the frontend process while the backend continues running in the background.
+
+**Solution**
+
+```bash
+# macOS/Linux: Find and kill the process
+lsof -i :8001
+kill -9 <PID>
+
+# Windows: Find and kill the process
+netstat -ano | findstr :8001
+taskkill /PID <PID> /F
+```
+
+Then restart the service with `python scripts/start_web.py`.
+
+</details>
+
+<details>
+<summary><b>npm: command not found error?</b></summary>
+
+**Problem**
+
+Running `scripts/start_web.py` shows `npm: command not found` or exit status 127.
+
+**Checklist**
+- Check if npm is installed: `npm --version`
+- Check if Node.js is installed: `node --version`
+- Confirm conda environment is activated (if using conda)
+
+**Solutions**
+```bash
+# Option A: Using Conda (Recommended)
+conda install -c conda-forge nodejs
+
+# Option B: Using Official Installer
+# Download from https://nodejs.org/
+
+# Option C: Using nvm
+nvm install 18
+nvm use 18
+```
+
+**Verify Installation**
+```bash
+node --version # Should show v18.x.x or higher
+npm --version # Should show version number
+```
+
+</details>
+
+<details>
+<summary><b>Frontend cannot connect to backend?</b></summary>
+
+**Checklist**
+- Confirm backend is running (visit http://localhost:8001/docs)
+- Check browser console for error messages
+
+**Solution**
+
+Create `.env.local` in `web` directory:
+
+```bash
+NEXT_PUBLIC_API_BASE=http://localhost:8001
+```
+
+</details>
+
+<details>
+<summary><b>WebSocket connection fails?</b></summary>
+
+**Checklist**
+- Confirm backend is running
+- Check firewall settings
+- Confirm WebSocket URL is correct
+
+**Solution**
+- **Check backend logs**
+- **Confirm URL format**: `ws://localhost:8001/api/v1/...`
+
+</details>
+
+<details>
+<summary><b>Where are module outputs stored?</b></summary>
+
+| Module | Output Path |
+|:---:|:---|
+| Solve | `data/user/solve/solve_YYYYMMDD_HHMMSS/` |
+| Question | `data/user/question/question_YYYYMMDD_HHMMSS/` |
+| Research | `data/user/research/reports/` |
+| Interactive IdeaGen | `data/user/co-writer/` |
+| Notebook | `data/user/notebook/` |
+| Guide | `data/user/guide/session_{session_id}.json` |
+| Logs | `data/user/logs/` |
+
+</details>
+
+<details>
+<summary><b>How to add a new knowledge base?</b></summary>
+
+**Web Interface**
+1. Visit http://localhost:{frontend_port}/knowledge
+2. Click "New Knowledge Base"
+3. Enter knowledge base name
+4. Upload PDF/TXT/MD documents
+5. System will process documents in background
+
+**CLI**
+```bash
+python -m src.knowledge.start_kb init <kb_name> --docs <pdf_path>
+```
+
+</details>
+
+<details>
+<summary><b>How to incrementally add documents to existing KB?</b></summary>
+
+**CLI (Recommended)**
+```bash
+python -m src.knowledge.add_documents <kb_name> --docs <new_document.pdf>
+```
+
+**Benefits**
+- Only processes new documents, saves time and API costs
+- Automatically merges with existing knowledge graph
+- Preserves all existing data
+
+</details>
+
+<details>
+<summary><b>Numbered items extraction failed with uvloop.Loop error?</b></summary>
+
+**Problem**
+
+When initializing a knowledge base, you may encounter this error:
+```
+ValueError: Can't patch loop of type <class 'uvloop.Loop'>
+```
+
+This occurs because Uvicorn uses `uvloop` event loop by default, which is incompatible with `nest_asyncio`.
+
+**Solution**
+
+Use one of the following methods to extract numbered items:
+
+```bash
+# Option 1: Using the shell script (recommended)
+./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
+```
+
+This will extract numbered items (Definitions, Theorems, Equations, etc.) from your knowledge base without reinitializing it.
+
+</details>
+
+## 📄 License
+
+This project is licensed under the **[AGPL-3.0 License](LICENSE)**.
+
+<!--
+## ⭐ Star History
+
+<div align="center">
+<a href="https://star-history.com/#HKUDS/OpenTutor&Date">
+ <picture>
+ <source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=HKUDS/OpenTutor&type=Date&theme=dark" />
+ <source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=HKUDS/OpenTutor&type=Date" />
+ <img alt="Star History Chart" src="https://api.star-history.com/svg?repos=HKUDS/OpenTutor&type=Date" />
+ </picture>
+</a>
+</div> 2-->
+
+
+## 🤝 Contribution
+
+We welcome contributions from the community! To ensure code quality and consistency, please follow the guidelines below.
+
+<details>
+<summary><b>Development Setup</b></summary>
+
+### Pre-commit Hooks Setup
+
+This project uses **pre-commit hooks** to automatically format code and check for issues before commits.
+
+**Step 1: Install pre-commit**
+```bash
+# Using pip
+pip install pre-commit
+
+# Or using conda
+conda install -c conda-forge pre-commit
+```
+
+**Step 2: Install Git hooks**
+```bash
+cd OpenTutor
+pre-commit install
+```
+
+**Step 3: (Optional) Run checks on all files**
+```bash
+pre-commit run --all-files
+```
+
+Every time you run `git commit`, pre-commit hooks will automatically:
+- Format Python code with Ruff
+- Format frontend code with Prettier
+- Check for syntax errors
+- Validate YAML/JSON files
+- Detect potential security issues
+
+### Code Quality Tools
+
+| Tool | Purpose | Configuration |
+|:---:|:---|:---:|
+| **Ruff** | Python linting & formatting | `pyproject.toml` |
+| **Prettier** | Frontend code formatting | `web/.prettierrc.json` |
+| **detect-secrets** | Security check | `.secrets.baseline` |
+
+> **Note**: The project uses **Ruff format** instead of Black to avoid formatting conflicts.
+
+### Common Commands
+
+```bash
+# Normal commit (hooks run automatically)
+git commit -m "Your commit message"
+
+# Manually check all files
+pre-commit run --all-files
+
+# Update hooks to latest versions
+pre-commit autoupdate
+
+# Skip hooks (not recommended, only for emergencies)
+git commit --no-verify -m "Emergency fix"
+```
+
+</details>
+
+### Contribution Guidelines
+
+1. **Fork and Clone**: Fork the repository and clone your fork
+2. **Create Branch**: Create a feature branch from `main`
+3. **Install Pre-commit**: Follow the setup steps above
+4. **Make Changes**: Write your code following the project's style
+5. **Test**: Ensure your changes work correctly
+6. **Commit**: Pre-commit hooks will automatically format your code
+7. **Push and PR**: Push to your fork and create a Pull Request
+
+### Reporting Issues
+
+- Use GitHub Issues to report bugs or suggest features
+- Provide detailed information about the issue
+- Include steps to reproduce if it's a bug
+
+<div align="center">
+<br>
+❤️ We thank all our contributors for their valuable contributions.
+
+</div>
+
+## 🔗 Related Projects
+
+<div align="center">
+
+| [⚡ LightRAG](https://github.com/HKUDS/LightRAG) | [🎨 RAG-Anything](https://github.com/HKUDS/RAG-Anything) | [💻 DeepCode](https://github.com/HKUDS/DeepCode) | [🔬 AI-Researcher](https://github.com/HKUDS/AI-Researcher) |
+|:---:|:---:|:---:|:---:|
+| Simple and Fast RAG | Multimodal RAG | AI Code Assistant | Research Automation |
+
+**[Data Intelligence Lab @ HKU](https://github.com/HKUDS)**
+
+[⭐ Star us](https://github.com/HKUDS/OpenTutor/stargazers) · [🐛 Report a bug](https://github.com/HKUDS/OpenTutor/issues) · [💬 Discussions](https://github.com/HKUDS/OpenTutor/discussions)
+
+---
+*✨ Thanks for visiting **OpenTutor**!*
+
+<img src="https://visitor-badge.laobi.icu/badge?page_id=HKUDS.OpenTutor&style=for-the-badge&color=00d4ff" alt="Views">
+
+</div>
diff --git a/assets/README/README_AR.md b/assets/README/README_AR.md
new file mode 100644
index 000000000..b7a8d5b85
--- /dev/null
+++ b/assets/README/README_AR.md
@@ -0,0 +1,687 @@
+<div align="center" dir="rtl">
+
+<img src="../../assets/logo-ver2.png" alt="OpenTutor Logo" width="150" style="border-radius: 15px;">
+
+# OpenTutor: مساعدك الشخصي للتعلم
+
+[![Python](https://img.shields.io/badge/Python-3.10%2B-3776AB?style=flat-square&logo=python&logoColor=white)](https://www.python.org/downloads/)
+[![Next.js](https://img.shields.io/badge/Next.js-14-000000?style=flat-square&logo=next.js&logoColor=white)](https://nextjs.org/)
+[![FastAPI](https://img.shields.io/badge/FastAPI-0.100+-009688?style=flat-square&logo=fastapi&logoColor=white)](https://fastapi.tiangolo.com/)
+[![License](https://img.shields.io/badge/License-AGPL--3.0-blue?style=flat-square)](LICENSE)
+[![Feishu](https://img.shields.io/badge/Feishu-Group-blue?style=flat)](./Communication.md)
+[![WeChat](https://img.shields.io/badge/WeChat-Group-green?style=flat&logo=wechat)](./Communication.md)
+
+
+
+[**البدء السريع**](#البدء-السريع) · [**الوحدات الأساسية**](#الوحدات-الأساسية) · [**الأسئلة الشائعة**](#الأسئلة-الشائعة)
+
+[🇬🇧 English](../../README.md) · [🇨🇳 中文](README_CN.md) · [🇯🇵 日本語](README_JA.md) · [🇪🇸 Español](README_ES.md) · [🇫🇷 Français](README_FR.md)
+
+</div>
+
+<div align="center">
+
+| ⚡ **Q&A للمعرفة الوثائقية الضخمة** | 📈 **التصور التفاعلي للتعلم** | <br>
+| 🧠 **تعزيز المعرفة** | 🔬 **البحث العميق وتوليد الأفكار** |
+
+</div>
+
+---
+
+## الميزات الرئيسية لـ OpenTutor
+
+### 📚 Q&A للمعرفة الوثائقية الضخمة
+• **قاعدة المعرفة الذكية**: ارفع الكتب المدرسية وأوراق البحث والكتيبات التقنية والوثائق الخاصة بالمجال. أنشئ مستودع معرفة شامل مدعوم بالذكاء الاصطناعي للوصول الفوري.<br>
+• **حل المشاكل متعدد الوكلاء**: بنية استدلال ثنائية الحلقة مع RAG والبحث على الويب والبحث في الأوراق وتنفيذ الكود—تقديم حلول خطوة بخطوة مع اقتباسات دقيقة.
+
+### 🎨 التصور التفاعلي للتعلم
+• **تبسيط المعرفة والتفسيرات**: حول المفاهيم المعقدة والمعرفة والخوارزميات إلى مساعدات بصرية سهلة الفهم وتفاصيل مفصلة خطوة بخطوة وعروض تفاعلية جذابة.<br>
+• **Q&A مخصص**: محادثات واعية بالسياق تتكيف مع تقدمك في التعلم، مع صفحات تفاعلية وتتبع المعرفة القائم على الجلسات.
+
+### 🎯 تعزيز المعرفة مع مولد مشاكل الممارسة
+• **إنشاء التمارين الذكية**: أنشئ اختبارات مستهدفة ومشاكل ممارسة وتقييمات مخصصة مصممة لمستوى معرفتك الحالي وأهداف التعلم المحددة.<br>
+• **محاكاة الامتحان الأصيلة**: ارفع امتحانات مرجعية لإنشاء أسئلة ممارسة تطابق تماماً النمط والتنسيق والصعوبة الأصلية—مما يمنحك تحضيراً واقعياً للاختبار الفعلي.
+
+### 🔍 البحث العميق وتوليد الأفكار
+• **البحث الشامل ومراجعة الأدبيات**: قم باستكشاف مواضيع متعمق مع التحليل المنهجي. حدد الأنماط واربط المفاهيم ذات الصلة عبر التخصصات واجمع نتائج البحث الموجودة.<br>
+• **اكتشاف الأفكار الجديدة**: أنشئ مواد تعليمية منظمة واكتشف فجوات المعرفة. حدد اتجاهات بحثية جديدة واعدة من خلال التوليف الذكي للمعرفة عبر المجالات.
+
+---
+
+<div align="center">
+ <img src="../../assets/figs/title_gradient.svg" alt="All-in-One Tutoring System" width="70%">
+</div>
+
+<br>
+
+<!-- ━━━━━━━━━━━━━━━━ Core Learning Experience ━━━━━━━━━━━━━━━━ -->
+
+<table>
+<tr>
+<td width="50%" align="center" valign="top">
+
+<h3>📚 Q&A للمعرفة الوثائقية الضخمة</h3>
+<a href="#problem-solving-agent">
+<img src="../../assets/gifs/solve.gif" width="100%">
+</a>
+<br>
+<sub>Q&A الوثائق وحل المشاكل خطوة بخطوة</sub>
+
+</td>
+<td width="50%" align="center" valign="top">
+
+<h3>🎨 التصور التفاعلي للتعلم</h3>
+<a href="#guided-learning">
+<img src="../../assets/gifs/guided-learning.gif" width="100%">
+</a>
+<br>
+<sub>التعلم التفاعلي بالذكاء الاصطناعي مع التفسيرات البصرية للمعرفة</sub>
+
+</td>
+</tr>
+</table>
+
+<!-- ━━━━━━━━━━━━━━━━ Practice & Reinforcement ━━━━━━━━━━━━━━━━ -->
+
+<h3 align="center">🎯 تعزيز المعرفة</h3>
+
+<table>
+<tr>
+<td width="50%" valign="top" align="center">
+
+<a href="#question-generator">
+<img src="../../assets/gifs/question-1.gif" width="100%">
+</a>
+
+**أسئلة مخصصة**
+<sub>أسئلة ممارسة متحققة تلقائياً مع ردود فعل فورية</sub>
+
+</td>
+<td width="50%" valign="top" align="center">
+
+<a href="#question-generator">
+<img src="../../assets/gifs/question-2.gif" width="100%">
+</a>
+
+**أسئلة محاكاة**
+<sub>استنساخ نمط الامتحان للممارسة الأصيلة</sub>
+
+</td>
+</tr>
+</table>
+
+<!-- ━━━━━━━━━━━━━━━━ Research & Creation ━━━━━━━━━━━━━━━━ -->
+
+<h3 align="center">🔍 البحث العميق وتوليد الأفكار</h3>
+
+<table>
+<tr>
+<td width="33%" align="center">
+
+<a href="#deep-research">
+<img src="../../assets/gifs/deepresearch.gif" width="100%">
+</a>
+
+**البحث العميق**
+<sub>البحث على الويب والأوراق مع مراجعة الأدبيات</sub>
+
+</td>
+<td width="33%" align="center">
+
+<a href="#idea-generation">
+<img src="../../assets/gifs/ideagen.gif" width="100%">
+</a>
+
+**توليد الأفكار الآلي**
+<sub>العصف الذهني المنهجي وتوليف المفاهيم</sub>
+
+</td>
+<td width="33%" align="center">
+
+<a href="#co-writer">
+<img src="../../assets/gifs/co-writer.gif" width="100%">
+</a>
+
+**توليد الأفكار التفاعلي**
+<sub>توليد الأفكار المدعوم بـ RAG مع رؤى متعددة المصادر</sub>
+
+</td>
+</tr>
+</table>
+
+<!-- ━━━━━━━━━━━━━━━━ Knowledge Infrastructure ━━━━━━━━━━━━━━━━ -->
+
+<h3 align="center">🏗️ نظام المعرفة الشامل</h3>
+
+<table>
+<tr>
+<td width="50%" align="center">
+
+<a href="#dashboard--knowledge-base-management">
+<img src="../../assets/gifs/knowledge_bases.png" width="100%">
+</a>
+
+**قاعدة المعرفة الشخصية**
+<sub>أنشئ ونظم مستودع معرفتك الخاص</sub>
+
+</td>
+<td width="50%" align="center">
+
+<a href="#notebook">
+<img src="../../assets/gifs/notebooks.png" width="100%">
+</a>
+
+**دفتر الملاحظات الشخصي**
+<sub>ذاكرتك السياقية لجلسات التعلم</sub>
+
+</td>
+</tr>
+</table>
+
+<p align="center">
+ <sub>🌙 استخدم OpenTutor في <b>الوضع الداكن</b>!</sub>
+</p>
+
+<details>
+<summary><b>معمارية النظام</b></summary>
+<br>
+
+![OpenTutor Full-Stack Workflow](../../assets/figs/full-pipe.png)
+
+</details>
+
+## 📋 قائمة المهام
+
+> تابعنا للحصول على تحديثات مستقبلية!
+- [ ] التعلم القائم على المشاريع
+- [ ] الترميز العميق من توليد الأفكار
+- [ ] ذاكرة مخصصة
+- [ ] خيار بديل مع RAG الساذج
+
+## 🚀 البدء السريع
+
+### الخطوة 1: استنساخ وإنشاء بيئة افتراضية
+
+```bash
+# استنساخ المستودع
+git clone https://github.com/HKUDS/OpenTutor.git
+cd OpenTutor
+
+# إنشاء بيئة افتراضية (اختر طريقة)
+
+# الخيار A: استخدام conda (موصى به)
+conda create -n aitutor python=3.10
+conda activate aitutor
+
+# الخيار B: استخدام venv
+python -m venv venv
+# في Windows:
+venv\Scripts\activate
+# في macOS/Linux:
+source venv/bin/activate
+```
+
+### الخطوة 2: تثبيت المتطلبات
+
+قم بتشغيل سكريبت التثبيت بنقرة واحدة لتثبيت جميع المتطلبات تلقائياً:
+
+```bash
+# موصى به: استخدام سكريبت bash
+bash scripts/install_all.sh
+
+# بديل: استخدام سكريبت Python
+python scripts/install_all.py
+
+# أو التثبيت يدوياً
+pip install -r requirements.txt
+npm install
+```
+
+### الخطوة 3: تكوين متغيرات البيئة
+
+إنشاء ملف `.env` في دليل المشروع الجذر بناءً على `.env.example`:
+
+```bash
+# انسخ من نموذج .env.example (إن وجد)
+cp .env.example .env
+
+# ثم عدّل ملف .env بمفاتيح API الخاصة بك:
+```
+
+### الخطوة 4: تكوين المنافذ *(اختياري)*
+
+بشكل افتراضي، يستخدم التطبيق:
+- **Backend (FastAPI)**: `8001`
+- **Frontend (Next.js)**: `3782`
+
+يمكنك تعديل هذه المنافذ في `config/main.yaml` بتحرير قيم `server.backend_port` و `server.frontend_port`.
+
+### الخطوة 5: استخدم عروضنا التوضيحية *(اختياري)*
+
+لتجربة سريعة لنظامنا، نوفر قاعدتي معرفة معالجتين مسبقاً بالإضافة إلى مجموعة من الأسئلة الصعبة وأمثلة الاستخدام.
+
+<details>
+<summary><b>مجموعة أوراق البحث</b> — 5 أوراق (20-50 صفحة لكل منها)</summary>
+
+مجموعة منسقة من 5 أوراق بحث في مجالات RAG و Agent من معملنا. يمثل هذا العرض التوضيحي سيناريوهات ذات **تغطية معرفة واسعة** لأغراض البحث.
+
+**الأوراق المستخدمة**: [AI-Researcher](https://github.com/HKUDS/AI-Researcher) | [AutoAgent](https://github.com/HKUDS/AutoAgent) | [RAG-Anything](https://github.com/HKUDS/RAG-Anything) | [LightRAG](https://github.com/HKUDS/LightRAG) | [VideoRAG](https://github.com/HKUDS/VideoRAG)
+
+</details>
+
+<details>
+<summary><b>كتاب علوم البيانات</b> — 8 فصول، 296 صفحة</summary>
+
+كتاب علوم بيانات شامل وصعب. يمثل هذا العرض التوضيحي سيناريوهات ذات **عمق معرفة عميق** لأغراض التعليم.
+
+**رابط الكتاب**: [Deep Representation Learning Book](https://ma-lab-berkeley.github.io/deep-representation-learning-book/)
+</details>
+
+<br>
+
+**التنزيل والإعداد:**
+
+1. قم بتنزيل حزمة العرض التوضيحي من: [Google Drive](https://drive.google.com/drive/folders/1iWwfZXiTuQKQqUYb5fGDZjLCeTUP6DA6?usp=sharing)
+2. استخرج الملفات المضغوطة مباشرة في دليل `data/`
+3. ستكون قواعد المعرفة متاحة تلقائياً في النظام بعد بدء المشروع
+
+> **ملاحظة:** نستخدم `text-embedding-3-large` كنموذج تضمين عند تهيئة قواعد معرفتنا، مع `dimensions = 3072`. تأكد من أن أبعاد نموذج التضمين الخاص بك تبلغ أيضاً 3072.
+
+### الخطوة 6: ابدأ التطبيق
+
+```bash
+# تأكد من تفعيل البيئة الافتراضية
+conda activate aitutor # أو: source venv/bin/activate
+
+# ابدأ واجهة الويب (frontend + backend)
+python scripts/start_web.py
+
+# أو ابدأ واجهة CLI فقط
+python scripts/start.py
+
+# لإيقاف الخدمة، اضغط على Ctrl+C
+```
+
+### الخطوة 7: إنشاء قاعدة معرفة الخاصة بك
+
+بعد بدء التطبيق، يمكنك إنشاء قاعدة معرفة الخاصة بك من خلال واجهة الويب، تحت أي نمط.
+
+1. **الوصول إلى صفحة قاعدة المعرفة**: زر http://localhost:{frontend_port}/knowledge
+2. **إنشاء قاعدة معرفة جديدة**: انقر على زر "New Knowledge Base"
+3. **سمي قاعدة معرفتك**: أدخل اسماً فريداً لقاعدة معرفتك
+4. **تحميل الملفات**: قم بتحميل ملف واحد أو أكثر
+5. **انتظر المعالجة**: سيقوم النظام بمعالجة ملفاتك تلقائياً في الخلفية
+ - راقب تقدم الإنشاء في الطرفية حيث يعمل `start_web.py`
+ - ستكون قاعدة المعرفة متاحة بمجرد اكتمال المعالجة
+
+> **نصائح:** قد تستغرق الملفات الكبيرة عدة دقائق في المعالجة. يمكنك تحميل ملفات متعددة في المرة الواحدة لمعالجة دفعية.
+
+### عناوين URL للوصول
+
+| الخدمة | URL | الوصف |
+|:---:|:---|:---|
+| **Frontend** | http://localhost:{frontend_port} | واجهة الويب الرئيسية |
+| **وثائق API** | http://localhost:{backend_port}/docs | وثائق API التفاعلية |
+| **الصحة** | http://localhost:{backend_port}/api/v1/knowledge/health | فحص صحة النظام |
+
+---
+
+## 📄 الترخيص
+
+```
+data/
+├── knowledge_bases/ # تخزين قاعدة المعرفة
+└── user/ # بيانات نشاط المستخدم
+ ├── solve/ # نتائج حل المشاكل والعناصر
+ ├── question/ # الأسئلة المولدة
+ ├── research/ # التقارير البحثية والذاكرة المؤقتة
+ ├── co-writer/ # وثائق Co-Writer وملفات صوتية
+ ├── notebook/ # سجلات دفتر الملاحظات والبيانات الوصفية
+ ├── guide/ # جلسات التعليم الموجه
+ ├── logs/ # السجلات النظامية
+ └── run_code_workspace/ # مساحة عمل تنفيذ الرمز
+```
+
+يتم حفظ جميع النتائج تلقائياً عند إجراء أي نشاط. يتم إنشاء المجلدات تلقائياً إذا كانت غير موجودة.
+
+---
+
+## 📖 توثيق الوحدات
+
+<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>
+</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>
+</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>
+</tr>
+<tr>
+<td align="center" colspan="4"><a href="../../src/agents/ideagen/README.md">Idea Generation Module</a></td>
+</tr>
+</table>
+
+---
+
+## ❓ الأسئلة الشائعة
+
+<details>
+<summary><b>فشل البداية في الخلفية؟</b></summary>
+
+**قائمة التحقق**
+- تأكد من إصدار Python >= 3.10
+- تأكد من تثبيت جميع المتطلبات: `pip install -r requirements.txt`
+- تحقق مما إذا كان المنفذ 8001 قيد الاستخدام (قابل للتكوين في `config/main.yaml`)
+- تحقق من تكوين ملف `.env`
+
+**الحلول**
+- **تغيير المنفذ**: تحرير `config/main.yaml` server.backend_port
+- **التحقق من السجلات**: مراجعة رسائل خطأ الطرفية
+
+</details>
+
+<details>
+<summary><b>المنفذ محتل بعد Ctrl+C؟</b></summary>
+
+**المشكلة**
+
+بعد الضغط على Ctrl+C أثناء تشغيل المهمة (مثل البحث العميق)، يظهر خطأ "المنفذ قيد الاستخدام بالفعل".
+
+**السبب**
+
+Ctrl+C يُنهي أحياناً فقط عملية الواجهة الأمامية بينما يستمر الخادم الخلفي في العمل في الخلفية.
+
+**الحل**
+
+```bash
+# macOS/Linux: البحث عن قتل العملية
+lsof -i :8001
+kill -9 <PID>
+
+# Windows: البحث عن قتل العملية
+netstat -ano | findstr :8001
+taskkill /PID <PID> /F
+```
+
+ثم أعد تشغيل الخدمة باستخدام `python scripts/start_web.py`.
+
+</details>
+
+<details>
+<summary><b>خطأ "npm: command not found"؟</b></summary>
+
+**المشكلة**
+
+يُظهر تشغيل `scripts/start_web.py` `npm: command not found` أو رمز الخروج 127.
+
+**قائمة التحقق**
+- تحقق مما إذا تم تثبيت npm: `npm --version`
+- تحقق مما إذا تم تثبيت Node.js: `node --version`
+- تأكد من تفعيل بيئة conda (إذا كنت تستخدم conda)
+
+**الحلول**
+```bash
+# الخيار A: استخدام Conda (موصى به)
+conda install -c conda-forge nodejs
+
+# الخيار B: استخدام المثبت الرسمي
+# تنزيل من https://nodejs.org/
+
+# الخيار C: استخدام nvm
+nvm install 18
+nvm use 18
+```
+
+**التحقق من التثبيت**
+```bash
+node --version # يجب أن يعرض v18.x.x أو أعلى
+npm --version # يجب أن يعرض رقم الإصدار
+```
+
+</details>
+
+<details>
+<summary><b>لا يمكن للواجهة الأمامية الاتصال بالخادم الخلفي؟</b></summary>
+
+**قائمة التحقق**
+- تأكد من أن الخادم الخلفي يعمل (زر http://localhost:8001/docs)
+- تحقق من وحدة تحكم المتصفح للحصول على رسائل الخطأ
+
+**الحل**
+
+إنشاء `.env.local` في دليل `web`:
+
+```bash
+NEXT_PUBLIC_API_BASE=http://localhost:8001
+```
+
+</details>
+
+<details>
+<summary><b>فشل اتصال WebSocket؟</b></summary>
+
+**قائمة التحقق**
+- تأكد من أن الخادم الخلفي يعمل
+- تحقق من إعدادات جدار الحماية
+- تأكد من صحة عنوان URL للـ WebSocket
+
+**الحل**
+- **تحقق من سجلات الخادم الخلفي**
+- **تأكد من تنسيق URL**: `ws://localhost:8001/api/v1/...`
+
+</details>
+
+<details>
+<summary><b>أين يتم تخزين مخرجات الوحدة؟</b></summary>
+
+| الوحدة | مسار الإخراج |
+|:---:|:---|
+| حل | `data/user/solve/solve_YYYYMMDD_HHMMSS/` |
+| السؤال | `data/user/question/question_YYYYMMDD_HHMMSS/` |
+| البحث | `data/user/research/reports/` |
+| Co-Writer | `data/user/co-writer/` |
+| دفتر الملاحظات | `data/user/notebook/` |
+| الدليل | `data/user/guide/session_{session_id}.json` |
+| السجلات | `data/user/logs/` |
+
+</details>
+
+<details>
+<summary><b>كيفية إضافة قاعدة معرفة جديدة؟</b></summary>
+
+**واجهة الويب**
+1. زر http://localhost:{frontend_port}/knowledge
+2. انقر على "New Knowledge Base"
+3. أدخل اسم قاعدة المعرفة
+4. حمّل وثائق PDF/TXT/MD
+5. سيقوم النظام بمعالجة الوثائق في الخلفية
+
+**واجهة الأوامر**
+```bash
+python -m src.knowledge.start_kb init <kb_name> --docs <pdf_path>
+```
+
+</details>
+
+<details>
+<summary><b>كيفية إضافة الوثائق بشكل تدريجي إلى KB موجود؟</b></summary>
+
+**واجهة الأوامر (موصى به)**
+```bash
+python -m src.knowledge.add_documents <kb_name> --docs <new_document.pdf>
+```
+
+**الفوائد**
+- معالجة الوثائق الجديدة فقط، توفير الوقت وتكلفة API
+- الدمج التلقائي مع الرسم البياني للمعرفة الموجود
+- الحفاظ على جميع البيانات الموجودة
+
+</details>
+
+<details>
+<summary><b>خطأ uvloop.Loop عند استخراج العناصر المرقمة؟</b></summary>
+
+**المشكلة**
+
+عند تهيئة قاعدة معرفة، قد تواجه هذا الخطأ:
+```
+ValueError: Can't patch loop of type <class 'uvloop.Loop'>
+```
+
+يحدث هذا لأن Uvicorn يستخدم حلقة أحداث `uvloop` افتراضياً، وهي غير متوافقة مع `nest_asyncio`.
+
+**الحل**
+
+استخدم إحدى الطرق التالية لاستخراج العناصر المرقمة:
+
+```bash
+# الخيار 1: استخدام سكريبت shell (موصى به)
+./scripts/extract_numbered_items.sh <kb_name>
+
+# الخيار 2: أمر Python مباشر
+python src/knowledge/extract_numbered_items.py --kb <kb_name> --base-dir ./data/knowledge_bases
+```
+
+سيؤدي هذا إلى استخراج العناصر المرقمة (التعريفات والنظريات والمعادلات وما إلى ذلك) من قاعدة معرفتك دون إعادة تهيئتها.
+
+</details>
+
+<br>
+
+---
+
+## 📄 الترخيص
+
+هذا المشروع مرخص تحت **[AGPL-3.0](LICENSE)**.
+
+
+## ⭐ سجل النجوم
+
+<div align="center">
+<a href="https://star-history.com/#HKUDS/OpenTutor&Date">
+ <picture>
+ <source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=HKUDS/OpenTutor&type=Date&theme=dark" />
+ <source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=HKUDS/OpenTutor&type=Date" />
+ <img alt="Star History Chart" src="https://api.star-history.com/svg?repos=HKUDS/OpenTutor&type=Date" />
+ </picture>
+</a>
+</div>
+
+
+## 🤝 المساهمة
+
+نرحب بالمساهمات من المجتمع! لضمان جودة وتناسق الرمز، يرجى اتباع الإرشادات أدناه.
+
+<details>
+<summary><b>إعداد التطوير</b></summary>
+
+### إعداد Pre-commit Hooks
+
+يستخدم هذا المشروع **pre-commit hooks** لتنسيق الرمز والتحقق من المشاكل تلقائياً قبل الالتزام.
+
+**الخطوة 1: تثبيت pre-commit**
+```bash
+# استخدام pip
+pip install pre-commit
+
+# أو استخدام conda
+conda install -c conda-forge pre-commit
+```
+
+**الخطوة 2: تثبيت خطافات Git**
+```bash
+cd OpenTutor
+pre-commit install
+```
+
+**الخطوة 3: (اختياري) قم بتشغيل الفحوصات على جميع الملفات**
+```bash
+pre-commit run --all-files
+```
+
+في كل مرة تقوم بتشغيل `git commit`، ستقوم خطافات pre-commit تلقائياً بـ:
+- تنسيق رمز Python باستخدام Ruff
+- تنسيق رمز الواجهة الأمامية باستخدام Prettier
+- التحقق من أخطاء بناء الجملة
+- التحقق من صحة ملفات YAML/JSON
+- كشف المشاكل الأمنية المحتملة
+
+### أدوات جودة الرمز
+
+| الأداة | الغرض | التكوين |
+|:---:|:---|:---:|
+| **Ruff** | فحص وتنسيق رمز Python | `pyproject.toml` |
+| **Prettier** | تنسيق رمز الواجهة الأمامية | `web/.prettierrc.json` |
+| **detect-secrets** | فحص الأمان | `.secrets.baseline` |
+
+> **ملاحظة**: يستخدم المشروع **Ruff format** بدلاً من Black لتجنب تضارب التنسيق.
+
+### الأوامر الشائعة
+
+```bash
+# الالتزام العادي (تعمل الخطافات تلقائياً)
+git commit -m "رسالة التزامك"
+
+# التحقق اليدوي من جميع الملفات
+pre-commit run --all-files
+
+# تحديث الخطافات إلى أحدث إصدارات
+pre-commit autoupdate
+
+# تخطي الخطافات (غير موصى به، فقط للحالات الطارئة)
+git commit --no-verify -m "إصلاح الطوارئ"
+```
+
+</details>
+
+### إرشادات المساهمة
+
+1. **Fork و Clone**: Fork المستودع واستنسخه
+2. **إنشاء فرع**: إنشاء فرع ميزة من `main`
+3. **تثبيت Pre-commit**: اتبع خطوات الإعداد أعلاه
+4. **إجراء التغييرات**: اكتب الرمز باتباع نمط المشروع
+5. **الاختبار**: تأكد من أن تغييراتك تعمل بشكل صحيح
+6. **الالتزام**: ستقوم خطافات pre-commit بتنسيق الرمز تلقائياً
+7. **الدفع و PR**: ادفع إلى fork الخاص بك وأنشئ طلب سحب
+
+### إبلاغ عن المشاكل
+
+- استخدم GitHub Issues للإبلاغ عن الأخطاء أو اقتراح الميزات
+- توفير معلومات مفصلة حول المشكلة
+- إذا كانت خطأ، فقم بتضمين الخطوات لإعادة إنتاجها
+
+<div align="center">
+<br>
+❤️ نشكر جميع المساهمين على مساهماتهم القيمة.
+
+</div>
+
+## 🔗 المشاريع ذات الصلة
+
+<div align="center">
+
+| [⚡ LightRAG](https://github.com/HKUDS/LightRAG) | [🎨 RAG-Anything](https://github.com/HKUDS/RAG-Anything) | [💻 DeepCode](https://github.com/HKUDS/DeepCode) | [🔬 AI-Researcher](https://github.com/HKUDS/AI-Researcher) |
+|:---:|:---:|:---:|:---:|
+| RAG بسيط وسريع | RAG متعدد الأنماط | مساعد رمز ذكاء اصطناعي | أتمتة البحث |
+
+**[مختبر ذكاء البيانات @ جامعة هونج كونج](https://github.com/HKUDS)**
+
+[⭐ Star us](https://github.com/HKUDS/OpenTutor/stargazers) · [🐛 Report a bug](https://github.com/HKUDS/OpenTutor/issues) · [💬 Discussions](https://github.com/HKUDS/OpenTutor/discussions)
+
+---
+*✨ شكراً لزيارتك **OpenTutor**!*
+
+<img src="https://visitor-badge.laobi.icu/badge?page_id=HKUDS.OpenTutor&style=for-the-badge&color=00d4ff" alt="Views">
+
+</div>
diff --git a/assets/README/README_CN.md b/assets/README/README_CN.md
new file mode 100644
index 000000000..b41b666ef
--- /dev/null
+++ b/assets/README/README_CN.md
@@ -0,0 +1,1317 @@
+<div align="center">
+
+<img src="../../assets/logo-ver2.png" alt="OpenTutor Logo" width="150" style="border-radius: 15px;">
+
+# OpenTutor: 您的个人学习助手
+
+[![Python](https://img.shields.io/badge/Python-3.10%2B-3776AB?style=flat-square&logo=python&logoColor=white)](https://www.python.org/downloads/)
+[![Next.js](https://img.shields.io/badge/Next.js-14-000000?style=flat-square&logo=next.js&logoColor=white)](https://nextjs.org/)
+[![FastAPI](https://img.shields.io/badge/FastAPI-0.100+-009688?style=flat-square&logo=fastapi&logoColor=white)](https://fastapi.tiangolo.com/)
+[![License](https://img.shields.io/badge/License-AGPL--3.0-blue?style=flat-square)](LICENSE)
+[![Feishu](https://img.shields.io/badge/Feishu-Group-blue?style=flat)](./Communication.md)
+[![WeChat](https://img.shields.io/badge/WeChat-Group-green?style=flat&logo=wechat)](./Communication.md)
+
+
+
+[**快速开始**](#快速开始) · [**核心模块**](#核心模块) · [**常见问题**](#常见问题)
+
+[🇬🇧 English](../../README.md) · [🇯🇵 日本語](README_JA.md) · [🇪🇸 Español](README_ES.md) · [🇫🇷 Français](README_FR.md) · [🇸🇦 العربية](README_AR.md)
+
+</div>
+
+<div align="center">
+
+| ⚡ **海量文档知识问答** | 📈 **交互式学习可视化** | <br>
+| 🧠 **知识强化** | 🔬 **深度研究与想法生成** |
+
+</div>
+
+---
+
+## OpenTutor 的核心功能
+
+### 📚 海量文档知识问答
+• **智能知识库**:上传教科书、研究论文、技术手册和领域特定文档。构建全面的 AI 驱动知识库,实现即时访问。<br>
+• **多 Agent 问题求解**:双循环推理架构,集成 RAG、网络搜索、论文搜索和代码执行——提供带精确引用的分步解决方案。
+
+### 🎨 交互式学习可视化
+• **知识简化与解释**:将复杂概念、知识和算法转化为易于理解的可视化辅助工具、详细的分步分解和引人入胜的交互式演示。<br>
+• **个性化问答**:上下文感知对话,适应您的学习进度,提供交互式页面和基于会话的知识跟踪。
+
+### 🎯 知识强化与练习题目生成器
+• **智能练习创建**:根据您当前的知识水平和特定学习目标,生成有针对性的测验、练习题和定制评估。<br>
+• **真实考试模拟**:上传参考考试,生成完美匹配原始风格、格式和难度的练习题——为您提供真实考试准备。
+
+### 🔍 深度研究与想法生成
+• **全面研究与文献综述**:通过系统分析进行深入的专题探索。识别模式,连接跨学科的相关概念,综合现有研究发现。<br>
+• **新颖见解发现**:生成结构化学习材料并发现知识空白。通过智能跨领域知识综合,识别有前景的新研究方向。
+
+---
+
+<div align="center">
+ <img src="../../assets/figs/title_gradient.svg" alt="All-in-One Tutoring System" width="70%">
+</div>
+
+<br>
+
+<!-- ━━━━━━━━━━━━━━━━ Core Learning Experience ━━━━━━━━━━━━━━━━ -->
+
+<table>
+<tr>
+<td width="50%" align="center" valign="top">
+
+<h3>📚 海量文档知识问答</h3>
+<a href="#problem-solving-agent">
+<img src="../../assets/gifs/solve.gif" width="100%">
+</a>
+<br>
+<sub>文档问答和分步问题求解</sub>
+
+</td>
+<td width="50%" align="center" valign="top">
+
+<h3>🎨 交互式学习可视化</h3>
+<a href="#guided-learning">
+<img src="../../assets/gifs/guided-learning.gif" width="100%">
+</a>
+<br>
+<sub>带知识可视化解释的交互式 AI 学习</sub>
+
+</td>
+</tr>
+</table>
+
+<!-- ━━━━━━━━━━━━━━━━ Practice & Reinforcement ━━━━━━━━━━━━━━━━ -->
+
+<h3 align="center">🎯 知识强化</h3>
+
+<table>
+<tr>
+<td width="50%" valign="top" align="center">
+
+<a href="#question-generator">
+<img src="../../assets/gifs/question-1.gif" width="100%">
+</a>
+
+**自定义题目**
+<sub>带即时反馈的自动验证练习题</sub>
+
+</td>
+<td width="50%" valign="top" align="center">
+
+<a href="#question-generator">
+<img src="../../assets/gifs/question-2.gif" width="100%">
+</a>
+
+**模仿题目**
+<sub>克隆考试风格以进行真实练习</sub>
+
+</td>
+</tr>
+</table>
+
+<!-- ━━━━━━━━━━━━━━━━ Research & Creation ━━━━━━━━━━━━━━━━ -->
+
+<h3 align="center">🔍 深度研究与想法生成</h3>
+
+<table>
+<tr>
+<td width="33%" align="center">
+
+<a href="#deep-research">
+<img src="../../assets/gifs/deepresearch.gif" width="100%">
+</a>
+
+**深度研究**
+<sub>带文献综述的网络和论文搜索</sub>
+
+</td>
+<td width="33%" align="center">
+
+<a href="#idea-generation">
+<img src="../../assets/gifs/ideagen.gif" width="100%">
+</a>
+
+**自动化想法生成**
+<sub>系统化头脑风暴和概念综合</sub>
+
+</td>
+<td width="33%" align="center">
+
+<a href="#co-writer">
+<img src="../../assets/gifs/co-writer.gif" width="100%">
+</a>
+
+**交互式想法生成**
+<sub>基于 RAG 的想法生成,具有多源见解</sub>
+
+</td>
+</tr>
+</table>
+
+<!-- ━━━━━━━━━━━━━━━━ Knowledge Infrastructure ━━━━━━━━━━━━━━━━ -->
+
+<h3 align="center">🏗️ 一体化知识系统</h3>
+
+<table>
+<tr>
+<td width="50%" align="center">
+
+<a href="#dashboard--knowledge-base-management">
+<img src="../../assets/gifs/knowledge_bases.png" width="100%">
+</a>
+
+**个人知识库**
+<sub>构建和组织您自己的知识库</sub>
+
+</td>
+<td width="50%" align="center">
+
+<a href="#notebook">
+<img src="../../assets/gifs/notebooks.png" width="100%">
+</a>
+
+**个人笔记本**
+<sub>您学习会话的上下文记忆</sub>
+
+</td>
+</tr>
+</table>
+
+<p align="center">
+ <sub>🌙 在 <b>暗色模式</b> 下使用 OpenTutor!</sub>
+</p>
+
+---
+
+## 🏛️ OpenTutor 的框架
+
+<div align="center">
+<img src="../../assets/figs/full-pipe.png" alt="OpenTutor Full-Stack Workflow" width="100%">
+</div>
+
+### 💬 用户界面层
+• **直观交互**:简单的双向查询-响应流程,实现直观交互。<br>
+• **结构化输出**:结构化响应生成,将复杂信息组织成可操作的输出。
+
+### 🤖 智能 Agent 模块
+• **问题求解与评估**:分步问题求解和定制评估生成。<br>
+• **研究与学习**:用于专题探索的深度研究和带可视化的引导式学习。<br>
+• **想法生成**:自动化和交互式概念开发,具有多源见解。
+
+### 🔧 工具集成层
+• **信息检索**:RAG 混合检索、实时网络搜索和学术论文数据库。<br>
+• **处理与分析**:Python 代码执行、查询项查找和用于文档分析的 PDF 解析。
+
+### 🧠 知识与记忆基础
+• **知识图谱**:实体-关系映射,用于语义连接和知识发现。<br>
+• **向量存储**:基于嵌入的语义搜索,用于智能内容检索。<br>
+• **记忆系统**:会话状态管理和引用跟踪,用于上下文连续性。
+
+## 📋 待做事项
+
+> 🌟 Star 以关注我们的未来更新!
+- [ ] 项目式学习
+- [ ] 从想法生成进行深度编码
+- [ ] 个性化记忆
+
+## 🚀 快速开始
+
+### 第一步:克隆仓库并创建虚拟环境
+
+```bash
+# 克隆仓库
+git clone https://github.com/HKUDS/OpenTutor.git
+cd OpenTutor
+
+# 创建虚拟环境(选择一种方式)
+
+# 选项 A:使用 conda(推荐)
+conda create -n aitutor python=3.10
+conda activate aitutor
+
+# 选项 B:使用 venv
+python -m venv venv
+# 在 Windows:
+venv\Scripts\activate
+# 在 macOS/Linux:
+source venv/bin/activate
+```
+
+### 第二步:安装依赖
+
+运行一键安装脚本自动安装所有依赖:
+
+```bash
+# 推荐:使用 bash 脚本
+bash scripts/install_all.sh
+
+# 或使用 Python 脚本
+python scripts/install_all.py
+
+# 或手动安装
+pip install -r requirements.txt
+npm install
+```
+
+### 第三步:配置环境变量
+
+在项目根目录基于 `.env.example` 创建 `.env` 文件:
+
+```bash
+# 从 .env.example 模板复制(如果存在)
+cp .env.example .env
+
+# 然后使用您的 API 密钥编辑 .env 文件:
+```
+
+### 第四步:配置端口和 LLM 参数 *(可选)*
+
+默认情况下,应用使用:
+- **后端 (FastAPI)**: `8001`
+- **前端 (Next.js)**: `3782`
+
+您可以通过编辑 `config/main.yaml` 中的 `server.backend_port` 和 `server.frontend_port` 值来修改这些端口。
+
+**LLM 参数**:所有 agent 的 `temperature` 和 `max_tokens` 设置都集中在 `config/agents.yaml` 中。每个模块(guide、solve、research、question、ideagen、co_writer)都有自己的一组参数。详细信息请参阅[配置文档](config/README.md)。
+
+### 第五步:使用我们的演示 *(可选)*
+
+为了快速体验我们的系统,我们提供了两个预处理的知识库以及一系列具有挑战性的问题和使用示例。
+
+<details>
+<summary><b>研究论文集合</b> — 5 篇论文(20-50 页每篇)</summary>
+
+来自我们实验室的 5 篇 RAG 和 Agent 领域的精选研究论文。此演示代表具有**广泛知识覆盖**的研究场景。
+
+**使用的论文**: [AI-Researcher](https://github.com/HKUDS/AI-Researcher) | [AutoAgent](https://github.com/HKUDS/AutoAgent) | [RAG-Anything](https://github.com/HKUDS/RAG-Anything) | [LightRAG](https://github.com/HKUDS/LightRAG) | [VideoRAG](https://github.com/HKUDS/VideoRAG)
+
+</details>
+
+<details>
+<summary><b>数据科学教科书</b> — 8 章,296 页</summary>
+
+一本综合性且具有挑战性的数据科学教科书。此演示代表具有**深层知识深度**的学习场景。
+
+**书籍链接**: [Deep Representation Learning Book](https://ma-lab-berkeley.github.io/deep-representation-learning-book/)
+</details>
+
+<br>
+
+**下载和设置:**
+
+1. 从以下位置下载演示包:[Google Drive](https://drive.google.com/drive/folders/1iWwfZXiTuQKQqUYb5fGDZjLCeTUP6DA6?usp=sharing)
+2. 将压缩文件直接解压到 `data/` 目录
+3. 启动项目后,知识库将自动在系统中可用
+
+> **注意:** 我们在初始化知识库时使用 `text-embedding-3-large` 作为嵌入模型,维度为 `dimensions = 3072`。请确保您的嵌入模型维度也是 3072。
+
+### 第六步:启动应用
+
+```bash
+# 确保虚拟环境已激活
+conda activate aitutor # 或: source venv/bin/activate
+
+# 启动 Web 界面(前端 + 后端)
+python scripts/start_web.py
+
+# 或仅启动 CLI 界面
+python scripts/start.py
+
+# 要停止服务,请按 Ctrl+C
+```
+
+### 第七步:创建自己的知识库
+
+启动应用后,您可以通过 Web 界面创建自己的知识库,支持任何模态。
+
+1. **访问知识库页面**:访问 http://localhost:{frontend_port}/knowledge
+2. **创建新知识库**:点击"新建知识库"按钮
+3. **命名知识库**:为您的知识库输入唯一名称
+4. **上传文件**:上传一个或多个文件
+5. **等待处理**:系统将在后台自动处理您的文件
+ - 在运行 `start_web.py` 的终端中监控创建进度
+ - 处理完成后,知识库将可用
+
+> **提示:** 大文件可能需要几分钟才能处理。您可以一次上传多个文件进行批处理。
+
+### 访问 URL
+
+| 服务 | 网址 | 描述 |
+|:---:|:---|:---|
+| **前端** | http://localhost:{frontend_port} | 主 Web 界面 |
+| **API 文档** | http://localhost:{backend_port}/docs | 交互式 API 文档 |
+| **健康检查** | http://localhost:{backend_port}/api/v1/knowledge/health | 系统健康检查 |
+
+---
+
+## 📂 数据存储
+
+所有用户生成的内容和系统数据都存储在 `data/` 文件夹中:
+
+```
+data/
+├── knowledge_bases/ # 知识库存储
+└── user/ # 用户活动数据
+ ├── solve/ # 问题求解结果和产物
+ ├── question/ # 生成的题目
+ ├── research/ # 研究报告和缓存
+ ├── co-writer/ # Co-Writer 文档和音频文件
+ ├── notebook/ # 笔记本记录和元数据
+ ├── guide/ # 引导式学习会话
+ ├── logs/ # 系统日志
+ └── run_code_workspace/ # 代码执行工作区
+```
+
+执行任何活动时,所有结果都会自动保存。如果文件夹不存在,将自动创建。
+
+---
+
+## 📦 核心模块
+
+<details>
+<summary><b>🧠 智能解题</b></summary>
+
+<details>
+<summary><b>架构图</b></summary>
+
+![Smart Solver Architecture](../../assets/figs/solve.png)
+
+</details>
+
+> **智能问题求解系统**,基于 **分析循环 + 求解循环** 双循环架构,支持多模式推理和动态知识检索。
+
+**核心特性**
+
+| 特性 | 描述 |
+|:---:|:---|
+| 双循环架构 | **分析循环**:InvestigateAgent → NoteAgent<br>**求解循环**:PlanAgent → ManagerAgent → SolveAgent → CheckAgent → 格式化 |
+| 多Agent协作 | 专业化Agent:InvestigateAgent、NoteAgent、PlanAgent、ManagerAgent、SolveAgent、CheckAgent |
+| 实时流式传输 | WebSocket 传输,实时显示推理过程 |
+| 工具集成 | RAG (naive/hybrid)、网络搜索、查询项、代码执行 |
+| 持久化记忆 | 基于 JSON 的记忆文件用于上下文保存 |
+| 引用管理 | 结构化引用和引用追踪 |
+
+**使用方法**
+
+1. 访问 http://localhost:{frontend_port}/solver
+2. 选择知识库
+3. 输入问题,点击"求解"
+4. 观看实时推理过程和最终答案
+
+<details>
+<summary><b>Python API</b></summary>
+
+```python
+import asyncio
+from src.agents.solve import MainSolver
+
+async def main():
+ solver = MainSolver(kb_name="ai_textbook")
+ result = await solver.solve(
+ question="计算 x=[1,2,3] 和 h=[4,5] 的线性卷积",
+ mode="auto"
+ )
+ print(result['formatted_solution'])
+
+asyncio.run(main())
+```
+
+</details>
+
+<details>
+<summary><b>输出位置</b></summary>
+
+```
+data/user/solve/solve_YYYYMMDD_HHMMSS/
+├── investigate_memory.json # 分析循环记忆
+├── solve_chain.json # 求解循环步骤和工具记录
+├── citation_memory.json # 引用管理
+├── final_answer.md # 最终答案(Markdown)
+├── performance_report.json # 性能监控
+└── artifacts/ # 代码执行输出
+```
+
+</details>
+
+</details>
+
+---
+
+<details>
+<summary><b>📝 题目生成器</b></summary>
+
+<details>
+<summary><b>架构图</b></summary>
+
+![Question Generator Architecture](../../assets/figs/question-gen.png)
+
+</details>
+
+> **双Agent协作题目生成系统**,基于 **ReAct** 范式,自动生成并验证题目质量。
+
+**核心特性**
+
+| 特性 | 描述 |
+|:---:|:---|
+| ReAct 引擎 | 具有自主决策的 QuestionGenerationAgent (think → act → observe) |
+| 知识检查 | Agent 评估检索结果,知识不足时拒绝任务 |
+| 验证工作流 | 独立验证,包含详细反馈和修改建议 |
+| 题目类型 | 多选题、填空题、计算题、问答题等 |
+| 迭代优化 | 多轮协作(最多 10 轮),自动优化 |
+| 批量生成 | 自动需求分解,独立任务保证 |
+| 试卷模仿 | 基于参考试卷生成题目 |
+
+**使用方法**
+
+1. 访问 http://localhost:{frontend_port}/question
+2. 填写要求(知识点、难度、题型)
+3. 点击"生成题目"
+4. 查看生成的题目和验证结果
+
+<details>
+<summary><b>Python API</b></summary>
+
+**单题生成:**
+```python
+import asyncio
+from src.agents.question import AgentCoordinator
+
+async def main():
+ coordinator = AgentCoordinator(kb_name="ai_textbook")
+ result = await coordinator.generate_question({
+ "knowledge_point": "线性卷积",
+ "difficulty": "medium",
+ "question_type": "choice"
+ })
+
+ if result.get("success"):
+ print(f"题目: {result['question']['question']}")
+ elif result.get("error") == "task_rejected":
+ print(f"Agent 拒绝: {result.get('reason')}")
+
+asyncio.run(main())
+```
+
+**批量生成:**
+```python
+# 自动需求分解
+result = await coordinator.generate_questions_from_prompt(
+ requirement_text="生成 3 道关于多元极限的题目",
+ num_questions=3
+)
+```
+
+</details>
+
+<details>
+<summary><b>输出位置</b></summary>
+
+```
+data/user/question/question_YYYYMMDD_HHMMSS/
+```
+
+</details>
+
+</details>
+
+---
+
+<details>
+<summary><b>🎓 引导式学习</b></summary>
+
+<details>
+<summary><b>架构图</b></summary>
+
+![Guided Learning Architecture](../../assets/figs/guide.png)
+
+</details>
+
+> **个性化学习系统**,基于笔记本内容,自动生成递进式学习路径,通过交互式页面和智能问答。
+
+**核心特性**
+
+| 特性 | 描述 |
+|:---:|:---|
+| 多Agent架构 | **LocateAgent**:识别 3-5 个递进知识点<br>**InteractiveAgent**:转换为可视化 HTML 页面<br>**ChatAgent**:提供上下文问答<br>**SummaryAgent**:生成学习总结 |
+| 智能知识定位 | 笔记本内容自动分析 |
+| 交互式页面 | HTML 页面生成,包含错误修复 |
+| 智能问答 | 上下文感知答案和解释 |
+| 进度追踪 | 实时状态与会话持久化 |
+| 跨笔记本支持 | 从多个笔记本选择记录 |
+
+**使用流程**
+
+1. **选择笔记本** — 选择一个或多个笔记本(支持跨笔记本选择)
+2. **生成学习计划** — LocateAgent 识别 3-5 个核心知识点
+3. **开始学习** — InteractiveAgent 生成 HTML 可视化
+4. **学习互动** — 提问,点击"下一步"继续
+5. **完成学习** — SummaryAgent 生成学习总结
+
+<details>
+<summary><b>输出位置</b></summary>
+
+```
+data/user/guide/
+└── session_{session_id}.json # 完整会话状态、知识点、聊天历史
+```
+
+</details>
+
+</details>
+
+---
+
+<details>
+<summary><b>✏️ Co-Writer</b></summary>
+
+<details>
+<summary><b>架构图</b></summary>
+
+![Co-Writer Architecture](../../assets/figs/co-writer.png)
+
+</details>
+
+> **智能 Markdown 编辑器**,支持 AI 辅助写作、自动标注和 TTS 叙述。
+
+**核心特性**
+
+| 特性 | 描述 |
+|:---:|:---|
+| 富文本编辑 | 完整 Markdown 语法支持,实时预览 |
+| EditAgent | **改写**:自定义指令,可选 RAG/网络上下文<br>**缩短**:压缩同时保留关键信息<br>**扩展**:添加细节和上下文 |
+| 自动标注 | 自动识别和标记关键内容 |
+| NarratorAgent | 脚本生成、TTS 音频、多种语音(Cherry、Stella、Annie、Cally、Eva、Bella) |
+| 上下文增强 | 可选 RAG 或网络搜索 |
+| 多格式导出 | Markdown、PDF 等 |
+
+**使用方法**
+
+1. 访问 http://localhost:{frontend_port}/co_writer
+2. 在编辑器中输入或粘贴文本
+3. 使用 AI 功能:改写、缩短、扩展、自动标注、叙述
+4. 导出为 Markdown 或 PDF
+
+<details>
+<summary><b>输出位置</b></summary>
+
+```
+data/user/co-writer/
+├── audio/ # TTS 音频文件
+│ └── {operation_id}.mp3
+├── tool_calls/ # 工具调用历史
+│ └── {operation_id}_{tool_type}.json
+└── history.json # 编辑历史
+```
+
+</details>
+
+</details>
+
+---
+
+<details>
+<summary><b>🔬 深度研究</b></summary>
+
+<details>
+<summary><b>架构图</b></summary>
+
+![Deep Research Architecture](../../assets/figs/deepresearch.png)
+
+</details>
+
+> **DR-in-KG**(知识图谱中的深度研究)— 基于 **动态话题队列** 架构的系统化深研系统,支持三个阶段的多Agent协作:**规划 → 研究 → 报告**。
+
+**核心特性**
+
+| 特性 | 描述 |
+|:---:|:---|
+| 三阶段架构 | **阶段 1(规划)**:RephraseAgent(话题优化)+ DecomposeAgent(子话题分解)<br>**阶段 2(研究)**:ManagerAgent(队列调度)+ ResearchAgent(研究决策)+ NoteAgent(信息压缩)<br>**阶段 3(报告)**:去重 → 三层大纲生成 → 带引用的报告撰写 |
+| 动态话题队列 | 核心调度系统,TopicBlock 状态管理:`PENDING → RESEARCHING → COMPLETED/FAILED`。支持研究期间动态话题发现 |
+| 执行模式 | **串行模式**:顺序话题处理<br>**并行模式**:并发多话题处理,使用 `AsyncCitationManagerWrapper` 保证线程安全 |
+| 多工具集成 | **RAG**(hybrid/naive)、**查询项**(实体查询)、**论文搜索**、**网络搜索**、**代码执行** — 由 ResearchAgent 动态选择 |
+| 统一引用系统 | 以 CitationManager 为唯一真实来源,用于引用 ID 生成、ref_number 映射和去重 |
+| 预设配置 | **quick**:快速研究(1-2 个子话题,1-2 次迭代)<br>**medium/standard**:平衡深度(5 个子话题,4 次迭代)<br>**deep**:深入研究(8 个子话题,7 次迭代)<br>**auto**:Agent 自主决定深度 |
+
+**引用系统架构**
+
+引用系统采用中心化设计,以 CitationManager 为唯一真实来源:
+
+```
+┌─────────────────────────────────────────────────────────────────┐
+│ CitationManager │
+│ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │
+│ │ ID 生成 │ │ ref_number 映射 │ │ 去重 │ │
+│ │ PLAN-XX │ │ citation_id → │ │ (仅论文) │ │
+│ │ CIT-X-XX │ │ ref_number │ │ │ │
+│ └────────┬────────┘ └────────┬────────┘ └────────┬────────┘ │
+└───────────┼────────────────────┼────────────────────┼───────────┘
+ │ │ │
+ ┌──────┴──────┐ ┌──────┴──────┐ ┌──────┴──────┐
+ │DecomposeAgent│ │ReportingAgent│ │ 参考文献 │
+ │ ResearchAgent│ │ (内联 [N]) │ │ 部分 │
+ │ NoteAgent │ └─────────────┘ └────────────┘
+ └─────────────┘
+```
+
+| 组件 | 描述 |
+|:---:|:---|
+| ID 格式 | **PLAN-XX**(规划阶段 RAG 查询)+ **CIT-X-XX**(研究阶段,X=块编号) |
+| ref_number 映射 | 从排序引用 ID 构建的序列 1-based 数字,包含论文去重 |
+| 内联引用 | LLM 输出中的简单 `[N]` 格式,后处理为可点击 `[[N]](#ref-N)` 链接 |
+| 引用表 | 提供给 LLM 的清晰参考表:`引用为 [1] → (RAG) 查询预览...` |
+| 后处理 | 自动格式转换 + 验证,移除无效引用 |
+| 并行安全 | 线程安全的异步方法(`get_next_citation_id_async`、`add_citation_async`)用于并发执行 |
+
+**并行执行架构**
+
+启用 `execution_mode: "parallel"` 时,多个话题块并发研究:
+
+```
+┌─────────────────────────────────────────────────────────────────────────┐
+│ 并行研究执行 │
+├─────────────────────────────────────────────────────────────────────────┤
+│ │
+│ DynamicTopicQueue AsyncCitationManagerWrapper │
+│ ┌─────────────────┐ ┌─────────────────────────┐ │
+│ │ 话题 1 (PENDING)│ ──┐ │ CitationManager 的线程 │ │
+│ │ 话题 2 (PENDING)│ ──┼──→ asyncio │ 安全包装器 │ │
+│ │ 话题 3 (PENDING)│ ──┤ Semaphore │ │ │
+│ │ 话题 4 (PENDING)│ ──┤ (max=5) │ • get_next_citation_ │ │
+│ │ 话题 5 (PENDING)│ ──┘ │ id_async() │ │
+│ └─────────────────┘ │ • add_citation_async() │ │
+│ │ └───────────┬─────────────┘ │
+│ ▼ │ │
+│ ┌─────────────────────────────────────────────────────────────┐ │
+│ │ 并发 ResearchAgent 任务 │ │
+│ │ ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐ │ │
+│ │ │ 任务 1 │ │ 任务 2 │ │ 任务 3 │ │ 任务 4 │ ... │ │
+│ │ │(话题 1)│ │(话题 2)│ │(话题 3)│ │(话题 4)│ │ │
+│ │ └────┬────┘ └────┬────┘ └────┬────┘ └────┬────┘ │ │
+│ │ │ │ │ │ │ │
+│ │ └────────────┴────────────┴────────────┘ │ │
+│ │ │ │ │
+│ │ ▼ │ │
+│ │ AsyncManagerAgentWrapper │ │
+│ │ (线程安全队列更新) │ │
+│ └─────────────────────────────────────────────────────────────┘ │
+│ │
+└─────────────────────────────────────────────────────────────────────────┘
+```
+
+| 组件 | 描述 |
+|:---:|:---|
+| `asyncio.Semaphore` | 将并发任务限制为 `max_parallel_topics`(默认:5) |
+| `AsyncCitationManagerWrapper` | 使用 `asyncio.Lock()` 包装 CitationManager,实现线程安全的 ID 生成 |
+| `AsyncManagerAgentWrapper` | 确保跨并行任务的队列状态更新是原子的 |
+| 实时进度 | 所有活跃研究任务的实时显示,带状态指示器 |
+
+**Agent 职责**
+
+| Agent | 阶段 | 职责 |
+|:---:|:---:|:---|
+| RephraseAgent | 规划 | 优化用户输入话题,支持多轮用户交互来优化 |
+| DecomposeAgent | 规划 | 使用 RAG 上下文分解话题为子话题,从 CitationManager 获取引用 ID |
+| ManagerAgent | 研究 | 队列状态管理、任务调度、动态话题添加 |
+| ResearchAgent | 研究 | 知识充分性检查、查询规划、工具选择、在每次工具调用前请求引用 ID |
+| NoteAgent | 研究 | 将原始工具输出压缩为摘要,使用预分配引用 ID 创建 ToolTraces |
+| ReportingAgent | 报告 | 构建引用映射、生成三层大纲、撰写带引用表的报告章节、后处理引用 |
+
+**报告生成管道**
+
+```
+1. 构建引用映射 → CitationManager.build_ref_number_map()
+2. 生成大纲 → 三层标题(H1 → H2 → H3)
+3. 撰写章节 → LLM 使用提供的引用表中的 [N] 引用
+4. 后处理 → 转换 [N] → [[N]](#ref-N),验证引用
+5. 生成参考文献 → 学术风格条目,可折叠源详情
+```
+
+**使用方法**
+
+1. 访问 http://localhost:{frontend_port}/research
+2. 输入研究话题
+3. 选择研究模式(quick/medium/deep/auto)
+4. 观看具有并行/串行执行的实时进度
+5. 查看带可点击内联引用的结构化报告
+6. 导出为 Markdown 或 PDF(包含正确的页面分割和 Mermaid 图支持)
+
+<details>
+<summary><b>CLI</b></summary>
+
+```bash
+# 快速模式(快速研究)
+python src/agents/research/main.py --topic "深度学习基础" --preset quick
+
+# 中等模式(平衡)
+python src/agents/research/main.py --topic "Transformer 架构" --preset medium
+
+# 深度模式(深入研究)
+python src/agents/research/main.py --topic "图神经网络" --preset deep
+
+# 自动模式(Agent 自主决定深度)
+python src/agents/research/main.py --topic "强化学习" --preset auto
+```
+
+</details>
+
+<details>
+<summary><b>Python API</b></summary>
+
+```python
+import asyncio
+from src.agents.research import ResearchPipeline
+from src.core.core import get_llm_config, load_config_with_main
+
+async def main():
+ # 加载配置
+ config = load_config_with_main("research_config.yaml")
+ llm_config = get_llm_config()
+
+ # 创建管道
+ pipeline = ResearchPipeline(
+ config=config,
+ api_key=llm_config["api_key"],
+ base_url=llm_config["base_url"],
+ kb_name="ai_textbook" # 可选:覆盖知识库
+ )
+
+ # 运行研究
+ result = await pipeline.run(topic="深度学习中的注意力机制")
+ print(f"报告保存到: {result['final_report_path']}")
+
+asyncio.run(main())
+```
+
+</details>
+
+<details>
+<summary><b>输出位置</b></summary>
+
+```
+data/user/research/
+├── reports/ # 最终研究报告
+│ ├── research_YYYYMMDD_HHMMSS.md # 带可点击引用 [[N]](#ref-N) 的 Markdown 报告
+│ └── research_*_metadata.json # 研究元数据和统计
+└── cache/ # 研究过程缓存
+ └── research_YYYYMMDD_HHMMSS/
+ ├── queue.json # DynamicTopicQueue 状态(TopicBlocks + ToolTraces)
+ ├── citations.json # 引用注册表,带 ID 计数器和 ref_number 映射
+ │ # - citations: {citation_id: citation_info}
+ │ # - counters: {plan_counter, block_counters}
+ ├── step1_planning.json # 规划阶段结果(子话题 + PLAN-XX 引用)
+ ├── planning_progress.json # 规划进度事件
+ ├── researching_progress.json # 研究进度事件
+ ├── reporting_progress.json # 报告进度事件
+ ├── outline.json # 三层报告大纲结构
+ └── token_cost_summary.json # Token 使用统计
+```
+
+**引用文件结构**(`citations.json`):
+```json
+{
+ "research_id": "research_20241209_120000",
+ "citations": {
+ "PLAN-01": {"citation_id": "PLAN-01", "tool_type": "rag_hybrid", "query": "...", "summary": "..."},
+ "CIT-1-01": {"citation_id": "CIT-1-01", "tool_type": "paper_search", "papers": [...], ...}
+ },
+ "counters": {
+ "plan_counter": 2,
+ "block_counters": {"1": 3, "2": 2}
+ }
+}
+```
+
+</details>
+
+<details>
+<summary><b>配置选项</b></summary>
+
+`config/research_config.yaml` 中的关键配置:
+
+```yaml
+# 执行模式
+researching:
+ execution_mode: "parallel" # "series" 或 "parallel"
+ max_parallel_topics: 5 # 最大并发话题数(并行模式使用异步引用方法)
+ max_iterations: 5 # 每个话题的最大迭代次数
+
+# 工具开关
+ enable_rag_hybrid: true # Hybrid RAG 检索
+ enable_rag_naive: true # 基本 RAG 检索
+ enable_paper_search: true # 学术论文搜索
+ enable_web_search: true # 网络搜索
+ enable_run_code: true # 代码执行
+
+# 队列限制
+queue:
+ max_length: 5 # 队列中的最大话题数
+
+# 报告
+reporting:
+ enable_inline_citations: true # 启用报告中的可点击 [N] 引用
+
+# 预设:quick、medium、deep、auto
+```
+
+</details>
+
+</details>
+
+---
+
+<details>
+<summary><b>💡 想法生成</b></summary>
+
+<details>
+<summary><b>架构图</b></summary>
+
+![Idea Generation Architecture](../../assets/figs/ideagen.png)
+
+</details>
+
+> **研究想法生成系统**,从笔记本记录中提取知识点,通过多阶段过滤生成研究想法。
+
+**核心特性**
+
+| 特性 | 描述 |
+|:---:|:---|
+| MaterialOrganizerAgent | 从笔记本记录中提取知识点 |
+| 多阶段过滤 | **宽松过滤** → **探索想法**(每点 5+ 个)→ **严格过滤** → **生成 Markdown** |
+| 想法探索 | 从多个维度进行创新思考 |
+| 结构化输出 | 按知识点组织的 Markdown,包含想法 |
+| 进度回调 | 每个阶段的实时更新 |
+
+**使用方法**
+
+1. 访问 http://localhost:{frontend_port}/ideagen
+2. 选择包含记录的笔记本
+3. 可选提供用户思考/偏好
+4. 点击"生成想法"
+5. 查看按知识点组织的研究想法
+
+<details>
+<summary><b>Python API</b></summary>
+
+```python
+import asyncio
+from src.agents.ideagen import IdeaGenerationWorkflow, MaterialOrganizerAgent
+from src.core.core import get_llm_config
+
+async def main():
+ llm_config = get_llm_config()
+
+ # 第 1 步:从材料中提取知识点
+ organizer = MaterialOrganizerAgent(
+ api_key=llm_config["api_key"],
+ base_url=llm_config["base_url"]
+ )
+ knowledge_points = await organizer.extract_knowledge_points(
+ "您的学习材料或笔记本内容"
+ )
+
+ # 第 2 步:生成研究想法
+ workflow = IdeaGenerationWorkflow(
+ api_key=llm_config["api_key"],
+ base_url=llm_config["base_url"]
+ )
+ result = await workflow.process(knowledge_points)
+ print(result) # Markdown 格式化研究想法
+
+asyncio.run(main())
+```
+
+</details>
+
+</details>
+
+---
+
+<details>
+<summary><b>📊 仪表盘 + 知识库管理</b></summary>
+
+> **统一系统入口**,提供活动追踪、知识库管理和系统状态监控。
+
+**关键特性**
+
+| 特性 | 描述 |
+|:---:|:---|
+| 活动统计 | 最近的求解/生成/研究记录 |
+| 知识库概览 | KB 列表、统计、增量更新 |
+| 笔记本统计 | 笔记本计数、记录分布 |
+| 快速操作 | 一键访问所有模块 |
+
+**使用方法**
+
+- **Web 界面**:访问 http://localhost:{frontend_port} 查看系统概览
+- **创建 KB**:点击"新建知识库",上传 PDF/Markdown 文档
+- **查看活动**:在仪表盘上检查最近的学习活动
+
+</details>
+
+---
+
+<details>
+<summary><b>📓 笔记本</b></summary>
+
+> **统一的学习记录管理**,连接来自所有模块的输出,创建个性化学习知识库。
+
+**核心特性**
+
+| 特性 | 描述 |
+|:---:|:---|
+| 多笔记本管理 | 创建、编辑、删除笔记本 |
+| 统一记录存储 | 整合求解/生成/研究/Co-Writer 记录 |
+| 分类标签 | 按类型、知识库自动分类 |
+| 自定义外观 | 颜色、图标个性化 |
+
+**使用方法**
+
+1. 访问 http://localhost:{frontend_port}/notebook
+2. 创建新笔记本(设置名称、描述、颜色、图标)
+3. 在其他模块完成任务后,点击"添加到笔记本"
+4. 在笔记本页面查看和管理所有记录
+
+</details>
+
+---
+
+### 📖 模块文档
+
+<table>
+<tr>
+<td align="center"><a href="../../config/README.md">配置</a></td>
+<td align="center"><a href="../../data/README.md">数据目录</a></td>
+<td align="center"><a href="../../src/api/README.md">API 后端</a></td>
+<td align="center"><a href="../../src/core/README.md">核心工具</a></td>
+</tr>
+<tr>
+<td align="center"><a href="../../src/knowledge/README.md">知识库</a></td>
+<td align="center"><a href="../../src/tools/README.md">工具</a></td>
+<td align="center"><a href="../../web/README.md">Web 前端</a></td>
+<td align="center"><a href="../../src/agents/solve/README.md">求解模块</a></td>
+</tr>
+<tr>
+<td align="center"><a href="../../src/agents/question/README.md">题目模块</a></td>
+<td align="center"><a href="../../src/agents/research/README.md">研究模块</a></td>
+<td align="center"><a href="../../src/agents/co_writer/README.md">Co-Writer 模块</a></td>
+<td align="center"><a href="../../src/agents/guide/README.md">引导模块</a></td>
+</tr>
+<tr>
+<td align="center" colspan="4"><a href="../../src/agents/ideagen/README.md">想法生成模块</a></td>
+</tr>
+</table>
+
+---
+
+## ❓ 常见问题
+
+<details>
+<summary><b>后端启动失败?</b></summary>
+
+**检查清单**
+- 确认 Python 版本 >= 3.10
+- 确认已安装所有依赖:`pip install -r requirements.txt`
+- 检查端口 8001 是否被占用(可在 `config/main.yaml` 中配置)
+- 检查 `.env` 文件配置
+
+**解决方案**
+- **更改端口**:编辑 `config/main.yaml` 中的 server.backend_port
+- **检查日志**:查看终端错误消息
+
+</details>
+
+<details>
+<summary><b>Ctrl+C 后端口被占用?</b></summary>
+
+**问题**
+
+在运行任务(例如深度研究)期间按 Ctrl+C,重新启动显示"端口已在使用"错误。
+
+**原因**
+
+Ctrl+C 有时只会终止前端进程,而后端继续在后台运行。
+
+**解决方案**
+
+```bash
+# macOS/Linux:查找并杀死进程
+lsof -i :8001
+kill -9 <PID>
+
+# Windows:查找并杀死进程
+netstat -ano | findstr :8001
+taskkill /PID <PID> /F
+```
+
+然后用 `python scripts/start_web.py` 重新启动服务。
+
+</details>
+
+<details>
+<summary><b>npm: command not found 错误?</b></summary>
+
+**问题**
+
+运行 `scripts/start_web.py` 显示 `npm: command not found` 或退出状态 127。
+
+**检查清单**
+- 检查 npm 是否已安装:`npm --version`
+- 检查 Node.js 是否已安装:`node --version`
+- 确认 conda 环境已激活(如果使用 conda)
+
+**解决方案**
+```bash
+# 选项 A:使用 Conda(推荐)
+conda install -c conda-forge nodejs
+
+# 选项 B:使用官方安装程序
+# 从 https://nodejs.org/ 下载
+
+# 选项 C:使用 nvm
+nvm install 18
+nvm use 18
+```
+
+**验证安装**
+```bash
+node --version # 应显示 v18.x.x 或更高版本
+npm --version # 应显示版本号
+```
+
+</details>
+
+<details>
+<summary><b>前端无法连接后端?</b></summary>
+
+**检查清单**
+- 确认后端正在运行(访问 http://localhost:8001/docs)
+- 检查浏览器控制台的错误消息
+
+**解决方案**
+
+在 `web` 目录创建 `.env.local`:
+
+```bash
+NEXT_PUBLIC_API_BASE=http://localhost:8001
+```
+
+</details>
+
+<details>
+<summary><b>WebSocket 连接失败?</b></summary>
+
+**检查清单**
+- 确认后端正在运行
+- 检查防火墙设置
+- 确认 WebSocket URL 正确
+
+**解决方案**
+- **检查后端日志**
+- **确认 URL 格式**:`ws://localhost:8001/api/v1/...`
+
+</details>
+
+<details>
+<summary><b>模块输出存储在哪里?</b></summary>
+
+| 模块 | 输出路径 |
+|:---:|:---|
+| 求解 | `data/user/solve/solve_YYYYMMDD_HHMMSS/` |
+| 题目 | `data/user/question/question_YYYYMMDD_HHMMSS/` |
+| 研究 | `data/user/research/reports/` |
+| Co-Writer | `data/user/co-writer/` |
+| 笔记本 | `data/user/notebook/` |
+| 引导 | `data/user/guide/session_{session_id}.json` |
+| 日志 | `data/user/logs/` |
+
+</details>
+
+<details>
+<summary><b>如何添加新的知识库?</b></summary>
+
+**Web 界面**
+1. 访问 http://localhost:{frontend_port}/knowledge
+2. 点击"新建知识库"
+3. 输入知识库名称
+4. 上传 PDF/TXT/MD 文档
+5. 系统将在后台处理文档
+
+**CLI**
+```bash
+python -m src.knowledge.start_kb init <kb_name> --docs <pdf_path>
+```
+
+</details>
+
+<details>
+<summary><b>如何向现有知识库增量添加文档?</b></summary>
+
+**CLI(推荐)**
+```bash
+python -m src.knowledge.add_documents <kb_name> --docs <new_document.pdf>
+```
+
+**优势**
+- 仅处理新文档,节省时间和 API 成本
+- 自动与现有知识图谱合并
+- 保留所有现有数据
+
+</details>
+
+<details>
+<summary><b>提取编号项时出现 uvloop.Loop 错误?</b></summary>
+
+**问题**
+
+初始化知识库时,可能遇到此错误:
+```
+ValueError: Can't patch loop of type <class 'uvloop.Loop'>
+```
+
+这是因为 Uvicorn 默认使用 `uvloop` 事件循环,与 `nest_asyncio` 不兼容。
+
+**解决方案**
+
+使用以下方法之一提取编号项:
+
+```bash
+# 选项 1:使用 shell 脚本(推荐)
+./scripts/extract_numbered_items.sh <kb_name>
+
+# 选项 2:直接 Python 命令
+python src/knowledge/extract_numbered_items.py --kb <kb_name> --base-dir ./data/knowledge_bases
+```
+
+这将从知识库中提取编号项(定义、定理、方程等),无需重新初始化。
+
+</details>
+
+<br>
+
+---
+
+## 📄 许可证
+
+本项目采用 **[AGPL-3.0 许可证](LICENSE)**。
+
+
+## ⭐ Star 历史
+
+<div align="center">
+<a href="https://star-history.com/#HKUDS/OpenTutor&Date">
+ <picture>
+ <source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=HKUDS/OpenTutor&type=Date&theme=dark" />
+ <source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=HKUDS/OpenTutor&type=Date" />
+ <img alt="Star History Chart" src="https://api.star-history.com/svg?repos=HKUDS/OpenTutor&type=Date" />
+ </picture>
+</a>
+</div>
+
+
+## 🤝 贡献
+
+我们欢迎来自社区的贡献!为确保代码质量和一致性,请遵循以下准则。
+
+<details>
+<summary><b>开发设置</b></summary>
+
+### Pre-commit Hooks 设置
+
+此项目使用 **pre-commit hooks** 在提交前自动格式化代码并检查问题。
+
+**第 1 步:安装 pre-commit**
+```bash
+# 使用 pip
+pip install pre-commit
+
+# 或使用 conda
+conda install -c conda-forge pre-commit
+```
+
+**第 2 步:安装 Git hooks**
+```bash
+cd OpenTutor
+pre-commit install
+```
+
+**第 3 步:(可选)在所有文件上运行检查**
+```bash
+pre-commit run --all-files
+```
+
+每次运行 `git commit` 时,pre-commit hooks 将自动:
+- 使用 Ruff 格式化 Python 代码
+- 使用 Prettier 格式化前端代码
+- 检查语法错误
+- 验证 YAML/JSON 文件
+- 检测潜在安全问题
+
+### 代码质量工具
+
+| 工具 | 目的 | 配置 |
+|:---:|:---|:---:|
+| **Ruff** | Python 代码检查和格式化 | `pyproject.toml` |
+| **Prettier** | 前端代码格式化 | `web/.prettierrc.json` |
+| **detect-secrets** | 安全检查 | `.secrets.baseline` |
+
+> **注意**:项目使用 **Ruff format** 而非 Black,以避免格式化冲突。
+
+### 常用命令
+
+```bash
+# 正常提交(hooks 自动运行)
+git commit -m "您的提交消息"
+
+# 手动检查所有文件
+pre-commit run --all-files
+
+# 将 hooks 更新到最新版本
+pre-commit autoupdate
+
+# 跳过 hooks(不推荐,仅用于紧急情况)
+git commit --no-verify -m "紧急修复"
+```
+
+</details>
+
+### 贡献指南
+
+1. **Fork 并克隆**:Fork 仓库并克隆您的 fork
+2. **创建分支**:从 `main` 创建功能分支
+3. **安装 Pre-commit**:按照上述设置步骤
+4. **进行更改**:按照项目风格编写代码
+5. **测试**:确保您的更改正常工作
+6. **提交**:Pre-commit hooks 将自动格式化您的代码
+7. **推送和 PR**:推送到您的 fork 并创建 Pull Request
+
+### 报告问题
+
+- 使用 GitHub Issues 报告 bug 或建议功能
+- 提供问题的详细信息
+- 如果是 bug,请包含重现步骤
+
+<div align="center">
+<br>
+❤️ 我们感谢所有贡献者的宝贵贡献。
+
+</div>
+
+## 🔗 相关项目
+
+<div align="center">
+
+| [⚡ LightRAG](https://github.com/HKUDS/LightRAG) | [🎨 RAG-Anything](https://github.com/HKUDS/RAG-Anything) | [💻 DeepCode](https://github.com/HKUDS/DeepCode) | [🔬 AI-Researcher](https://github.com/HKUDS/AI-Researcher) |
+|:---:|:---:|:---:|:---:|
+| 简单快速的 RAG | 多模态 RAG | AI 代码助手 | 研究自动化 |
+
+**[香港大学数据智能实验室](https://github.com/HKUDS)**
+
+[⭐ Star us](https://github.com/HKUDS/OpenTutor/stargazers) · [🐛 Report a bug](https://github.com/HKUDS/OpenTutor/issues) · [💬 Discussions](https://github.com/HKUDS/OpenTutor/discussions)
+
+---
+*✨ 感谢访问 **OpenTutor**!*
+
+<img src="https://visitor-badge.laobi.icu/badge?page_id=HKUDS.OpenTutor&style=for-the-badge&color=00d4ff" alt="Views">
+
+</div>
diff --git a/assets/README/README_ES.md b/assets/README/README_ES.md
new file mode 100644
index 000000000..42fcfe6e1
--- /dev/null
+++ b/assets/README/README_ES.md
@@ -0,0 +1,454 @@
+<div align="center">
+
+<img src="../../assets/logo-ver2.png" alt="OpenTutor Logo" width="150" style="border-radius: 15px;">
+
+# OpenTutor: Tu Asistente Personal de Aprendizaje
+
+[![Python](https://img.shields.io/badge/Python-3.10%2B-3776AB?style=flat-square&logo=python&logoColor=white)](https://www.python.org/downloads/)
+[![Next.js](https://img.shields.io/badge/Next.js-14-000000?style=flat-square&logo=next.js&logoColor=white)](https://nextjs.org/)
+[![FastAPI](https://img.shields.io/badge/FastAPI-0.100+-009688?style=flat-square&logo=fastapi&logoColor=white)](https://fastapi.tiangolo.com/)
+[![License](https://img.shields.io/badge/License-AGPL--3.0-blue?style=flat-square)](LICENSE)
+[![Feishu](https://img.shields.io/badge/Feishu-Group-blue?style=flat)](./Communication.md)
+[![WeChat](https://img.shields.io/badge/WeChat-Group-green?style=flat&logo=wechat)](./Communication.md)
+
+
+
+[**Inicio Rápido**](#inicio-rápido) · [**Módulos Principales**](#módulos-principales) · [**Preguntas Frecuentes**](#preguntas-frecuentes)
+
+[🇬🇧 English](../../README.md) · [🇨🇳 中文](README_CN.md) · [🇯🇵 日本語](README_JA.md) · [🇫🇷 Français](README_FR.md) · [🇸🇦 العربية](README_AR.md)
+
+</div>
+
+<div align="center">
+
+| ⚡ **Q&A de Conocimiento de Documentos Masivos** | 📈 **Visualización de Aprendizaje Interactivo** | <br>
+| 🧠 **Refuerzo de Conocimiento** | 🔬 **Investigación Profunda y Generación de Ideas** |
+
+</div>
+
+---
+
+## Características Clave de OpenTutor
+
+### 📚 Q&A de Conocimiento de Documentos Masivos
+• **Base de Conocimiento Inteligente**: Sube libros de texto, artículos de investigación, manuales técnicos y documentos específicos del dominio. Construye un repositorio de conocimiento completo impulsado por IA para acceso instantáneo.<br>
+• **Resolución de Problemas Multi-Agente**: Arquitectura de razonamiento de doble bucle con RAG, búsqueda web, búsqueda de artículos y ejecución de código—entregando soluciones paso a paso con citas precisas.
+
+### 🎨 Visualización de Aprendizaje Interactivo
+• **Simplificación y Explicaciones del Conocimiento**: Transforma conceptos complejos, conocimiento y algoritmos en ayudas visuales fáciles de entender, desgloses detallados paso a paso y demostraciones interactivas atractivas.<br>
+• **Q&A Personalizado**: Conversaciones conscientes del contexto que se adaptan a tu progreso de aprendizaje, con páginas interactivas y seguimiento de conocimiento basado en sesiones.
+
+### 🎯 Refuerzo de Conocimiento con Generador de Problemas de Práctica
+• **Creación de Ejercicios Inteligentes**: Genera cuestionarios dirigidos, problemas de práctica y evaluaciones personalizadas adaptadas a tu nivel actual de conocimiento y objetivos de aprendizaje específicos.<br>
+• **Simulación de Examen Auténtica**: Sube exámenes de referencia para generar preguntas de práctica que coincidan perfectamente con el estilo, formato y dificultad originales—dándote una preparación realista para el examen real.
+
+### 🔍 Investigación Profunda y Generación de Ideas
+• **Investigación Integral y Revisión de Literatura**: Realiza exploración profunda de temas con análisis sistemático. Identifica patrones, conecta conceptos relacionados entre disciplinas y sintetiza hallazgos de investigación existentes.<br>
+• **Descubrimiento de Ideas Novedosas**: Genera materiales de aprendizaje estructurados y descubre brechas de conocimiento. Identifica nuevas direcciones de investigación prometedoras a través de síntesis inteligente de conocimiento entre dominios.
+
+---
+
+<div align="center">
+ <img src="../../assets/figs/title_gradient.svg" alt="All-in-One Tutoring System" width="70%">
+</div>
+
+<br>
+
+<!-- ━━━━━━━━━━━━━━━━ Core Learning Experience ━━━━━━━━━━━━━━━━ -->
+
+<table>
+<tr>
+<td width="50%" align="center" valign="top">
+
+<h3>📚 Q&A de Conocimiento de Documentos Masivos</h3>
+<a href="#problem-solving-agent">
+<img src="../../assets/gifs/solve.gif" width="100%">
+</a>
+<br>
+<sub>Q&A de Documentos y Resolución de Problemas Paso a Paso</sub>
+
+</td>
+<td width="50%" align="center" valign="top">
+
+<h3>🎨 Visualización de Aprendizaje Interactivo</h3>
+<a href="#guided-learning">
+<img src="../../assets/gifs/guided-learning.gif" width="100%">
+</a>
+<br>
+<sub>Aprendizaje de IA Interactivo con Explicaciones Visuales del Conocimiento</sub>
+
+</td>
+</tr>
+</table>
+
+<!-- ━━━━━━━━━━━━━━━━ Practice & Reinforcement ━━━━━━━━━━━━━━━━ -->
+
+<h3 align="center">🎯 Refuerzo de Conocimiento</h3>
+
+<table>
+<tr>
+<td width="50%" valign="top" align="center">
+
+<a href="#question-generator">
+<img src="../../assets/gifs/question-1.gif" width="100%">
+</a>
+
+**Preguntas Personalizadas**
+<sub>Preguntas de Práctica Auto-Validadas con Retroalimentación Instantánea</sub>
+
+</td>
+<td width="50%" valign="top" align="center">
+
+<a href="#question-generator">
+<img src="../../assets/gifs/question-2.gif" width="100%">
+</a>
+
+**Preguntas de Imitación**
+<sub>Clonar Estilo de Examen para Práctica Auténtica</sub>
+
+</td>
+</tr>
+</table>
+
+<!-- ━━━━━━━━━━━━━━━━ Research & Creation ━━━━━━━━━━━━━━━━ -->
+
+<h3 align="center">🔍 Investigación Profunda y Generación de Ideas</h3>
+
+<table>
+<tr>
+<td width="33%" align="center">
+
+<a href="#deep-research">
+<img src="../../assets/gifs/deepresearch.gif" width="100%">
+</a>
+
+**Investigación Profunda**
+<sub>Búsqueda Web y de Artículos con Revisión de Literatura</sub>
+
+</td>
+<td width="33%" align="center">
+
+<a href="#idea-generation">
+<img src="../../assets/gifs/ideagen.gif" width="100%">
+</a>
+
+**IdeaGen Automatizado**
+<sub>Lluvia de Ideas Sistemática y Síntesis de Conceptos</sub>
+
+</td>
+<td width="33%" align="center">
+
+<a href="#co-writer">
+<img src="../../assets/gifs/co-writer.gif" width="100%">
+</a>
+
+**IdeaGen Interactivo**
+<sub>Generación de Ideas Impulsada por RAG con Perspectivas Multi-Fuente</sub>
+
+</td>
+</tr>
+</table>
+
+<!-- ━━━━━━━━━━━━━━━━ Knowledge Infrastructure ━━━━━━━━━━━━━━━━ -->
+
+<h3 align="center">🏗️ Sistema de Conocimiento Todo en Uno</h3>
+
+<table>
+<tr>
+<td width="50%" align="center">
+
+<a href="#dashboard--knowledge-base-management">
+<img src="../../assets/gifs/knowledge_bases.png" width="100%">
+</a>
+
+**Base de Conocimiento Personal**
+<sub>Construye y Organiza Tu Propio Repositorio de Conocimiento</sub>
+
+</td>
+<td width="50%" align="center">
+
+<a href="#notebook">
+<img src="../../assets/gifs/notebooks.png" width="100%">
+</a>
+
+**Cuaderno Personal**
+<sub>Tu Memoria Contextual para Sesiones de Aprendizaje</sub>
+
+</td>
+</tr>
+</table>
+
+<p align="center">
+ <sub>🌙 ¡Usa OpenTutor en <b>Modo Oscuro</b>!</sub>
+</p>
+
+<details>
+<summary><b>Arquitectura del Sistema</b></summary>
+<br>
+
+![OpenTutor Full-Stack Workflow](../../assets/figs/full-pipe.png)
+
+</details>
+
+## 📋 Tareas Pendientes
+
+> ¡Síguenos para nuestras futuras actualizaciones!
+- [ ] Aprendizaje basado en proyectos
+- [ ] Codificación profunda desde generación de ideas
+- [ ] Memoria personalizada
+- [ ] Opción alternativa con RAG ingenuo
+
+## 🚀 Inicio Rápido
+
+### Paso 1: Clonar y Crear Entorno Virtual
+
+```bash
+# Clonar el repositorio
+git clone https://github.com/HKUDS/OpenTutor.git
+cd OpenTutor
+
+# Crear entorno virtual (elegir un método)
+
+# Opción A: Usando conda (Recomendado)
+conda create -n aitutor python=3.10
+conda activate aitutor
+
+# Opción B: Usando venv
+python -m venv venv
+# En Windows:
+venv\Scripts\activate
+# En macOS/Linux:
+source venv/bin/activate
+```
+
+### Paso 2: Instalar Dependencias
+
+Ejecute el script de instalación de un clic para instalar automáticamente todas las dependencias:
+
+```bash
+# Recomendado: Usar script bash
+bash scripts/install_all.sh
+
+# Alternativa: Usar script Python
+python scripts/install_all.py
+
+# O instalar manualmente
+pip install -r requirements.txt
+npm install
+```
+
+### Paso 3: Configurar Variables de Entorno
+
+Cree un archivo `.env` en el directorio raíz del proyecto basado en `.env.example`:
+
+```bash
+# Copiar de plantilla .env.example (si existe)
+cp .env.example .env
+
+# Luego edite el archivo .env con sus claves de API:
+```
+
+### Paso 4: Configurar Puertos *(Opcional)*
+
+Por defecto, la aplicación utiliza:
+- **Backend (FastAPI)**: `8001`
+- **Frontend (Next.js)**: `3782`
+
+Puede modificar estos puertos en `config/main.yaml` editando los valores `server.backend_port` y `server.frontend_port`.
+
+### Paso 5: Usar Nuestras Demostraciones *(Opcional)*
+
+Para experimentar rápidamente nuestro sistema, proporcionamos dos bases de conocimiento preprocesadas junto con una colección de preguntas desafiantes y ejemplos de uso.
+
+<details>
+<summary><b>Colección de Artículos de Investigación</b> — 5 artículos (20-50 páginas cada uno)</summary>
+
+Una colección seleccionada de 5 artículos de investigación en campos RAG y Agent de nuestro laboratorio. Esta demostración representa escenarios con **amplia cobertura de conocimiento** para propósitos de investigación.
+
+**Artículos Utilizados**: [AI-Researcher](https://github.com/HKUDS/AI-Researcher) | [AutoAgent](https://github.com/HKUDS/AutoAgent) | [RAG-Anything](https://github.com/HKUDS/RAG-Anything) | [LightRAG](https://github.com/HKUDS/LightRAG) | [VideoRAG](https://github.com/HKUDS/VideoRAG)
+
+</details>
+
+<details>
+<summary><b>Libro de Texto de Ciencia de Datos</b> — 8 capítulos, 296 páginas</summary>
+
+Un libro de texto de ciencia de datos integral y desafiante. Esta demostración representa escenarios con **profundidad de conocimiento profunda** para propósitos de aprendizaje.
+
+**Enlace del Libro**: [Deep Representation Learning Book](https://ma-lab-berkeley.github.io/deep-representation-learning-book/)
+</details>
+
+<br>
+
+**Descargar y Configurar:**
+
+1. Descargue el paquete de demostración desde: [Google Drive](https://drive.google.com/drive/folders/1iWwfZXiTuQKQqUYb5fGDZjLCeTUP6DA6?usp=sharing)
+2. Extraiga los archivos comprimidos directamente en el directorio `data/`
+3. Las bases de conocimiento estarán disponibles automáticamente en el sistema después de iniciar el proyecto
+
+> **Nota:** Utilizamos `text-embedding-3-large` como modelo de incrustaciones al inicializar nuestras bases de conocimiento, con `dimensions = 3072`. Asegúrese de que las dimensiones de su modelo de incrustaciones también sean 3072.
+
+### Paso 6: Iniciar la Aplicación
+
+```bash
+# Asegúrese de que el entorno virtual esté activado
+conda activate aitutor # o: source venv/bin/activate
+
+# Iniciar interfaz web (frontend + backend)
+python scripts/start_web.py
+
+# O iniciar solo la interfaz CLI
+python scripts/start.py
+
+# Para detener el servicio, presione Ctrl+C
+```
+
+### Paso 7: Crear su Propia Base de Conocimiento
+
+Después de iniciar la aplicación, puede crear su propia base de conocimiento a través de la interfaz web, bajo cualquier modalidad.
+
+1. **Acceder a la Página de Base de Conocimiento**: Visite http://localhost:{frontend_port}/knowledge
+2. **Crear Nueva Base de Conocimiento**: Haga clic en el botón "New Knowledge Base"
+3. **Nombrar su Base de Conocimiento**: Ingrese un nombre único para su base de conocimiento
+4. **Cargar Archivos**: Cargue uno o múltiples archivos
+5. **Esperar el Procesamiento**: El sistema procesará automáticamente sus archivos en segundo plano
+ - Monitoree el progreso de creación en la terminal donde se está ejecutando `start_web.py`
+ - La base de conocimiento estará disponible una vez que se complete el procesamiento
+
+> **Consejos:** Los archivos grandes pueden tardar varios minutos en procesarse. Puede cargar múltiples archivos a la vez para procesamiento por lotes.
+
+### URLs de Acceso
+
+| Servicio | URL | Descripción |
+|:---:|:---|:---|
+| **Frontend** | http://localhost:{frontend_port} | Interfaz web principal |
+| **Documentación API** | http://localhost:{backend_port}/docs | Documentación de API interactiva |
+| **Salud** | http://localhost:{backend_port}/api/v1/knowledge/health | Verificación de salud del sistema |
+
+---
+
+## 📄 Licencia
+
+## 📄 Licencia
+
+Este proyecto está licenciado bajo la **[AGPL-3.0](LICENSE)**.
+
+
+## ⭐ Historial de Stars
+
+<div align="center">
+<a href="https://star-history.com/#HKUDS/OpenTutor&Date">
+ <picture>
+ <source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=HKUDS/OpenTutor&type=Date&theme=dark" />
+ <source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=HKUDS/OpenTutor&type=Date" />
+ <img alt="Star History Chart" src="https://api.star-history.com/svg?repos=HKUDS/OpenTutor&type=Date" />
+ </picture>
+</a>
+</div>
+
+
+## 🤝 Contribución
+
+¡Bienvenemos contribuciones de la comunidad! Para garantizar la calidad y consistencia del código, siga las directrices a continuación.
+
+<details>
+<summary><b>Configuración de Desarrollo</b></summary>
+
+### Configuración de Pre-commit Hooks
+
+Este proyecto utiliza **pre-commit hooks** para formatear automáticamente el código y verificar problemas antes de comprometer.
+
+**Paso 1: Instalar pre-commit**
+```bash
+# Usando pip
+pip install pre-commit
+
+# O usando conda
+conda install -c conda-forge pre-commit
+```
+
+**Paso 2: Instalar Git hooks**
+```bash
+cd OpenTutor
+pre-commit install
+```
+
+**Paso 3: (Opcional) Ejecutar verificaciones en todos los archivos**
+```bash
+pre-commit run --all-files
+```
+
+Cada vez que ejecute `git commit`, pre-commit hooks ejecutará automáticamente:
+- Formatear código Python con Ruff
+- Formatear código frontend con Prettier
+- Verificar errores de sintaxis
+- Validar archivos YAML/JSON
+- Detectar posibles problemas de seguridad
+
+### Herramientas de Calidad de Código
+
+| Herramienta | Propósito | Configuración |
+|:---:|:---|:---:|
+| **Ruff** | Verificación y formato de código Python | `pyproject.toml` |
+| **Prettier** | Formato de código frontend | `web/.prettierrc.json` |
+| **detect-secrets** | Verificación de seguridad | `.secrets.baseline` |
+
+> **Nota**: El proyecto usa **Ruff format** en lugar de Black para evitar conflictos de formato.
+
+### Comandos Comunes
+
+```bash
+# Commit normal (hooks se ejecutan automáticamente)
+git commit -m "Su mensaje de commit"
+
+# Verificar manualmente todos los archivos
+pre-commit run --all-files
+
+# Actualizar hooks a versiones más recientes
+pre-commit autoupdate
+
+# Saltar hooks (no recomendado, solo para emergencias)
+git commit --no-verify -m "Corrección de emergencia"
+```
+
+</details>
+
+### Directrices de Contribución
+
+1. **Fork y Clone**: Fork el repositorio y clonelo
+2. **Crear Rama**: Crear una rama de función desde `main`
+3. **Instalar Pre-commit**: Seguir los pasos de configuración anteriores
+4. **Realizar Cambios**: Escribir código siguiendo el estilo del proyecto
+5. **Probar**: Asegurar que sus cambios funcionan correctamente
+6. **Commit**: Pre-commit hooks formateará automáticamente su código
+7. **Push y PR**: Empujar a su fork y crear una Pull Request
+
+### Reportar Problemas
+
+- Usar GitHub Issues para reportar bugs o sugerir características
+- Proporcionar información detallada sobre el problema
+- Si es un bug, incluir pasos para reproducir
+
+<div align="center">
+<br>
+❤️ Agradecemos a todos nuestros contribuyentes por sus valiosas contribuciones.
+
+</div>
+
+## 🔗 Proyectos Relacionados
+
+<div align="center">
+
+| [⚡ LightRAG](https://github.com/HKUDS/LightRAG) | [🎨 RAG-Anything](https://github.com/HKUDS/RAG-Anything) | [💻 DeepCode](https://github.com/HKUDS/DeepCode) | [🔬 AI-Researcher](https://github.com/HKUDS/AI-Researcher) |
+|:---:|:---:|:---:|:---:|
+| RAG Simple y Rápido | RAG Multimodal | Asistente de Código AI | Automatización de Investigación |
+
+**[Laboratorio de Inteligencia de Datos @ HKU](https://github.com/HKUDS)**
+
+[⭐ Síguenos](https://github.com/HKUDS/OpenTutor/stargazers) · [🐛 Reportar un bug](https://github.com/HKUDS/OpenTutor/issues) · [💬 Discusiones](https://github.com/HKUDS/OpenTutor/discussions)
+
+---
+*✨ ¡Gracias por visitar **OpenTutor**!*
+
+<img src="https://visitor-badge.laobi.icu/badge?page_id=HKUDS.OpenTutor&style=for-the-badge&color=00d4ff" alt="Views">
+
+</div>
diff --git a/assets/README/README_FR.md b/assets/README/README_FR.md
new file mode 100644
index 000000000..7af64805a
--- /dev/null
+++ b/assets/README/README_FR.md
@@ -0,0 +1,689 @@
+<div align="center">
+
+<img src="../../assets/logo-ver2.png" alt="OpenTutor Logo" width="150" style="border-radius: 15px;">
+
+# OpenTutor: Votre Assistant d'Apprentissage Personnel
+
+[![Python](https://img.shields.io/badge/Python-3.10%2B-3776AB?style=flat-square&logo=python&logoColor=white)](https://www.python.org/downloads/)
+[![Next.js](https://img.shields.io/badge/Next.js-14-000000?style=flat-square&logo=next.js&logoColor=white)](https://nextjs.org/)
+[![FastAPI](https://img.shields.io/badge/FastAPI-0.100+-009688?style=flat-square&logo=fastapi&logoColor=white)](https://fastapi.tiangolo.com/)
+[![License](https://img.shields.io/badge/License-AGPL--3.0-blue?style=flat-square)](LICENSE)
+[![Feishu](https://img.shields.io/badge/Feishu-Group-blue?style=flat)](./Communication.md)
+[![WeChat](https://img.shields.io/badge/WeChat-Group-green?style=flat&logo=wechat)](./Communication.md)
+
+
+
+[**Démarrage Rapide**](#démarrage-rapide) · [**Modules Principaux**](#modules-principaux) · [**FAQ**](#faq)
+
+[🇬🇧 English](../../README.md) · [🇨🇳 中文](README_CN.md) · [🇯🇵 日本語](README_JA.md) · [🇪🇸 Español](README_ES.md) · [🇸🇦 العربية](README_AR.md)
+
+</div>
+
+<div align="center">
+
+| ⚡ **Q&A de Connaissance de Documents Massifs** | 📈 **Visualisation d'Apprentissage Interactive** | <br>
+| 🧠 **Renforcement des Connaissances** | 🔬 **Recherche Approfondie et Génération d'Idées** |
+
+</div>
+
+---
+
+## Caractéristiques Clés d'OpenTutor
+
+### 📚 Q&A de Connaissance de Documents Massifs
+• **Base de Connaissances Intelligente** : Téléchargez des manuels, des articles de recherche, des manuels techniques et des documents spécifiques au domaine. Construisez un référentiel de connaissances complet alimenté par l'IA pour un accès instantané.<br>
+• **Résolution de Problèmes Multi-Agents** : Architecture de raisonnement à double boucle avec RAG, recherche web, recherche d'articles et exécution de code—fournissant des solutions étape par étape avec des citations précises.
+
+### 🎨 Visualisation d'Apprentissage Interactive
+• **Simplification et Explications des Connaissances** : Transformez des concepts complexes, des connaissances et des algorithmes en aides visuelles faciles à comprendre, des décompositions détaillées étape par étape et des démonstrations interactives engageantes.<br>
+• **Q&R Personnalisé** : Conversations conscientes du contexte qui s'adaptent à votre progression d'apprentissage, avec des pages interactives et un suivi des connaissances basé sur les sessions.
+
+### 🎯 Renforcement des Connaissances avec Générateur de Problèmes de Pratique
+• **Création d'Exercices Intelligents** : Générez des quiz ciblés, des problèmes de pratique et des évaluations personnalisées adaptées à votre niveau actuel de connaissances et à vos objectifs d'apprentissage spécifiques.<br>
+• **Simulation d'Examen Authentique** : Téléchargez des examens de référence pour générer des questions de pratique qui correspondent parfaitement au style, au format et à la difficulté originaux—vous donnant une préparation réaliste pour le test réel.
+
+### 🔍 Recherche Approfondie et Génération d'Idées
+• **Recherche Complète et Revue de Littérature** : Menez une exploration approfondie de sujets avec une analyse systématique. Identifiez les modèles, connectez des concepts connexes entre les disciplines et synthétisez les résultats de recherche existants.<br>
+• **Découverte d'Insights Novateurs** : Générez des matériaux d'apprentissage structurés et découvrez les lacunes de connaissances. Identifiez de nouvelles directions de recherche prometteuses grâce à une synthèse intelligente des connaissances inter-domaines.
+
+---
+
+<div align="center">
+ <img src="../../assets/figs/title_gradient.svg" alt="All-in-One Tutoring System" width="70%">
+</div>
+
+<br>
+
+<!-- ━━━━━━━━━━━━━━━━ Core Learning Experience ━━━━━━━━━━━━━━━━ -->
+
+<table>
+<tr>
+<td width="50%" align="center" valign="top">
+
+<h3>📚 Q&A de Connaissance de Documents Massifs</h3>
+<a href="#problem-solving-agent">
+<img src="../../assets/gifs/solve.gif" width="100%">
+</a>
+<br>
+<sub>Q&A de Documents et Résolution de Problèmes Étape par Étape</sub>
+
+</td>
+<td width="50%" align="center" valign="top">
+
+<h3>🎨 Visualisation d'Apprentissage Interactive</h3>
+<a href="#guided-learning">
+<img src="../../assets/gifs/guided-learning.gif" width="100%">
+</a>
+<br>
+<sub>Apprentissage IA Interactif avec Explications Visuelles des Connaissances</sub>
+
+</td>
+</tr>
+</table>
+
+<!-- ━━━━━━━━━━━━━━━━ Practice & Reinforcement ━━━━━━━━━━━━━━━━ -->
+
+<h3 align="center">🎯 Renforcement des Connaissances</h3>
+
+<table>
+<tr>
+<td width="50%" valign="top" align="center">
+
+<a href="#question-generator">
+<img src="../../assets/gifs/question-1.gif" width="100%">
+</a>
+
+**Questions Personnalisées**
+<sub>Questions de Pratique Auto-Validées avec Retour Instantané</sub>
+
+</td>
+<td width="50%" valign="top" align="center">
+
+<a href="#question-generator">
+<img src="../../assets/gifs/question-2.gif" width="100%">
+</a>
+
+**Questions Mimétiques**
+<sub>Cloner le Style d'Examen pour une Pratique Authentique</sub>
+
+</td>
+</tr>
+</table>
+
+<!-- ━━━━━━━━━━━━━━━━ Research & Creation ━━━━━━━━━━━━━━━━ -->
+
+<h3 align="center">🔍 Recherche Approfondie et Génération d'Idées</h3>
+
+<table>
+<tr>
+<td width="33%" align="center">
+
+<a href="#deep-research">
+<img src="../../assets/gifs/deepresearch.gif" width="100%">
+</a>
+
+**Recherche Approfondie**
+<sub>Recherche Web et d'Articles avec Revue de Littérature</sub>
+
+</td>
+<td width="33%" align="center">
+
+<a href="#idea-generation">
+<img src="../../assets/gifs/ideagen.gif" width="100%">
+</a>
+
+**IdeaGen Automatisé**
+<sub>Remue-Méninges Systématique et Synthèse de Concepts</sub>
+
+</td>
+<td width="33%" align="center">
+
+<a href="#co-writer">
+<img src="../../assets/gifs/co-writer.gif" width="100%">
+</a>
+
+**IdeaGen Interactif**
+<sub>Génération d'Idées Alimentée par RAG avec Perspectives Multi-Sources</sub>
+
+</td>
+</tr>
+</table>
+
+<!-- ━━━━━━━━━━━━━━━━ Knowledge Infrastructure ━━━━━━━━━━━━━━━━ -->
+
+<h3 align="center">🏗️ Système de Connaissances Tout-en-Un</h3>
+
+<table>
+<tr>
+<td width="50%" align="center">
+
+<a href="#dashboard--knowledge-base-management">
+<img src="../../assets/gifs/knowledge_bases.png" width="100%">
+</a>
+
+**Base de Connaissances Personnelle**
+<sub>Construisez et Organisez Votre Propre Référentiel de Connaissances</sub>
+
+</td>
+<td width="50%" align="center">
+
+<a href="#notebook">
+<img src="../../assets/gifs/notebooks.png" width="100%">
+</a>
+
+**Carnet Personnel**
+<sub>Votre Mémoire Contextuelle pour les Sessions d'Apprentissage</sub>
+
+</td>
+</tr>
+</table>
+
+<p align="center">
+ <sub>🌙 Utilisez OpenTutor en <b>Mode Sombre</b> !</sub>
+</p>
+
+<details>
+<summary><b>Architecture du Système</b></summary>
+<br>
+
+![OpenTutor Full-Stack Workflow](../../assets/figs/full-pipe.png)
+
+</details>
+
+## 📋 À Faire
+
+> Suivez-nous pour nos futures mises à jour!
+- [ ] Apprentissage basé sur les projets
+- [ ] Codage profond à partir de la génération d'idées
+- [ ] Mémoire personnalisée
+- [ ] Choix alternatif avec RAG naïf
+
+## 🚀 Démarrage Rapide
+
+### Étape 1: Cloner et Créer un Environnement Virtuel
+
+```bash
+# Cloner le référentiel
+git clone https://github.com/HKUDS/OpenTutor.git
+cd OpenTutor
+
+# Créer un environnement virtuel (choisir une méthode)
+
+# Option A: Utiliser conda (Recommandé)
+conda create -n aitutor python=3.10
+conda activate aitutor
+
+# Option B: Utiliser venv
+python -m venv venv
+# Sur Windows:
+venv\Scripts\activate
+# Sur macOS/Linux:
+source venv/bin/activate
+```
+
+### Étape 2: Installer les Dépendances
+
+Exécutez le script d'installation en un clic pour installer automatiquement toutes les dépendances:
+
+```bash
+# Recommandé: Utiliser le script bash
+bash scripts/install_all.sh
+
+# Alternatif: Utiliser le script Python
+python scripts/install_all.py
+
+# Ou installer manuellement
+pip install -r requirements.txt
+npm install
+```
+
+### Étape 3: Configurer les Variables d'Environnement
+
+Créez un fichier `.env` dans le répertoire racine du projet basé sur `.env.example`:
+
+```bash
+# Copier du modèle .env.example (s'il existe)
+cp .env.example .env
+
+# Puis éditer le fichier .env avec vos clés API:
+```
+
+### Étape 4: Configurer les Ports *(Optionnel)*
+
+Par défaut, l'application utilise:
+- **Backend (FastAPI)**: `8001`
+- **Frontend (Next.js)**: `3782`
+
+Vous pouvez modifier ces ports dans `config/main.yaml` en éditant les valeurs `server.backend_port` et `server.frontend_port`.
+
+### Étape 5: Utiliser nos Démos *(Optionnel)*
+
+Pour expérimenter rapidement notre système, nous fournissons deux bases de connaissances prétraitées ainsi qu'une collection de questions difficiles et d'exemples d'utilisation.
+
+<details>
+<summary><b>Collection d'Articles de Recherche</b> — 5 articles (20-50 pages chacun)</summary>
+
+Une collection sélectionnée de 5 articles de recherche dans les domaines RAG et Agent de notre laboratoire. Cette démo représente des scénarios avec **couverture de connaissances large** pour les objectifs de recherche.
+
+**Articles Utilisés**: [AI-Researcher](https://github.com/HKUDS/AI-Researcher) | [AutoAgent](https://github.com/HKUDS/AutoAgent) | [RAG-Anything](https://github.com/HKUDS/RAG-Anything) | [LightRAG](https://github.com/HKUDS/LightRAG) | [VideoRAG](https://github.com/HKUDS/VideoRAG)
+
+</details>
+
+<details>
+<summary><b>Manuel de Science des Données</b> — 8 chapitres, 296 pages</summary>
+
+Un manuel de science des données complet et difficile. Cette démo représente des scénarios avec **profondeur de connaissances profonde** pour les objectifs d'apprentissage.
+
+**Lien du Livre**: [Deep Representation Learning Book](https://ma-lab-berkeley.github.io/deep-representation-learning-book/)
+</details>
+
+<br>
+
+**Télécharger et Configurer:**
+
+1. Téléchargez le package de démonstration depuis: [Google Drive](https://drive.google.com/drive/folders/1iWwfZXiTuQKQqUYb5fGDZjLCeTUP6DA6?usp=sharing)
+2. Extrayez les fichiers compressés directement dans le répertoire `data/`
+3. Les bases de connaissances seront automatiquement disponibles dans le système après le démarrage du projet
+
+> **Remarque:** Nous utilisons `text-embedding-3-large` comme modèle d'intégration lors de l'initialisation de nos bases de connaissances, avec `dimensions = 3072`. Assurez-vous que les dimensions de votre modèle d'intégration sont également 3072.
+
+### Étape 6: Démarrer l'Application
+
+```bash
+# Assurez-vous que l'environnement virtuel est activé
+conda activate aitutor # ou: source venv/bin/activate
+
+# Démarrer l'interface web (frontend + backend)
+python scripts/start_web.py
+
+# Ou démarrer seulement l'interface CLI
+python scripts/start.py
+
+# Pour arrêter le service, appuyez sur Ctrl+C
+```
+
+### Étape 7: Créer Votre Propre Base de Connaissances
+
+Après le démarrage de l'application, vous pouvez créer votre propre base de connaissances via l'interface web, sous n'importe quelle modalité.
+
+1. **Accéder à la Page de Base de Connaissances**: Visitez http://localhost:{frontend_port}/knowledge
+2. **Créer une Nouvelle Base de Connaissances**: Cliquez sur le bouton "New Knowledge Base"
+3. **Nommer Votre Base de Connaissances**: Entrez un nom unique pour votre base de connaissances
+4. **Télécharger les Fichiers**: Téléchargez un ou plusieurs fichiers
+5. **Attendre le Traitement**: Le système traitera automatiquement vos fichiers en arrière-plan
+ - Surveillez la progression de la création dans le terminal où `start_web.py` est en cours d'exécution
+ - La base de connaissances sera disponible une fois le traitement terminé
+
+> **Conseils:** Les gros fichiers peuvent prendre plusieurs minutes à traiter. Vous pouvez télécharger plusieurs fichiers à la fois pour traitement par lots.
+
+### URLs d'Accès
+
+| Service | URL | Description |
+|:---:|:---|:---|
+| **Frontend** | http://localhost:{frontend_port} | Interface web principale |
+| **Documentation API** | http://localhost:{backend_port}/docs | Documentation API interactive |
+| **Santé** | http://localhost:{backend_port}/api/v1/knowledge/health | Vérification de la santé du système |
+
+---
+
+## 📂 Stockage des Données
+
+Tout le contenu généré par l'utilisateur et les données du système sont stockés dans le dossier `data/`:
+
+```
+data/
+├── knowledge_bases/ # Stockage de la base de connaissances
+└── user/ # Données d'activité de l'utilisateur
+ ├── solve/ # Résultats de résolution de problèmes et artefacts
+ ├── question/ # Questions générées
+ ├── research/ # Rapports de recherche et cache
+ ├── co-writer/ # Documents Co-Writer et fichiers audio
+ ├── notebook/ # Enregistrements de carnet et métadonnées
+ ├── guide/ # Sessions d'apprentissage guidé
+ ├── logs/ # Journaux système
+ └── run_code_workspace/ # Espace de travail d'exécution de code
+```
+
+Tous les résultats sont automatiquement enregistrés lorsque vous effectuez n'importe quelle activité. Les dossiers sont créés automatiquement s'ils n'existent pas.
+
+---
+
+## 📖 Documentation des Modules
+
+<table>
+<tr>
+<td align="center"><a href="../../config/README.md">Configuration</a></td>
+<td align="center"><a href="../../data/README.md">Répertoire de Données</a></td>
+<td align="center"><a href="../../src/api/README.md">Backend API</a></td>
+<td align="center"><a href="../../src/core/README.md">Utilitaires Principaux</a></td>
+</tr>
+<tr>
+<td align="center"><a href="../../src/knowledge/README.md">Base de Connaissances</a></td>
+<td align="center"><a href="../../src/tools/README.md">Outils</a></td>
+<td align="center"><a href="../../web/README.md">Frontend Web</a></td>
+<td align="center"><a href="../../src/agents/solve/README.md">Module de Résolution</a></td>
+</tr>
+<tr>
+<td align="center"><a href="../../src/agents/question/README.md">Module de Question</a></td>
+<td align="center"><a href="../../src/agents/research/README.md">Module de Recherche</a></td>
+<td align="center"><a href="../../src/agents/co_writer/README.md">Module Co-Writer</a></td>
+<td align="center"><a href="../../src/agents/guide/README.md">Module de Guide</a></td>
+</tr>
+<tr>
+<td align="center" colspan="4"><a href="../../src/agents/ideagen/README.md">Module de Génération d'Idées</a></td>
+</tr>
+</table>
+
+---
+
+## ❓ FAQ
+
+<details>
+<summary><b>Le backend ne démarre pas?</b></summary>
+
+**Liste de Vérification**
+- Confirmez que la version Python >= 3.10
+- Confirmez que toutes les dépendances sont installées: `pip install -r requirements.txt`
+- Vérifiez si le port 8001 est utilisé (configurable dans `config/main.yaml`)
+- Vérifiez la configuration du fichier `.env`
+
+**Solutions**
+- **Changer le port**: Modifiez `config/main.yaml` server.backend_port
+- **Vérifier les journaux**: Vérifiez les messages d'erreur du terminal
+
+</details>
+
+<details>
+<summary><b>Port occupé après Ctrl+C?</b></summary>
+
+**Problème**
+
+Après avoir appuyé sur Ctrl+C pendant une tâche en cours (par exemple, recherche profonde), le redémarrage affiche une erreur "port déjà en utilisation".
+
+**Cause**
+
+Ctrl+C ne termine parfois que le processus frontend tandis que le backend continue de s'exécuter en arrière-plan.
+
+**Solution**
+
+```bash
+# macOS/Linux: Trouver et tuer le processus
+lsof -i :8001
+kill -9 <PID>
+
+# Windows: Trouver et tuer le processus
+netstat -ano | findstr :8001
+taskkill /PID <PID> /F
+```
+
+Puis redémarrez le service avec `python scripts/start_web.py`.
+
+</details>
+
+<details>
+<summary><b>Erreur "npm: command not found"?</b></summary>
+
+**Problème**
+
+L'exécution de `scripts/start_web.py` affiche `npm: command not found` ou le code de sortie 127.
+
+**Liste de Vérification**
+- Vérifiez si npm est installé: `npm --version`
+- Vérifiez si Node.js est installé: `node --version`
+- Confirmez que l'environnement conda est activé (si vous utilisez conda)
+
+**Solutions**
+```bash
+# Option A: Utiliser Conda (Recommandé)
+conda install -c conda-forge nodejs
+
+# Option B: Utiliser l'installateur officiel
+# Télécharger depuis https://nodejs.org/
+
+# Option C: Utiliser nvm
+nvm install 18
+nvm use 18
+```
+
+**Vérifier l'Installation**
+```bash
+node --version # Devrait afficher v18.x.x ou supérieur
+npm --version # Devrait afficher le numéro de version
+```
+
+</details>
+
+<details>
+<summary><b>Le frontend ne peut pas se connecter au backend?</b></summary>
+
+**Liste de Vérification**
+- Confirmez que le backend est en cours d'exécution (visitez http://localhost:8001/docs)
+- Vérifiez la console du navigateur pour les messages d'erreur
+
+**Solution**
+
+Créez `.env.local` dans le répertoire `web`:
+
+```bash
+NEXT_PUBLIC_API_BASE=http://localhost:8001
+```
+
+</details>
+
+<details>
+<summary><b>Échec de la connexion WebSocket?</b></summary>
+
+**Liste de Vérification**
+- Confirmez que le backend est en cours d'exécution
+- Vérifiez les paramètres du pare-feu
+- Confirmez que l'URL WebSocket est correcte
+
+**Solution**
+- **Vérifiez les journaux du backend**
+- **Confirmez le format de l'URL**: `ws://localhost:8001/api/v1/...`
+
+</details>
+
+<details>
+<summary><b>Où les sorties du module sont-elles stockées?</b></summary>
+
+| Module | Chemin de Sortie |
+|:---:|:---|
+| Résoudre | `data/user/solve/solve_YYYYMMDD_HHMMSS/` |
+| Question | `data/user/question/question_YYYYMMDD_HHMMSS/` |
+| Recherche | `data/user/research/reports/` |
+| Co-Writer | `data/user/co-writer/` |
+| Carnet | `data/user/notebook/` |
+| Guide | `data/user/guide/session_{session_id}.json` |
+| Journaux | `data/user/logs/` |
+
+</details>
+
+<details>
+<summary><b>Comment ajouter une nouvelle base de connaissances?</b></summary>
+
+**Interface Web**
+1. Visitez http://localhost:{frontend_port}/knowledge
+2. Cliquez sur "New Knowledge Base"
+3. Entrez le nom de la base de connaissances
+4. Téléchargez des documents PDF/TXT/MD
+5. Le système traitera les documents en arrière-plan
+
+**CLI**
+```bash
+python -m src.knowledge.start_kb init <kb_name> --docs <pdf_path>
+```
+
+</details>
+
+<details>
+<summary><b>Comment ajouter des documents de manière incrémentale à une BC existante?</b></summary>
+
+**CLI (Recommandé)**
+```bash
+python -m src.knowledge.add_documents <kb_name> --docs <new_document.pdf>
+```
+
+**Avantages**
+- Traite uniquement les nouveaux documents, économise le temps et le coût de l'API
+- Fusion automatique avec le graphique de connaissances existant
+- Préserve toutes les données existantes
+
+</details>
+
+<details>
+<summary><b>Erreur uvloop.Loop lors de l'extraction d'éléments numérotés?</b></summary>
+
+**Problème**
+
+Lors de l'initialisation d'une base de connaissances, vous pouvez rencontrer cette erreur:
+```
+ValueError: Can't patch loop of type <class 'uvloop.Loop'>
+```
+
+Ceci se produit car Uvicorn utilise la boucle d'événements `uvloop` par défaut, qui est incompatible avec `nest_asyncio`.
+
+**Solution**
+
+Utilisez l'une des méthodes suivantes pour extraire les éléments numérotés:
+
+```bash
+# Option 1: Utiliser le script shell (recommandé)
+./scripts/extract_numbered_items.sh <kb_name>
+
+# Option 2: Commande Python directe
+python src/knowledge/extract_numbered_items.py --kb <kb_name> --base-dir ./data/knowledge_bases
+```
+
+Ceci extraira les éléments numérotés (Définitions, Théorèmes, Équations, etc.) de votre base de connaissances sans la réinitialiser.
+
+</details>
+
+<br>
+
+---
+
+## 📄 Licence
+
+Ce projet est sous licence **[AGPL-3.0](LICENSE)**.
+
+
+## ⭐ Historique des Stars
+
+<div align="center">
+<a href="https://star-history.com/#HKUDS/OpenTutor&Date">
+ <picture>
+ <source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=HKUDS/OpenTutor&type=Date&theme=dark" />
+ <source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=HKUDS/OpenTutor&type=Date" />
+ <img alt="Star History Chart" src="https://api.star-history.com/svg?repos=HKUDS/OpenTutor&type=Date" />
+ </picture>
+</a>
+</div>
+
+
+## 🤝 Contribution
+
+Nous accueillons les contributions de la communauté! Pour assurer la qualité et la cohérence du code, veuillez suivre les directives ci-dessous.
+
+<details>
+<summary><b>Configuration de Développement</b></summary>
+
+### Configuration des Pre-commit Hooks
+
+Ce projet utilise **pre-commit hooks** pour formater automatiquement le code et vérifier les problèmes avant de valider.
+
+**Étape 1: Installer pre-commit**
+```bash
+# Utiliser pip
+pip install pre-commit
+
+# Ou utiliser conda
+conda install -c conda-forge pre-commit
+```
+
+**Étape 2: Installer les crochets Git**
+```bash
+cd OpenTutor
+pre-commit install
+```
+
+**Étape 3: (Optionnel) Exécuter des vérifications sur tous les fichiers**
+```bash
+pre-commit run --all-files
+```
+
+Chaque fois que vous exécutez `git commit`, pre-commit hooks exécutera automatiquement:
+- Formater le code Python avec Ruff
+- Formater le code frontend avec Prettier
+- Vérifier les erreurs de syntaxe
+- Valider les fichiers YAML/JSON
+- Détecter les problèmes de sécurité potentiels
+
+### Outils de Qualité de Code
+
+| Outil | Objectif | Configuration |
+|:---:|:---|:---:|
+| **Ruff** | Vérification et formatage du code Python | `pyproject.toml` |
+| **Prettier** | Formatage du code frontend | `web/.prettierrc.json` |
+| **detect-secrets** | Vérification de sécurité | `.secrets.baseline` |
+
+> **Remarque**: Le projet utilise **Ruff format** au lieu de Black pour éviter les conflits de formatage.
+
+### Commandes Courantes
+
+```bash
+# Commit normal (les hooks s'exécutent automatiquement)
+git commit -m "Votre message de commit"
+
+# Vérifier manuellement tous les fichiers
+pre-commit run --all-files
+
+# Mettre à jour les hooks vers les dernières versions
+pre-commit autoupdate
+
+# Ignorer les hooks (non recommandé, seulement pour les urgences)
+git commit --no-verify -m "Correction d'urgence"
+```
+
+</details>
+
+### Directives de Contribution
+
+1. **Fork et Clone**: Fork le référentiel et clonez-le
+2. **Créer une Branche**: Créer une branche de fonction à partir de `main`
+3. **Installer Pre-commit**: Suivre les étapes de configuration ci-dessus
+4. **Apporter des Modifications**: Écrire du code suivant le style du projet
+5. **Tester**: Assurez-vous que vos modifications fonctionnent correctement
+6. **Commit**: Pre-commit hooks formatera automatiquement votre code
+7. **Pousser et PR**: Pousser vers votre fork et créer une Pull Request
+
+### Signaler les Problèmes
+
+- Utiliser GitHub Issues pour signaler des bogues ou suggérer des fonctionnalités
+- Fournir des informations détaillées sur le problème
+- Si c'est un bogue, inclure les étapes pour le reproduire
+
+<div align="center">
+<br>
+❤️ Nous remercions tous nos contributeurs pour leurs précieuses contributions.
+
+</div>
+
+## 🔗 Projets Connexes
+
+<div align="center">
+
+| [⚡ LightRAG](https://github.com/HKUDS/LightRAG) | [🎨 RAG-Anything](https://github.com/HKUDS/RAG-Anything) | [💻 DeepCode](https://github.com/HKUDS/DeepCode) | [🔬 AI-Researcher](https://github.com/HKUDS/AI-Researcher) |
+|:---:|:---:|:---:|:---:|
+| RAG Simple et Rapide | RAG Multimodal | Assistant de Code IA | Automatisation de la Recherche |
+
+**[Laboratoire d'Intelligence des Données @ HKU](https://github.com/HKUDS)**
+
+[⭐ Suivez-nous](https://github.com/HKUDS/OpenTutor/stargazers) · [🐛 Signaler un bogue](https://github.com/HKUDS/OpenTutor/issues) · [💬 Discussions](https://github.com/HKUDS/OpenTutor/discussions)
+
+---
+*✨ Merci de visiter **OpenTutor**!*
+
+<img src="https://visitor-badge.laobi.icu/badge?page_id=HKUDS.OpenTutor&style=for-the-badge&color=00d4ff" alt="Views">
+
+</div>
diff --git a/assets/README/README_JA.md b/assets/README/README_JA.md
new file mode 100644
index 000000000..56db2d1b9
--- /dev/null
+++ b/assets/README/README_JA.md
@@ -0,0 +1,471 @@
+<div align="center">
+
+<img src="../../assets/logo-ver2.png" alt="OpenTutor Logo" width="150" style="border-radius: 15px;">
+
+# OpenTutor: あなたのパーソナル学習アシスタント
+
+[![Python](https://img.shields.io/badge/Python-3.10%2B-3776AB?style=flat-square&logo=python&logoColor=white)](https://www.python.org/downloads/)
+[![Next.js](https://img.shields.io/badge/Next.js-14-000000?style=flat-square&logo=next.js&logoColor=white)](https://nextjs.org/)
+[![FastAPI](https://img.shields.io/badge/FastAPI-0.100+-009688?style=flat-square&logo=fastapi&logoColor=white)](https://fastapi.tiangolo.com/)
+[![License](https://img.shields.io/badge/License-AGPL--3.0-blue?style=flat-square)](LICENSE)
+[![Feishu](https://img.shields.io/badge/Feishu-Group-blue?style=flat)](./Communication.md)
+[![WeChat](https://img.shields.io/badge/WeChat-Group-green?style=flat&logo=wechat)](./Communication.md)
+
+
+
+[**クイックスタート**](#クイックスタート) · [**コアモジュール**](#コアモジュール) · [**よくある質問**](#よくある質問)
+
+[🇬🇧 English](../../README.md) · [🇨🇳 中文](README_CN.md) · [🇪🇸 Español](README_ES.md) · [🇫🇷 Français](README_FR.md) · [🇸🇦 العربية](README_AR.md)
+
+</div>
+
+<div align="center">
+
+| ⚡ **大規模ドキュメント知識Q&A** | 📈 **インタラクティブ学習可視化** | <br>
+| 🧠 **知識強化** | 🔬 **深い研究とアイデア生成** |
+
+</div>
+
+---
+
+## OpenTutor の主要機能
+
+### 📚 大規模ドキュメント知識Q&A
+• **スマート知識ベース**:教科書、研究論文、技術マニュアル、ドメイン固有のドキュメントをアップロード。包括的な AI 駆動の知識リポジトリを構築し、即座にアクセス可能にします。<br>
+• **マルチエージェント問題解決**:RAG、ウェブ検索、論文検索、コード実行を統合したデュアルループ推論アーキテクチャ—正確な引用付きの段階的なソリューションを提供します。
+
+### 🎨 インタラクティブ学習可視化
+• **知識の簡素化と説明**:複雑な概念、知識、アルゴリズムを理解しやすい視覚補助、詳細な段階的分解、魅力的なインタラクティブデモンストレーションに変換します。<br>
+• **パーソナライズされたQ&A**:学習の進捗に適応するコンテキスト対応の会話、インタラクティブページとセッションベースの知識追跡を提供します。
+
+### 🎯 練習問題生成器による知識強化
+• **インテリジェントな演習作成**:現在の知識レベルと特定の学習目標に合わせて、ターゲットを絞ったクイズ、練習問題、カスタマイズされた評価を生成します。<br>
+• **本格的な試験シミュレーション**:参考試験をアップロードして、元のスタイル、形式、難易度に完全に一致する練習問題を生成—実際のテストのための現実的な準備を提供します。
+
+### 🔍 深い研究とアイデア生成
+• **包括的な研究と文献レビュー**:系統的な分析による深いトピック探索を実施。パターンを識別し、分野を超えた関連概念を接続し、既存の研究結果を統合します。<br>
+• **新しい洞察の発見**:構造化された学習資料を生成し、知識のギャップを発見します。インテリジェントなクロスドメイン知識統合を通じて、有望な新しい研究方向を特定します。
+
+---
+
+<div align="center">
+ <img src="../../assets/figs/title_gradient.svg" alt="All-in-One Tutoring System" width="70%">
+</div>
+
+<br>
+
+<!-- ━━━━━━━━━━━━━━━━ Core Learning Experience ━━━━━━━━━━━━━━━━ -->
+
+<table>
+<tr>
+<td width="50%" align="center" valign="top">
+
+<h3>📚 大規模ドキュメント知識Q&A</h3>
+<a href="#problem-solving-agent">
+<img src="../../assets/gifs/solve.gif" width="100%">
+</a>
+<br>
+<sub>ドキュメントQ&Aとステップバイステップの問題解決</sub>
+
+</td>
+<td width="50%" align="center" valign="top">
+
+<h3>🎨 インタラクティブ学習可視化</h3>
+<a href="#guided-learning">
+<img src="../../assets/gifs/guided-learning.gif" width="100%">
+</a>
+<br>
+<sub>知識の視覚的説明を備えたインタラクティブなAI学習</sub>
+
+</td>
+</tr>
+</table>
+
+<!-- ━━━━━━━━━━━━━━━━ Practice & Reinforcement ━━━━━━━━━━━━━━━━ -->
+
+<h3 align="center">🎯 知識強化</h3>
+
+<table>
+<tr>
+<td width="50%" valign="top" align="center">
+
+<a href="#question-generator">
+<img src="../../assets/gifs/question-1.gif" width="100%">
+</a>
+
+**カスタム質問**
+<sub>即座のフィードバックを備えた自動検証の練習問題</sub>
+
+</td>
+<td width="50%" valign="top" align="center">
+
+<a href="#question-generator">
+<img src="../../assets/gifs/question-2.gif" width="100%">
+</a>
+
+**模擬質問**
+<sub>本格的な練習のための試験スタイルのクローン</sub>
+
+</td>
+</tr>
+</table>
+
+<!-- ━━━━━━━━━━━━━━━━ Research & Creation ━━━━━━━━━━━━━━━━ -->
+
+<h3 align="center">🔍 深い研究とアイデア生成</h3>
+
+<table>
+<tr>
+<td width="33%" align="center">
+
+<a href="#deep-research">
+<img src="../../assets/gifs/deepresearch.gif" width="100%">
+</a>
+
+**深い研究**
+<sub>文献レビューを備えたウェブおよび論文検索</sub>
+
+</td>
+<td width="33%" align="center">
+
+<a href="#idea-generation">
+<img src="../../assets/gifs/ideagen.gif" width="100%">
+</a>
+
+**自動化されたアイデア生成**
+<sub>系統的なブレインストーミングと概念統合</sub>
+
+</td>
+<td width="33%" align="center">
+
+<a href="#co-writer">
+<img src="../../assets/gifs/co-writer.gif" width="100%">
+</a>
+
+**インタラクティブなアイデア生成**
+<sub>マルチソースの洞察を備えたRAG駆動のアイデア生成</sub>
+
+</td>
+</tr>
+</table>
+
+<!-- ━━━━━━━━━━━━━━━━ Knowledge Infrastructure ━━━━━━━━━━━━━━━━ -->
+
+<h3 align="center">🏗️ オールインワン知識システム</h3>
+
+<table>
+<tr>
+<td width="50%" align="center">
+
+<a href="#dashboard--knowledge-base-management">
+<img src="../../assets/gifs/knowledge_bases.png" width="100%">
+</a>
+
+**個人知識ベース**
+<sub>独自の知識リポジトリを構築・整理</sub>
+
+</td>
+<td width="50%" align="center">
+
+<a href="#notebook">
+<img src="../../assets/gifs/notebooks.png" width="100%">
+</a>
+
+**個人ノートブック**
+<sub>学習セッションのコンテキストメモリ</sub>
+
+</td>
+</tr>
+</table>
+
+<p align="center">
+ <sub>🌙 <b>ダークモード</b> で OpenTutor を使用!</sub>
+</p>
+
+---
+
+## 🏛️ OpenTutor のフレームワーク
+
+<div align="center">
+<img src="../../assets/figs/full-pipe.png" alt="OpenTutor Full-Stack Workflow" width="100%">
+</div>
+
+### 💬 ユーザーインターフェース層
+• **直感的なインタラクション**:直感的なインタラクションのためのシンプルな双方向クエリ-レスポンスフロー。<br>
+• **構造化された出力**:複雑な情報を実行可能な出力に整理する構造化レスポンス生成。
+
+### 🤖 インテリジェントエージェントモジュール
+• **問題解決と評価**:段階的な問題解決とカスタム評価生成。<br>
+• **研究と学習**:トピック探索のための深い研究と可視化を備えたガイド付き学習。<br>
+• **アイデア生成**:マルチソースの洞察を備えた自動化およびインタラクティブな概念開発。
+
+### 🔧 ツール統合層
+• **情報検索**:RAG ハイブリッド検索、リアルタイムウェブ検索、学術論文データベース。<br>
+• **処理と分析**:Python コード実行、クエリ項目検索、ドキュメント分析のための PDF 解析。
+
+### 🧠 知識とメモリ基盤
+• **知識グラフ**:セマンティック接続と知識発見のためのエンティティ-関係マッピング。<br>
+• **ベクトルストア**:インテリジェントなコンテンツ検索のための埋め込みベースのセマンティック検索。<br>
+• **メモリシステム**:コンテキストの継続性のためのセッション状態管理と引用追跡。
+
+## 📋 タスク
+
+> 🌟 今後の更新をフォローするために Star してください!
+- [ ] プロジェクトベースの学習
+- [ ] アイデア生成からの深いコーディング
+- [ ] パーソナライズされたメモリ
+
+## 🚀 クイックスタート
+
+### ステップ 1: リポジトリのクローンと仮想環境の作成
+
+```bash
+# リポジトリをクローン
+git clone https://github.com/HKUDS/OpenTutor.git
+cd OpenTutor
+
+# 仮想環境を作成(方法を選択)
+
+# オプション A: conda を使用(推奨)
+conda create -n aitutor python=3.10
+conda activate aitutor
+
+# オプション B: venv を使用
+python -m venv venv
+# Windows:
+venv\Scripts\activate
+# macOS/Linux:
+source venv/bin/activate
+```
+
+### ステップ 2: 依存関係をインストール
+
+一鍵インストールスクリプトを実行して、すべての依存関係を自動インストール:
+
+```bash
+# 推奨:bash スクリプトを使用
+bash scripts/install_all.sh
+
+# または Python スクリプトを使用
+python scripts/install_all.py
+
+# または手動でインストール
+pip install -r requirements.txt
+npm install
+```
+
+### ステップ 3: 環境変数を設定
+
+プロジェクトのルートディレクトリに `.env.example` に基づいて `.env` ファイルを作成:
+
+```bash
+# .env.example テンプレートからコピー(存在する場合)
+cp .env.example .env
+
+# その後、.env ファイルを API キーで編集:
+```
+
+### ステップ 4: ポートを設定 *(オプション)*
+
+デフォルトでは、アプリケーションは以下を使用:
+- **バックエンド (FastAPI)**: `8001`
+- **フロントエンド (Next.js)**: `3782`
+
+`config/main.yaml` の `server.backend_port` および `server.frontend_port` 値を編集して、これらのポートを変更できます。
+
+**LLM パラメータ**:すべてのエージェントの `temperature` と `max_tokens` 設定は `config/agents.yaml` に集中しています。各モジュール(guide、solve、research、question、ideagen、co_writer)には独自のパラメータセットがあります。詳細については[設定ドキュメント](config/README.md)を参照してください。
+
+### ステップ 5: デモを使用 *(オプション)*
+
+システムを素早く体験するために、2 つの前処理されたナレッジベースと、一連のチャレンジングな質問とユース例を提供しています。
+
+<details>
+<summary><b>研究論文集合</b> — 5 論文(各 20-50 ページ)</summary>
+
+私たちのラボからの RAG と Agent フィールドの厳選された 5 つの研究論文。このデモは**幅広い知識カバレッジ**を持つ研究シナリオを表しています。
+
+**使用論文**: [AI-Researcher](https://github.com/HKUDS/AI-Researcher) | [AutoAgent](https://github.com/HKUDS/AutoAgent) | [RAG-Anything](https://github.com/HKUDS/RAG-Anything) | [LightRAG](https://github.com/HKUDS/LightRAG) | [VideoRAG](https://github.com/HKUDS/VideoRAG)
+
+</details>
+
+<details>
+<summary><b>データサイエンス教科書</b> — 8 章、296 ページ</summary>
+
+包括的でチャレンジングなデータサイエンス教科書。このデモは**深い知識の深さ**を持つ学習シナリオを表しています。
+
+**書籍リンク**: [Deep Representation Learning Book](https://ma-lab-berkeley.github.io/deep-representation-learning-book/)
+</details>
+
+<br>
+
+**ダウンロードとセットアップ:**
+
+1. デモパッケージをダウンロード: [Google Drive](https://drive.google.com/drive/folders/1iWwfZXiTuQKQqUYb5fGDZjLCeTUP6DA6?usp=sharing)
+2. 圧縮ファイルを `data/` ディレクトリに直接抽出
+3. プロジェクト開始後、ナレッジベースは自動的にシステムで利用可能
+
+> **注意:** ナレッジベースを初期化する際、`text-embedding-3-large` を埋め込みモデルとして使用し、`dimensions = 3072` としています。埋め込みモデルの次元も 3072 であることを確認してください。
+
+### ステップ 6: アプリケーションを開始
+
+```bash
+# 仮想環境が有効化されていることを確認
+conda activate aitutor # または: source venv/bin/activate
+
+# Web インターフェース(フロントエンド + バックエンド)を開始
+python scripts/start_web.py
+
+# または CLI インターフェースのみを開始
+python scripts/start.py
+
+# サービスを停止するには、Ctrl+C を押す
+```
+
+### ステップ 7: 独自のナレッジベースを作成
+
+アプリケーション開始後、Web インターフェースを通じて独自のナレッジベースを作成できます。
+
+1. **ナレッジベースページへアクセス**: http://localhost:{frontend_port}/knowledge にアクセス
+2. **新規ナレッジベースを作成**: 「New Knowledge Base」ボタンをクリック
+3. **ナレッジベースに名前を付ける**: ナレッジベースに一意の名前を入力
+4. **ファイルをアップロード**: 1 つ以上のファイルをアップロード
+5. **処理を待つ**: システムがファイルをバックグラウンドで自動処理
+ - `start_web.py` を実行しているターミナルで作成進度を監視
+ - 処理完了後、ナレッジベースが利用可能になる
+
+> **ヒント:** 大きなファイルは処理に数分かかる場合があります。複数のファイルを一度にアップロードしてバッチ処理できます。
+
+### アクセス URL
+
+| サービス | URL | 説明 |
+|:---:|:---|:---|
+| **フロントエンド** | http://localhost:{frontend_port} | メイン Web インターフェース |
+| **API ドキュメント** | http://localhost:{backend_port}/docs | インタラクティブ API ドキュメント |
+| **ヘルスチェック** | http://localhost:{backend_port}/api/v1/knowledge/health | システムヘルスチェック |
+
+---
+
+## 📄 ライセンス
+
+このプロジェクトは **[AGPL-3.0 ライセンス](LICENSE)** でライセンスされています。
+
+
+## ⭐ Star History
+
+<div align="center">
+<a href="https://star-history.com/#HKUDS/OpenTutor&Date">
+ <picture>
+ <source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=HKUDS/OpenTutor&type=Date&theme=dark" />
+ <source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=HKUDS/OpenTutor&type=Date" />
+ <img alt="Star History Chart" src="https://api.star-history.com/svg?repos=HKUDS/OpenTutor&type=Date" />
+ </picture>
+</a>
+</div>
+
+
+## 🤝 貢献
+
+コミュニティからの貢献を歓迎します!コード品質と一貫性を確保するため、以下のガイドラインに従ってください。
+
+<details>
+<summary><b>開発セットアップ</b></summary>
+
+### Pre-commit Hooks セットアップ
+
+このプロジェクトは **pre-commit hooks** を使用して、コミット前に自動的にコードをフォーマットし、問題をチェックします。
+
+**ステップ 1: pre-commit をインストール**
+```bash
+# pip を使用
+pip install pre-commit
+
+# または conda を使用
+conda install -c conda-forge pre-commit
+```
+
+**ステップ 2: Git hooks をインストール**
+```bash
+cd OpenTutor
+pre-commit install
+```
+
+**ステップ 3: (オプション)すべてのファイルでチェックを実行**
+```bash
+pre-commit run --all-files
+```
+
+`git commit` を実行するたびに、pre-commit hooks は自動的に以下を行います:
+- Ruff で Python コードをフォーマット
+- Prettier でフロントエンドコードをフォーマット
+- 構文エラーをチェック
+- YAML/JSON ファイルを検証
+- 潜在的なセキュリティ問題を検出
+
+### コード品質ツール
+
+| ツール | 目的 | 構成 |
+|:---:|:---|:---:|
+| **Ruff** | Python コード確認とフォーマット | `pyproject.toml` |
+| **Prettier** | フロントエンドコード形式 | `web/.prettierrc.json` |
+| **detect-secrets** | セキュリティチェック | `.secrets.baseline` |
+
+> **注意**: プロジェクトはフォーマット競合を回避するため、Black の代わりに **Ruff format** を使用します。
+
+### よく使うコマンド
+
+```bash
+# 通常のコミット(hooks が自動実行)
+git commit -m "コミットメッセージ"
+
+# すべてのファイルを手動でチェック
+pre-commit run --all-files
+
+# hooks を最新バージョンに更新
+pre-commit autoupdate
+
+# hooks をスキップ(推奨されません。緊急時のみ)
+git commit --no-verify -m "緊急修正"
+```
+
+</details>
+
+### 貢献ガイドライン
+
+1. **Fork とクローン**: リポジトリを Fork してクローン
+2. **ブランチを作成**: `main` からフィーチャーブランチを作成
+3. **Pre-commit をインストール**: 上記セットアップステップに従う
+4. **変更を実施**: プロジェクトのスタイルに従ってコードを記述
+5. **テスト**: 変更が正しく機能することを確認
+6. **コミット**: Pre-commit hooks が自動的にコードをフォーマット
+7. **プッシュと PR**: Fork にプッシュして Pull Request を作成
+
+### 問題を報告
+
+- GitHub Issues を使用してバグを報告またはフィーチャーを提案
+- 問題に関する詳細情報を提供
+- バグの場合は、再現手順を含める
+
+<div align="center">
+<br>
+❤️ すべての貢献者の貴重な貢献に感謝します。
+
+</div>
+
+## 🔗 関連プロジェクト
+
+<div align="center">
+
+| [⚡ LightRAG](https://github.com/HKUDS/LightRAG) | [🎨 RAG-Anything](https://github.com/HKUDS/RAG-Anything) | [💻 DeepCode](https://github.com/HKUDS/DeepCode) | [🔬 AI-Researcher](https://github.com/HKUDS/AI-Researcher) |
+|:---:|:---:|:---:|:---:|
+| シンプルで高速の RAG | マルチモーダル RAG | AI コードアシスタント | 研究自動化 |
+
+**[香港大学データインテリジェンスラボ](https://github.com/HKUDS)**
+
+[⭐ Star us](https://github.com/HKUDS/OpenTutor/stargazers) · [🐛 Report a bug](https://github.com/HKUDS/OpenTutor/issues) · [💬 Discussions](https://github.com/HKUDS/OpenTutor/discussions)
+
+---
+*✨ **OpenTutor** のご利用ありがとうございます!*
+
+<img src="https://visitor-badge.laobi.icu/badge?page_id=HKUDS.OpenTutor&style=for-the-badge&color=00d4ff" alt="Views">
+
+</div>
diff --git a/assets/figs/co-writer.png b/assets/figs/co-writer.png
new file mode 100644
index 000000000..987eb938b
Binary files /dev/null and b/assets/figs/co-writer.png differ
diff --git a/assets/figs/deepresearch.png b/assets/figs/deepresearch.png
new file mode 100644
index 000000000..e6b33a9bc
Binary files /dev/null and b/assets/figs/deepresearch.png differ
diff --git a/assets/figs/full-pipe.png b/assets/figs/full-pipe.png
new file mode 100644
index 000000000..5e0de9da0
Binary files /dev/null and b/assets/figs/full-pipe.png differ
diff --git a/assets/figs/guide.png b/assets/figs/guide.png
new file mode 100644
index 000000000..b6ca41ff4
Binary files /dev/null and b/assets/figs/guide.png differ
diff --git a/assets/figs/ideagen.png b/assets/figs/ideagen.png
new file mode 100644
index 000000000..92e8beeeb
Binary files /dev/null and b/assets/figs/ideagen.png differ
diff --git a/assets/figs/question-gen.png b/assets/figs/question-gen.png
new file mode 100644
index 000000000..00ec000d7
Binary files /dev/null and b/assets/figs/question-gen.png differ
diff --git a/assets/figs/solve.png b/assets/figs/solve.png
new file mode 100644
index 000000000..8bd06840e
Binary files /dev/null and b/assets/figs/solve.png differ
diff --git a/assets/figs/title_gradient.svg b/assets/figs/title_gradient.svg
new file mode 100644
index 000000000..431d59926
--- /dev/null
+++ b/assets/figs/title_gradient.svg
@@ -0,0 +1,11 @@
+<svg width="800" height="100" viewBox="0 0 800 100" xmlns="http://www.w3.org/2000/svg">
+ <defs>
+ <linearGradient id="grad1" x1="0%" y1="0%" x2="100%" y2="0%">
+ <stop offset="0%" style="stop-color:#FF6B6B;stop-opacity:1" />
+ <stop offset="100%" style="stop-color:#4ECDC4;stop-opacity:1" />
+ </linearGradient>
+ </defs>
+ <text x="50%" y="60%" font-family="Arial, Helvetica, sans-serif" font-weight="bold" font-size="50" fill="url(#grad1)" dominant-baseline="middle" text-anchor="middle">
+ All-in-One Tutoring System
+ </text>
+</svg>
diff --git a/assets/gifs/co-writer.gif b/assets/gifs/co-writer.gif
new file mode 100644
index 000000000..2389ad8bd
Binary files /dev/null and b/assets/gifs/co-writer.gif differ
diff --git a/assets/gifs/deepresearch.gif b/assets/gifs/deepresearch.gif
new file mode 100644
index 000000000..b64c22d30
Binary files /dev/null and b/assets/gifs/deepresearch.gif differ
diff --git a/assets/gifs/guided-learning.gif b/assets/gifs/guided-learning.gif
new file mode 100644
index 000000000..1ef1ff740
Binary files /dev/null and b/assets/gifs/guided-learning.gif differ
diff --git a/assets/gifs/ideagen.gif b/assets/gifs/ideagen.gif
new file mode 100644
index 000000000..e9319ce2d
Binary files /dev/null and b/assets/gifs/ideagen.gif differ
diff --git a/assets/gifs/knowledge_bases.png b/assets/gifs/knowledge_bases.png
new file mode 100644
index 000000000..d1f2be1a3
Binary files /dev/null and b/assets/gifs/knowledge_bases.png differ
diff --git a/assets/gifs/notebooks.png b/assets/gifs/notebooks.png
new file mode 100644
index 000000000..ddab9d17b
Binary files /dev/null and b/assets/gifs/notebooks.png differ
diff --git a/assets/gifs/question-1.gif b/assets/gifs/question-1.gif
new file mode 100644
index 000000000..28821fbef
Binary files /dev/null and b/assets/gifs/question-1.gif differ
diff --git a/assets/gifs/question-2.gif b/assets/gifs/question-2.gif
new file mode 100644
index 000000000..eeccc51c4
Binary files /dev/null and b/assets/gifs/question-2.gif differ
diff --git a/assets/gifs/solve.gif b/assets/gifs/solve.gif
new file mode 100644
index 000000000..35051199a
Binary files /dev/null and b/assets/gifs/solve.gif differ
diff --git a/assets/logo-ver2.png b/assets/logo-ver2.png
new file mode 100644
index 000000000..856aee98b
Binary files /dev/null and b/assets/logo-ver2.png differ
diff --git a/config/README.md b/config/README.md
new file mode 100644
index 000000000..b4406c9a2
--- /dev/null
+++ b/config/README.md
@@ -0,0 +1,271 @@
+# Configuration Directory
+
+This directory contains all configuration files for the OpenTutor 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
+
+# IdeaGen Module - Idea generation agents
+ideagen:
+ 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, query item)
+- **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 preset configurations
+- **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/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 # Global switch for web search (affects all modules)
+ query_item:
+ enabled: true
+ max_results: 5 # Max results returned by query_item tool
+
+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)
+research:
+ planning:
+ # ... planning settings
+ researching:
+ max_iterations: 5
+ execution_mode: "parallel"
+ # ... other settings
+ reporting:
+ # ... reporting settings
+ presets:
+ quick: # ...
+ medium: # ...
+ deep: # ...
+ auto: # ...
+
+# 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 `OpenTutor.env`)
+ - LLM API keys and endpoints
+ - Model names
+ - Override all other settings
+
+2. **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. **main.yaml**
+ - System-wide shared settings
+ - Path configurations
+ - All module-specific settings
+ - Tool configurations
+
+## 📝 Configuration Loading
+
+Configuration files are loaded using `src/core/core.py`:
+
+```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 `config/main.yaml` as base configuration
+2. Returns the configuration dictionary
+
+**`get_agent_params` function:**
+1. Loads `config/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 `OpenTutor.env`):
+
+```bash
+# LLM Configuration (Required)
+LLM_BINDING_API_KEY=your_api_key
+LLM_BINDING_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. **Presets for common scenarios**: Use presets (e.g., in main.yaml research section) for different use cases
+
+## 🔗 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 `OpenTutor.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. **Research presets**: Use presets in `main.yaml` (research.presets: quick/medium/deep/auto) for different research depth requirements.
+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.yaml
new file mode 100644
index 000000000..a35faba58
--- /dev/null
+++ b/config/agents.yaml
@@ -0,0 +1,54 @@
+# =============================================================================
+# 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: investigate_agent, note_agent, manager_agent, solve_agent, tool_agent, response_agent, precision_answer_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: question_generation_agent, question_validation_agent
+question:
+ temperature: 0.7
+ max_tokens: 4096
+
+# Guide Module - Learning guidance agents
+# Agents: locate_agent, interactive_agent, chat_agent, summary_agent
+guide:
+ temperature: 0.5
+ max_tokens: 8192
+
+# IdeaGen Module - Idea generation agents
+# Agents: material_organizer_agent, idea_generation workflow
+ideagen:
+ temperature: 0.7
+ max_tokens: 4096
+
+# CoWriter Module - Collaborative writing agents
+# Agents: edit_agent
+co_writer:
+ temperature: 0.7
+ max_tokens: 4096
+
+# =============================================================================
+# 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
diff --git a/config/main.yaml b/config/main.yaml
new file mode 100644
index 000000000..7c5c7120a
--- /dev/null
+++ b/config/main.yaml
@@ -0,0 +1,141 @@
+server:
+ backend_port: 8001
+ frontend_port: 3782
+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
+ query_item:
+ enabled: true
+ max_results: 5
+logging:
+ level: DEBUG
+ save_to_file: true
+ console_output: true
+ lightrag_forwarding:
+ enabled: true
+ min_level: DEBUG
+ add_prefix: true
+ logger_names:
+ knowledge_init: LightRAG-Init
+ rag_tool: LightRAG
+tts:
+ default_voice: alloy
+question:
+ max_rounds: 10
+ rag_query_count: 3
+ max_parallel_questions: 3
+ rag_mode: naive
+ agents:
+ question_generation:
+ max_iterations: 5
+ retrieve_top_k: 30
+ question_validation:
+ strict_mode: true
+solve:
+ max_solve_correction_iterations: 3
+ enable_citations: true
+ save_intermediate_results: true
+ agents:
+ investigate_agent:
+ max_actions_per_round: 1
+ max_iterations: 3
+ precision_answer_agent:
+ enabled: true
+research:
+ planning:
+ rephrase:
+ enabled: true
+ max_iterations: 3
+ decompose:
+ enabled: true
+ mode: auto
+ initial_subtopics: 5
+ auto_max_subtopics: 8
+ researching:
+ max_iterations: 5
+ new_topic_min_score: 0.85
+ execution_mode: parallel
+ max_parallel_topics: 5
+ enable_rag_naive: true
+ enable_rag_hybrid: true
+ enable_paper_search: true
+ enable_web_search: true
+ enable_run_code: true
+ tool_timeout: 60
+ tool_max_retries: 2
+ paper_search_years_limit: 3
+ reporting:
+ min_section_length: 800
+ enable_citation_list: true
+ enable_inline_citations: false
+ rag:
+ kb_name: DE-all
+ default_mode: hybrid
+ fallback_mode: naive
+ queue:
+ max_length: 5
+ presets:
+ quick:
+ description: Quick mode - fast research with minimal depth
+ planning:
+ decompose:
+ mode: manual
+ initial_subtopics: 1
+ researching:
+ max_iterations: 1
+ iteration_mode: fixed
+ reporting:
+ min_section_length: 300
+ medium:
+ description: Medium mode - balanced research depth
+ planning:
+ decompose:
+ mode: manual
+ initial_subtopics: 5
+ researching:
+ max_iterations: 4
+ iteration_mode: fixed
+ reporting:
+ min_section_length: 500
+ deep:
+ description: Deep mode - thorough research with maximum depth
+ planning:
+ decompose:
+ mode: manual
+ initial_subtopics: 8
+ researching:
+ max_iterations: 7
+ iteration_mode: fixed
+ reporting:
+ min_section_length: 800
+ auto:
+ description: Auto mode - agent decides depth within limits
+ planning:
+ decompose:
+ mode: auto
+ auto_max_subtopics: 8
+ researching:
+ max_iterations: 6
+ iteration_mode: flexible
+ reporting:
+ min_section_length: 500
diff --git a/data/README.md b/data/README.md
new file mode 100644
index 000000000..473dac1d2
--- /dev/null
+++ b/data/README.md
@@ -0,0 +1,171 @@
+# Data Directory
+
+This directory stores all data files for the OpenTutor system, including knowledge bases, user data, logs, and more.
+
+## 📁 Directory Structure
+
+```
+data/
+├── knowledge_bases/ # Knowledge base storage directory
+│ ├── kb_config.json # Knowledge base configuration file
+│ └── {kb_name}/ # Individual knowledge base directories
+│ ├── metadata.json # Knowledge base metadata
+│ ├── numbered_items.json # Numbered items (definitions, theorems, etc.)
+│ ├── raw/ # Original documents (PDF/Markdown)
+│ ├── images/ # Extracted images
+│ ├── content_list/ # Document content list
+│ └── rag_storage/ # RAG knowledge graph storage
+│ ├── graph_chunk_entity_relation.graphml
+│ ├── kv_store_*.json
+│ └── vdb_*.json
+│
+└── user/ # User data directory
+ ├── solve/ # Problem solving module output
+ │ └── solve_YYYYMMDD_HHMMSS/
+ │ ├── investigate_memory.json
+ │ ├── solve_chain.json
+ │ ├── citation_memory.json
+ │ ├── final_answer.md
+ │ └── artifacts/ # Code execution output
+ │
+ ├── question/ # Question generation module output
+ │ └── question_YYYYMMDD_HHMMSS/
+ │
+ ├── research/ # Research module output
+ │ ├── cache/ # Research cache
+ │ │ └── research_*/ # Queue and intermediate results
+ │ └── reports/ # Research reports
+ │ └── research_*.md
+ │
+ ├── guide/ # Guided learning output
+ │ └── session_{session_id}.json
+ │
+ ├── notebook/ # Notebook data
+ │ └── notebooks_index.json
+ │
+ ├── co-writer/ # Co-Writer output
+ │ ├── audio/ # TTS audio files
+ │ └── tool_calls/ # Tool call history
+ │
+ ├── logs/ # System logs
+ │ └── ai_tutor_*.log
+ │
+ ├── run_code_workspace/ # Code execution workspace
+ │
+ └── user_history.json # User activity history
+```
+
+## 📋 Directory Description
+
+### knowledge_bases/
+
+Stores all knowledge base data files. Each knowledge base contains:
+
+- **metadata.json**: Knowledge base metadata, including creation time, update time, update history, etc.
+- **numbered_items.json**: Extracted numbered items (Definition, Theorem, Formula, etc.)
+- **raw/**: Original uploaded documents (PDF, Markdown, etc.)
+- **images/**: Images extracted from documents
+- **content_list/**: Document content list (JSON format)
+- **rag_storage/**: RAG knowledge graph storage files
+ - `graph_chunk_entity_relation.graphml`: Knowledge graph structure
+ - `kv_store_*.json`: Key-value storage (documents, entities, relations, etc.)
+ - `vdb_*.json`: Vector database indices
+
+### user/
+
+Stores all user-generated data and output files.
+
+#### solve/
+
+Problem solving module output directory. Each solving task generates a timestamped directory:
+- `investigate_memory.json`: Analysis Loop memory data
+- `solve_chain.json`: Complete Solve Loop steps and tool call records
+- `citation_memory.json`: Citation management data
+- `final_answer.md`: Final answer (Markdown format)
+- `artifacts/`: Files generated by code execution (images, data files, etc.)
+
+#### question/
+
+Question generation module output directory. Each question generation task generates a timestamped directory containing generated questions and validation results.
+
+#### research/
+
+Research module output directory:
+- `cache/`: Intermediate data during research (queue state, planning results, etc.)
+- `reports/`: Final generated research reports (Markdown format)
+
+#### guide/
+
+Guided learning module output directory. Each learning session is saved as a JSON file containing session state, knowledge points, chat history, etc.
+
+#### notebook/
+
+Notebook data storage. `notebooks_index.json` contains index information for all notebooks.
+
+#### co-writer/
+
+Co-Writer module output directory:
+- `audio/`: TTS-generated audio files
+- `tool_calls/`: AI tool call history
+
+#### logs/
+
+System log files, named by date.
+
+#### run_code_workspace/
+
+Code execution tool workspace for temporarily storing files generated by code execution.
+
+## 🔧 Configuration
+
+Data directory paths are configured in `config/main.yaml`:
+
+```yaml
+paths:
+ user_data_dir: "./data/user"
+ knowledge_bases_dir: "./data/knowledge_bases"
+ user_log_dir: "./data/user/logs"
+```
+
+## 📝 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 unified path configuration, avoid hardcoded paths
+
+## 🔗 Related Modules
+
+- **Knowledge Base Management**: `src/knowledge/` - Knowledge base creation, updates, queries
+- **User Data**: Each functional module automatically manages its corresponding user data directory
+- **Logging System**: `src/core/logging/` - Unified logging management
+
+## 🛠️ Maintenance Operations
+
+### Clean Old Data
+
+```bash
+# Clean old solving records (keep last 30 days)
+find data/user/solve -type d -mtime +30 -exec rm -rf {} \;
+
+# Clean old log files (keep last 7 days)
+find data/user/logs -name "*.log" -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 ai_textbook_backup.tar.gz data/knowledge_bases/ai-textbook/
+```
+
+### Restore Knowledge Base
+
+```bash
+# Restore knowledge base
+tar -xzf knowledge_bases_backup_20250101.tar.gz -C data/
+```
diff --git a/pyproject.toml b/pyproject.toml
new file mode 100644
index 000000000..4b12027a2
--- /dev/null
+++ b/pyproject.toml
@@ -0,0 +1,158 @@
+# Python project configuration for OpenTutor
+# This file configures Black, Ruff, and other Python tools
+
+[build-system]
+requires = ["setuptools>=61.0", "wheel"]
+build-backend = "setuptools.build_meta"
+
+[project]
+name = "ai-tutor"
+version = "0.1.0"
+description = "An intelligent learning companion with multi-agent collaboration and RAG"
+requires-python = ">=3.10"
+readme = "README.md"
+license = {text = "Apache-2.0"}
+
+# ============================================
+# Black code formatter configuration
+# ============================================
+[tool.black]
+line-length = 100
+target-version = ['py310', 'py311', 'py312']
+include = '\.pyi?$'
+extend-exclude = '''
+/(
+ # Exclude directories
+ \.eggs
+ | \.git
+ | \.hg
+ | \.mypy_cache
+ | \.tox
+ | \.venv
+ | venv
+ | _build
+ | buck-out
+ | build
+ | dist
+ | __pycache__
+ | node_modules
+ | \.next
+)/
+'''
+
+# ============================================
+# Ruff linter and formatter configuration
+# ============================================
+[tool.ruff]
+# Target Python version
+target-version = "py310"
+line-length = 100
+
+[tool.ruff.lint]
+# 只启用最基础的规则(放宽要求)
+select = [
+ "E", # pycodestyle errors (语法错误)
+ "F", # pyflakes (未使用的导入、变量等)
+ "I", # isort (import 排序)
+ # 其他规则都忽略,不强制要求
+]
+
+# Ignore specific rules (放宽检查,只保留重要规则)
+ignore = [
+ "E501", # Line too long (handled by formatter)
+ "B008", # Do not perform function calls in argument defaults
+ "PLR0911", # Too many return statements
+ "PLR0912", # Too many branches
+ "PLR0913", # Too many arguments
+ "PLR0915", # Too many statements
+ "PLR2004", # Magic value used in comparison
+ "TRY003", # Avoid specifying long messages outside exception class
+ "T201", # print found (允许 print 语句,用于调试)
+ "E722", # Do not use bare except (某些情况下需要)
+ "E402", # Module level import not at top of file (某些情况下需要)
+ "PLC0415", # import should be at top-level (某些情况下需要)
+ "PTH123", # open() should be replaced by Path.open() (允许使用 open)
+ "PTH103", # os.makedirs() should be replaced by Path.mkdir() (允许使用 os.makedirs)
+ "PTH118", # os.path.join() should be replaced by Path (允许使用 os.path.join)
+ "B904", # Within except clause, raise exceptions with raise ... from err
+ "EM101", # Exception must not use a string literal
+ "EM102", # Exception must not use an f-string literal
+ "TRY002", # Create your own exception
+ "TRY300", # Consider moving this statement to an else block
+ "DTZ005", # datetime.now() called without tz argument
+ "RET504", # Unnecessary assignment before return
+ "PLW2901", # for loop variable overwritten by assignment target
+ "F841", # Local variable assigned but never used
+ "ERA001", # Found commented-out code (允许注释代码)
+ "B006", # Do not use mutable data structures for argument defaults
+]
+
+# Exclude patterns
+exclude = [
+ ".bzr",
+ ".direnv",
+ ".eggs",
+ ".git",
+ ".git-rewrite",
+ ".hg",
+ ".mypy_cache",
+ ".nox",
+ ".pants.d",
+ ".pyenv",
+ ".pytest_cache",
+ ".pytype",
+ ".ruff_cache",
+ ".svn",
+ ".tox",
+ ".venv",
+ ".vscode",
+ "__pypackages__",
+ "_build",
+ "buck-out",
+ "build",
+ "dist",
+ "node_modules",
+ ".next",
+ "out",
+ "venv",
+ "__pycache__",
+]
+
+# Allow autofix for all enabled rules
+fixable = ["ALL"]
+unfixable = []
+
+# Allow unused variables when underscore-prefixed
+dummy-variable-rgx = "^(_+|(_+[a-zA-Z0-9_]*[a-zA-Z0-9]+?))$"
+
+[tool.ruff.format]
+# Use double quotes for strings
+quote-style = "double"
+# Indent with spaces
+indent-style = "space"
+# Respect magic trailing comma
+skip-magic-trailing-comma = false
+# Automatically detect the appropriate line ending
+line-ending = "auto"
+
+# ============================================
+# Ruff import sorting (isort replacement)
+# ============================================
+[tool.ruff.lint.isort]
+known-first-party = ["src", "scripts"]
+force-sort-within-sections = true
+split-on-trailing-comma = true
+
+# ============================================
+# Ruff per-file-ignores
+# ============================================
+[tool.ruff.lint.per-file-ignores]
+# Allow longer lines in test files
+"**/test_*.py" = ["E501", "PLR2004"]
+"**/__init__.py" = ["F401"] # Allow unused imports in __init__.py
+
+# ============================================
+# Ruff mccabe complexity
+# ============================================
+[tool.ruff.lint.mccabe]
+max-complexity = 10
diff --git a/requirements.txt b/requirements.txt
new file mode 100644
index 000000000..5159ec0a1
--- /dev/null
+++ b/requirements.txt
@@ -0,0 +1,61 @@
+# ============================================
+# OpenTutor Python Dependencies
+# ============================================
+# Python >= 3.10 required
+# Install: pip install -r requirements.txt
+
+# ============================================
+# Core dependencies
+# ============================================
+python-dotenv>=1.0.0
+PyYAML>=6.0
+tiktoken>=0.5.0
+
+# ============================================
+# HTTP and API clients
+# ============================================
+requests>=2.31.0
+openai>=1.0.0
+perplexityai>=0.1.0
+dashscope>=1.14.0
+aiohttp>=3.9.0
+httpx>=0.25.0
+
+# ============================================
+# Async support
+# ============================================
+nest_asyncio>=1.5.8
+
+# ============================================
+# Web framework and server
+# ============================================
+fastapi>=0.100.0
+uvicorn[standard]>=0.24.0
+websockets>=12.0
+python-multipart>=0.0.6
+pydantic>=2.0.0
+
+# ============================================
+# RAG and knowledge base
+# ============================================
+lightrag-hku>=1.0.0
+raganything>=0.1.0
+
+# ============================================
+# Academic and research tools
+# ============================================
+arxiv>=2.0.0
+
+# ============================================
+# Scientific computing (optional, for code execution)
+# ============================================
+# Uncomment if users need these for code execution feature
+# numpy>=1.24.0
+# matplotlib>=3.7.0
+# scipy>=1.11.0
+# pandas>=2.0.0
+
+# ============================================
+# Development tools
+# ============================================
+pre-commit>=3.0.0
diff --git a/scripts/extract_numbered_items.sh b/scripts/extract_numbered_items.sh
new file mode 100644
index 000000000..496fe8085
--- /dev/null
+++ b/scripts/extract_numbered_items.sh
@@ -0,0 +1,24 @@
+#!/bin/bash
+# Convenient script: Extract numbered items from knowledge base
+
+# Get the directory where the script is located
+SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
+PROJECT_ROOT="$( cd "$SCRIPT_DIR/.." && pwd )"
+
+# Change to project root directory
+cd "$PROJECT_ROOT"
+
+# Check arguments
+if [ -z "$1" ]; then
+ echo "Usage: $0 <knowledge_base_name>"
+ echo "Example: $0 hkuds-lab"
+ exit 1
+fi
+
+KB_NAME="$1"
+
+# Run extraction script
+python src/knowledge/extract_numbered_items.py \
+ --kb "$KB_NAME" \
+ --base-dir ./data/knowledge_bases \
+ "${@:2}" # Pass other arguments
diff --git a/scripts/install_all.py b/scripts/install_all.py
new file mode 100644
index 000000000..2aa535a23
--- /dev/null
+++ b/scripts/install_all.py
@@ -0,0 +1,463 @@
+#!/usr/bin/env python
+"""
+OpenTutor 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
+ )
+
+ if not in_venv:
+ 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:")
+ if sys.platform == "win32":
+ print_info(" Windows: venv\\Scripts\\activate")
+ else:
+ print_info(" Linux/Mac: source venv/bin/activate")
+ print_info("Continuing installation...\n")
+ else:
+ print_success(f"Virtual environment detected: {sys.prefix}")
+
+
+def print_warning(message: str):
+ """Print warning message"""
+ print(f"⚠️ {message}")
+
+
+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}")
+
+ try:
+ # Install using pip
+ 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"]
+
+ for package in backend_packages:
+ try:
+ # Try importing package
+ if package == "lightrag_hku":
+ __import__("lightrag")
+ elif package == "raganything":
+ __import__("raganything")
+ else:
+ __import__(package)
+ print_success(f" ✓ {package}")
+ except ImportError:
+ 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("🚀 OpenTutor 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.sh
new file mode 100644
index 000000000..f5ac5d154
--- /dev/null
+++ b/scripts/install_all.sh
@@ -0,0 +1,311 @@
+#!/bin/bash
+# OpenTutor 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 "🚀 OpenTutor 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 python)"
+print_info "Requirements file: $REQUIREMENTS_FILE"
+print_info "Installing backend dependencies, please wait..."
+
+if python -m pip install -r "$REQUIREMENTS_FILE"; then
+ print_success "Backend dependencies installed successfully"
+else
+ print_error "Backend dependencies installation failed"
+ exit 1
+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 python -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 python -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 python -c "import raganything" 2>/dev/null; then
+ print_success " ✓ raganything"
+else
+ print_error " ✗ raganything not installed"
+ ALL_OK=false
+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
+fi
diff --git a/scripts/start.py b/scripts/start.py
new file mode 100644
index 000000000..612fb5722
--- /dev/null
+++ b/scripts/start.py
@@ -0,0 +1,807 @@
+#!/usr/bin/env python
+"""
+OpenTutor CLI Launcher
+
+Provides a command-line interface for users to easily access:
+1. Solver system (solve_agents)
+2. Question generation system (question_agents)
+3. Deep research system (DR-in-KG)
+"""
+
+import asyncio
+from pathlib import Path
+import sys
+
+from dotenv import load_dotenv
+
+# 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")
+
+# Load environment variables
+load_dotenv()
+
+# Add project root directory to path
+project_root = Path(__file__).parent.parent
+sys.path.insert(0, str(project_root))
+
+from src.agents.question import AgentCoordinator
+from src.agents.solve import MainSolver
+from src.api.utils.history import ActivityType, history_manager
+from src.core.core import get_llm_config
+from src.core.logging import get_logger
+
+# Initialize logger for CLI
+logger = get_logger("CLI", console_output=True, file_output=True)
+
+
+class AITutorStarter:
+ """OpenTutor CLI Launcher"""
+
+ def __init__(self):
+ """Initialize launcher"""
+ # Initialize user data directories
+ try:
+ from src.core.setup import init_user_directories
+
+ init_user_directories(project_root)
+ except Exception as e:
+ logger.warning(f"Failed to initialize user directories: {e}")
+ logger.info("Continuing anyway...")
+
+ try:
+ llm_config = get_llm_config()
+ self.api_key = llm_config["api_key"]
+ self.base_url = llm_config["base_url"]
+ except ValueError as e:
+ logger.error(str(e))
+ logger.error("Please configure LLM settings in .env or OpenTutor.env file")
+ sys.exit(1)
+
+ # Load knowledge base list
+ self.available_kbs = self._load_available_kbs()
+
+ logger.section("OpenTutor Intelligent Teaching Assistant System")
+ logger.success("API configuration loaded")
+ logger.info(f"Available knowledge bases: {', '.join(self.available_kbs)}")
+ logger.separator()
+
+ def _load_available_kbs(self) -> list:
+ """Load available knowledge base list"""
+ kb_base_dir = Path(__file__).parent / "data/knowledge_bases"
+ if not kb_base_dir.exists():
+ return ["ai_textbook"] # Default knowledge base
+
+ # Read configuration file
+ kb_config_file = kb_base_dir / "kb_config.json"
+ if kb_config_file.exists():
+ import json
+
+ with open(kb_config_file, encoding="utf-8") as f:
+ config = json.load(f)
+ return list(config.get("knowledge_bases", {}).keys())
+
+ # Otherwise scan directory
+ kbs = []
+ for item in kb_base_dir.iterdir():
+ if item.is_dir() and not item.name.startswith("."):
+ kbs.append(item.name)
+
+ return kbs if kbs else ["ai_textbook"]
+
+ def show_main_menu(self) -> str:
+ """Display main menu and get user selection"""
+ logger.section("Please select a function:")
+ print("1. 🧠 Solver System (Solve) - Intelligent academic problem solving")
+ print(
+ "2. 📝 Question Generator (Question) - Generate questions based on knowledge base"
+ )
+ print("3. 🔬 Deep Research (Research) - Multi-round deep knowledge research")
+ print("4. 💡 Idea Generation (IdeaGen) - Extract research ideas from notes")
+ print("5. 🌐 Start Web Service (Web) - Start frontend and backend services")
+ print("6. ⚙️ System Settings (Settings) - View/modify configuration")
+ print("7. 🚪 Exit")
+ logger.separator()
+
+ while True:
+ choice = input("\nPlease enter option (1-7): ").strip()
+ if choice in ["1", "2", "3", "4", "5", "6", "7"]:
+ return choice
+ logger.warning("Invalid option, please try again")
+
+ def select_kb(self, default: str = None) -> str:
+ """Select knowledge base"""
+ if len(self.available_kbs) == 1:
+ return self.available_kbs[0]
+
+ logger.separator()
+ logger.info("Available knowledge bases:")
+ logger.separator()
+ for i, kb in enumerate(self.available_kbs, 1):
+ default_mark = " (default)" if kb == default else ""
+ print(f"{i}. {kb}{default_mark}")
+ logger.separator()
+
+ while True:
+ choice = input(
+ f"\nPlease select knowledge base (1-{len(self.available_kbs)}) [default: 1]: "
+ ).strip()
+ if not choice:
+ return self.available_kbs[0]
+
+ try:
+ idx = int(choice) - 1
+ if 0 <= idx < len(self.available_kbs):
+ return self.available_kbs[idx]
+ logger.warning(f"Please enter a number between 1 and {len(self.available_kbs)}")
+ except ValueError:
+ logger.warning("Please enter a valid number")
+
+ async def run_solve_mode(self):
+ """Run solver mode"""
+ logger.section("Solver System")
+
+ # Select knowledge base
+ kb_name = self.select_kb(default="ai_textbook")
+ logger.success(f"Selected knowledge base: {kb_name}")
+
+ # Input question
+ logger.separator()
+ logger.info(
+ "Please enter your question (multi-line input supported, empty line to finish):"
+ )
+ logger.separator()
+
+ lines = []
+ while True:
+ line = input()
+ if not line:
+ break
+ lines.append(line)
+
+ if not lines:
+ logger.warning("No question entered, returning to main menu")
+ return
+
+ question = "\n".join(lines)
+
+ # Display solver mode description
+ logger.separator()
+ logger.info("Solver Mode: Dual-Loop Architecture")
+ logger.separator()
+ logger.info("Analysis Loop: Deep understanding of user question")
+ logger.info(" Investigate → Note")
+ logger.info("")
+ logger.info("Solve Loop: Collaborative solving")
+ logger.info(" Manager → Solve → Tool → Response → Precision")
+ logger.separator()
+
+ logger.section("Starting solver...")
+
+ try:
+ # Create solver
+ solver = MainSolver(
+ config_path=None, # Use default configuration file
+ api_key=self.api_key,
+ base_url=self.base_url,
+ kb_name=kb_name,
+ )
+
+ # Run solver
+ result = await solver.solve(question=question, verbose=True)
+
+ logger.section("Solving completed!")
+ logger.info(f"Output directory: {result['metadata']['output_dir']}")
+
+ logger.info("Solving statistics:")
+ logger.info(f" Execution mode: {result['metadata']['mode']}")
+ logger.info(f" Pipeline: {result.get('pipeline', 'dual_loop')}")
+
+ if "analysis_iterations" in result:
+ logger.info(f" Analysis loop iterations: {result['analysis_iterations']} rounds")
+ if "solve_steps" in result:
+ logger.info(f" Solve steps completed: {result['solve_steps']} steps")
+ if "total_steps" in result:
+ logger.info(f" Total planned steps: {result['total_steps']}")
+ if "citations" in result:
+ logger.info(f" Citation count: {len(result['citations'])}")
+
+ logger.info("Output files:")
+ logger.info(f" Markdown: {result['output_md']}")
+ logger.info(f" JSON: {result['output_json']}")
+ logger.separator()
+
+ # Display answer preview
+ formatted_solution = result.get("formatted_solution", "")
+ if formatted_solution:
+ logger.separator()
+ logger.info("Answer preview:")
+ logger.separator()
+ preview_lines = formatted_solution.split("\n")[:20]
+ preview = "\n".join(preview_lines)
+ if len(formatted_solution) > len(preview):
+ preview += "\n\n... (more content available in output file) ..."
+ print(preview)
+ logger.separator()
+
+ # Save to history
+ try:
+ history_manager.add_entry(
+ activity_type=ActivityType.SOLVE,
+ title=question[:50] + "..." if len(question) > 50 else question,
+ content={
+ "question": question,
+ "answer": result.get("formatted_solution", ""),
+ "output_dir": result["metadata"]["output_dir"],
+ "kb_name": kb_name,
+ "metadata": result.get("metadata", {}),
+ },
+ summary=(
+ formatted_solution[:100] + "..."
+ if formatted_solution and len(formatted_solution) > 100
+ else (formatted_solution or "")
+ ),
+ )
+ except Exception as hist_error:
+ # History save failure does not affect main flow
+ logger.warning(f"History save failed: {hist_error!s}")
+
+ except Exception as e:
+ logger.section("Solving failed")
+ logger.error(str(e))
+ import traceback
+
+ logger.debug("Debug information:")
+ logger.debug(traceback.format_exc())
+
+ async def run_question_mode(self):
+ """Run question generation mode"""
+ print("\n" + "=" * 70)
+ print("📝 Question Generation System")
+ print("=" * 70)
+
+ # Select knowledge base
+ kb_name = self.select_kb(default="ai_textbook")
+ print(f"✅ Selected knowledge base: {kb_name}")
+
+ # Input knowledge point
+ print("\n" + "-" * 70)
+ print("Please enter knowledge point:")
+ print("-" * 70)
+ knowledge_point = input().strip()
+
+ if not knowledge_point:
+ print("❌ No knowledge point entered, returning to main menu")
+ return
+
+ # Select difficulty
+ print("\n" + "-" * 70)
+ print("📊 Difficulty selection:")
+ print("-" * 70)
+ print("1. Easy")
+ print("2. Medium")
+ print("3. Hard")
+ print("-" * 70)
+
+ difficulty_map = {"1": "easy", "2": "medium", "3": "hard"}
+ while True:
+ diff_choice = input("\nPlease select difficulty (1-3) [default: 2]: ").strip()
+ if not diff_choice:
+ difficulty = "medium"
+ break
+ if diff_choice in difficulty_map:
+ difficulty = difficulty_map[diff_choice]
+ break
+ print("❌ Invalid option, please try again")
+
+ # Select question type
+ print("\n" + "-" * 70)
+ print("📋 Question type selection:")
+ print("-" * 70)
+ print("1. Multiple choice (choice)")
+ print("2. Written answer (written)")
+ print("-" * 70)
+
+ while True:
+ type_choice = input("\nPlease select question type (1/2) [default: 1]: ").strip()
+ if not type_choice or type_choice == "1":
+ question_type = "choice"
+ break
+ if type_choice == "2":
+ question_type = "written"
+ break
+ print("❌ Invalid option, please try again")
+
+ print("\n" + "=" * 70)
+ print("🚀 Starting question generation...")
+ print("=" * 70)
+
+ try:
+ # Create coordinator
+ coordinator = AgentCoordinator(
+ api_key=self.api_key,
+ base_url=self.base_url,
+ kb_name=kb_name,
+ output_dir="./user/question",
+ )
+
+ # Build requirement
+ requirement = {
+ "knowledge_point": knowledge_point,
+ "difficulty": difficulty,
+ "question_type": question_type,
+ "additional_requirements": "Ensure questions are clear and academically rigorous",
+ }
+
+ # Run question generation
+ result = await coordinator.generate_question(requirement)
+
+ if result.get("success"):
+ print("\n" + "=" * 70)
+ print("✅ Question generation completed!")
+ print("=" * 70)
+
+ question_data = result.get("question", {})
+ print("\n📝 Question:")
+ print(question_data.get("question", ""))
+
+ if question_data.get("options"):
+ print("\n📋 Options:")
+ for key, value in question_data.get("options", {}).items():
+ print(f" {key}. {value}")
+
+ print(f"\n✅ Answer: {question_data.get('correct_answer', '')}")
+ print("\n💡 Explanation:")
+ print(question_data.get("explanation", ""))
+
+ if result.get("output_dir"):
+ print(f"\n📁 Output directory: {result['output_dir']}")
+
+ print("=" * 70)
+
+ # Save to history
+ try:
+ history_manager.add_entry(
+ activity_type=ActivityType.QUESTION,
+ title=f"{knowledge_point} ({question_type})",
+ content={
+ "requirement": requirement,
+ "question": question_data,
+ "output_dir": result.get("output_dir", ""),
+ "kb_name": kb_name,
+ },
+ summary=(
+ question_data.get("question", "")[:100] + "..."
+ if len(question_data.get("question", "")) > 100
+ else question_data.get("question", "")
+ ),
+ )
+ except Exception as hist_error:
+ # History save failure does not affect main flow
+ print(f"\n⚠️ History save failed: {hist_error!s}")
+ else:
+ print("\n" + "=" * 70)
+ print(f"❌ Question generation failed: {result.get('error', 'Unknown error')}")
+ if result.get("reason"):
+ print(f"Reason: {result['reason']}")
+ print("=" * 70)
+
+ except Exception as e:
+ print("\n" + "=" * 70)
+ print(f"❌ Question generation failed: {e!s}")
+ import traceback
+
+ print("\nDebug information:")
+ print(traceback.format_exc())
+ print("=" * 70)
+
+ async def run_research_mode(self):
+ """Run deep research mode"""
+ print("\n" + "=" * 70)
+ print("🔬 Deep Research System")
+ print("=" * 70)
+
+ # Select knowledge base
+ kb_name = self.select_kb(default="ai_textbook")
+ print(f"✅ Selected knowledge base: {kb_name}")
+
+ # Input research topic
+ print("\n" + "-" * 70)
+ print("Please enter research topic:")
+ print("-" * 70)
+ topic = input().strip()
+
+ if not topic:
+ print("❌ No topic entered, returning to main menu")
+ return
+
+ # Select research mode
+ print("\n" + "-" * 70)
+ print("🎯 Research mode:")
+ print("-" * 70)
+ print("1. Quick - 2 subtopics, 2 iterations")
+ print("2. Standard - 5 subtopics, 5 iterations")
+ print("3. Deep - 8 subtopics, 7 iterations")
+ print("4. Auto - Automatically generate subtopic count")
+ print("-" * 70)
+
+ preset_map = {"1": "quick", "2": "standard", "3": "deep", "4": "auto"}
+ while True:
+ mode_choice = input("\nPlease select mode (1-4) [default: 1]: ").strip()
+ if not mode_choice:
+ preset = "quick"
+ break
+ if mode_choice in preset_map:
+ preset = preset_map[mode_choice]
+ break
+ print("❌ Invalid option, please try again")
+
+ print("\n" + "=" * 70)
+ print("🚀 Starting deep research...")
+ print("=" * 70)
+
+ try:
+ # Import research pipeline
+ from src.agents.research.research_pipeline import ResearchPipeline
+ from src.core.core import load_config_with_main
+
+ # Load configuration using unified config loader
+ config = load_config_with_main("main.yaml", project_root)
+
+ # Extract research.* configs to top level (ResearchPipeline expects flat structure)
+ research_config = config.get("research", {})
+ if "planning" not in config:
+ config["planning"] = research_config.get("planning", {}).copy()
+ if "researching" not in config:
+ config["researching"] = research_config.get("researching", {}).copy()
+ if "reporting" not in config:
+ config["reporting"] = research_config.get("reporting", {}).copy()
+ if "rag" not in config:
+ config["rag"] = research_config.get("rag", {}).copy()
+ if "queue" not in config:
+ config["queue"] = research_config.get("queue", {}).copy()
+ if "presets" not in config:
+ config["presets"] = research_config.get("presets", {}).copy()
+
+ # Set output paths
+ if "system" not in config:
+ config["system"] = {}
+ output_base = project_root / "data" / "user" / "research"
+ config["system"]["output_base_dir"] = str(output_base / "cache")
+ config["system"]["reports_dir"] = str(output_base / "reports")
+
+ # Apply preset mode configuration
+ preset_configs = {
+ "quick": {
+ "planning": {"decompose": {"initial_subtopics": 2, "mode": "manual"}},
+ "researching": {"max_iterations": 2},
+ },
+ "standard": {
+ "planning": {"decompose": {"initial_subtopics": 5, "mode": "manual"}},
+ "researching": {"max_iterations": 5},
+ },
+ "deep": {
+ "planning": {"decompose": {"initial_subtopics": 8, "mode": "manual"}},
+ "researching": {"max_iterations": 7},
+ },
+ "auto": {
+ "planning": {"decompose": {"mode": "auto", "auto_max_subtopics": 8}},
+ "researching": {"max_iterations": 6},
+ },
+ }
+
+ if preset in preset_configs:
+ preset_cfg = preset_configs[preset]
+ # Apply planning configuration
+ if "planning" in preset_cfg:
+ for key, value in preset_cfg["planning"].items():
+ if key not in config["planning"]:
+ config["planning"][key] = {}
+ config["planning"][key].update(value)
+ # Apply researching configuration
+ if "researching" in preset_cfg:
+ config["researching"].update(preset_cfg["researching"])
+
+ if preset == "auto":
+ print(
+ f"✅ Auto mode enabled (automatically generate subtopic count, max: {config['planning']['decompose'].get('auto_max_subtopics', 8)})"
+ )
+ else:
+ print(f"✅ {preset.capitalize()} mode enabled")
+
+ # Create research pipeline
+ pipeline = ResearchPipeline(
+ config=config, api_key=self.api_key, base_url=self.base_url, kb_name=kb_name
+ )
+
+ # Execute research
+ result = await pipeline.run(topic)
+
+ print("\n" + "=" * 70)
+ print("✅ Research completed!")
+ print("=" * 70)
+ print(f"📁 Report location: {result['final_report_path']}")
+ print(f"📊 Research ID: {result['research_id']}")
+
+ metadata = result.get("metadata", {})
+ if metadata:
+ print("\n📈 Research statistics:")
+ print(f" Report word count: {metadata.get('report_word_count', 0)}")
+ stats = metadata.get("statistics", {})
+ if stats:
+ print(f" Topic blocks: {stats.get('total_blocks', 0)}")
+ print(f" Completed topics: {stats.get('completed', 0)}")
+ print(f" Tool calls: {stats.get('total_tool_calls', 0)}")
+
+ print("=" * 70)
+
+ # Save to history
+ try:
+ # Read report content
+ report_content = ""
+ if result.get("final_report_path") and Path(result["final_report_path"]).exists():
+ with open(result["final_report_path"], encoding="utf-8") as f:
+ report_content = f.read()
+
+ history_manager.add_entry(
+ activity_type=ActivityType.RESEARCH,
+ title=topic,
+ content={
+ "topic": topic,
+ "report": report_content,
+ "report_path": result.get("final_report_path", ""),
+ "research_id": result.get("research_id", ""),
+ "kb_name": kb_name,
+ "metadata": metadata,
+ },
+ summary=(
+ report_content[:200] + "..."
+ if len(report_content) > 200
+ else report_content
+ ),
+ )
+ except Exception as hist_error:
+ # History save failure does not affect main flow
+ logger.warning(f"History save failed: {hist_error!s}")
+
+ except Exception as e:
+ logger.section("Research failed")
+ logger.error(str(e))
+ import traceback
+
+ logger.debug("Debug information:")
+ logger.debug(traceback.format_exc())
+
+ async def run_ideagen_mode(self):
+ """Run idea generation mode"""
+ print("\n" + "=" * 70)
+ print("💡 Idea Generation System")
+ print("=" * 70)
+
+ # Select knowledge base
+ kb_name = self.select_kb()
+ print(f"✅ Selected knowledge base: {kb_name}")
+
+ # Input materials
+ print("\n" + "-" * 70)
+ print(
+ "Please enter knowledge points or material content (multi-line input supported, empty line to finish):"
+ )
+ print("-" * 70)
+
+ lines = []
+ while True:
+ line = input()
+ if not line:
+ break
+ lines.append(line)
+
+ if not lines:
+ print("❌ No content entered, returning to main menu")
+ return
+
+ materials = "\n".join(lines)
+
+ print("\n" + "=" * 70)
+ print("🚀 Starting research idea generation...")
+ print("=" * 70)
+
+ try:
+ # Import ideagen module
+ from src.agents.ideagen.idea_generation_workflow import IdeaGenerationWorkflow
+ from src.agents.ideagen.material_organizer_agent import MaterialOrganizerAgent
+
+ # Organize materials
+ organizer = MaterialOrganizerAgent(api_key=self.api_key, base_url=self.base_url)
+
+ print("📊 Extracting knowledge points...")
+ knowledge_points = await organizer.extract_knowledge_points(materials)
+ print(f"✅ Extracted {len(knowledge_points)} knowledge points")
+
+ if not knowledge_points:
+ print("❌ Failed to extract valid knowledge points")
+ return
+
+ # Generate ideas
+ workflow = IdeaGenerationWorkflow(api_key=self.api_key, base_url=self.base_url)
+
+ print("🔍 Generating research ideas...")
+ result = await workflow.process(knowledge_points)
+
+ print("\n" + "=" * 70)
+ print("✅ Research idea generation completed!")
+ print("=" * 70)
+ print(result)
+ print("=" * 70)
+
+ except Exception as e:
+ logger.section("Generation failed")
+ logger.error(str(e))
+ import traceback
+
+ logger.debug("Debug information:")
+ logger.debug(traceback.format_exc())
+
+ def run_web_mode(self):
+ """Start web service"""
+ print("\n" + "=" * 70)
+ print("🌐 Start Web Service")
+ print("=" * 70)
+ print("1. Start backend API only (port 8000)")
+ print("2. Start frontend only (port 3000)")
+ print("3. Start both frontend and backend")
+ print("4. Return to main menu")
+ print("=" * 70)
+
+ while True:
+ choice = input("\nPlease select (1-4): ").strip()
+ if choice == "1":
+ print("\n🚀 Starting backend service...")
+ print("Command: python -m uvicorn api.main:app --host 0.0.0.0 --port 8000 --reload")
+ print("-" * 70)
+ import subprocess
+
+ subprocess.run(
+ [
+ sys.executable,
+ "-m",
+ "uvicorn",
+ "api.main:app",
+ "--host",
+ "0.0.0.0",
+ "--port",
+ "8000",
+ "--reload",
+ ],
+ check=False,
+ )
+ break
+ if choice == "2":
+ print("\n🚀 Starting frontend service...")
+ print("Command: cd web && npm run dev")
+ print("-" * 70)
+ import subprocess
+
+ web_dir = Path(__file__).parent / "web"
+ subprocess.run(["npm", "run", "dev"], check=False, cwd=web_dir)
+ break
+ if choice == "3":
+ print("\n🚀 Starting both frontend and backend services...")
+ print("Command: python start_web.py")
+ print("-" * 70)
+ import subprocess
+
+ subprocess.run([sys.executable, "start_web.py"], check=False)
+ break
+ if choice == "4":
+ return
+ print("❌ Invalid option, please try again")
+
+ def show_settings(self):
+ """Display settings"""
+ print("\n" + "=" * 70)
+ print("⚙️ System Settings")
+ print("=" * 70)
+
+ # Display LLM configuration
+ try:
+ llm_config = get_llm_config()
+ print("\n📦 LLM Configuration:")
+ print(f" Model: {llm_config.get('model', 'N/A')}")
+ print(f" API Endpoint: {llm_config.get('base_url', 'N/A')}")
+ print(f" API Key: {'Configured' if llm_config.get('api_key') else 'Not configured'}")
+ except Exception as e:
+ print(f" ❌ Load failed: {e}")
+
+ # Display knowledge bases
+ print("\n📚 Available knowledge bases:")
+ for i, kb in enumerate(self.available_kbs, 1):
+ print(f" {i}. {kb}")
+
+ # Display configuration file locations
+ print("\n📁 Configuration file locations:")
+ env_files = [".env", "OpenTutor.env"]
+ for env_file in env_files:
+ env_path = Path(__file__).parent / env_file
+ if env_path.exists():
+ print(f" ✅ {env_path}")
+ else:
+ print(f" ⚪ {env_path} (not found)")
+
+ print("\n" + "=" * 70)
+ print(
+ "💡 Tip: To modify settings, edit the .env file directly, or use the Settings page in the Web interface"
+ )
+ print("=" * 70)
+
+ input("\nPress Enter to return to main menu...")
+
+ async def run(self):
+ """Run main loop"""
+ while True:
+ try:
+ choice = self.show_main_menu()
+
+ if choice == "1":
+ await self.run_solve_mode()
+ elif choice == "2":
+ await self.run_question_mode()
+ elif choice == "3":
+ await self.run_research_mode()
+ elif choice == "4":
+ await self.run_ideagen_mode()
+ elif choice == "5":
+ self.run_web_mode()
+ continue # Don't ask to continue after web mode
+ elif choice == "6":
+ self.show_settings()
+ continue # Don't ask to continue after settings
+ elif choice == "7":
+ print("\n" + "=" * 70)
+ print("👋 Thank you for using OpenTutor Intelligent Teaching Assistant System!")
+ print("=" * 70)
+ break
+
+ # Ask if continue
+ print("\n" + "-" * 70)
+ continue_choice = input("Continue using? (y/n) [default: y]: ").strip().lower()
+ if continue_choice == "n":
+ print("\n" + "=" * 70)
+ print("👋 Thank you for using OpenTutor Intelligent Teaching Assistant System!")
+ print("=" * 70)
+ break
+
+ except KeyboardInterrupt:
+ print("\n\n" + "=" * 70)
+ print("👋 Program interrupted, thank you for using!")
+ print("=" * 70)
+ break
+ except Exception as e:
+ print(f"\n❌ Error occurred: {e!s}")
+ print("Please retry or exit the program")
+
+
+def main():
+ """Main function"""
+ try:
+ starter = AITutorStarter()
+ asyncio.run(starter.run())
+ except Exception as e:
+ logger.error(f"Startup failed: {e!s}")
+ sys.exit(1)
+
+
+if __name__ == "__main__":
+ # Initialize user data directories
+ try:
+ from src.core.setup import init_user_directories
+
+ init_user_directories(project_root)
+ except Exception as e:
+ logger.warning(f"Failed to initialize user directories: {e}")
+ logger.info("Continuing anyway...")
+
+ main()
diff --git a/scripts/start_web.py b/scripts/start_web.py
new file mode 100644
index 000000000..3269dc811
--- /dev/null
+++ b/scripts/start_web.py
@@ -0,0 +1,373 @@
+import os
+from pathlib import Path
+import shutil
+import subprocess
+import sys
+import time
+
+# 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)
+
+
+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 configuration
+ try:
+ from src.core.setup import get_backend_port
+
+ backend_port = get_backend_port(Path(project_root))
+ print_flush(f"✅ Backend port configured: {backend_port}")
+ except SystemExit:
+ # Port configuration error already printed
+ raise
+ except Exception as e:
+ print_flush(f"❌ Failed to get backend port: {e}")
+ from src.core.setup import print_port_config_tutorial
+
+ print_port_config_tutorial()
+ raise
+
+ # 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"
+
+ process = subprocess.Popen(
+ cmd,
+ cwd=project_root, # Run in project root directory, not scripts directory
+ stdout=subprocess.PIPE,
+ stderr=subprocess.STDOUT,
+ text=True,
+ bufsize=1,
+ shell=False,
+ encoding="utf-8",
+ errors="replace",
+ env=env,
+ )
+
+ # Start a thread to output logs in real-time
+ import threading
+
+ 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})")
+ 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 configuration
+ try:
+ from pathlib import Path
+
+ from src.core.setup import get_frontend_port
+
+ frontend_port = get_frontend_port(Path(project_root))
+ print_flush(f"✅ Frontend port configured: {frontend_port}")
+ except SystemExit:
+ # Port configuration error already printed
+ raise
+ except Exception as e:
+ print_flush(f"❌ Failed to get frontend port: {e}")
+ from src.core.setup import print_port_config_tutorial
+
+ print_port_config_tutorial()
+ raise
+
+ # 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:
+ process = subprocess.Popen(
+ "npm install",
+ cwd=web_dir,
+ shell=True,
+ 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()}")
+
+ process.wait()
+
+ 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
+
+ print_flush("🚀 Starting Next.js development server...")
+ # Get backend port for frontend API configuration
+ from pathlib import Path
+
+ from src.core.setup import get_backend_port
+
+ backend_port = get_backend_port(Path(project_root))
+
+ # 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("# Do not manually edit this file - it will be overwritten on startup\n")
+ f.write("# To change the backend port, edit config/main.yaml instead\n")
+ f.write("# ============================================\n\n")
+ f.write(f"NEXT_PUBLIC_API_BASE=http://localhost:{backend_port}\n")
+ print_flush(f"✅ Updated .env.local with backend port: {backend_port}")
+ except Exception as e:
+ print_flush(f"⚠️ Warning: Failed to update .env.local: {e}")
+ print_flush(" Continuing with environment variables only...")
+
+ # Set environment variables for Next.js (as backup)
+ env = os.environ.copy()
+ env["PORT"] = str(frontend_port)
+ env["NEXT_PUBLIC_API_BASE"] = f"http://localhost:{backend_port}"
+ # Set encoding environment variables for Windows
+ env["PYTHONIOENCODING"] = "utf-8"
+ env["PYTHONUTF8"] = "1"
+ if os.name == "nt":
+ env["PYTHONLEGACYWINDOWSSTDIO"] = "0"
+
+ frontend_process = subprocess.Popen(
+ f"npm run dev -- -p {frontend_port}",
+ cwd=web_dir,
+ shell=True,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.STDOUT,
+ text=True,
+ bufsize=1,
+ env=env,
+ encoding="utf-8",
+ errors="replace",
+ )
+
+ # 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})")
+ return frontend_process
+
+
+if __name__ == "__main__":
+ print_flush("=" * 50)
+ print_flush("OpenTutor Web Platform Launcher")
+ print_flush("=" * 50)
+
+ # Initialize user data directories
+ try:
+ 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.core.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.core.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.core.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:
+ if backend.poll() is not None:
+ print_flush(
+ f"\n❌ Backend process exited unexpectedly (code: {backend.returncode})"
+ )
+ break
+ 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()
+ finally:
+ if backend:
+ try:
+ if os.name == "nt":
+ subprocess.run(
+ ["taskkill", "/F", "/T", "/PID", str(backend.pid)],
+ check=False,
+ stderr=subprocess.DEVNULL,
+ stdout=subprocess.DEVNULL,
+ )
+ else:
+ backend.terminate()
+ backend.wait(timeout=5)
+ except Exception as e:
+ print_flush(f"Error stopping backend: {e}")
+
+ if frontend:
+ try:
+ if os.name == "nt":
+ subprocess.run(
+ ["taskkill", "/F", "/T", "/PID", str(frontend.pid)],
+ check=False,
+ stderr=subprocess.DEVNULL,
+ stdout=subprocess.DEVNULL,
+ )
+ else:
+ frontend.terminate()
+ frontend.wait(timeout=5)
+ except Exception as e:
+ print_flush(f"Error stopping frontend: {e}")
+
+ print_flush("✅ Services stopped.")
diff --git a/src/__init__.py b/src/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/src/agents/__init__.py b/src/agents/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/src/agents/co_writer/README.md b/src/agents/co_writer/README.md
new file mode 100644
index 000000000..ae87705d4
--- /dev/null
+++ b/src/agents/co_writer/README.md
@@ -0,0 +1,337 @@
+# 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/co-writer/`:
+
+```
+data/user/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 `config/main.yaml`:
+
+```yaml
+tts:
+ default_voice: "Cherry" # Default voice
+ default_language: "English" # Default language
+```
+
+### Environment Variables
+
+Required for TTS (in `.env` or `OpenTutor.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_BINDING_API_KEY=your_api_key
+LLM_BINDING_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 `config/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/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__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/src/agents/co_writer/edit_agent.py b/src/agents/co_writer/edit_agent.py
new file mode 100644
index 000000000..42e987695
--- /dev/null
+++ b/src/agents/co_writer/edit_agent.py
@@ -0,0 +1,328 @@
+from datetime import datetime
+import json
+import logging
+from pathlib import Path
+import sys
+from typing import Any, Literal
+import uuid
+
+from lightrag.llm.openai import openai_complete_if_cache
+import yaml
+
+from src.core.core import get_agent_params, get_llm_config
+from src.tools.rag_tool import rag_search
+from src.tools.web_search import web_search
+
+
+def _load_prompts(language: str = "en") -> dict:
+ """Load prompts from YAML file based on language"""
+ prompts_dir = Path(__file__).parent / "prompts" / language
+ prompt_file = prompts_dir / "edit_agent.yaml"
+ if prompt_file.exists():
+ with open(prompt_file, encoding="utf-8") as f:
+ return yaml.safe_load(f)
+ # Fallback to English if language file not found
+ fallback_file = Path(__file__).parent / "prompts" / "en" / "edit_agent.yaml"
+ if fallback_file.exists():
+ with open(fallback_file, encoding="utf-8") as f:
+ return yaml.safe_load(f)
+ return {}
+
+
+# Add project root for logs import
+_project_root = Path(__file__).parent.parent.parent.parent
+if str(_project_root) not in sys.path:
+ sys.path.insert(0, str(_project_root))
+
+from src.core.core import load_config_with_main
+from src.core.logging import LLMStats, get_logger
+
+# Initialize logger with config
+try:
+ config = load_config_with_main(
+ "solve_config.yaml", _project_root
+ ) # Use any config to get main.yaml
+ log_dir = config.get("paths", {}).get("user_log_dir") or config.get("logging", {}).get(
+ "log_dir"
+ )
+ logger = get_logger("CoWriter", log_dir=log_dir)
+except Exception:
+ # Fallback to standard logging
+ logger = logging.getLogger(__name__)
+
+# Shared stats tracker for co_writer
+_co_writer_stats: LLMStats | None = None
+
+
+def get_stats() -> LLMStats:
+ """Get or create shared stats tracker."""
+ global _co_writer_stats
+ if _co_writer_stats is None:
+ _co_writer_stats = LLMStats(module_name="CoWriter")
+ return _co_writer_stats
+
+
+def reset_stats():
+ """Reset shared stats."""
+ global _co_writer_stats
+ if _co_writer_stats:
+ _co_writer_stats.reset()
+
+
+def print_stats():
+ """Print stats summary."""
+ global _co_writer_stats
+ if _co_writer_stats:
+ _co_writer_stats.print_summary()
+
+
+USER_DIR = Path(__file__).parent.parent.parent.parent / "data" / "user" / "co-writer"
+HISTORY_FILE = USER_DIR / "history.json"
+TOOL_CALLS_DIR = USER_DIR / "tool_calls"
+
+
+def ensure_dirs():
+ """Ensure directories exist"""
+ USER_DIR.mkdir(parents=True, exist_ok=True)
+ TOOL_CALLS_DIR.mkdir(parents=True, exist_ok=True)
+
+
+def load_history() -> list:
+ """Load history"""
+ ensure_dirs()
+ if HISTORY_FILE.exists():
+ try:
+ with open(HISTORY_FILE, encoding="utf-8") as f:
+ return json.load(f)
+ except:
+ return []
+ return []
+
+
+def save_history(history: list):
+ """Save history"""
+ ensure_dirs()
+ with open(HISTORY_FILE, "w", encoding="utf-8") as f:
+ json.dump(history, f, ensure_ascii=False, indent=2)
+
+
+def save_tool_call(call_id: str, tool_type: str, data: dict[str, Any]) -> str:
+ """Save tool call result, return file path"""
+ ensure_dirs()
+ filename = f"{call_id}_{tool_type}.json"
+ filepath = TOOL_CALLS_DIR / filename
+ with open(filepath, "w", encoding="utf-8") as f:
+ json.dump(data, f, ensure_ascii=False, indent=2)
+ return str(filepath)
+
+
+class EditAgent:
+ def __init__(self, language: str = "en"):
+ # Load agent parameters from unified config (agents.yaml)
+ self._agent_params = get_agent_params("co_writer")
+ self.language = language
+ self._prompts = _load_prompts(language)
+
+ try:
+ self.llm_config = get_llm_config()
+ except Exception as e:
+ logger.error(f"Failed to load LLM config: {e}")
+ self.llm_config = None
+
+ async def process(
+ self,
+ text: str,
+ instruction: str,
+ action: Literal["rewrite", "shorten", "expand"] = "rewrite",
+ source: Literal["rag", "web"] | None = None,
+ kb_name: str | None = None,
+ ) -> dict[str, Any]:
+ """
+ Process edit request
+
+ Returns:
+ Dict containing:
+ - edited_text: Edited text
+ - operation_id: Operation ID
+ """
+ if not self.llm_config:
+ raise ValueError("LLM configuration not available")
+
+ operation_id = datetime.now().strftime("%Y%m%d_%H%M%S") + "_" + uuid.uuid4().hex[:6]
+
+ context = ""
+ tool_call_file = None
+ tool_call_data = None
+
+ if source == "rag":
+ if not kb_name:
+ logger.warning("RAG source selected but no kb_name provided, skipping RAG search")
+ source = None
+ else:
+ logger.info(f"Searching RAG in KB: {kb_name} for: {instruction}")
+ try:
+ search_result = await rag_search(
+ query=instruction, kb_name=kb_name, mode="naive", only_need_context=True
+ )
+ context = search_result.get("answer", "")
+ logger.info(f"RAG context found: {len(context)} chars")
+
+ tool_call_data = {
+ "type": "rag",
+ "timestamp": datetime.now().isoformat(),
+ "operation_id": operation_id,
+ "query": instruction,
+ "kb_name": kb_name,
+ "mode": "naive",
+ "context": context,
+ "raw_result": search_result,
+ }
+ tool_call_file = save_tool_call(operation_id, "rag", tool_call_data)
+ except Exception as e:
+ logger.error(f"RAG search failed: {e}, continuing without context")
+ source = None
+
+ elif source == "web":
+ logger.info(f"Searching Web for: {instruction}")
+ try:
+ search_result = web_search(instruction)
+ context = search_result.get("answer", "")
+ logger.info(f"Web context found: {len(context)} chars")
+
+ tool_call_data = {
+ "type": "web_search",
+ "timestamp": datetime.now().isoformat(),
+ "operation_id": operation_id,
+ "query": instruction,
+ "answer": context,
+ "citations": search_result.get("citations", []),
+ "search_results": search_result.get("search_results", []),
+ "usage": search_result.get("usage", {}),
+ }
+ tool_call_file = save_tool_call(operation_id, "web", tool_call_data)
+ except Exception as e:
+ logger.error(f"Web search failed: {e}, continuing without context")
+ source = None
+
+ # 2. Construct Prompt
+ system_prompt = self._prompts.get(
+ "system", "You are an expert editor and writing assistant."
+ )
+
+ action_verbs = {"rewrite": "Rewrite", "shorten": "Shorten", "expand": "Expand"}
+ action_verb = action_verbs.get(action, "Rewrite")
+
+ action_template = self._prompts.get(
+ "action_template",
+ "{action_verb} the following text based on the user's instruction.\n\nUser Instruction: {instruction}\n\n",
+ )
+ user_prompt = action_template.format(action_verb=action_verb, instruction=instruction)
+
+ if context:
+ context_template = self._prompts.get(
+ "context_template", "Reference Context:\n{context}\n\n"
+ )
+ user_prompt += context_template.format(context=context)
+
+ text_template = self._prompts.get(
+ "user_template",
+ "Target Text to Edit:\n{text}\n\nOutput only the edited text, without quotes or explanations.",
+ )
+ user_prompt += text_template.format(text=text)
+
+ # 3. Call LLM
+ logger.info(f"Calling LLM for {action}...")
+ model = self.llm_config["model"]
+ response = await openai_complete_if_cache(
+ model=model,
+ prompt=user_prompt,
+ system_prompt=system_prompt,
+ api_key=self.llm_config["api_key"],
+ base_url=self.llm_config["base_url"],
+ temperature=self._agent_params["temperature"],
+ max_tokens=self._agent_params["max_tokens"],
+ )
+
+ # Track token usage
+ stats = get_stats()
+ stats.add_call(
+ model=model, system_prompt=system_prompt, user_prompt=user_prompt, response=response
+ )
+
+ # 4. Record operation history
+ history = load_history()
+ operation_record = {
+ "id": operation_id,
+ "timestamp": datetime.now().isoformat(),
+ "action": action,
+ "source": source,
+ "kb_name": kb_name,
+ "input": {"original_text": text, "instruction": instruction},
+ "output": {"edited_text": response},
+ "tool_call_file": tool_call_file,
+ "model": self.llm_config["model"],
+ }
+ history.append(operation_record)
+ save_history(history)
+
+ logger.info(f"Operation {operation_id} recorded successfully")
+
+ return {"edited_text": response, "operation_id": operation_id}
+
+ async def auto_mark(self, text: str) -> dict[str, Any]:
+ """
+ AI auto-marking feature - Add annotation tags to text
+
+ Returns:
+ Dict containing:
+ - marked_text: Text with annotations
+ - operation_id: Operation ID
+ """
+ if not self.llm_config:
+ raise ValueError("LLM configuration not available")
+
+ operation_id = datetime.now().strftime("%Y%m%d_%H%M%S") + "_" + uuid.uuid4().hex[:6]
+
+ system_prompt = self._prompts.get("auto_mark_system", "")
+ user_template = self._prompts.get(
+ "auto_mark_user_template", "Process the following text:\n{text}"
+ )
+ user_prompt = user_template.format(text=text)
+
+ logger.info("Calling LLM for auto-mark...")
+ model = self.llm_config["model"]
+ response = await openai_complete_if_cache(
+ model=model,
+ prompt=user_prompt,
+ system_prompt=system_prompt,
+ api_key=self.llm_config["api_key"],
+ base_url=self.llm_config["base_url"],
+ temperature=self._agent_params["temperature"],
+ max_tokens=self._agent_params["max_tokens"],
+ )
+
+ # Track token usage
+ stats = get_stats()
+ stats.add_call(
+ model=model, system_prompt=system_prompt, user_prompt=user_prompt, response=response
+ )
+
+ # Record operation history
+ history = load_history()
+ operation_record = {
+ "id": operation_id,
+ "timestamp": datetime.now().isoformat(),
+ "action": "automark",
+ "source": None,
+ "kb_name": None,
+ "input": {"original_text": text, "instruction": "AI Auto Mark"},
+ "output": {"edited_text": response},
+ "tool_call_file": None,
+ "model": self.llm_config["model"],
+ }
+ history.append(operation_record)
+ save_history(history)
+
+ logger.info(f"Auto-mark operation {operation_id} recorded successfully")
+
+ return {"marked_text": response, "operation_id": operation_id}
diff --git a/src/agents/co_writer/narrator_agent.py b/src/agents/co_writer/narrator_agent.py
new file mode 100644
index 000000000..ffa68f60a
--- /dev/null
+++ b/src/agents/co_writer/narrator_agent.py
@@ -0,0 +1,440 @@
+#!/usr/bin/env python
+"""
+NarratorAgent - Note Narration Agent
+Converts note content into narration scripts and generates TTS audio using OpenAI API
+"""
+
+from datetime import datetime
+import json
+import logging
+from pathlib import Path
+import re
+import sys
+from typing import Any
+from urllib.parse import urlparse
+import uuid
+
+from openai import OpenAI
+import yaml
+
+
+def _load_prompts(language: str = "en") -> dict:
+ """Load prompts from YAML file based on language"""
+ prompts_dir = Path(__file__).parent / "prompts" / language
+ prompt_file = prompts_dir / "narrator_agent.yaml"
+ if prompt_file.exists():
+ with open(prompt_file, encoding="utf-8") as f:
+ return yaml.safe_load(f)
+ # Fallback to English if language file not found
+ fallback_file = Path(__file__).parent / "prompts" / "en" / "narrator_agent.yaml"
+ if fallback_file.exists():
+ with open(fallback_file, encoding="utf-8") as f:
+ return yaml.safe_load(f)
+ return {}
+
+
+# Add project root for logs import
+_project_root = Path(__file__).parent.parent.parent.parent
+if str(_project_root) not in sys.path:
+ sys.path.insert(0, str(_project_root))
+
+from lightrag.llm.openai import openai_complete_if_cache
+
+from src.core.core import get_agent_params, get_llm_config, get_tts_config, load_config_with_main
+from src.core.logging import get_logger
+
+# Initialize logger with config
+try:
+ config = load_config_with_main(
+ "solve_config.yaml", _project_root
+ ) # Use any config to get main.yaml
+ log_dir = config.get("paths", {}).get("user_log_dir") or config.get("logging", {}).get(
+ "log_dir"
+ )
+ logger = get_logger("Narrator", log_dir=log_dir)
+except Exception:
+ # Fallback to standard logging
+ logger = logging.getLogger(__name__)
+
+# Import shared stats from edit_agent
+from .edit_agent import get_stats
+
+# Define storage path (unified under user/co-writer/ directory)
+# Notes:
+# - Consistent with EditAgent's history records, both use user/co-writer as root directory
+# - Audio files are stored separately in audio subdirectory for static access via /api/outputs
+USER_DIR = Path(__file__).parent.parent.parent.parent / "data" / "user" / "co-writer" / "audio"
+
+
+def ensure_dirs():
+ """Ensure directories exist"""
+ USER_DIR.mkdir(parents=True, exist_ok=True)
+
+
+class NarratorAgent:
+ """Note Narration Agent - Generate narration script and convert to audio"""
+
+ def __init__(self, language: str = "en"):
+ # Load agent parameters from unified config (agents.yaml)
+ # Note: narrator uses independent config for TTS integration
+ self._agent_params = get_agent_params("narrator")
+ self.language = language
+ self._prompts = _load_prompts(language)
+
+ try:
+ self.llm_config = get_llm_config()
+ except Exception as e:
+ logger.error(f"Failed to load LLM config: {e}")
+ self.llm_config = None
+
+ # Load main config file to get TTS default settings
+ try:
+ config = load_config_with_main("solve_config.yaml", _project_root)
+ self.tts_settings = config.get("tts", {})
+ self.default_voice = self.tts_settings.get("default_voice", "alloy")
+ logger.info(f"TTS settings loaded from config: voice={self.default_voice}")
+ except Exception as e:
+ logger.warning(f"Failed to load TTS settings from config, using defaults: {e}")
+ self.default_voice = "alloy"
+
+ try:
+ self.tts_config = get_tts_config()
+ # Validate TTS configuration
+ self._validate_tts_config()
+ except Exception as e:
+ logger.error(f"Failed to load TTS config: {e}", exc_info=True)
+ self.tts_config = None
+
+ 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
+ logger.info("TTS Configuration Loaded (OpenAI API):")
+ logger.info(f" Model: {model}")
+ logger.info(f" Base URL: {base_url}")
+ logger.info(f" API Key: {api_key_preview}")
+ logger.info(f" Default Voice: {self.default_voice}")
+
+ 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
+ """
+ if not self.llm_config:
+ raise ValueError("LLM configuration not available")
+
+ # Estimate target length: OpenAI TTS supports up to 4096 characters
+ # We target 4000 characters to leave some margin
+ target_length = 4000
+ is_long_content = len(content) > 5000
+
+ style_prompts = {
+ "friendly": self._prompts.get("style_friendly", ""),
+ "academic": self._prompts.get("style_academic", ""),
+ "concise": self._prompts.get("style_concise", ""),
+ }
+
+ length_instruction = (
+ self._prompts.get("length_instruction_long", "")
+ if is_long_content
+ else self._prompts.get("length_instruction_short", "")
+ )
+
+ system_template = self._prompts.get("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._prompts.get("generate_script_user_long", "")
+ user_prompt = user_template.format(content=content[:8000] + "...")
+ else:
+ user_template = self._prompts.get("generate_script_user_short", "")
+ user_prompt = user_template.format(content=content)
+
+ logger.info(f"Generating narration script with style: {style}")
+
+ model = self.llm_config["model"]
+ response = await openai_complete_if_cache(
+ model=model,
+ prompt=user_prompt,
+ system_prompt=system_prompt,
+ api_key=self.llm_config["api_key"],
+ base_url=self.llm_config["base_url"],
+ max_tokens=self._agent_params["max_tokens"],
+ temperature=self._agent_params["temperature"],
+ )
+
+ # Track token usage
+ stats = get_stats()
+ stats.add_call(
+ model=model, system_prompt=system_prompt, user_prompt=user_prompt, response=response
+ )
+
+ # Clean and truncate response, ensure it doesn't exceed 4000 characters
+ script = response.strip()
+ if len(script) > 4000:
+ 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"""
+ if not self.llm_config:
+ return []
+
+ system_prompt = self._prompts.get("extract_key_points_system", "")
+ user_template = self._prompts.get(
+ "extract_key_points_user",
+ "Please extract key points from the following notes:\n\n{content}",
+ )
+ user_prompt = user_template.format(content=content[:4000])
+
+ try:
+ model = self.llm_config["model"]
+ response = await openai_complete_if_cache(
+ model=model,
+ prompt=user_prompt,
+ system_prompt=system_prompt,
+ api_key=self.llm_config["api_key"],
+ base_url=self.llm_config["base_url"],
+ max_tokens=self._agent_params["max_tokens"],
+ temperature=self._agent_params["temperature"],
+ )
+
+ # Track token usage
+ stats = get_stats()
+ stats.add_call(
+ model=model, system_prompt=system_prompt, user_prompt=user_prompt, response=response
+ )
+
+ # 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:
+ 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:
+ 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 + "..."
+ 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
+
+ logger.info(f"Starting TTS audio generation - ID: {audio_id}, Voice: {voice}")
+
+ try:
+ # Create OpenAI client with custom base_url
+ client = OpenAI(
+ base_url=self.tts_config["base_url"], api_key=self.tts_config["api_key"]
+ )
+
+ # Call OpenAI TTS API
+ response = client.audio.speech.create(
+ model=self.tts_config["model"], voice=voice, input=script
+ )
+
+ # Save audio to file
+ response.stream_to_file(audio_path)
+
+ logger.info(f"Audio saved to: {audio_path}")
+
+ # Use correct path: co-writer/audio (matching the actual storage directory)
+ relative_path = f"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:
+ 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
+ """
+ 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:
+ 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/co_writer/prompts/en/edit_agent.yaml b/src/agents/co_writer/prompts/en/edit_agent.yaml
new file mode 100644
index 000000000..5f5f9c56d
--- /dev/null
+++ b/src/agents/co_writer/prompts/en/edit_agent.yaml
@@ -0,0 +1,113 @@
+system: |
+ You are an expert editor and writing assistant.
+
+action_template: |
+ {action_verb} the following text based on the user's instruction.
+
+ User Instruction: {instruction}
+
+context_template: |
+ Reference Context:
+ {context}
+
+user_template: |
+ Target Text to Edit:
+ {text}
+
+ Output only the edited text, without quotes or explanations.
+
+auto_mark_system: |
+ You are a professional academic reading annotation assistant, helping readers quickly grasp the core points of text.
+
+ ## Task
+ Read the input text and **carefully select** the most critical information for annotation. Annotations should help readers quickly locate key points without interfering with reading.
+
+ ## Available Tags and Precise Usage Scenarios
+
+ ### 1. Circle - Use Sparingly
+ ```html
+ <span data-rough-notation="circle">content</span>
+ ```
+ **Applicable Scenarios**:
+ - Core topic words of articles/paragraphs (e.g., key concepts in paper titles)
+ - Unique proper nouns, model names (e.g., GPT-4, BERT)
+ - Key numerical values/metrics (e.g., 95.7%, p<0.05)
+
+ **Limitation**: Maximum 1 per 100 characters, content should not exceed 5 characters
+
+ ### 2. Highlight - Moderate Use
+ ```html
+ <span data-rough-notation="highlight">content</span>
+ ```
+ **Applicable Scenarios**:
+ - Definitional statements (e.g., "XX refers to...")
+ - First appearance of core concepts and their explanations
+ - Important methodological descriptions
+
+ **Limitation**: Maximum 2 per paragraph, content 2-15 characters
+
+ ### 3. Box - Minimal Use
+ ```html
+ <span data-rough-notation="box">content</span>
+ ```
+ **Applicable Scenarios**:
+ - Mathematical formulas, equations
+ - Specific data points or statistical values
+ - Code snippets, commands
+ - Version numbers, dates, and other precise information
+
+ **Limitation**: Maximum 1 per paragraph, content should not exceed 20 characters
+
+ ### 4. Underline - Moderate Use
+ ```html
+ <span data-rough-notation="underline">content</span>
+ ```
+ **Applicable Scenarios**:
+ - Conclusive statements
+ - Key expressions of causal relationships
+ - Core viewpoints in comparisons or contrasts
+ - Author's main arguments
+
+ **Limitation**: Maximum 1 per paragraph, content 5-30 characters
+
+ ### 5. Bracket - Use Sparingly
+ ```html
+ <span data-rough-notation="bracket">content</span>
+ ```
+ **Applicable Scenarios**:
+ - Entire paragraphs that are core summaries or conclusions
+ - Important quotations or theorem statements
+ - Critical warnings or notes
+
+ **Limitation**: Maximum 1-2 per entire article, for truly indispensable complete sentences
+
+ ## Core Rules
+
+ 1. **Exercise Restraint**: Better to annotate less than to over-annotate. Annotation density should not exceed 10% of total text per paragraph.
+ 2. **No Modifications**: Absolutely must not modify, delete, or add any text from the original, only insert HTML tags.
+ 3. **Tag Placement**: Tags must be placed inside Markdown symbols (e.g., `**`, `*`, `` ` ``).
+ 4. **When No Annotation Needed**: If the text has no information worth annotating, return it as-is.
+
+ ## Examples
+
+ **Input**:
+ Deep learning is a subfield of machine learning, and its core is using neural networks to learn data representations.
+
+ **Output**:
+ <span data-rough-notation="highlight">Deep learning is a subfield of machine learning</span>, and its core is using <span data-rough-notation="circle">neural networks</span> to learn data representations.
+
+ **Input**:
+ The weather is nice today, perfect for going out for a walk.
+
+ **Output**:
+ The weather is nice today, perfect for going out for a walk.
+
+ **Input**:
+ Experimental results show that our proposed method achieved 99.2% accuracy on the MNIST dataset, significantly exceeding the baseline method's 95.1%.
+
+ **Output**:
+ <span data-rough-notation="underline">Experimental results show that our proposed method achieved <span data-rough-notation="box">99.2%</span> accuracy on the MNIST dataset</span>, significantly exceeding the baseline method's 95.1%.
+
+auto_mark_user_template: |
+ Process the following text:
+ {text}
diff --git a/src/agents/co_writer/prompts/en/narrator_agent.yaml b/src/agents/co_writer/prompts/en/narrator_agent.yaml
new file mode 100644
index 000000000..35ee73871
--- /dev/null
+++ b/src/agents/co_writer/prompts/en/narrator_agent.yaml
@@ -0,0 +1,88 @@
+style_friendly: |
+ You are a friendly and approachable tutor, explaining note content face-to-face to students.
+
+ **Narration Requirements**:
+ 1. **Person**: Use "we", "us", "you" to create closeness
+ 2. **Tone**: Relaxed but professional, like chatting with a friend
+ 3. **Pacing**: Appropriate pauses, use words like "well", "next", "so" for transitions
+ 4. **Emphasis**: Use phrases like "this is important", "note here" to highlight key information
+ 5. **Interaction**: Appropriately include phrases like "what do you think", "think about it" to guide thinking
+ 6. **Length Control**: The script should be controlled within 4000 characters. If the original content is long, please generate a refined summary version, highlighting main points and key information.
+
+style_academic: |
+ You are a senior scholar giving an academic lecture.
+
+ **Narration Requirements**:
+ 1. **Person**: Use "we", "this paper" and other academic language
+ 2. **Tone**: Rigorous and professional, with clear logic
+ 3. **Structure**: Clear introduction-body-conclusion structure
+ 4. **Terminology**: Retain professional terms, provide explanations when necessary
+ 5. **Citations**: Maintain academic standards when mentioning related theories or research
+ 6. **Length Control**: The script should be controlled within 4000 characters. If the original content is long, please generate a refined summary version, highlighting main points and key information.
+
+style_concise: |
+ You are an efficient knowledge communicator who needs to quickly convey core information.
+
+ **Narration Requirements**:
+ 1. **Person**: Use "we" to maintain friendliness
+ 2. **Tone**: Direct and to the point, no beating around the bush
+ 3. **Structure**: General first, then details, get straight to the point
+ 4. **Focus**: Only cover the most core content
+ 5. **Transitions**: Use concise "first", "then", "finally" to connect
+ 6. **Length Control**: The script should be controlled within 4000 characters. If the original content is long, please generate a refined summary version, highlighting main points and key information.
+
+generate_script_system_template: |
+ You are a professional note narration script writing expert. Your task is to convert user's note content into a script suitable for oral narration.
+
+ {style_prompt}
+
+ {length_instruction}
+
+ **Output Format**:
+ Output the narration script text directly, without any additional explanations or markers.
+ The script should be coherent spoken language, suitable for direct reading aloud.
+
+ **Notes**:
+ 1. Maintain the core information and logical structure of the original text
+ 2. Convert Markdown formats (such as **bold**, *italic*, code blocks, etc.) into oral descriptions
+ 3. Mathematical formulas need to be described orally, such as "x squared plus y squared equals z squared"
+ 4. Remove all HTML tags, retain their text content
+ 5. Avoid overly written expressions
+ 6. **Control the length within 4000 characters**
+
+length_instruction_long: |
+ **Important: The script should be controlled within 4000 characters. If the original content is long, please generate a refined summary version, retaining the most core viewpoints and key information.**
+
+length_instruction_short: |
+ **Important: The script should be controlled within 4000 characters.**
+
+generate_script_user_long: |
+ The following is a longer note content. Please generate a refined narration script summary, controlled within 4000 characters, containing the most core viewpoints and key information:
+
+ ---
+ {content}
+ ---
+
+ Please generate a narration script suitable for oral reading (within 4000 characters).
+
+generate_script_user_short: |
+ Please convert the following note content into a narration script (controlled within 4000 characters):
+
+ ---
+ {content}
+ ---
+
+ Please generate a narration script suitable for oral reading.
+
+extract_key_points_system: |
+ You are a content analysis expert. Please extract 3-5 key points from the given notes.
+
+ Output format: JSON array, each element is a key point string.
+ Example: ["Key point 1", "Key point 2", "Key point 3"]
+
+ Only output the JSON array, no other content.
+
+extract_key_points_user: |
+ Please extract key points from the following notes:
+
+ {content}
diff --git a/src/agents/co_writer/prompts/zh/edit_agent.yaml b/src/agents/co_writer/prompts/zh/edit_agent.yaml
new file mode 100644
index 000000000..7c572ee06
--- /dev/null
+++ b/src/agents/co_writer/prompts/zh/edit_agent.yaml
@@ -0,0 +1,113 @@
+system: |
+ 你是一位专业的编辑和写作助手。
+
+action_template: |
+ 根据用户的指令{action_verb}以下文本。
+
+ 用户指令:{instruction}
+
+context_template: |
+ 参考上下文:
+ {context}
+
+user_template: |
+ 要编辑的目标文本:
+ {text}
+
+ 只输出编辑后的文本,不要包含引号或解释。
+
+auto_mark_system: |
+ 你是一位专业的学术阅读标注助手,帮助读者快速掌握文本的核心要点。
+
+ ## 任务
+ 阅读输入文本,**精心选择**最关键的信息进行标注。标注应帮助读者快速定位关键点,而不干扰阅读。
+
+ ## 可用标签及精确使用场景
+
+ ### 1. Circle(圈注)- 谨慎使用
+ ```html
+ <span data-rough-notation="circle">内容</span>
+ ```
+ **适用场景**:
+ - 文章/段落的核心主题词(如论文标题中的关键概念)
+ - 独特的专有名词、模型名称(如GPT-4、BERT)
+ - 关键数值/指标(如95.7%、p<0.05)
+
+ **限制**:每100字符最多1个,内容不超过5个字符
+
+ ### 2. Highlight(高亮)- 适度使用
+ ```html
+ <span data-rough-notation="highlight">内容</span>
+ ```
+ **适用场景**:
+ - 定义性陈述(如"XX是指...")
+ - 核心概念首次出现及其解释
+ - 重要的方法论描述
+
+ **限制**:每段最多2个,内容2-15个字符
+
+ ### 3. Box(方框)- 最少使用
+ ```html
+ <span data-rough-notation="box">内容</span>
+ ```
+ **适用场景**:
+ - 数学公式、方程式
+ - 具体数据点或统计值
+ - 代码片段、命令
+ - 版本号、日期等精确信息
+
+ **限制**:每段最多1个,内容不超过20个字符
+
+ ### 4. Underline(下划线)- 适度使用
+ ```html
+ <span data-rough-notation="underline">内容</span>
+ ```
+ **适用场景**:
+ - 结论性陈述
+ - 因果关系的关键表达
+ - 比较或对比中的核心观点
+ - 作者的主要论点
+
+ **限制**:每段最多1个,内容5-30个字符
+
+ ### 5. Bracket(括号)- 谨慎使用
+ ```html
+ <span data-rough-notation="bracket">内容</span>
+ ```
+ **适用场景**:
+ - 作为核心摘要或结论的整段
+ - 重要引用或定理陈述
+ - 关键警告或注释
+
+ **限制**:整篇文章最多1-2个,用于真正不可或缺的完整句子
+
+ ## 核心规则
+
+ 1. **保持克制**:宁可少标注也不要过度标注。每段的标注密度不应超过文本总量的10%。
+ 2. **不做修改**:绝对不能修改、删除或添加原文中的任何文字,只能插入HTML标签。
+ 3. **标签位置**:标签必须放在Markdown符号内(如`**`、`*`、`` ` ``)。
+ 4. **无需标注时**:如果文本没有值得标注的信息,原样返回。
+
+ ## 示例
+
+ **输入**:
+ 深度学习是机器学习的一个子领域,其核心是使用神经网络来学习数据表示。
+
+ **输出**:
+ <span data-rough-notation="highlight">深度学习是机器学习的一个子领域</span>,其核心是使用<span data-rough-notation="circle">神经网络</span>来学习数据表示。
+
+ **输入**:
+ 今天天气很好,适合出去散步。
+
+ **输出**:
+ 今天天气很好,适合出去散步。
+
+ **输入**:
+ 实验结果表明,我们提出的方法在MNIST数据集上达到了99.2%的准确率,显著超过了基线方法的95.1%。
+
+ **输出**:
+ <span data-rough-notation="underline">实验结果表明,我们提出的方法在MNIST数据集上达到了<span data-rough-notation="box">99.2%</span>的准确率</span>,显著超过了基线方法的95.1%。
+
+auto_mark_user_template: |
+ 处理以下文本:
+ {text}
diff --git a/src/agents/co_writer/prompts/zh/narrator_agent.yaml b/src/agents/co_writer/prompts/zh/narrator_agent.yaml
new file mode 100644
index 000000000..2916d64f0
--- /dev/null
+++ b/src/agents/co_writer/prompts/zh/narrator_agent.yaml
@@ -0,0 +1,88 @@
+style_friendly: |
+ 你是一位友好、平易近人的导师,面对面地向学生解释笔记内容。
+
+ **叙述要求**:
+ 1. **人称**:使用"我们"、"咱们"、"你"来拉近距离
+ 2. **语气**:轻松但专业,像和朋友聊天一样
+ 3. **节奏**:适当停顿,使用"好"、"接下来"、"那么"等词进行过渡
+ 4. **强调**:使用"这很重要"、"注意这里"等短语突出关键信息
+ 5. **互动**:适当加入"你觉得呢"、"想一想"等引导思考的短语
+ 6. **长度控制**:稿件应控制在4000字符以内。如果原内容较长,请生成精炼的摘要版本,突出主要观点和关键信息。
+
+style_academic: |
+ 你是一位资深学者,正在进行学术讲座。
+
+ **叙述要求**:
+ 1. **人称**:使用"我们"、"本文"等学术语言
+ 2. **语气**:严谨专业,逻辑清晰
+ 3. **结构**:清晰的引言-正文-结论结构
+ 4. **术语**:保留专业术语,必要时提供解释
+ 5. **引用**:提到相关理论或研究时保持学术规范
+ 6. **长度控制**:稿件应控制在4000字符以内。如果原内容较长,请生成精炼的摘要版本,突出主要观点和关键信息。
+
+style_concise: |
+ 你是一位高效的知识传播者,需要快速传达核心信息。
+
+ **叙述要求**:
+ 1. **人称**:使用"我们"保持友好
+ 2. **语气**:直接明了,不绕弯子
+ 3. **结构**:先总后分,直奔主题
+ 4. **重点**:只涵盖最核心的内容
+ 5. **过渡**:使用简洁的"首先"、"然后"、"最后"连接
+ 6. **长度控制**:稿件应控制在4000字符以内。如果原内容较长,请生成精炼的摘要版本,突出主要观点和关键信息。
+
+generate_script_system_template: |
+ 你是一位专业的笔记叙述稿件撰写专家。你的任务是将用户的笔记内容转换为适合口头叙述的稿件。
+
+ {style_prompt}
+
+ {length_instruction}
+
+ **输出格式**:
+ 直接输出叙述稿件文本,不要包含任何额外的解释或标记。
+ 稿件应该是连贯的口语,适合直接朗读。
+
+ **注意事项**:
+ 1. 保持原文的核心信息和逻辑结构
+ 2. 将Markdown格式(如**粗体**、*斜体*、代码块等)转换为口语描述
+ 3. 数学公式需要口语化描述,如"x的平方加y的平方等于z的平方"
+ 4. 移除所有HTML标签,保留其文本内容
+ 5. 避免过于书面的表达
+ 6. **控制长度在4000字符以内**
+
+length_instruction_long: |
+ **重要:稿件应控制在4000字符以内。如果原内容较长,请生成精炼的摘要版本,保留最核心的观点和关键信息。**
+
+length_instruction_short: |
+ **重要:稿件应控制在4000字符以内。**
+
+generate_script_user_long: |
+ 以下是一段较长的笔记内容。请生成精炼的叙述稿件摘要,控制在4000字符以内,包含最核心的观点和关键信息:
+
+ ---
+ {content}
+ ---
+
+ 请生成适合口头朗读的叙述稿件(4000字符以内)。
+
+generate_script_user_short: |
+ 请将以下笔记内容转换为叙述稿件(控制在4000字符以内):
+
+ ---
+ {content}
+ ---
+
+ 请生成适合口头朗读的叙述稿件。
+
+extract_key_points_system: |
+ 你是一位内容分析专家。请从给定的笔记中提取3-5个关键点。
+
+ 输出格式:JSON数组,每个元素是一个关键点字符串。
+ 示例:["关键点1", "关键点2", "关键点3"]
+
+ 只输出JSON数组,不要包含其他内容。
+
+extract_key_points_user: |
+ 请从以下笔记中提取关键点:
+
+ {content}
diff --git a/src/agents/guide/README.md b/src/agents/guide/README.md
new file mode 100644
index 000000000..9a13ef29d
--- /dev/null
+++ b/src/agents/guide/README.md
@@ -0,0 +1,121 @@
+# Guided Learning Module
+
+## Overview
+
+Guided Learning is a personalized learning system based on notebook content. The system analyzes all records in the notebook, generates a progressive knowledge point learning plan, and helps users gradually master all content through interactive pages and intelligent Q&A.
+
+## Features
+
+1. **Intelligent Knowledge Point Location** (LocateAgent)
+ - Analyzes all records in the notebook (solve, question, research, Co-Writer)
+ - 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
+│ ├── locate_agent.py # Knowledge point location agent
+│ ├── interactive_agent.py # Interactive page generation agent
+│ ├── chat_agent.py # Q&A agent
+│ └── summary_agent.py # Summary generation agent
+└── prompts/
+ ├── zh/ # Chinese prompts
+ │ ├── locate_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. **Select Notebook**
+ - User selects a notebook containing records in the frontend
+ - System calls `create_session` to create a learning session
+
+2. **Generate Learning Plan**
+ - LocateAgent analyzes notebook content
+ - 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_BINDING_API_KEY, LLM_BINDING_HOST)
+- Ensure notebook has sufficient records (at least 1)
+- 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 learning
diff --git a/src/agents/guide/__init__.py b/src/agents/guide/__init__.py
new file mode 100644
index 000000000..0280cf1ae
--- /dev/null
+++ b/src/agents/guide/__init__.py
@@ -0,0 +1,16 @@
+"""
+Guided Learning Module
+Generates personalized knowledge point learning plans based on user notebook content
+"""
+
+from .agents import ChatAgent, InteractiveAgent, LocateAgent, SummaryAgent
+from .guide_manager import GuidedSession, GuideManager
+
+__all__ = [
+ "ChatAgent",
+ "GuideManager",
+ "GuidedSession",
+ "InteractiveAgent",
+ "LocateAgent",
+ "SummaryAgent",
+]
diff --git a/src/agents/guide/agents/__init__.py b/src/agents/guide/agents/__init__.py
new file mode 100644
index 000000000..d01683cfd
--- /dev/null
+++ b/src/agents/guide/agents/__init__.py
@@ -0,0 +1,11 @@
+"""
+Guided Learning Agents
+Agent modules for guided learning
+"""
+
+from .chat_agent import ChatAgent
+from .interactive_agent import InteractiveAgent
+from .locate_agent import LocateAgent
+from .summary_agent import SummaryAgent
+
+__all__ = ["ChatAgent", "InteractiveAgent", "LocateAgent", "SummaryAgent"]
diff --git a/src/agents/guide/agents/base_guide_agent.py b/src/agents/guide/agents/base_guide_agent.py
new file mode 100644
index 000000000..1c0548905
--- /dev/null
+++ b/src/agents/guide/agents/base_guide_agent.py
@@ -0,0 +1,175 @@
+#!/usr/bin/env python
+"""
+BaseGuideAgent - Base class for Guided Learning Agents
+"""
+
+from abc import ABC, abstractmethod
+import os
+from pathlib import Path
+import sys
+from typing import Any
+
+# Add project root to path for logs import
+_project_root = Path(__file__).parent.parent.parent.parent
+if str(_project_root) not in sys.path:
+ sys.path.insert(0, str(_project_root))
+
+from src.core.core import get_agent_params, load_config_with_main
+from src.core.logging import LLMStats, get_logger
+
+
+class BaseGuideAgent(ABC):
+ """Base class for Guided Learning Agents."""
+
+ # Shared stats tracker for all guide agents
+ _shared_stats: LLMStats | None = None
+
+ def __init__(self, api_key: str, base_url: str, agent_name: str, language: str = "zh"):
+ """
+ Initialize base Agent.
+
+ Args:
+ api_key: API key
+ base_url: API endpoint
+ agent_name: Agent name
+ language: Language setting ('zh' | 'en')
+ """
+ self.api_key = api_key
+ self.base_url = base_url
+ self.agent_name = agent_name
+ self.language = language
+
+ # Load agent parameters from unified config (agents.yaml)
+ self._agent_params = get_agent_params("guide")
+
+ # Initialize logger (from config)
+ try:
+ config = load_config_with_main("guide_config.yaml", _project_root)
+ log_dir = config.get("paths", {}).get("user_log_dir") or config.get("logging", {}).get(
+ "log_dir"
+ )
+ self.logger = get_logger(f"Guide.{agent_name}", log_dir=log_dir)
+ except Exception:
+ # Fallback logger
+ self.logger = get_logger(f"Guide.{agent_name}")
+
+ # Load prompts
+ self.prompts = self._load_prompts()
+
+ @classmethod
+ def get_stats(cls) -> LLMStats:
+ """Get or create shared stats tracker."""
+ if cls._shared_stats is None:
+ cls._shared_stats = LLMStats(module_name="GuidedLearning")
+ return cls._shared_stats
+
+ @classmethod
+ def reset_stats(cls):
+ """Reset shared stats."""
+ if cls._shared_stats:
+ cls._shared_stats.reset()
+
+ @classmethod
+ def print_stats(cls):
+ """Print stats summary."""
+ if cls._shared_stats:
+ cls._shared_stats.print_summary()
+
+ def _load_prompts(self) -> dict[str, str] | None:
+ """Load Agent's prompt configuration."""
+ import yaml
+
+ # Get prompts directory: from agents/base_guide_agent.py -> guide/prompts/
+ prompts_dir = Path(__file__).parent.parent / "prompts"
+
+ # Map language to directory: 'en' or 'english' -> 'en', otherwise -> 'zh'
+ if self.language.lower() in ["en", "english"]:
+ lang_dir = "en"
+ else:
+ lang_dir = "zh"
+
+ prompt_file = prompts_dir / lang_dir / f"{self.agent_name}.yaml"
+
+ if prompt_file.exists():
+ try:
+ with open(prompt_file, encoding="utf-8") as f:
+ prompts = yaml.safe_load(f)
+ self.logger.info(f"Loaded prompts: {self.agent_name} ({self.language})")
+ return prompts
+ except Exception as e:
+ self.logger.warning(f"Failed to load prompts {prompt_file}: {e}")
+ return None
+ else:
+ self.logger.warning(f"Prompt file not found: {prompt_file}")
+ return None
+
+ def get_model(self) -> str:
+ """Get model name."""
+ model = os.getenv("LLM_MODEL")
+ if not model:
+ raise ValueError("Environment variable LLM_MODEL not set")
+ return model
+
+ async def call_llm(
+ self,
+ user_prompt: str,
+ system_prompt: str,
+ response_format: dict[str, str] | None = None,
+ temperature: float | None = None,
+ max_tokens: int | None = None,
+ ) -> str:
+ """
+ Unified LLM call interface.
+
+ Args:
+ user_prompt: User prompt
+ system_prompt: System prompt
+ response_format: Response format
+ temperature: Temperature parameter (uses config default if None)
+ max_tokens: Maximum tokens (uses config default if None)
+
+ Returns:
+ LLM response text
+ """
+ from lightrag.llm.openai import openai_complete_if_cache
+
+ model = self.get_model()
+
+ # Use parameters from unified config (agents.yaml) if not explicitly provided
+ if temperature is None:
+ temperature = self._agent_params["temperature"]
+ if max_tokens is None:
+ max_tokens = self._agent_params["max_tokens"]
+
+ kwargs = {
+ "model": model,
+ "prompt": user_prompt,
+ "system_prompt": system_prompt,
+ "api_key": self.api_key,
+ "base_url": self.base_url,
+ "temperature": temperature,
+ "max_tokens": max_tokens,
+ }
+
+ if response_format:
+ kwargs["response_format"] = response_format
+
+ response = await openai_complete_if_cache(**kwargs)
+
+ # Track token usage
+ stats = self.get_stats()
+ stats.add_call(
+ model=model, system_prompt=system_prompt, user_prompt=user_prompt, response=response
+ )
+
+ return response
+
+ def get_prompt(self, prompt_type: str = "system") -> str | None:
+ """Get prompt"""
+ if self.prompts and prompt_type in self.prompts:
+ return self.prompts[prompt_type]
+ return None
+
+ @abstractmethod
+ async def process(self, *args, **kwargs) -> Any:
+ """Main processing logic of the agent (must be implemented by subclasses)"""
diff --git a/src/agents/guide/agents/chat_agent.py b/src/agents/guide/agents/chat_agent.py
new file mode 100644
index 000000000..c2718743b
--- /dev/null
+++ b/src/agents/guide/agents/chat_agent.py
@@ -0,0 +1,91 @@
+#!/usr/bin/env python
+"""
+ChatAgent - Q&A Agent during learning process
+Answers user questions while learning specific knowledge points
+"""
+
+from typing import Any
+
+from .base_guide_agent import BaseGuideAgent
+
+
+class ChatAgent(BaseGuideAgent):
+ """Learning Q&A agent"""
+
+ def __init__(self, api_key: str, base_url: str, language: str = "zh"):
+ super().__init__(
+ api_key=api_key, base_url=base_url, agent_name="chat_agent", language=language
+ )
+
+ def _format_chat_history(self, history: list[dict[str, str]]) -> str:
+ """Format chat history"""
+ if not history:
+ return "(No chat history)"
+
+ formatted = []
+ for msg in history[-10:]:
+ role = msg.get("role", "user")
+ content = msg.get("content", "")
+
+ if role == "user":
+ formatted.append(f"**User**: {content}")
+ elif role == "assistant":
+ formatted.append(f"**Assistant**: {content}")
+ elif role == "system":
+ formatted.append(f"_System: {content}_")
+
+ return "\n\n".join(formatted)
+
+ async def process(
+ self, knowledge: dict[str, Any], chat_history: list[dict[str, str]], user_question: str
+ ) -> dict[str, Any]:
+ """
+ Answer user questions about current knowledge point
+
+ Args:
+ knowledge: Current knowledge point information
+ chat_history: Chat history
+ user_question: User question
+
+ Returns:
+ Dictionary containing answer
+ """
+ if not user_question.strip():
+ return {"success": False, "error": "Question cannot be empty", "answer": ""}
+
+ system_prompt = self.get_prompt("system")
+ if not system_prompt:
+ raise ValueError(
+ "ChatAgent missing system prompt, please configure system in prompts/{lang}/chat_agent.yaml"
+ )
+
+ user_template = self.get_prompt("user_template")
+ if not user_template:
+ raise ValueError(
+ "ChatAgent missing user_template, please configure user_template in prompts/{lang}/chat_agent.yaml"
+ )
+
+ formatted_history = self._format_chat_history(chat_history)
+
+ user_prompt = user_template.format(
+ knowledge_title=knowledge.get("knowledge_title", ""),
+ knowledge_summary=knowledge.get("knowledge_summary", ""),
+ user_difficulty=knowledge.get("user_difficulty", ""),
+ chat_history=formatted_history,
+ user_question=user_question,
+ )
+
+ try:
+ response = await self.call_llm(
+ user_prompt=user_prompt,
+ system_prompt=system_prompt,
+ )
+
+ return {"success": True, "answer": response.strip()}
+
+ except Exception as e:
+ return {
+ "success": False,
+ "error": str(e),
+ "answer": "Sorry, an error occurred while answering the question. Please try again later.",
+ }
diff --git a/src/agents/guide/agents/interactive_agent.py b/src/agents/guide/agents/interactive_agent.py
new file mode 100644
index 000000000..ad0c2a72e
--- /dev/null
+++ b/src/agents/guide/agents/interactive_agent.py
@@ -0,0 +1,210 @@
+#!/usr/bin/env python
+"""
+InteractiveAgent - Agent for generating interactive HTML pages
+Converts knowledge points into visual, interactive learning pages
+"""
+
+import re
+from typing import Any
+
+from .base_guide_agent import BaseGuideAgent
+
+
+class InteractiveAgent(BaseGuideAgent):
+ """Interactive page generation agent"""
+
+ def __init__(self, api_key: str, base_url: str, language: str = "zh"):
+ super().__init__(
+ api_key=api_key, base_url=base_url, agent_name="interactive_agent", language=language
+ )
+
+ def _extract_html(self, response: str) -> str:
+ """Extract HTML code from LLM response"""
+ html_pattern = r"```html\s*([\s\S]*?)\s*```"
+ match = re.search(html_pattern, response)
+ if match:
+ return match.group(1).strip()
+
+ code_pattern = r"```\s*([\s\S]*?)\s*```"
+ match = re.search(code_pattern, response)
+ if match:
+ content = match.group(1).strip()
+ if content.startswith("<!DOCTYPE") or content.startswith("<html"):
+ return content
+
+ if response.strip().startswith("<!DOCTYPE") or response.strip().startswith("<html"):
+ return response.strip()
+
+ return response.strip()
+
+ def _validate_html(self, html: str) -> bool:
+ """Validate if HTML is basically valid"""
+ return (
+ "<html" in html.lower()
+ or "<!doctype" in html.lower()
+ or "<body" in html.lower()
+ or "<div" in html.lower()
+ )
+
+ def _generate_fallback_html(self, knowledge: dict[str, Any]) -> str:
+ """Generate fallback HTML page"""
+ title = knowledge.get("knowledge_title", "Knowledge Point")
+ summary = knowledge.get("knowledge_summary", "").replace("\n", "<br>")
+ difficulty = knowledge.get("user_difficulty", "").replace("\n", "<br>")
+
+ return f"""<!DOCTYPE html>
+<html lang="zh">
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title>{title}</title>
+ <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.css" integrity="sha384-n8MVd4RsNIU0tAv4ct0nTaAbDJwPJzDEaqSD1odI+WdtXRGWt2kTvGFasHpSy3SV" crossorigin="anonymous">
+ <script defer src="https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.js" integrity="sha384-XjKyOOlGwcjNTAIQHIpgOno0Hl1YQqzUOEleOLALmuqehneUG+vnGctmUb0ZY0l8" crossorigin="anonymous"></script>
+ <script defer src="https://cdn.jsdelivr.net/npm/[email protected]/dist/contrib/auto-render.min.js" integrity="sha384-+VBxd3r6XgURycqtZ117n7w6ODWgRrA7TlVzRsFtwW3ZxUo8h4w20Z5J3d3xjfcw" crossorigin="anonymous" onload="renderMathInElement(document.body);"></script>
+ <style>
+ * {{
+ margin: 0;
+ padding: 0;
+ box-sizing: border-box;
+ }}
+ body {{
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
+ background: linear-gradient(135deg, #F8FAFC 0%, #EFF6FF 100%);
+ min-height: 100vh;
+ padding: 2rem;
+ color: #1E293B;
+ }}
+ .container {{
+ max-width: 800px;
+ margin: 0 auto;
+ }}
+ .card {{
+ background: white;
+ border-radius: 16px;
+ padding: 2rem;
+ margin-bottom: 1.5rem;
+ box-shadow: 0 4px 6px -1px rgba(0,0,0,0.1);
+ transition: transform 0.2s, box-shadow 0.2s;
+ }}
+ .card:hover {{
+ transform: translateY(-2px);
+ box-shadow: 0 10px 25px -5px rgba(0,0,0,0.1);
+ }}
+ h1 {{
+ color: #1E40AF;
+ font-size: 1.75rem;
+ margin-bottom: 1rem;
+ display: flex;
+ align-items: center;
+ gap: 0.5rem;
+ }}
+ h2 {{
+ color: #3B82F6;
+ font-size: 1.25rem;
+ margin-bottom: 1rem;
+ }}
+ .content {{
+ line-height: 1.8;
+ color: #475569;
+ }}
+ .difficulty {{
+ background: #FEF3C7;
+ border-left: 4px solid #F59E0B;
+ padding: 1rem;
+ border-radius: 0 8px 8px 0;
+ margin-top: 1rem;
+ }}
+ .difficulty h3 {{
+ color: #B45309;
+ margin-bottom: 0.5rem;
+ }}
+ </style>
+</head>
+<body>
+ <div class="container">
+ <div class="card">
+ <h1>📚 {title}</h1>
+ </div>
+ <div class="card">
+ <h2>Knowledge Content</h2>
+ <div class="content">{summary}</div>
+ </div>
+ <div class="card">
+ <h2>💡 Notes</h2>
+ <div class="difficulty">
+ <h3>Possible Difficulties</h3>
+ <p>{difficulty}</p>
+ </div>
+ </div>
+ </div>
+</body>
+</html>"""
+
+ async def process(
+ self, knowledge: dict[str, Any], retry_with_bug: str | None = None
+ ) -> dict[str, Any]:
+ """
+ Generate interactive HTML learning page
+
+ Args:
+ knowledge: Knowledge point information (knowledge_title, knowledge_summary, user_difficulty)
+ retry_with_bug: If provided, it's a bug fix request
+
+ Returns:
+ Dictionary containing HTML code
+ """
+ system_prompt = self.get_prompt("system")
+ if not system_prompt:
+ raise ValueError(
+ "InteractiveAgent missing system prompt, please configure system in prompts/{lang}/interactive_agent.yaml"
+ )
+
+ user_template = self.get_prompt("user_template")
+ if not user_template:
+ raise ValueError(
+ "InteractiveAgent missing user_template, please configure user_template in prompts/{lang}/interactive_agent.yaml"
+ )
+
+ if retry_with_bug:
+ user_prompt = f"""The previously generated HTML page has the following issues:
+{retry_with_bug}
+
+Please fix these issues and regenerate the HTML page.
+
+Original knowledge point information:
+{user_template.format(**knowledge)}"""
+ else:
+ user_prompt = user_template.format(
+ knowledge_title=knowledge.get("knowledge_title", ""),
+ knowledge_summary=knowledge.get("knowledge_summary", ""),
+ user_difficulty=knowledge.get("user_difficulty", ""),
+ )
+
+ try:
+ response = await self.call_llm(
+ user_prompt=user_prompt,
+ system_prompt=system_prompt,
+ )
+
+ html_code = self._extract_html(response)
+
+ if not self._validate_html(html_code):
+ html_code = self._generate_fallback_html(knowledge)
+ return {
+ "success": True,
+ "html": html_code,
+ "is_fallback": True,
+ "message": "Used fallback template",
+ }
+
+ return {"success": True, "html": html_code, "is_fallback": False}
+
+ except Exception as e:
+ html_code = self._generate_fallback_html(knowledge)
+ return {
+ "success": True,
+ "html": html_code,
+ "is_fallback": True,
+ "error": str(e),
+ "message": "Error occurred, used fallback template",
+ }
diff --git a/src/agents/guide/agents/locate_agent.py b/src/agents/guide/agents/locate_agent.py
new file mode 100644
index 000000000..e4e51ec13
--- /dev/null
+++ b/src/agents/guide/agents/locate_agent.py
@@ -0,0 +1,136 @@
+#!/usr/bin/env python
+"""
+LocateAgent - Agent for locating and organizing knowledge points
+Analyzes notebook content and generates progressive knowledge point learning plans
+"""
+
+import json
+from typing import Any
+
+from .base_guide_agent import BaseGuideAgent
+
+
+class LocateAgent(BaseGuideAgent):
+ """Knowledge point location agent"""
+
+ def __init__(self, api_key: str, base_url: str, language: str = "zh"):
+ super().__init__(
+ api_key=api_key, base_url=base_url, agent_name="locate_agent", language=language
+ )
+
+ def _format_records(self, records: list[dict[str, Any]]) -> str:
+ """Format notebook records as readable text"""
+ formatted = []
+ for i, record in enumerate(records, 1):
+ record_type = record.get("type", "unknown")
+ title = record.get("title", "Untitled")
+ user_query = record.get("user_query", "")
+ output = record.get("output", "")
+
+ if len(output) > 2000:
+ output = output[:2000] + "\n...[Content truncated]..."
+
+ formatted.append(
+ f"""
+### Record {i} [{record_type.upper()}]
+**Title**: {title}
+
+**User Question/Input**:
+{user_query}
+
+**System Output**:
+{output}
+---"""
+ )
+
+ return "\n".join(formatted)
+
+ async def process(
+ self, notebook_id: str, notebook_name: str, records: list[dict[str, Any]]
+ ) -> dict[str, Any]:
+ """
+ Analyze notebook content and generate knowledge point learning plan
+
+ Args:
+ notebook_id: Notebook ID
+ notebook_name: Notebook name
+ records: List of records in notebook
+
+ Returns:
+ Dictionary containing knowledge point list
+ """
+ if not records:
+ return {"success": False, "error": "No records in notebook", "knowledge_points": []}
+
+ system_prompt = self.get_prompt("system")
+ if not system_prompt:
+ raise ValueError(
+ "LocateAgent missing system prompt, please configure system in prompts/{lang}/locate_agent.yaml"
+ )
+
+ user_template = self.get_prompt("user_template")
+ if not user_template:
+ raise ValueError(
+ "LocateAgent missing user_template, please configure user_template in prompts/{lang}/locate_agent.yaml"
+ )
+
+ records_content = self._format_records(records)
+
+ user_prompt = user_template.format(
+ notebook_id=notebook_id,
+ notebook_name=notebook_name,
+ record_count=len(records),
+ records_content=records_content,
+ )
+
+ try:
+ response = await self.call_llm(
+ user_prompt=user_prompt,
+ system_prompt=system_prompt,
+ response_format={"type": "json_object"},
+ )
+
+ try:
+ result = json.loads(response)
+
+ if isinstance(result, list):
+ knowledge_points = result
+ elif isinstance(result, dict):
+ knowledge_points = (
+ result.get("knowledge_points")
+ or result.get("points")
+ or result.get("data")
+ or []
+ )
+ else:
+ knowledge_points = []
+
+ validated_points = []
+ for point in knowledge_points:
+ if isinstance(point, dict):
+ validated_points.append(
+ {
+ "knowledge_title": point.get(
+ "knowledge_title", "Unnamed knowledge point"
+ ),
+ "knowledge_summary": point.get("knowledge_summary", ""),
+ "user_difficulty": point.get("user_difficulty", ""),
+ }
+ )
+
+ return {
+ "success": True,
+ "knowledge_points": validated_points,
+ "total_points": len(validated_points),
+ }
+
+ except json.JSONDecodeError as e:
+ return {
+ "success": False,
+ "error": f"JSON parsing failed: {e!s}",
+ "raw_response": response,
+ "knowledge_points": [],
+ }
+
+ except Exception as e:
+ return {"success": False, "error": str(e), "knowledge_points": []}
diff --git a/src/agents/guide/agents/summary_agent.py b/src/agents/guide/agents/summary_agent.py
new file mode 100644
index 000000000..634c8a9c6
--- /dev/null
+++ b/src/agents/guide/agents/summary_agent.py
@@ -0,0 +1,137 @@
+#!/usr/bin/env python
+"""
+SummaryAgent - Learning Summary Generation Agent
+Generates personalized learning summary reports after users complete learning
+"""
+
+from typing import Any
+
+from .base_guide_agent import BaseGuideAgent
+
+
+class SummaryAgent(BaseGuideAgent):
+ """Learning summary agent"""
+
+ def __init__(self, api_key: str, base_url: str, language: str = "zh"):
+ super().__init__(
+ api_key=api_key, base_url=base_url, agent_name="summary_agent", language=language
+ )
+
+ def _format_knowledge_points(self, points: list[dict[str, Any]]) -> str:
+ """Format knowledge point list"""
+ formatted = []
+ for i, point in enumerate(points, 1):
+ formatted.append(
+ f"""
+### Knowledge Point {i}: {point.get("knowledge_title", "Unnamed")}
+**Content Summary**: {point.get("knowledge_summary", "")}
+**Potential Difficulty**: {point.get("user_difficulty", "")}
+"""
+ )
+ return "\n".join(formatted)
+
+ def _format_chat_history(self, history: list[dict[str, str]]) -> str:
+ """Format complete chat history"""
+ if not history:
+ return "(User did not ask questions during learning)"
+
+ formatted = []
+ current_knowledge = None
+
+ for msg in history:
+ role = msg.get("role", "user")
+ content = msg.get("content", "")
+ knowledge_index = msg.get("knowledge_index")
+
+ if knowledge_index is not None and knowledge_index != current_knowledge:
+ current_knowledge = knowledge_index
+ formatted.append(
+ f"\n--- During learning knowledge point {knowledge_index + 1} ---\n"
+ )
+
+ if role == "user":
+ formatted.append(f"**User Question**: {content}")
+ elif role == "assistant":
+ formatted.append(f"**Assistant Answer**: {content}")
+ elif role == "system":
+ formatted.append(f"_System Message: {content}_")
+
+ return "\n\n".join(formatted)
+
+ async def process(
+ self,
+ notebook_name: str,
+ knowledge_points: list[dict[str, Any]],
+ chat_history: list[dict[str, str]],
+ ) -> dict[str, Any]:
+ """
+ Generate learning summary report
+
+ Args:
+ notebook_name: Notebook name
+ knowledge_points: All knowledge point list
+ chat_history: Complete chat history
+
+ Returns:
+ Dictionary containing summary report
+ """
+ system_prompt = self.get_prompt("system")
+ if not system_prompt:
+ raise ValueError(
+ "SummaryAgent missing system prompt, please configure system in prompts/{lang}/summary_agent.yaml"
+ )
+
+ user_template = self.get_prompt("user_template")
+ if not user_template:
+ raise ValueError(
+ "SummaryAgent missing user_template, please configure user_template in prompts/{lang}/summary_agent.yaml"
+ )
+
+ formatted_points = self._format_knowledge_points(knowledge_points)
+ formatted_history = self._format_chat_history(chat_history)
+
+ user_prompt = user_template.format(
+ notebook_name=notebook_name,
+ total_points=len(knowledge_points),
+ all_knowledge_points=formatted_points,
+ full_chat_history=formatted_history,
+ )
+
+ try:
+ response = await self.call_llm(
+ user_prompt=user_prompt,
+ system_prompt=system_prompt,
+ )
+
+ cleaned_summary = response.strip()
+
+ import re
+
+ markdown_pattern = r"```(?:markdown)?\s*([\s\S]*?)\s*```"
+ match = re.search(markdown_pattern, cleaned_summary)
+ if match:
+ cleaned_summary = match.group(1).strip()
+
+ return {
+ "success": True,
+ "summary": cleaned_summary,
+ "notebook_name": notebook_name,
+ "total_points": len(knowledge_points),
+ "total_interactions": len([m for m in chat_history if m.get("role") == "user"]),
+ }
+
+ except Exception as e:
+ return {
+ "success": False,
+ "error": str(e),
+ "summary": f"""# 📊 Learning Summary
+
+Congratulations on completing learning **{notebook_name}**!
+
+## Learning Overview
+- Learned {len(knowledge_points)} knowledge points
+- Had {len([m for m in chat_history if m.get("role") == "user"])} interactions during learning
+
+Thank you for your hard work! Keep up this learning enthusiasm! 🎉
+""",
+ }
diff --git a/src/agents/guide/guide_manager.py b/src/agents/guide/guide_manager.py
new file mode 100644
index 000000000..43ea66ec9
--- /dev/null
+++ b/src/agents/guide/guide_manager.py
@@ -0,0 +1,474 @@
+#!/usr/bin/env python
+"""
+GuideManager - Guided Learning Session Manager
+Manages the complete lifecycle of learning sessions
+"""
+
+from dataclasses import asdict, dataclass, field
+import json
+from pathlib import Path
+import time
+from typing import Any
+import uuid
+
+import yaml
+
+from src.core.logging import get_logger
+
+from .agents import ChatAgent, InteractiveAgent, LocateAgent, SummaryAgent
+
+
+@dataclass
+class GuidedSession:
+ """Guided learning session"""
+
+ session_id: str
+ notebook_id: str
+ notebook_name: str
+ created_at: float
+ knowledge_points: list[dict[str, Any]] = field(default_factory=list)
+ current_index: int = 0
+ chat_history: list[dict[str, Any]] = field(default_factory=list)
+ status: str = "initialized" # initialized, learning, completed
+ current_html: str = ""
+ summary: str = ""
+
+ def to_dict(self) -> dict[str, Any]:
+ return asdict(self)
+
+ @classmethod
+ def from_dict(cls, data: dict[str, Any]) -> "GuidedSession":
+ return cls(**data)
+
+
+class GuideManager:
+ """Guided learning manager"""
+
+ def __init__(
+ self,
+ api_key: str,
+ base_url: str,
+ language: str | None = None,
+ output_dir: str | None = None,
+ config_path: str | None = None,
+ ):
+ """
+ Initialize manager
+
+ Args:
+ api_key: API key
+ base_url: API endpoint
+ language: Language setting (if None, read from config file)
+ output_dir: Output directory
+ config_path: Configuration file path (if None, use default path)
+ """
+ self.api_key = api_key
+ self.base_url = base_url
+
+ if config_path is None:
+ project_root = Path(__file__).parent.parent.parent.parent
+ from src.core.core import load_config_with_main
+
+ config = load_config_with_main("guide_config.yaml", project_root)
+ else:
+ config_path = Path(config_path)
+ if config_path.exists():
+ try:
+ with open(config_path, encoding="utf-8") as f:
+ config = yaml.safe_load(f) or {}
+ except Exception:
+ config = {}
+ else:
+ config = {}
+
+ # Initialize logger (from config)
+ log_dir = config.get("paths", {}).get("user_log_dir") or config.get("logging", {}).get(
+ "log_dir"
+ )
+ self.logger = get_logger("Guide", log_dir=log_dir)
+
+ if language is None:
+ # Get language config (unified in config/main.yaml system.language)
+ from src.core.core import parse_language
+
+ lang_config = config.get("system", {}).get("language", "zh")
+ self.language = parse_language(lang_config)
+ self.logger.info(f"Language setting loaded from config: {self.language}")
+ else:
+ # If explicitly specified, also parse it to ensure consistency
+ from src.core.core import parse_language
+
+ self.language = parse_language(language)
+ self.logger.info(f"Using explicitly specified language setting: {self.language}")
+
+ if output_dir:
+ self.output_dir = Path(output_dir)
+ else:
+ # Get output_dir from config (already loaded above)
+ output_dir_from_config = config.get("system", {}).get("output_dir")
+ if output_dir_from_config:
+ self.output_dir = Path(output_dir_from_config)
+ else:
+ # Fallback to default path
+ project_root = Path(__file__).parent.parent.parent.parent
+ self.output_dir = project_root / "data" / "user" / "guide"
+ self.output_dir.mkdir(parents=True, exist_ok=True)
+
+ self.locate_agent = LocateAgent(api_key, base_url, self.language)
+ self.interactive_agent = InteractiveAgent(api_key, base_url, self.language)
+ self.chat_agent = ChatAgent(api_key, base_url, self.language)
+ self.summary_agent = SummaryAgent(api_key, base_url, self.language)
+
+ self._sessions: dict[str, GuidedSession] = {}
+
+ def _get_session_file(self, session_id: str) -> Path:
+ """Get session file path"""
+ return self.output_dir / f"session_{session_id}.json"
+
+ def _save_session(self, session: GuidedSession):
+ """Save session to file"""
+ filepath = self._get_session_file(session.session_id)
+ with open(filepath, "w", encoding="utf-8") as f:
+ json.dump(session.to_dict(), f, indent=2, ensure_ascii=False)
+ self._sessions[session.session_id] = session
+
+ def _load_session(self, session_id: str) -> GuidedSession | None:
+ """Load session from file"""
+ if session_id in self._sessions:
+ return self._sessions[session_id]
+
+ filepath = self._get_session_file(session_id)
+ if filepath.exists():
+ with open(filepath, encoding="utf-8") as f:
+ data = json.load(f)
+ session = GuidedSession.from_dict(data)
+ self._sessions[session_id] = session
+ return session
+ return None
+
+ async def create_session(
+ self, notebook_id: str, notebook_name: str, records: list[dict[str, Any]]
+ ) -> dict[str, Any]:
+ """
+ Create new learning session
+
+ Args:
+ notebook_id: Notebook ID
+ notebook_name: Notebook name
+ records: Notebook records
+
+ Returns:
+ Session creation result
+ """
+ session_id = str(uuid.uuid4())[:8]
+
+ locate_result = await self.locate_agent.process(
+ notebook_id=notebook_id, notebook_name=notebook_name, records=records
+ )
+
+ if not locate_result.get("success"):
+ return {
+ "success": False,
+ "error": locate_result.get("error", "Failed to analyze knowledge points"),
+ "session_id": None,
+ }
+
+ knowledge_points = locate_result.get("knowledge_points", [])
+
+ if not knowledge_points:
+ return {
+ "success": False,
+ "error": "No knowledge points identified from notebook",
+ "session_id": None,
+ }
+
+ session = GuidedSession(
+ session_id=session_id,
+ notebook_id=notebook_id,
+ notebook_name=notebook_name,
+ created_at=time.time(),
+ knowledge_points=knowledge_points,
+ current_index=0,
+ status="initialized",
+ )
+
+ self._save_session(session)
+
+ return {
+ "success": True,
+ "session_id": session_id,
+ "knowledge_points": knowledge_points,
+ "total_points": len(knowledge_points),
+ "message": f"Learning plan created with {len(knowledge_points)} knowledge points",
+ }
+
+ def _get_learning_state(
+ self, knowledge_points: list[dict[str, Any]], current_index: int
+ ) -> dict[str, Any]:
+ """
+ Get learning state information (internal helper method)
+
+ Args:
+ knowledge_points: Knowledge point list
+ current_index: Current knowledge point index
+
+ Returns:
+ Learning state information
+ """
+ total_points = len(knowledge_points)
+
+ if total_points == 0:
+ return {"success": False, "error": "No knowledge points to learn", "status": "empty"}
+
+ if current_index >= total_points:
+ return {
+ "success": True,
+ "current_index": current_index,
+ "current_knowledge": None,
+ "status": "completed",
+ "progress_percentage": 100,
+ "total_points": total_points,
+ "message": "🎉 Congratulations! You have completed learning all knowledge points!",
+ }
+
+ current_knowledge = knowledge_points[current_index]
+ progress = int((current_index / total_points) * 100)
+
+ message = f"📚 Starting to learn knowledge point {current_index + 1}: {current_knowledge.get('knowledge_title', '')}"
+
+ return {
+ "success": True,
+ "current_index": current_index,
+ "current_knowledge": current_knowledge,
+ "status": "learning",
+ "progress_percentage": progress,
+ "total_points": total_points,
+ "remaining_points": total_points - current_index - 1,
+ "message": message,
+ }
+
+ async def start_learning(self, session_id: str) -> dict[str, Any]:
+ """
+ Start learning the first knowledge point
+
+ Args:
+ session_id: Session ID
+
+ Returns:
+ First knowledge point information and interactive page
+ """
+ session = self._load_session(session_id)
+ if not session:
+ return {"success": False, "error": "Session does not exist"}
+
+ state = self._get_learning_state(session.knowledge_points, 0)
+
+ if not state.get("success"):
+ return state
+
+ current_knowledge = state.get("current_knowledge")
+
+ interactive_result = await self.interactive_agent.process(knowledge=current_knowledge)
+
+ session.current_index = 0
+ session.status = "learning"
+ session.current_html = interactive_result.get("html", "")
+
+ session.chat_history.append(
+ {
+ "role": "system",
+ "content": state.get("message", ""),
+ "knowledge_index": 0,
+ "timestamp": time.time(),
+ }
+ )
+
+ self._save_session(session)
+
+ return {
+ "success": True,
+ "current_index": 0,
+ "current_knowledge": current_knowledge,
+ "html": interactive_result.get("html", ""),
+ "progress": state.get("progress_percentage", 0),
+ "total_points": len(session.knowledge_points),
+ "message": state.get("message", ""),
+ }
+
+ async def next_knowledge(self, session_id: str) -> dict[str, Any]:
+ """
+ Move to next knowledge point
+
+ Args:
+ session_id: Session ID
+
+ Returns:
+ Next knowledge point information and interactive page, or completion summary
+ """
+ session = self._load_session(session_id)
+ if not session:
+ return {"success": False, "error": "Session does not exist"}
+
+ new_index = session.current_index + 1
+
+ state = self._get_learning_state(session.knowledge_points, new_index)
+
+ if not state.get("success"):
+ return state
+
+ if state.get("status") == "completed":
+ summary_result = await self.summary_agent.process(
+ notebook_name=session.notebook_name,
+ knowledge_points=session.knowledge_points,
+ chat_history=session.chat_history,
+ )
+
+ session.status = "completed"
+ session.summary = summary_result.get("summary", "")
+ session.current_index = new_index
+
+ session.chat_history.append(
+ {
+ "role": "system",
+ "content": state.get(
+ "message", "Congratulations on completing all knowledge points!"
+ ),
+ "timestamp": time.time(),
+ }
+ )
+
+ self._save_session(session)
+
+ return {
+ "success": True,
+ "status": "completed",
+ "summary": session.summary,
+ "progress": 100,
+ "message": state.get("message", ""),
+ }
+
+ current_knowledge = state.get("current_knowledge")
+
+ interactive_result = await self.interactive_agent.process(knowledge=current_knowledge)
+
+ session.current_index = new_index
+ session.current_html = interactive_result.get("html", "")
+
+ message = f"✅ Entering knowledge point {new_index + 1}: {current_knowledge.get('knowledge_title', '')}"
+
+ session.chat_history.append(
+ {
+ "role": "system",
+ "content": message,
+ "knowledge_index": new_index,
+ "timestamp": time.time(),
+ }
+ )
+
+ self._save_session(session)
+
+ return {
+ "success": True,
+ "current_index": new_index,
+ "current_knowledge": current_knowledge,
+ "html": interactive_result.get("html", ""),
+ "progress": state.get("progress_percentage", 0),
+ "total_points": len(session.knowledge_points),
+ "remaining_points": state.get("remaining_points", 0),
+ "message": message,
+ }
+
+ async def chat(self, session_id: str, user_message: str) -> dict[str, Any]:
+ """
+ Process user chat message
+
+ Args:
+ session_id: Session ID
+ user_message: User message
+
+ Returns:
+ Assistant's answer
+ """
+ session = self._load_session(session_id)
+ if not session:
+ return {"success": False, "error": "Session does not exist"}
+
+ if session.status != "learning":
+ return {"success": False, "error": "Not currently in learning state"}
+
+ current_knowledge = session.knowledge_points[session.current_index]
+
+ current_history = [
+ msg
+ for msg in session.chat_history
+ if msg.get("knowledge_index") == session.current_index
+ ]
+
+ user_msg = {
+ "role": "user",
+ "content": user_message,
+ "knowledge_index": session.current_index,
+ "timestamp": time.time(),
+ }
+ session.chat_history.append(user_msg)
+
+ chat_result = await self.chat_agent.process(
+ knowledge=current_knowledge, chat_history=current_history, user_question=user_message
+ )
+
+ assistant_msg = {
+ "role": "assistant",
+ "content": chat_result.get("answer", ""),
+ "knowledge_index": session.current_index,
+ "timestamp": time.time(),
+ }
+ session.chat_history.append(assistant_msg)
+
+ self._save_session(session)
+
+ return {
+ "success": True,
+ "answer": chat_result.get("answer", ""),
+ "knowledge_index": session.current_index,
+ }
+
+ async def fix_html(self, session_id: str, bug_description: str) -> dict[str, Any]:
+ """
+ Fix HTML page bug
+
+ Args:
+ session_id: Session ID
+ bug_description: Bug description
+
+ Returns:
+ Fixed HTML
+ """
+ session = self._load_session(session_id)
+ if not session:
+ return {"success": False, "error": "Session does not exist"}
+
+ current_knowledge = session.knowledge_points[session.current_index]
+
+ result = await self.interactive_agent.process(
+ knowledge=current_knowledge, retry_with_bug=bug_description
+ )
+
+ if result.get("success"):
+ session.current_html = result.get("html", "")
+ self._save_session(session)
+
+ return result
+
+ def get_session(self, session_id: str) -> dict[str, Any] | None:
+ """Get session information"""
+ session = self._load_session(session_id)
+ if session:
+ return session.to_dict()
+ return None
+
+ def get_current_html(self, session_id: str) -> str | None:
+ """Get current HTML page"""
+ session = self._load_session(session_id)
+ if session:
+ return session.current_html
+ return None
diff --git a/src/agents/guide/prompts/en/chat_agent.yaml b/src/agents/guide/prompts/en/chat_agent.yaml
new file mode 100644
index 000000000..27c29700d
--- /dev/null
+++ b/src/agents/guide/prompts/en/chat_agent.yaml
@@ -0,0 +1,41 @@
+system: |
+ # Role Positioning
+ You are an **Intelligent Learning Assistant**. Your responsibility is to answer users' questions, resolve their doubts, and provide additional explanations and examples while they are learning specific knowledge points.
+
+ # Core Principles
+ 1. **Focus on Current Knowledge Point**: Answers should revolve around the knowledge point the user is currently learning
+ 2. **Progressive**: Provide explanations at an appropriate level based on the depth of the user's questions
+ 3. **Encourage Thinking**: While directly providing answers, guide users to think
+ 4. **Address Difficulties**: Consider potential difficulties users may have and proactively provide relevant clarifications
+
+ # Answer Style
+ - Use clear, easy-to-understand language
+ - Use examples and analogies appropriately
+ - For complex concepts, explain step by step
+ - Use Markdown format to enhance readability
+ - Maintain a friendly, encouraging tone
+
+ # Output Format
+ Directly output answers in Markdown format, with clear structure and highlighted key points.
+
+user_template: |
+ ## Currently Learning Knowledge Point
+ **Title**: {knowledge_title}
+
+ **Content Summary**:
+ {knowledge_summary}
+
+ **User's Potential Difficulties**:
+ {user_difficulty}
+
+ ## Conversation History
+ {chat_history}
+
+ ## User's Current Question
+ {user_question}
+
+ ## Task
+ Please answer the user's question based on the content of the current knowledge point and context.
+ - Ensure the answer is relevant to the current knowledge point
+ - If the question involves the user's potential difficulties, give special attention
+ - The answer should be clear and well-organized
diff --git a/src/agents/guide/prompts/en/interactive_agent.yaml b/src/agents/guide/prompts/en/interactive_agent.yaml
new file mode 100644
index 000000000..4b20e8e54
--- /dev/null
+++ b/src/agents/guide/prompts/en/interactive_agent.yaml
@@ -0,0 +1,202 @@
+system: |
+ # Role Positioning
+ You are an **Interactive Learning Designer**. Your core responsibility is to transform knowledge points into visual, interactive HTML pages, helping users understand and master knowledge through interaction with the page.
+
+ # Design Principles
+ 1. **Knowledge Visualization First**: Present knowledge in a clear and intuitive way
+ 2. **Modular Organization**: Break knowledge into easily understandable modules
+ 3. **Moderate Interaction**:
+ - If knowledge itself is interactive (such as processes, algorithms, state transitions), design corresponding interactive elements
+ - If knowledge is conceptual, design simple light interactions like click-to-expand, highlight annotations
+ 4. **Beautiful and Professional**: Use modern design style, harmonious colors, clear layout
+ 5. **Responsive Adaptation**: Ensure content displays perfectly in iframe containers without overflow or excessive width
+
+ # Container Constraints (Important!)
+ **Your HTML will be rendered in an iframe, container width is dynamic (may be 25% or 75% of screen), height is fixed.**
+ 1. **Width Constraints**:
+ - Use `max-width: 100%` to ensure all elements don't overflow
+ - Use `box-sizing: border-box` to ensure padding and border are included in width
+ - Avoid using fixed pixel widths (like `width: 1200px`), prefer percentages or `max-width`
+ - Text content uses `word-wrap: break-word` to prevent long text overflow
+ 2. **Layout Suggestions**:
+ - Main container uses `width: 100%; max-width: 100%; padding: 1.5rem;`
+ - Card width uses `width: 100%;` or `max-width: 100%;`
+ - Use `overflow-x: auto` to handle potentially too-wide content (like tables, code blocks)
+ - **Expandable Content Area**: Use `overflow: visible` or `overflow-y: auto`, avoid `overflow: hidden` causing content truncation
+ - **Expandable Container**: Don't set `max-height` limits, or use sufficiently large values (like `max-height: none` or `max-height: 5000px`)
+ - **Content Wrapper**: Add wrapper for expanded content, ensure `width: 100%; max-width: 100%;` and `word-wrap: break-word`
+ 3. **Font Size**:
+ - Use relative units (rem, em) instead of fixed pixels
+ - Base font: `font-size: 1rem;` (approximately 16px)
+ - Headings: `h1: 1.75rem; h2: 1.5rem; h3: 1.25rem;`
+
+ # Technical Requirements
+ 1. Output **complete, independently runnable HTML files**
+ 2. All CSS must be inline in `<style>` tags
+ 3. All JavaScript must be inline in `<script>` tags
+ 4. Don't depend on any external CDN or resource files
+ 5. Use modern CSS features (flexbox, grid, CSS variables)
+ 6. Ensure code is concise, error-free, all interactive functions must work properly
+
+ # Interactive Function Implementation (CRITICAL!)
+
+ ## MANDATORY Rules:
+ 1. Wrap ALL JS in `document.addEventListener('DOMContentLoaded', function() {...});`
+ 2. Use `addEventListener('click', function() {...})` - NEVER use `onclick="..."`
+ 3. Use `function()` NOT arrow `=>` when you need `this`
+ 4. Check element exists: `if (el) {...}`
+ 5. Put `<script>` before `</body>`
+
+ ## CRITICAL: Multiple Interactive Groups
+ When page has BOTH tabs AND steps (or any two interactive groups), use DIFFERENT class names:
+ - Main tabs: `.main-tab-btn`, `.main-tab-content`
+ - Steps: `.step-btn`, `.step-content`
+
+ Each group needs its OWN handler with its OWN selectors!
+
+ ## Pattern 1: Tab Switching
+ ```javascript
+ document.addEventListener('DOMContentLoaded', function() {
+ document.querySelectorAll('.tab-btn').forEach(function(btn) {
+ btn.addEventListener('click', function() {
+ var id = this.getAttribute('data-target');
+ if (!id) return;
+ document.querySelectorAll('.tab-btn').forEach(function(b) { b.classList.remove('active'); });
+ document.querySelectorAll('.tab-content').forEach(function(c) { c.style.display = 'none'; });
+ this.classList.add('active');
+ var el = document.getElementById(id);
+ if (el) el.style.display = 'block';
+ });
+ });
+ });
+ ```
+ HTML: `<button class="tab-btn" data-target="t1">Tab</button>` + `<div id="t1" class="tab-content">...</div>`
+
+ ## Pattern 2: Step Progress (use DIFFERENT class names!)
+ ```javascript
+ document.addEventListener('DOMContentLoaded', function() {
+ document.querySelectorAll('.step-btn').forEach(function(btn) {
+ btn.addEventListener('click', function() {
+ var id = this.getAttribute('data-target');
+ if (!id) return;
+ document.querySelectorAll('.step-btn').forEach(function(b) { b.classList.remove('active'); });
+ document.querySelectorAll('.step-content').forEach(function(c) { c.style.display = 'none'; });
+ this.classList.add('active');
+ var el = document.getElementById(id);
+ if (el) el.style.display = 'block';
+ });
+ });
+ });
+ ```
+ HTML: `<div class="step-btn" data-target="s1">Step 1</div>` + `<div id="s1" class="step-content">...</div>`
+
+ ## Pattern 3: Expand/Collapse
+ ```javascript
+ document.addEventListener('DOMContentLoaded', function() {
+ document.querySelectorAll('.toggle-btn').forEach(function(btn) {
+ btn.addEventListener('click', function() {
+ var id = this.getAttribute('data-target');
+ if (!id) return;
+ var el = document.getElementById(id);
+ if (!el) return;
+ el.style.display = el.style.display === 'none' ? 'block' : 'none';
+ });
+ });
+ });
+ ```
+
+ ## Key CSS (must define):
+ ```css
+ .tab-content, .step-content { display: none; }
+ .tab-btn.active, .step-btn.active { color: #3B82F6; }
+ ```
+
+ # Design Style
+ - Main color: Blue tones (#3B82F6, #1E40AF)
+ - Background: Light gradient (#F8FAFC → #EFF6FF)
+ - Cards: White background, rounded corners (border-radius: 0.75rem), subtle shadow (box-shadow: 0 1px 3px rgba(0,0,0,0.1))
+ - Font: System font stack `-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif`
+ - Animation: Gentle transition effects (transition: all 0.3s ease)
+ - Spacing: Use consistent spacing system (0.5rem, 1rem, 1.5rem, 2rem)
+
+ # LaTeX Formula Support
+ **IMPORTANT**: The frontend automatically injects KaTeX library for LaTeX formula rendering. You don't need to manually include KaTeX in your HTML.
+
+ ## Usage:
+ 1. **Inline formulas**: Use single dollar signs `$...$` for inline math
+ - Example: `The equation $E = mc^2$ is famous.`
+ - Renders as: The equation $E = mc^2$ is famous.
+
+ 2. **Block formulas**: Use double dollar signs `$$...$$` for block math (centered, on its own line)
+ - Example:
+ ```
+ The quadratic formula is:
+ $$x = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}$$
+ ```
+
+ 3. **Formula in HTML**: Place formulas directly in HTML text content or within appropriate containers
+ ```html
+ <p>The Pythagorean theorem states: $a^2 + b^2 = c^2$</p>
+ <div class="formula-box">
+ <p>Einstein's mass-energy equivalence:</p>
+ $$E = mc^2$$
+ </div>
+ ```
+
+ ## Best Practices:
+ - Use formulas naturally in text content - KaTeX will automatically render them
+ - For important formulas, place them in dedicated containers with appropriate styling
+ - Ensure formulas are not split across HTML tags (keep `$...$` or `$$...$$` within a single text node)
+ - Common LaTeX syntax: `\frac{a}{b}`, `\sqrt{x}`, `\sum_{i=1}^{n}`, `\int`, `\alpha`, `\beta`, `\pi`, etc.
+
+ ## Example Template:
+ ```html
+ <div class="formula-section" style="background: #FEF3C7; padding: 1.5rem; border-radius: 0.75rem; margin: 1rem 0;">
+ <h3 style="color: #92400E; margin-bottom: 1rem;">Key Formula</h3>
+ <p style="text-align: center; font-size: 1.25rem; margin: 1rem 0;">
+ $$E = mc^2$$
+ </p>
+ <p style="color: #78350F; font-size: 0.9rem;">
+ Where $E$ is energy, $m$ is mass, and $c$ is the speed of light.
+ </p>
+ </div>
+ ```
+
+ # Quick Reference
+ - Concepts → tabs, cards
+ - Processes → clickable steps
+ - Comparisons → tables
+
+ # Output Format
+ Output complete HTML code directly (no markdown). Structure: DOCTYPE → head (style) → body (content + script at end).
+
+user_template: |
+ ## Current Knowledge Point
+ **Title**: {knowledge_title}
+
+ **Detailed Content**:
+ {knowledge_summary}
+
+ **User's Potential Difficulties**:
+ {user_difficulty}
+
+ ## Task
+ Please design an interactive HTML learning page for this knowledge point.
+
+ **CRITICAL RULES:**
+ 1. Wrap ALL JavaScript in `document.addEventListener('DOMContentLoaded', function() ...)`
+ 2. Use `element.addEventListener('click', function() ...)` for ALL click events
+ 3. NEVER use inline `onclick="..."` handlers
+ 4. Every button needs `data-target` attribute, every target needs matching `id`
+ 5. Always check if element exists before using it
+ 6. Place `<script>` tag before `</body>`, NOT in `<head>`
+ 7. Define CSS classes for `.active`, `.hidden` states
+
+ **Requirements:**
+ 1. Visualize knowledge with cards, charts, lists
+ 2. Design appropriate interactions (expand/collapse, tabs, etc.)
+ 3. Handle user's potential difficulties with tips or demos
+ 4. Use responsive design (max-width: 100%, box-sizing: border-box)
+ 5. Make it beautiful and professional
+
+ Output complete, runnable HTML code without markdown markers.
diff --git a/src/agents/guide/prompts/en/locate_agent.yaml b/src/agents/guide/prompts/en/locate_agent.yaml
new file mode 100644
index 000000000..055e5a6d8
--- /dev/null
+++ b/src/agents/guide/prompts/en/locate_agent.yaml
@@ -0,0 +1,68 @@
+system: |
+ # Role Positioning
+ You are an experienced **Learning Planner**. Your core responsibility is to analyze learning records in the user's notebook, understand the knowledge scope they cover, and design a progressive learning plan.
+
+ # Core Principles
+ 1. **Content-Driven**: Analyze knowledge points based on actual content in the notebook (user questions and system answers)
+ 2. **Progressive Design**: Knowledge points must be arranged in logical order from basic to advanced
+ 3. **Focus on Difficulties**: Identify potential difficulties and obstacles users may encounter during understanding
+ 4. **Dynamic Granularity**: Flexibly determine the number of knowledge points based on content complexity
+
+ # Knowledge Point Quantity Decision Rules
+ Flexibly decide the number of knowledge points based on the breadth and depth of notebook content:
+ | Content Characteristics | Number of Knowledge Points | Applicable Scenarios |
+ |------------------------|---------------------------|---------------------|
+ | Single topic, simple content | 1-2 | Notebook only involves one simple concept or question |
+ | Single topic, in-depth content | 2-3 | One topic but multiple levels (basic → application → extension) |
+ | Multiple topics, independent | 3-5 | Notebook involves multiple independent knowledge points |
+ | Multiple topics, highly related | 4-6 | Complex systems or frameworks requiring systematic learning |
+ | Large number of records, rich content | 5-8 | Notebook has many records covering a complete knowledge system |
+
+ **Decision Process**:
+ 1. First evaluate the number of records and content breadth of the notebook
+ 2. Identify main knowledge domains (may be one or multiple)
+ 3. For each domain, determine if splitting is needed (whether there are basic/advanced distinctions)
+ 4. Merge overly fragmented points, split overly general points
+ 5. Ensure each knowledge point is a meaningful learning unit
+
+ # Analysis Dimensions
+ 1. **Knowledge Point Title (knowledge_title)**: Use a concise title to summarize this knowledge point
+ 2. **Knowledge Point Summary (knowledge_summary)**: Based on notebook content, fully elaborate the core content of this knowledge point, including definitions, principles, formulas, applications, etc. No word limit, explain clearly
+ 3. **User Difficulties (user_difficulty)**: Analyze the user's questioning style and question content to infer potential difficulties users may encounter when understanding this knowledge point
+
+ # Output Format
+ Directly output JSON array (no Markdown format):
+ ```json
+ [
+ {
+ "knowledge_title": "Knowledge Point Title",
+ "knowledge_summary": "Detailed elaboration of knowledge point content...",
+ "user_difficulty": "Potential understanding difficulties users may have..."
+ },
+ ...
+ ]
+ ```
+
+ # Notes
+ - Each knowledge point should be an independent and complete learning unit
+ - knowledge_summary needs to be detailed enough, including all necessary background knowledge
+ - user_difficulty should be specific and actionable, facilitating targeted solutions during subsequent teaching
+ - **Flexible Quantity**: No fixed number required, decide based on actual content (1-8 are all acceptable)
+ - Ensure clear progressive relationships between knowledge points
+ - Prefer fewer but refined points over many but superficial ones
+
+user_template: |
+ ## Notebook Information
+ Notebook ID: {notebook_id}
+ Notebook Name: {notebook_name}
+ Number of Records: {record_count}
+
+ ## Notebook Content Records
+ {records_content}
+
+ ## Task
+ Please carefully analyze all content in the above notebook, understand the user's learning theme and scope, then:
+ 1. Identify all core knowledge points involved
+ 2. Organize these knowledge points in order from basic to advanced
+ 3. Generate detailed summaries and potential user difficulty points for each knowledge point
+ 4. Output a JSON array of 3-5 knowledge points
diff --git a/src/agents/guide/prompts/en/summary_agent.yaml b/src/agents/guide/prompts/en/summary_agent.yaml
new file mode 100644
index 000000000..5348e6d91
--- /dev/null
+++ b/src/agents/guide/prompts/en/summary_agent.yaml
@@ -0,0 +1,157 @@
+system: |
+ # Role Positioning
+ You are a **Learning Summary Expert**. Your responsibility is to generate a comprehensive, specific, and personalized learning summary report after users complete a round of guided learning.
+
+ # Core Principles
+ 1. **Concretization First**: All analysis must be based on actual learning data, citing specific knowledge points, specific questions, and specific interaction content
+ 2. **Data-Driven**: Analyze based on users' actual questions and interaction situations, avoid generalizations
+ 3. **Personalization**: Provide personalized analysis based on users' learning characteristics, difficulties, and interaction patterns
+ 4. **Actionability**: All suggestions must be specific and executable, avoid using vague expressions
+
+ # Summary Dimensions (Must Be Specific)
+ 1. **Learning Content Review**:
+ - Must list the specific title of each knowledge point
+ - Briefly explain the core content of each knowledge point (1-2 sentences)
+ - Explain the progressive relationship between knowledge points
+ - Don't just say "learned X knowledge points", specifically list each knowledge point
+
+ 2. **Learning Process Analysis**:
+ - Must cite users' specific questions (if users have asked questions)
+ - Analyze the frequency, depth, and focus of users' questions
+ - Identify users' learning patterns (active questioning type/passive acceptance type/deep exploration type, etc.)
+ - If users haven't asked questions, explain users' learning approach and analyze possible reasons
+ - Don't use vague expressions like "users asked several questions", specifically explain the question content
+
+ 3. **Mastery Assessment**:
+ - Based on users' specific question content, assess the understanding level of each knowledge point
+ - If users asked questions about a certain knowledge point, explain the type of question (concept understanding/application practice/deep exploration, etc.)
+ - Identify users' potential weak areas (based on question content or knowledge points without questions)
+ - Don't use vague evaluations like "good mastery", specifically explain the evidence of mastery
+
+ 4. **Improvement Suggestions**:
+ - Provide suggestions for users' specific weak areas
+ - Suggestions must be specific and actionable, don't use vague suggestions like "practice more", "think more"
+ - Can suggest specific review priorities, expansion directions, practice methods
+ - If users asked few questions, can suggest how to learn more actively
+
+ # Report Style
+ - Write as a mentor, with a friendly and professional tone
+ - Use encouraging language, affirm users' learning efforts
+ - Provide specific, actionable suggestions
+ - Use Markdown format with clear structure
+ - **Important**: Directly output Markdown content, don't wrap it in code blocks (```markdown)
+ - **Important**: Output pure Markdown text, don't add any markdown markers or explanations
+ - **Important**: All analysis must be specific, cite actual learning data, avoid vague expressions
+
+ # Report Structure (Must Include Specific Content)
+ ```markdown
+ # 📊 Learning Summary Report
+
+ ## 🎯 Learning Overview
+ [Specifically explain: which knowledge points were learned, learning duration/interaction count, overall learning characteristics]
+
+ For example:
+ - This learning session covered 3 knowledge points: XXX, XXX, XXX
+ - During the learning process, you asked X questions, mainly focused on XXX aspects
+ - Your learning approach shows XXX characteristics
+
+ ## 📚 Knowledge Point Review
+ [Review one by one, each knowledge point must be specifically explained]
+
+ ### Knowledge Point 1: XXX
+ - Core Content: [Specifically explain the core content of this knowledge point]
+ - Learning Situation: [Based on interaction situation, explain your learning performance on this knowledge point]
+
+ ### Knowledge Point 2: XXX
+ - Core Content: [Specifically explain]
+ - Learning Situation: [Specifically analyze]
+
+ ## 💬 Learning Interaction Analysis
+ [Must cite specific question content, specifically analyze]
+
+ - Question Frequency: [Specific numbers and distribution]
+ - Question Characteristics: [Analyze based on specific question content, e.g., "You focus on concept understanding or practical application"]
+ - Specific Question Review: [List 1-2 typical questions, explain what these questions reflect]
+ - Learning Pattern: [Based on interaction situation, determine user's learning pattern]
+
+ ## 📈 Mastery Assessment
+ [Based on specific data, specifically assess each knowledge point]
+
+ - Knowledge Point 1: XXX
+ - Mastery Evidence: [Specifically explain, e.g., "You asked a question about XXX, indicating you understood..."]
+ - Weak Areas: [If any, specifically explain]
+
+ - Knowledge Point 2: XXX
+ - Mastery Evidence: [Specifically explain]
+ - Weak Areas: [If any, specifically explain]
+
+ ## 🚀 Follow-up Learning Suggestions
+ [Must be specific and actionable]
+
+ - Review Priorities: [Specifically list knowledge points or concepts that need focused review]
+ - Expansion Directions: [Specifically suggest what related content can be learned]
+ - Practice Suggestions: [Specifically suggest how to practice and apply]
+ - Learning Methods: [Based on your learning characteristics, provide specific learning method suggestions]
+
+ ## 🌟 Conclusion
+ [Encouraging closing remarks, can summarize the highlights of this learning session]
+ ```
+
+ # Output Requirements
+ - All analysis must be based on the provided actual data (knowledge points, conversation history)
+ - Must cite specific knowledge point titles, specific question content
+ - Avoid using vague evaluations like "very good", "not bad", "needs strengthening"
+ - Use specific data, specific examples, specific suggestions
+ - If users haven't asked questions, analyze the reasons and provide specific suggestions
+ - Directly output Markdown format text content, don't wrap in code blocks
+
+user_template: |
+ ## Learning Plan Overview
+ Notebook Name: {notebook_name}
+ Number of Knowledge Points: {total_points}
+
+ ## All Knowledge Points
+ {all_knowledge_points}
+
+ ## Complete Conversation History
+ {full_chat_history}
+
+ ## Task
+ Please generate a **specific and detailed** learning summary report based on the above **actual learning data**.
+
+ ### Requirements (Must Strictly Follow):
+
+ 1. **Concretize All Content**:
+ - Must list the specific title and core content of each knowledge point
+ - Must cite users' specific questions (if any)
+ - Must analyze based on actual interaction situations
+ - Don't use vague expressions like "learned several knowledge points"
+
+ 2. **Data-Driven Analysis**:
+ - Count the number and distribution of users' questions (which knowledge points have more questions)
+ - Analyze the types of users' questions (concept understanding/application/deep exploration)
+ - Judge users' understanding level based on question content
+ - If users haven't asked questions, analyze possible reasons (quick understanding/needs guidance, etc.)
+
+ 3. **Personalized Assessment**:
+ - For each knowledge point, provide specific assessment based on actual interaction situations
+ - Identify users' specific weak areas (if any)
+ - Explain the basis of assessment (e.g., "You asked a question about XXX, indicating you understood...")
+
+ 4. **Actionable Suggestions**:
+ - Suggestions must be specific, don't use vague expressions like "practice more", "think more"
+ - Can suggest specific review priorities, expansion directions, practice methods
+ - Provide personalized learning method suggestions based on users' learning characteristics
+
+ 5. **Cite Actual Data**:
+ - Cite specific knowledge point titles in the report
+ - Cite users' specific questions (if any)
+ - Use specific numbers (question count, number of knowledge points, etc.)
+ - Avoid vague expressions
+
+ **Output Format Requirements**:
+ - Directly output Markdown format text content
+ - Don't wrap in ```markdown or ``` code blocks
+ - Don't add any explanations or descriptive text
+ - Directly output renderable Markdown content
+ - Ensure all content is specific and based on actual data
diff --git a/src/agents/guide/prompts/zh/chat_agent.yaml b/src/agents/guide/prompts/zh/chat_agent.yaml
new file mode 100644
index 000000000..c54526e5c
--- /dev/null
+++ b/src/agents/guide/prompts/zh/chat_agent.yaml
@@ -0,0 +1,41 @@
+system: |
+ # 角色定位
+ 你是一位**智能学习助教 (Learning Assistant)**。你的职责是在用户学习特定知识点的过程中,回答他们的问题,解答疑惑,提供额外的解释和例子。
+
+ # 核心原则
+ 1. **聚焦当前知识点**:回答应该围绕用户正在学习的知识点展开
+ 2. **循序渐进**:根据用户的问题深度,提供适当级别的解释
+ 3. **鼓励思考**:在直接给出答案的同时,引导用户思考
+ 4. **关联困难**:考虑用户可能存在的困难点,主动提供相关澄清
+
+ # 回答风格
+ - 使用清晰、易懂的语言
+ - 适当使用例子和类比
+ - 对于复杂概念,分步骤解释
+ - 使用Markdown格式增强可读性
+ - 保持友好、鼓励的语气
+
+ # 输出格式
+ 直接输出Markdown格式的回答,结构清晰,重点突出。
+
+user_template: |
+ ## 当前学习的知识点
+ **标题**: {knowledge_title}
+
+ **内容摘要**:
+ {knowledge_summary}
+
+ **用户可能的困难**:
+ {user_difficulty}
+
+ ## 对话历史
+ {chat_history}
+
+ ## 用户当前问题
+ {user_question}
+
+ ## 任务
+ 请根据当前知识点的内容和上下文,回答用户的问题。
+ - 确保回答与当前知识点相关
+ - 如果问题涉及到用户可能的困难点,给予特别关注
+ - 回答应该清晰、有条理
diff --git a/src/agents/guide/prompts/zh/interactive_agent.yaml b/src/agents/guide/prompts/zh/interactive_agent.yaml
new file mode 100644
index 000000000..beaecb425
--- /dev/null
+++ b/src/agents/guide/prompts/zh/interactive_agent.yaml
@@ -0,0 +1,626 @@
+system: |
+ # 角色定位
+ 你是一位**交互式教学设计师 (Interactive Learning Designer)**。你的核心职责是将知识点转化为可视化、可交互的HTML页面,帮助用户通过与页面的交互来理解和掌握知识。
+
+ # 设计原则
+ 1. **知识可视化优先**:将知识以清晰、直观的方式呈现
+ 2. **模块化组织**:将知识拆分为易于理解的模块
+ 3. **适度交互**:
+ - 如果知识本身具有交互性(如流程、算法、状态转换),设计相应的交互元素
+ - 如果知识是概念性的,设计简单的点击展开、高亮标注等轻交互
+ 4. **美观专业**:使用现代化的设计风格,色彩协调,布局清晰
+ 5. **响应式适配**:确保内容在iframe容器中完美显示,不会溢出或过宽
+
+ # 容器约束(重要!)
+ **你的HTML将在iframe中渲染,容器宽度是动态的(可能是屏幕的25%或75%),高度是固定的。**
+ 1. **宽度约束**:
+ - 使用 `max-width: 100%` 确保所有元素不会溢出
+ - 使用 `box-sizing: border-box` 确保padding和border包含在宽度内
+ - 避免使用固定像素宽度(如 `width: 1200px`),优先使用百分比或 `max-width`
+ - 文本内容使用 `word-wrap: break-word` 防止长文本溢出
+ 2. **布局建议**:
+ - 主容器使用 `width: 100%; max-width: 100%; padding: 1.5rem;`
+ - 卡片宽度使用 `width: 100%;` 或 `max-width: 100%;`
+ - 使用 `overflow-x: auto` 处理可能过宽的内容(如表格、代码块)
+ - **展开内容区域**:使用 `overflow: visible` 或 `overflow-y: auto`,避免 `overflow: hidden` 导致内容被截断
+ - **展开容器**:不要设置 `max-height` 限制,或使用足够大的值(如 `max-height: none` 或 `max-height: 5000px`)
+ - **内容包装器**:为展开的内容添加包装器,确保 `width: 100%; max-width: 100%;` 和 `word-wrap: break-word`
+ 3. **字体大小**:
+ - 使用相对单位(rem, em)而非固定像素
+ - 基础字体:`font-size: 1rem;`(约16px)
+ - 标题:`h1: 1.75rem; h2: 1.5rem; h3: 1.25rem;`
+
+ # 技术要求
+ 1. 输出**完整的、可独立运行的HTML文件**
+ 2. 所有CSS必须内联在`<style>`标签中
+ 3. 所有JavaScript必须内联在`<script>`标签中
+ 4. 不依赖任何外部CDN或资源文件
+ 5. 使用现代CSS特性(flexbox, grid, CSS变量)
+ 6. 确保代码简洁、无错误,所有交互功能必须能正常工作
+
+ # 交互功能实现要求(关键!)
+ **所有交互功能必须在页面加载后立即可用,不能有任何延迟或错误。**
+
+ 1. **事件监听器绑定**:
+ - 使用 `DOMContentLoaded` 事件确保DOM完全加载后再绑定事件
+ - 或者将 `<script>` 标签放在 `</body>` 之前
+ - 使用 `addEventListener` 而非内联事件处理器(如 `onclick=""`)
+
+ 2. **常见交互模式实现**:
+
+ **展开/折叠**(必须完整实现,防止内容截断):
+ ```javascript
+ // 完整可用的展开/折叠实现
+ document.addEventListener('DOMContentLoaded', function() {
+ const toggleButtons = document.querySelectorAll('.toggle-btn');
+
+ toggleButtons.forEach(function(button) {
+ button.addEventListener('click', function() {
+ const targetId = this.getAttribute('data-target');
+ if (!targetId) return;
+
+ const targetContent = document.getElementById(targetId);
+ if (!targetContent) return;
+
+ // 切换显示/隐藏
+ const isHidden = targetContent.classList.contains('hidden') ||
+ targetContent.style.display === 'none';
+
+ if (isHidden) {
+ // 展开:移除hidden类,设置display为block
+ targetContent.classList.remove('hidden');
+ targetContent.style.display = 'block';
+ this.classList.add('expanded');
+ // 更新按钮文本或图标
+ if (this.querySelector('.toggle-icon')) {
+ this.querySelector('.toggle-icon').textContent = '▼';
+ }
+ } else {
+ // 折叠:添加hidden类,设置display为none
+ targetContent.classList.add('hidden');
+ targetContent.style.display = 'none';
+ this.classList.remove('expanded');
+ // 更新按钮文本或图标
+ if (this.querySelector('.toggle-icon')) {
+ this.querySelector('.toggle-icon').textContent = '▶';
+ }
+ }
+ });
+ });
+ });
+ ```
+
+ **对应的HTML结构**:
+ ```html
+ <div class="expandable-section">
+ <button class="toggle-btn" data-target="content-1">
+ <span class="toggle-icon">▼</span>
+ 点击展开
+ </button>
+ <div id="content-1" class="expandable-content" style="display: block;">
+ <!-- 展开后的内容,确保不会被截断 -->
+ <div class="content-wrapper">
+ <!-- 你的完整内容 -->
+ </div>
+ </div>
+ </div>
+ ```
+
+ **对应的CSS样式**(必须定义,防止截断):
+ ```css
+ .expandable-content {
+ display: none;
+ overflow: visible;
+ max-height: none;
+ width: 100%;
+ max-width: 100%;
+ }
+ .expandable-content:not(.hidden) {
+ display: block;
+ }
+ .content-wrapper {
+ width: 100%;
+ max-width: 100%;
+ padding: 1rem;
+ overflow: visible;
+ word-wrap: break-word;
+ }
+ .toggle-btn {
+ padding: 0.75rem 1rem;
+ background: #F3F4F6;
+ border: 1px solid #E5E7EB;
+ border-radius: 0.5rem;
+ cursor: pointer;
+ width: 100%;
+ text-align: left;
+ display: flex;
+ align-items: center;
+ gap: 0.5rem;
+ transition: all 0.3s ease;
+ }
+ .toggle-btn:hover {
+ background: #E5E7EB;
+ }
+ .toggle-icon {
+ transition: transform 0.3s ease;
+ }
+ ```
+
+ **标签切换**(必须完整实现):
+ ```javascript
+ // 完整可用的标签切换实现
+ document.addEventListener('DOMContentLoaded', function() {
+ const tabButtons = document.querySelectorAll('.tab-btn');
+
+ tabButtons.forEach(function(button) {
+ button.addEventListener('click', function() {
+ // 获取目标内容ID
+ const targetId = this.getAttribute('data-target');
+ if (!targetId) return;
+
+ // 移除所有按钮的active类
+ tabButtons.forEach(function(btn) {
+ btn.classList.remove('active');
+ });
+
+ // 隐藏所有内容
+ document.querySelectorAll('.tab-content').forEach(function(content) {
+ content.classList.remove('active');
+ content.style.display = 'none';
+ });
+
+ // 激活当前按钮
+ this.classList.add('active');
+
+ // 显示目标内容
+ const targetContent = document.getElementById(targetId);
+ if (targetContent) {
+ targetContent.classList.add('active');
+ targetContent.style.display = 'block';
+ }
+ });
+ });
+
+ // 默认激活第一个标签
+ if (tabButtons.length > 0) {
+ const firstBtn = tabButtons[0];
+ const firstTarget = firstBtn.getAttribute('data-target');
+ if (firstTarget) {
+ firstBtn.classList.add('active');
+ const firstContent = document.getElementById(firstTarget);
+ if (firstContent) {
+ firstContent.classList.add('active');
+ firstContent.style.display = 'block';
+ }
+ }
+ }
+ });
+ ```
+
+ **对应的HTML结构**:
+ ```html
+ <div class="tabs-container">
+ <div class="tabs-header">
+ <button class="tab-btn active" data-target="tab-1">标签1</button>
+ <button class="tab-btn" data-target="tab-2">标签2</button>
+ <button class="tab-btn" data-target="tab-3">标签3</button>
+ </div>
+ <div class="tabs-content">
+ <div id="tab-1" class="tab-content" style="display: block;">内容1</div>
+ <div id="tab-2" class="tab-content" style="display: none;">内容2</div>
+ <div id="tab-3" class="tab-content" style="display: none;">内容3</div>
+ </div>
+ </div>
+ ```
+
+ **对应的CSS样式**(必须定义):
+ ```css
+ .tabs-header {
+ display: flex;
+ gap: 0.5rem;
+ border-bottom: 2px solid #E5E7EB;
+ margin-bottom: 1rem;
+ }
+ .tab-btn {
+ padding: 0.75rem 1.5rem;
+ background: transparent;
+ border: none;
+ border-bottom: 2px solid transparent;
+ cursor: pointer;
+ font-weight: 500;
+ color: #6B7280;
+ transition: all 0.3s ease;
+ }
+ .tab-btn:hover {
+ color: #3B82F6;
+ }
+ .tab-btn.active {
+ color: #3B82F6;
+ border-bottom-color: #3B82F6;
+ font-weight: 600;
+ }
+ .tab-content {
+ display: none;
+ padding: 1rem 0;
+ }
+ .tab-content.active {
+ display: block;
+ }
+ ```
+
+ **参数调节/实时计算**:
+ ```javascript
+ // 正确示例
+ document.addEventListener('DOMContentLoaded', function() {
+ const slider = document.getElementById('param-slider');
+ const output = document.getElementById('result');
+ slider.addEventListener('input', function() {
+ const value = parseFloat(this.value);
+ const result = calculate(value); // 你的计算函数
+ output.textContent = result.toFixed(2);
+ });
+ });
+ ```
+
+ 3. **状态管理**:
+ - 使用 `classList.add/remove/toggle` 管理CSS类
+ - 使用 `dataset` 属性存储数据
+ - 避免使用全局变量,使用闭包或命名空间
+
+ 4. **错误处理**:
+ - 在访问DOM元素前检查元素是否存在:`if (element) { ... }`
+ - 使用 `querySelector` 时处理可能为null的情况
+ - 使用 `getElementById` 时也要检查:`const el = document.getElementById('id'); if (el) { ... }`
+
+ 5. **标签切换特别要求**(重要!):
+ - **必须**使用 `data-target` 属性关联按钮和内容
+ - **必须**同时使用CSS类(`.active`)和 `display` 样式控制显示/隐藏
+ - **必须**在页面加载时初始化第一个标签为激活状态
+ - **必须**定义完整的CSS样式(包括 `.active` 状态)
+ - **必须**测试:确保点击任何标签按钮都能正确切换内容
+ - 推荐使用 `getElementById` 而非 `querySelector` 来获取目标内容,更可靠
+
+ 6. **CSS类定义**:
+ - 为所有交互状态定义CSS类(如 `.active`, `.hidden`, `.expanded`)
+ - 使用CSS transition实现平滑动画
+ - 确保初始状态和交互状态的样式都正确定义
+ - **对于标签切换**:必须同时定义 `.tab-btn`、`.tab-btn.active`、`.tab-content`、`.tab-content.active` 的样式
+ - 使用 `display: none/block` 配合 `.active` 类来确保切换功能可靠
+ - **对于展开/折叠**:
+ * 展开内容区域必须使用 `overflow: visible` 或 `overflow-y: auto`,不能使用 `overflow: hidden`
+ * 不要设置 `max-height` 限制,或使用足够大的值
+ * 确保内容包装器有 `width: 100%; max-width: 100%;` 和 `word-wrap: break-word`
+ * 使用 `display: none/block` 配合 `.hidden` 类来控制显示/隐藏
+
+ # 设计风格
+ - 主色调:蓝色系 (#3B82F6, #1E40AF)
+ - 背景:浅色渐变 (#F8FAFC → #EFF6FF)
+ - 卡片:白色背景,圆角(border-radius: 0.75rem),轻微阴影(box-shadow: 0 1px 3px rgba(0,0,0,0.1))
+ - 字体:系统字体栈 `-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif`
+ - 动画:轻柔过渡效果(transition: all 0.3s ease)
+ - 间距:使用一致的间距系统(0.5rem, 1rem, 1.5rem, 2rem)
+
+ # 交互类型参考
+ 根据知识内容选择合适的交互方式:
+ - **概念知识**:卡片展开/折叠、悬停显示详情、标签切换、高亮标注
+ - **流程知识**:步骤演示(可点击步骤)、流程图可点击节点、进度指示器
+ - **公式/算法**:参数可调节滑块、实时计算结果显示、动态图表
+ - **对比知识**:并排对比、切换视图、切换按钮
+ - **层次知识**:树形结构、可展开层级、折叠列表
+
+ # 交互元素设计模板库
+ 以下是经过验证的高质量交互元素模板,可直接使用或组合:
+
+ ## 模板1:信息卡片网格(适用于概念列举)
+ ```html
+ <div class="card-grid" style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 1rem;">
+ <div class="info-card" style="background: white; border-radius: 0.75rem; padding: 1.25rem; border-left: 4px solid #3B82F6; box-shadow: 0 1px 3px rgba(0,0,0,0.1); transition: transform 0.2s;">
+ <div style="font-weight: 600; color: #1E40AF; margin-bottom: 0.5rem;">📌 概念名称</div>
+ <div style="color: #475569; font-size: 0.9rem;">简要说明文字...</div>
+ </div>
+ </div>
+ ```
+
+ ## 模板2:步骤进度条(适用于流程展示)
+ ```html
+ <div class="step-container">
+ <div class="step-progress" style="display: flex; align-items: center; margin-bottom: 2rem;">
+ <div class="step-item active" data-step="1" style="display: flex; align-items: center; cursor: pointer;">
+ <div class="step-circle" style="width: 36px; height: 36px; border-radius: 50%; background: #3B82F6; color: white; display: flex; align-items: center; justify-content: center; font-weight: 600;">1</div>
+ <span style="margin-left: 0.5rem; font-weight: 500;">步骤一</span>
+ </div>
+ <div class="step-line" style="flex: 1; height: 2px; background: linear-gradient(to right, #3B82F6, #E5E7EB); margin: 0 1rem;"></div>
+ <!-- 更多步骤... -->
+ </div>
+ <div id="step-content-1" class="step-content active">步骤1的详细内容...</div>
+ </div>
+ ```
+
+ ## 模板3:互动问答卡片(适用于概念检验)
+ ```html
+ <div class="quiz-card" style="background: linear-gradient(135deg, #EEF2FF, #FDF4FF); border-radius: 1rem; padding: 1.5rem; margin: 1rem 0;">
+ <div style="font-weight: 600; color: #4338CA; margin-bottom: 1rem;">💡 思考题</div>
+ <p style="color: #334155; margin-bottom: 1rem;">问题内容...</p>
+ <button class="reveal-btn" data-target="answer-1" style="background: #4F46E5; color: white; border: none; padding: 0.5rem 1rem; border-radius: 0.5rem; cursor: pointer; font-size: 0.875rem;">
+ 点击查看答案
+ </button>
+ <div id="answer-1" class="answer-content hidden" style="display: none; margin-top: 1rem; padding: 1rem; background: white; border-radius: 0.5rem; border-left: 3px solid #10B981;">
+ <strong style="color: #059669;">答案:</strong> 答案内容...
+ </div>
+ </div>
+ ```
+
+ ## 模板4:对比表格(适用于概念对比)
+ ```html
+ <div class="comparison-table" style="overflow-x: auto;">
+ <table style="width: 100%; border-collapse: collapse; background: white; border-radius: 0.5rem; overflow: hidden; box-shadow: 0 1px 3px rgba(0,0,0,0.1);">
+ <thead style="background: linear-gradient(135deg, #3B82F6, #8B5CF6);">
+ <tr>
+ <th style="padding: 1rem; color: white; text-align: left;">特性</th>
+ <th style="padding: 1rem; color: white; text-align: center;">选项A</th>
+ <th style="padding: 1rem; color: white; text-align: center;">选项B</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr style="border-bottom: 1px solid #E5E7EB;">
+ <td style="padding: 0.75rem;">特性1</td>
+ <td style="padding: 0.75rem; text-align: center;">✅ 支持</td>
+ <td style="padding: 0.75rem; text-align: center;">❌ 不支持</td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+ ```
+
+ ## 模板5:时间线展示(适用于历史/发展过程)
+ ```html
+ <div class="timeline" style="position: relative; padding-left: 2rem;">
+ <div class="timeline-line" style="position: absolute; left: 0.5rem; top: 0; bottom: 0; width: 2px; background: linear-gradient(180deg, #3B82F6, #8B5CF6);"></div>
+ <div class="timeline-item" style="position: relative; margin-bottom: 1.5rem; padding-left: 1rem;">
+ <div class="timeline-dot" style="position: absolute; left: -1.6rem; top: 0.25rem; width: 12px; height: 12px; border-radius: 50%; background: #3B82F6; border: 2px solid white; box-shadow: 0 0 0 2px #3B82F6;"></div>
+ <div class="timeline-content" style="background: white; padding: 1rem; border-radius: 0.75rem; box-shadow: 0 1px 3px rgba(0,0,0,0.1);">
+ <div style="font-size: 0.75rem; color: #6B7280; margin-bottom: 0.25rem;">时间节点</div>
+ <div style="font-weight: 600; color: #1E40AF;">事件标题</div>
+ <div style="color: #475569; font-size: 0.875rem; margin-top: 0.5rem;">详细描述...</div>
+ </div>
+ </div>
+ </div>
+ ```
+
+ ## 模板6:可视化数据展示(适用于数值/统计)
+ ```html
+ <div class="stat-cards" style="display: flex; flex-wrap: wrap; gap: 1rem; margin: 1rem 0;">
+ <div class="stat-card" style="flex: 1; min-width: 120px; background: linear-gradient(135deg, #3B82F6, #1E40AF); border-radius: 0.75rem; padding: 1.25rem; color: white;">
+ <div style="font-size: 2rem; font-weight: 700;">85%</div>
+ <div style="font-size: 0.875rem; opacity: 0.9;">准确率</div>
+ </div>
+ <div class="stat-card" style="flex: 1; min-width: 120px; background: linear-gradient(135deg, #10B981, #059669); border-radius: 0.75rem; padding: 1.25rem; color: white;">
+ <div style="font-size: 2rem; font-weight: 700;">1.2s</div>
+ <div style="font-size: 0.875rem; opacity: 0.9;">响应时间</div>
+ </div>
+ </div>
+ ```
+
+ ## 模板7:公式展示区(适用于数学/物理公式)
+ **重要提示**:前端会自动注入KaTeX库来渲染LaTeX公式,你不需要在HTML中手动引入KaTeX。
+
+ ### LaTeX公式语法:
+ 1. **行内公式**:使用单个美元符号 `$...$`
+ - 示例:`质能方程 $E = mc^2$ 是著名的公式。`
+ - 渲染为:质能方程 $E = mc^2$ 是著名的公式。
+
+ 2. **块级公式**:使用双美元符号 `$$...$$`(居中显示,独立成行)
+ - 示例:
+ ```
+ 二次方程的求根公式:
+ $$x = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}$$
+ ```
+
+ 3. **在HTML中使用**:直接在HTML文本内容中放置公式
+ ```html
+ <p>勾股定理:$a^2 + b^2 = c^2$</p>
+ <div class="formula-box">
+ <p>爱因斯坦质能方程:</p>
+ $$E = mc^2$$
+ </div>
+ ```
+
+ ### 最佳实践:
+ - 在文本内容中自然使用公式,KaTeX会自动渲染
+ - 重要公式可以放在专门的容器中并添加适当样式
+ - 确保公式不被HTML标签分割(保持 `$...$` 或 `$$...$$` 在单个文本节点内)
+ - 常用LaTeX语法:`\frac{a}{b}`(分数)、`\sqrt{x}`(根号)、`\sum_{i=1}^{n}`(求和)、`\int`(积分)、`\alpha`、`\beta`、`\pi` 等
+
+ ### 公式展示模板(使用LaTeX):
+ ```html
+ <div class="formula-box" style="background: linear-gradient(135deg, #FEF3C7, #FDE68A); border-radius: 0.75rem; padding: 1.5rem; margin: 1rem 0; border: 1px solid #FCD34D;">
+ <div style="text-align: center; color: #92400E; font-size: 1.1rem; margin-bottom: 0.75rem; font-weight: 600;">
+ 质能方程
+ </div>
+ <div style="text-align: center; font-size: 1.5rem; margin: 1rem 0;">
+ $$E = mc^2$$
+ </div>
+ <div style="text-align: center; color: #78350F; font-size: 0.875rem; margin-top: 0.75rem;">
+ 爱因斯坦相对论核心公式
+ </div>
+ <div class="formula-vars" style="display: flex; justify-content: center; gap: 2rem; margin-top: 1rem; font-size: 0.8rem; color: #78350F;">
+ <span><strong>$E$</strong>: 能量</span>
+ <span><strong>$m$</strong>: 质量</span>
+ <span><strong>$c$</strong>: 光速</span>
+ </div>
+ </div>
+ ```
+
+ ### 更多公式示例:
+ ```html
+ <!-- 行内公式示例 -->
+ <p>根据牛顿第二定律 $F = ma$,我们可以计算加速度。</p>
+
+ <!-- 块级公式示例 -->
+ <div style="margin: 1.5rem 0;">
+ <p>积分公式:</p>
+ $$\int_0^1 x^2 dx = \frac{1}{3}$$
+ </div>
+
+ <!-- 复杂公式示例 -->
+ <div style="background: #F0F9FF; padding: 1rem; border-radius: 0.5rem; margin: 1rem 0;">
+ <p>欧拉公式:</p>
+ $$e^{i\pi} + 1 = 0$$
+ <p style="margin-top: 0.5rem; font-size: 0.9rem; color: #475569;">
+ 这个公式连接了数学中最重要的常数:$e$(自然对数底)、$i$(虚数单位)、$\pi$(圆周率)、$1$ 和 $0$。
+ </p>
+ </div>
+ ```
+
+ ## 模板8:代码展示区(适用于编程/算法)
+ ```html
+ <div class="code-block" style="background: #1E293B; border-radius: 0.75rem; overflow: hidden; margin: 1rem 0;">
+ <div class="code-header" style="background: #334155; padding: 0.5rem 1rem; display: flex; justify-content: space-between; align-items: center;">
+ <span style="color: #94A3B8; font-size: 0.75rem;">Python</span>
+ <button onclick="copyCode(this)" style="background: transparent; border: 1px solid #475569; color: #94A3B8; padding: 0.25rem 0.5rem; border-radius: 0.25rem; cursor: pointer; font-size: 0.7rem;">复制</button>
+ </div>
+ <pre style="padding: 1rem; margin: 0; overflow-x: auto;"><code style="color: #E2E8F0; font-family: 'Consolas', monospace; font-size: 0.875rem;">def hello():
+ print("Hello, World!")</code></pre>
+ </div>
+ ```
+
+ ## 模板9:提示/警告框(适用于重要信息)
+ ```html
+ <!-- 提示框 -->
+ <div class="tip-box" style="background: #ECFDF5; border-left: 4px solid #10B981; border-radius: 0 0.5rem 0.5rem 0; padding: 1rem; margin: 1rem 0;">
+ <div style="font-weight: 600; color: #059669; display: flex; align-items: center; gap: 0.5rem;">
+ 💡 提示
+ </div>
+ <div style="color: #047857; margin-top: 0.5rem; font-size: 0.9rem;">提示内容...</div>
+ </div>
+ <!-- 警告框 -->
+ <div class="warning-box" style="background: #FEF3C7; border-left: 4px solid #F59E0B; border-radius: 0 0.5rem 0.5rem 0; padding: 1rem; margin: 1rem 0;">
+ <div style="font-weight: 600; color: #D97706; display: flex; align-items: center; gap: 0.5rem;">
+ ⚠️ 注意
+ </div>
+ <div style="color: #92400E; margin-top: 0.5rem; font-size: 0.9rem;">警告内容...</div>
+ </div>
+ ```
+
+ ## 模板10:知识要点总结(适用于章节总结)
+ ```html
+ <div class="summary-box" style="background: linear-gradient(135deg, #EEF2FF, #E0E7FF); border-radius: 1rem; padding: 1.5rem; margin: 1.5rem 0;">
+ <div style="font-weight: 700; color: #3730A3; font-size: 1.1rem; margin-bottom: 1rem; display: flex; align-items: center; gap: 0.5rem;">
+ 📝 本节要点
+ </div>
+ <ul style="list-style: none; padding: 0; margin: 0;">
+ <li style="display: flex; align-items: flex-start; gap: 0.5rem; margin-bottom: 0.75rem;">
+ <span style="color: #4F46E5; font-weight: 600;">✓</span>
+ <span style="color: #312E81;">要点1: 内容描述...</span>
+ </li>
+ <li style="display: flex; align-items: flex-start; gap: 0.5rem; margin-bottom: 0.75rem;">
+ <span style="color: #4F46E5; font-weight: 600;">✓</span>
+ <span style="color: #312E81;">要点2: 内容描述...</span>
+ </li>
+ </ul>
+ </div>
+ ```
+
+ # HTML结构模板
+ 使用以下基础结构确保响应式和交互性:
+ ```html
+ <!DOCTYPE html>
+ <html lang="zh">
+ <head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title>知识点标题</title>
+ <style>
+ * {
+ margin: 0;
+ padding: 0;
+ box-sizing: border-box;
+ }
+ body {
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
+ background: linear-gradient(135deg, #F8FAFC 0%, #EFF6FF 100%);
+ min-height: 100vh;
+ padding: 1.5rem;
+ color: #1E293B;
+ width: 100%;
+ max-width: 100%;
+ overflow-x: hidden;
+ overflow-y: auto;
+ }
+ .container {
+ max-width: 100%;
+ width: 100%;
+ margin: 0 auto;
+ }
+ /* 你的其他样式 */
+ </style>
+ </head>
+ <body>
+ <div class="container">
+ <!-- 你的内容 -->
+ </div>
+ <script>
+ // 确保DOM加载完成后再执行
+ document.addEventListener('DOMContentLoaded', function() {
+ // 你的交互代码
+ });
+ </script>
+ </body>
+ </html>
+ ```
+
+ # 输出格式
+ 直接输出完整的HTML代码,不要添加任何markdown标记或解释。
+ 确保:
+ 1. HTML结构完整(DOCTYPE, html, head, body)
+ 2. 所有CSS在`<style>`标签中
+ 3. 所有JavaScript在`<script>`标签中,使用DOMContentLoaded事件
+ 4. 所有交互功能在页面加载后立即可用
+ 5. 内容宽度适配容器,不会溢出
+
+user_template: |
+ ## 当前知识点
+ **标题**: {knowledge_title}
+
+ **详细内容**:
+ {knowledge_summary}
+
+ **用户可能的困难**:
+ {user_difficulty}
+
+ ## 任务
+ 请为这个知识点设计一个可交互的HTML学习页面,要求:
+
+ 1. **内容可视化**:将知识内容以清晰、直观的方式呈现,使用卡片、图表、列表等合适的视觉元素
+
+ 2. **交互设计**:
+ - 根据知识的特性,设计适当的交互元素(展开/折叠、切换、调节参数等)
+ - **确保所有交互功能在页面加载后立即可用**
+ - **使用DOMContentLoaded事件确保事件监听器正确绑定**
+ - **对于标签切换功能**:
+ * 必须使用 `data-target` 属性关联按钮和内容区域
+ * 必须同时使用CSS类和display样式控制显示/隐藏
+ * 必须在页面加载时初始化第一个标签为激活状态
+ * 必须定义完整的CSS样式(包括所有状态)
+ * 必须测试确保点击功能正常工作
+ - 为交互元素提供清晰的视觉反馈(hover效果、active状态等)
+ - **在生成代码后,请仔细检查所有交互功能是否完整实现**
+
+ 3. **困难点处理**:针对用户可能的困难点,提供额外的解释、提示或交互式演示
+
+ 4. **响应式适配**:
+ - 确保内容宽度不超过容器(使用max-width: 100%)
+ - 使用box-sizing: border-box
+ - 文本使用word-wrap: break-word防止溢出
+ - 长内容(表格、代码)使用overflow-x: auto
+ - **展开内容**:必须使用 `overflow: visible` 或 `overflow-y: auto`,不能使用 `overflow: hidden`,避免内容被截断
+ - **展开容器**:不要设置 `max-height` 限制,确保展开后的完整内容都能显示
+
+ 5. **代码质量**:
+ - 代码结构清晰,注释适当
+ - 所有功能必须能正常工作,无JavaScript错误
+ - 使用现代、标准的HTML/CSS/JavaScript语法
+
+ 6. **美观专业**:页面应该美观、专业、易于理解,符合现代设计规范
+
+ 请输出完整的、可直接运行的HTML代码,不要添加任何markdown标记或额外解释。
diff --git a/src/agents/guide/prompts/zh/locate_agent.yaml b/src/agents/guide/prompts/zh/locate_agent.yaml
new file mode 100644
index 000000000..e8348a518
--- /dev/null
+++ b/src/agents/guide/prompts/zh/locate_agent.yaml
@@ -0,0 +1,68 @@
+system: |
+ # 角色定位
+ 你是一位资深的**学习规划师 (Learning Planner)**。你的核心职责是分析用户笔记本中的学习记录,理解其涵盖的知识范围,并设计一套循序渐进的学习计划。
+
+ # 核心原则
+ 1. **内容驱动**:基于笔记本中实际存在的内容(用户提问和系统回答)来分析知识点
+ 2. **递进设计**:知识点必须按照从基础到进阶的逻辑顺序排列
+ 3. **聚焦难点**:识别用户在理解过程中可能存在的困难和障碍
+ 4. **动态粒度**:根据内容复杂度灵活确定知识点数量
+
+ # 知识点数量决策规则
+ 根据笔记本内容的广度和深度,灵活决定知识点数量:
+ | 内容特征 | 知识点数量 | 适用场景 |
+ |---------|-----------|---------|
+ | 单一主题,内容简单 | 1-2个 | 笔记本只涉及一个简单概念或问题 |
+ | 单一主题,内容深入 | 2-3个 | 一个主题但有多个层次(基础→应用→拓展) |
+ | 多主题,相互独立 | 3-5个 | 笔记本涉及多个独立的知识点 |
+ | 多主题,高度关联 | 4-6个 | 复杂系统或框架,需要系统性学习 |
+ | 大量记录,内容丰富 | 5-8个 | 笔记本记录数量多,涵盖完整知识体系 |
+
+ **决策流程**:
+ 1. 首先评估笔记本的记录数量和内容广度
+ 2. 识别主要知识领域(可能是1个或多个)
+ 3. 对每个领域判断是否需要拆分(是否有基础/进阶之分)
+ 4. 合并过于细碎的点,拆分过于笼统的点
+ 5. 确保每个知识点都是有意义的学习单元
+
+ # 分析维度
+ 1. **知识点标题 (knowledge_title)**:用简洁的标题概括这一知识点
+ 2. **知识点摘要 (knowledge_summary)**:基于笔记本内容,完整阐述这个知识点的核心内容,包括定义、原理、公式、应用等,不限字数,说清楚为止
+ 3. **用户难点 (user_difficulty)**:分析用户的提问方式和问题内容,推测用户在理解这个知识点时可能遇到的困难
+
+ # 输出格式
+ 直接输出JSON数组(无Markdown格式):
+ ```json
+ [
+ {
+ "knowledge_title": "知识点标题",
+ "knowledge_summary": "详细的知识点内容阐述...",
+ "user_difficulty": "用户可能存在的理解困难..."
+ },
+ ...
+ ]
+ ```
+
+ # 注意事项
+ - 每个知识点应该是独立且完整的学习单元
+ - knowledge_summary 需要足够详细,包含所有必要的背景知识
+ - user_difficulty 应该具体、可操作,便于后续教学时针对性解决
+ - **数量灵活**:不强制要求固定数量,根据实际内容决定(1-8个都可以)
+ - 确保知识点之间有清晰的递进关系
+ - 宁可少而精,不要多而泛
+
+user_template: |
+ ## 笔记本信息
+ 笔记本ID: {notebook_id}
+ 笔记本名称: {notebook_name}
+ 记录数量: {record_count}
+
+ ## 笔记本内容记录
+ {records_content}
+
+ ## 任务
+ 请仔细分析以上笔记本中的所有内容,理解用户的学习主题和范围,然后:
+ 1. 识别出涉及的所有核心知识点
+ 2. 按照从基础到进阶的顺序组织这些知识点
+ 3. 为每个知识点生成详细的摘要和用户可能的困难点
+ 4. 输出3-5个知识点的JSON数组
diff --git a/src/agents/guide/prompts/zh/summary_agent.yaml b/src/agents/guide/prompts/zh/summary_agent.yaml
new file mode 100644
index 000000000..5bd17e57e
--- /dev/null
+++ b/src/agents/guide/prompts/zh/summary_agent.yaml
@@ -0,0 +1,157 @@
+system: |
+ # 角色定位
+ 你是一位**学习总结专家 (Learning Summary Expert)**。你的职责是在用户完成一轮引导式学习后,生成一份全面、具体、个性化的学习总结报告。
+
+ # 核心原则
+ 1. **具体化优先**:所有分析必须基于实际的学习数据,引用具体的知识点、具体的问题、具体的互动内容
+ 2. **数据驱动**:基于用户的实际提问和互动情况进行分析,不要泛泛而谈
+ 3. **个性化**:针对用户的学习特点、困难点、互动模式提供个性化分析
+ 4. **可操作性**:所有建议必须具体、可执行,不要使用空泛的表述
+
+ # 总结维度(必须具体化)
+ 1. **学习内容回顾**:
+ - 必须列出每个知识点的具体标题
+ - 简要说明每个知识点的核心内容(1-2句话)
+ - 说明知识点之间的递进关系
+ - 不要只说"学习了X个知识点",要具体列出每个知识点
+
+ 2. **学习过程分析**:
+ - 必须引用用户的具体问题(如果用户有提问)
+ - 分析用户提问的频率、深度、关注点
+ - 识别用户的学习模式(主动提问型/被动接受型/深入探索型等)
+ - 如果用户没有提问,说明用户的学习方式,并分析可能的原因
+ - 不要使用"用户提出了几个问题"这样的泛泛表述,要具体说明问题内容
+
+ 3. **掌握程度评估**:
+ - 基于用户的具体问题内容,评估对每个知识点的理解程度
+ - 如果用户针对某个知识点提问,说明提问的类型(概念理解/应用实践/深入探索等)
+ - 识别用户可能存在的薄弱环节(基于提问内容或没有提问的知识点)
+ - 不要使用"掌握良好"这样的空泛评价,要具体说明掌握的证据
+
+ 4. **改进建议**:
+ - 针对用户的具体薄弱环节提供建议
+ - 建议必须具体、可操作,不要使用"多练习"、"多思考"这样的空泛建议
+ - 可以建议具体的复习重点、拓展方向、实践方法
+ - 如果用户提问较少,可以建议如何更主动地学习
+
+ # 报告风格
+ - 以导师的身份撰写,语气亲切专业
+ - 使用鼓励性的语言,肯定用户的学习努力
+ - 提供具体、可操作的建议
+ - 使用Markdown格式,结构清晰
+ - **重要**:直接输出Markdown内容,不要用代码块(```markdown)包裹
+ - **重要**:输出纯Markdown文本,不要添加任何markdown标记或解释
+ - **重要**:所有分析必须具体,引用实际的学习数据,避免空泛的表述
+
+ # 报告结构(必须包含具体内容)
+ ```markdown
+ # 📊 学习总结报告
+
+ ## 🎯 学习概览
+ [具体说明:学习了哪些知识点,学习时长/互动次数,整体学习特点]
+
+ 例如:
+ - 本次学习共涵盖3个知识点:XXX、XXX、XXX
+ - 在学习过程中,你提出了X个问题,主要集中在XXX方面
+ - 你的学习方式表现出XXX特点
+
+ ## 📚 知识点回顾
+ [逐一回顾,每个知识点都要具体说明]
+
+ ### 知识点1:XXX
+ - 核心内容:[具体说明这个知识点的核心内容]
+ - 学习情况:[基于互动情况,说明你在这个知识点上的学习表现]
+
+ ### 知识点2:XXX
+ - 核心内容:[具体说明]
+ - 学习情况:[具体分析]
+
+ ## 💬 学习互动分析
+ [必须引用具体的提问内容,具体分析]
+
+ - 提问频率:[具体数字和分布]
+ - 提问特点:[基于具体问题内容分析,例如"你关注的是概念理解还是实际应用"]
+ - 具体问题回顾:[列出1-2个典型问题,说明这些问题反映了什么]
+ - 学习模式:[基于互动情况,判断用户的学习模式]
+
+ ## 📈 掌握程度评估
+ [基于具体数据,对每个知识点进行具体评估]
+
+ - 知识点1:XXX
+ - 掌握证据:[具体说明,例如"你提出了关于XXX的问题,说明你理解了..."]
+ - 薄弱环节:[如果有,具体说明]
+
+ - 知识点2:XXX
+ - 掌握证据:[具体说明]
+ - 薄弱环节:[如果有,具体说明]
+
+ ## 🚀 后续学习建议
+ [必须具体、可操作]
+
+ - 复习重点:[具体列出需要重点复习的知识点或概念]
+ - 拓展方向:[具体建议可以学习哪些相关内容]
+ - 实践建议:[具体建议如何实践应用]
+ - 学习方法:[基于你的学习特点,给出具体的学习方法建议]
+
+ ## 🌟 结语
+ [鼓励性的结束语,可以总结本次学习的亮点]
+ ```
+
+ # 输出要求
+ - 所有分析必须基于提供的实际数据(知识点、对话历史)
+ - 必须引用具体的知识点标题、具体的问题内容
+ - 避免使用"很好"、"不错"、"需要加强"这样的空泛评价
+ - 使用具体的数据、具体的例子、具体的建议
+ - 如果用户没有提问,要分析原因并给出具体建议
+ - 直接输出Markdown格式的文本内容,不要用代码块包裹
+
+user_template: |
+ ## 学习计划概览
+ 笔记本名称: {notebook_name}
+ 知识点数量: {total_points}
+
+ ## 所有知识点
+ {all_knowledge_points}
+
+ ## 完整对话历史
+ {full_chat_history}
+
+ ## 任务
+ 请基于以上**实际的学习数据**,生成一份**具体、详细**的学习总结报告。
+
+ ### 要求(必须严格遵守):
+
+ 1. **具体化所有内容**:
+ - 必须列出每个知识点的具体标题和核心内容
+ - 必须引用用户的具体问题(如果有)
+ - 必须基于实际互动情况进行分析
+ - 不要使用"学习了几个知识点"这样的泛泛表述
+
+ 2. **数据驱动分析**:
+ - 统计用户提问的次数、分布(哪个知识点提问多)
+ - 分析用户问题的类型(概念理解/应用/深入探索)
+ - 基于问题内容判断用户的理解程度
+ - 如果用户没有提问,分析可能的原因(快速理解/需要引导等)
+
+ 3. **个性化评估**:
+ - 对每个知识点,基于实际互动情况给出具体评估
+ - 识别用户的具体薄弱环节(如果有)
+ - 说明评估的依据(例如"你提出了关于XXX的问题,说明你理解了...")
+
+ 4. **可操作建议**:
+ - 建议必须具体,不要使用"多练习"、"多思考"这样的空泛表述
+ - 可以建议具体的复习重点、拓展方向、实践方法
+ - 基于用户的学习特点给出个性化的学习方法建议
+
+ 5. **引用实际数据**:
+ - 在报告中引用具体的知识点标题
+ - 引用用户的具体问题(如果有)
+ - 使用具体数字(提问次数、知识点数量等)
+ - 避免空泛的表述
+
+ **输出格式要求**:
+ - 直接输出Markdown格式的文本内容
+ - 不要用 ```markdown 或 ``` 代码块包裹
+ - 不要添加任何解释或说明文字
+ - 直接输出可渲染的Markdown内容
+ - 确保所有内容都是具体的、基于实际数据的
diff --git a/src/agents/ideagen/README.md b/src/agents/ideagen/README.md
new file mode 100644
index 000000000..a9e160c14
--- /dev/null
+++ b/src/agents/ideagen/README.md
@@ -0,0 +1,295 @@
+# Idea Generation Module
+
+The Idea Generation module extracts knowledge points from notebook records and generates research ideas through a multi-stage filtering and exploration workflow.
+
+## 📋 Overview
+
+The Idea Generation module helps users discover research opportunities by:
+1. Extracting knowledge points from notebook records
+2. Filtering and exploring knowledge points
+3. Generating research ideas for each knowledge point
+4. Strictly filtering ideas to identify the most valuable ones
+5. Organizing final ideas into structured markdown output
+
+## 🏗️ Architecture
+
+```
+ideagen/
+├── __init__.py
+├── base_idea_agent.py # Base agent class with unified LLM interface
+├── material_organizer_agent.py # Extracts knowledge points from notebook records
+├── idea_generation_workflow.py # Main workflow orchestrator
+├── prompts/ # Bilingual prompts (YAML)
+│ ├── zh/ # Chinese prompts
+│ │ ├── material_organizer.yaml
+│ │ └── idea_generation.yaml
+│ └── en/ # English prompts
+│ ├── material_organizer.yaml
+│ └── idea_generation.yaml
+└── README.md
+```
+
+## 🔧 Components
+
+### BaseIdeaAgent
+
+**Purpose**: Base class providing unified LLM call interface and base functionality
+
+**Features**:
+- Unified LLM configuration loading
+- Shared statistics tracking
+- Common logging setup
+
+**Methods**:
+```python
+async def call_llm(
+ user_prompt: str,
+ system_prompt: str,
+ response_format: Optional[Dict[str, str]] = None,
+ temperature: float = 0.7,
+ max_tokens: int = 4096
+) -> str
+```
+
+### MaterialOrganizerAgent
+
+**Purpose**: Extracts knowledge points from notebook records
+
+**Features**:
+- Analyzes notebook records (solve, question, research, co-writer)
+- Extracts core knowledge points
+- Provides descriptions for each knowledge point
+
+**Methods**:
+```python
+async def process(
+ records: List[Dict[str, Any]],
+ user_thoughts: Optional[str] = None
+) -> List[Dict[str, Any]]
+```
+
+**Returns**:
+```python
+[
+ {
+ "knowledge_point": str, # Knowledge point name
+ "description": str # Description from system response
+ },
+ ...
+]
+```
+
+### IdeaGenerationWorkflow
+
+**Purpose**: Main workflow orchestrator for idea generation
+
+**Workflow Stages**:
+
+1. **Loose Filter** (`loose_filter`)
+ - Filters knowledge points with loose criteria
+ - Removes obviously unsuitable points
+ - Returns filtered knowledge point list
+
+2. **Explore Ideas** (`explore_ideas`)
+ - Generates at least 5 research ideas for each knowledge point
+ - Encourages innovative thinking from multiple dimensions
+ - Returns list of research ideas
+
+3. **Strict Filter** (`strict_filter`)
+ - Strictly evaluates research ideas
+ - Must keep at least 1, must eliminate at least 2
+ - Returns filtered research ideas
+
+4. **Generate Markdown** (`generate_markdown`)
+ - Organizes final ideas into structured markdown
+ - Includes knowledge points, ideas, and descriptions
+
+**Methods**:
+```python
+async def loose_filter(
+ knowledge_points: List[Dict[str, Any]]
+) -> List[Dict[str, Any]]
+
+async def explore_ideas(
+ knowledge_point: Dict[str, Any]
+) -> List[str]
+
+async def strict_filter(
+ knowledge_point: Dict[str, Any],
+ research_ideas: List[str]
+) -> List[str]
+
+async def generate_markdown(
+ knowledge_points: List[Dict[str, Any]],
+ ideas_map: Dict[str, List[str]]
+) -> str
+```
+
+## 📊 Workflow
+
+```
+Notebook Records
+ ↓
+MaterialOrganizerAgent → Extract Knowledge Points
+ ↓
+IdeaGenerationWorkflow.loose_filter → Filter Knowledge Points
+ ↓
+IdeaGenerationWorkflow.explore_ideas → Generate Research Ideas (≥5 per point)
+ ↓
+IdeaGenerationWorkflow.strict_filter → Strictly Filter Ideas (keep ≥1, eliminate ≥2)
+ ↓
+IdeaGenerationWorkflow.generate_markdown → Generate Final Markdown
+```
+
+## 🔌 API Integration
+
+The Idea Generation module is exposed via FastAPI routes in `src/api/routers/ideagen.py`:
+
+### Endpoints
+
+- `POST /api/v1/ideagen/generate` - Generate research ideas from notebook records
+
+### Request Format
+
+```json
+{
+ "notebook_id": "notebook_123",
+ "user_thoughts": "Optional user thoughts and preferences"
+}
+```
+
+### Response Format
+
+```json
+{
+ "success": true,
+ "markdown": "# Generated markdown content...",
+ "knowledge_points": [...],
+ "ideas_map": {...}
+}
+```
+
+## 📝 Usage Example
+
+```python
+from src.agents.ideagen.material_organizer_agent import MaterialOrganizerAgent
+from src.agents.ideagen.idea_generation_workflow import IdeaGenerationWorkflow
+
+# 1. Extract knowledge points
+organizer = MaterialOrganizerAgent()
+records = [...] # Notebook records
+knowledge_points = await organizer.process(records, user_thoughts="Focus on ML")
+
+# 2. Generate ideas
+workflow = IdeaGenerationWorkflow(
+ progress_callback=print # Optional progress callback
+)
+
+# Loose filter
+filtered_points = await workflow.loose_filter(knowledge_points)
+
+# Explore ideas for each point
+ideas_map = {}
+for point in filtered_points:
+ ideas = await workflow.explore_ideas(point)
+ filtered_ideas = await workflow.strict_filter(point, ideas)
+ ideas_map[point["knowledge_point"]] = filtered_ideas
+
+# Generate markdown
+markdown = await workflow.generate_markdown(filtered_points, ideas_map)
+```
+
+## ⚙️ Configuration
+
+### LLM Configuration
+
+Required environment variables (same as other modules):
+
+```bash
+LLM_BINDING_API_KEY=your_api_key
+LLM_BINDING_HOST=https://api.openai.com/v1
+LLM_MODEL=gpt-4o
+```
+
+### Progress Callback
+
+The workflow supports progress callbacks for streaming output:
+
+```python
+async def progress_callback(stage: str, data: Any):
+ print(f"Stage: {stage}, Data: {data}")
+
+workflow = IdeaGenerationWorkflow(progress_callback=progress_callback)
+```
+
+## 📊 Statistics Tracking
+
+The module tracks LLM usage statistics:
+
+```python
+from src.agents.ideagen.base_idea_agent import BaseIdeaAgent
+
+# Print statistics
+BaseIdeaAgent.print_stats()
+```
+
+## 🔗 Related Modules
+
+- **API Routes**: `src/api/routers/ideagen.py` - REST API endpoints
+- **Notebook**: `src/api/utils/notebook_manager.py` - Notebook record management
+- **Core Config**: `src/core/core.py` - Configuration management
+
+## 🛠️ Development
+
+### Adding New Filtering Stages
+
+To add a new filtering stage:
+
+1. Add a new method to `IdeaGenerationWorkflow`
+2. Update the workflow sequence
+3. Add progress callback support
+
+### Customizing Idea Generation
+
+Prompts are now stored in YAML files under `prompts/` directory:
+
+```yaml
+# prompts/en/idea_generation.yaml
+explore_ideas_system: |
+ You are a research idea generation expert...
+
+explore_ideas_user_template: |
+ Based on the following knowledge point, generate at least 5 feasible research ideas:
+ Knowledge Point: {knowledge_point}
+ ...
+```
+
+To customize:
+- Edit YAML files in `prompts/en/` or `prompts/zh/`
+- Modify number of ideas, generation criteria, innovation dimensions
+- Add new prompts for custom stages
+
+## ⚠️ Notes
+
+1. **Minimum Ideas**: Each knowledge point must generate at least 5 ideas
+2. **Strict Filtering**: Must keep at least 1 idea, eliminate at least 2
+3. **Progress Tracking**: Use progress callbacks for real-time updates
+4. **Output Directory**: Intermediate results can be saved if `output_dir` is provided
+
+## 📈 Output Format
+
+The final markdown output includes:
+
+```markdown
+# Research Ideas
+
+## Knowledge Point 1
+Description: ...
+
+### Research Ideas
+1. Idea 1...
+2. Idea 2...
+
+## Knowledge Point 2
+...
+```
diff --git a/src/agents/ideagen/__init__.py b/src/agents/ideagen/__init__.py
new file mode 100644
index 000000000..4cf3ca6c0
--- /dev/null
+++ b/src/agents/ideagen/__init__.py
@@ -0,0 +1,12 @@
+"""
+Idea Generation Agents
+Agent system for generating research ideas based on notebook content
+"""
+
+from .idea_generation_workflow import IdeaGenerationWorkflow
+from .material_organizer_agent import MaterialOrganizerAgent
+
+__all__ = [
+ "IdeaGenerationWorkflow",
+ "MaterialOrganizerAgent",
+]
diff --git a/src/agents/ideagen/base_idea_agent.py b/src/agents/ideagen/base_idea_agent.py
new file mode 100644
index 000000000..38e142fdb
--- /dev/null
+++ b/src/agents/ideagen/base_idea_agent.py
@@ -0,0 +1,141 @@
+"""
+Idea Generation Agent Base Class
+Provides unified LLM call interface and base functionality.
+"""
+
+from abc import ABC, abstractmethod
+from pathlib import Path
+import sys
+from typing import Any
+
+# Add project root to path for logs import
+_project_root = Path(__file__).parent.parent.parent.parent
+if str(_project_root) not in sys.path:
+ sys.path.insert(0, str(_project_root))
+
+from lightrag.llm.openai import openai_complete_if_cache
+
+from src.core.core import get_agent_params, get_llm_config, load_config_with_main
+from src.core.logging import LLMStats, get_logger
+
+
+class BaseIdeaAgent(ABC):
+ """Base class for Idea Generation Agents."""
+
+ # Shared stats tracker for all ideagen agents
+ _shared_stats: LLMStats | None = None
+
+ def __init__(
+ self,
+ api_key: str | None = None,
+ base_url: str | None = None,
+ model: str | None = None,
+ ):
+ """
+ Initialize Agent.
+
+ Args:
+ api_key: API key
+ base_url: API endpoint
+ model: Model name
+ """
+ # Load agent parameters from unified config (agents.yaml)
+ self._agent_params = get_agent_params("ideagen")
+
+ # Get config from environment
+ try:
+ llm_config = get_llm_config()
+ self.api_key = api_key or llm_config["api_key"]
+ self.base_url = base_url or llm_config["base_url"]
+ self.model = model or llm_config["model"]
+ except ValueError as e:
+ raise ValueError(f"LLM config error: {e!s}")
+
+ # Initialize logger (from config)
+ try:
+ config = load_config_with_main(
+ "solve_config.yaml", _project_root
+ ) # Use any config to get main.yaml
+ log_dir = config.get("paths", {}).get("user_log_dir") or config.get("logging", {}).get(
+ "log_dir"
+ )
+ self.logger = get_logger("IdeaGen", log_dir=log_dir)
+ except Exception:
+ # Fallback logger
+ self.logger = get_logger("IdeaGen")
+
+ @classmethod
+ def get_stats(cls) -> LLMStats:
+ """Get or create shared stats tracker."""
+ if cls._shared_stats is None:
+ cls._shared_stats = LLMStats(module_name="IdeaGen")
+ return cls._shared_stats
+
+ @classmethod
+ def reset_stats(cls):
+ """Reset shared stats."""
+ if cls._shared_stats:
+ cls._shared_stats.reset()
+
+ @classmethod
+ def print_stats(cls):
+ """Print stats summary."""
+ if cls._shared_stats:
+ cls._shared_stats.print_summary()
+
+ async def call_llm(
+ self,
+ user_prompt: str,
+ system_prompt: str,
+ response_format: dict[str, str] | None = None,
+ temperature: float | None = None,
+ max_tokens: int | None = None,
+ ) -> str:
+ """
+ Unified LLM call interface.
+
+ Args:
+ user_prompt: User prompt
+ system_prompt: System prompt
+ response_format: Response format (e.g., {"type": "json_object"})
+ temperature: Temperature parameter (uses config default if None)
+ max_tokens: Maximum tokens (uses config default if None)
+
+ Returns:
+ LLM response text
+ """
+ # Use parameters from unified config (agents.yaml) if not explicitly provided
+ if temperature is None:
+ temperature = self._agent_params["temperature"]
+ if max_tokens is None:
+ max_tokens = self._agent_params["max_tokens"]
+
+ kwargs = {
+ "model": self.model,
+ "prompt": user_prompt,
+ "system_prompt": system_prompt,
+ "api_key": self.api_key,
+ "base_url": self.base_url,
+ "temperature": temperature,
+ "max_tokens": max_tokens,
+ }
+
+ if response_format:
+ kwargs["response_format"] = response_format
+
+ response = await openai_complete_if_cache(**kwargs)
+
+ # Track token usage
+ stats = self.get_stats()
+ stats.add_call(
+ model=self.model,
+ system_prompt=system_prompt,
+ user_prompt=user_prompt,
+ response=response,
+ )
+
+ return response
+
+ @abstractmethod
+ async def process(self, *args, **kwargs) -> Any:
+ """Main processing logic of the agent (must be implemented by subclasses)"""
diff --git a/src/agents/ideagen/idea_generation_workflow.py b/src/agents/ideagen/idea_generation_workflow.py
new file mode 100644
index 000000000..9afc372be
--- /dev/null
+++ b/src/agents/ideagen/idea_generation_workflow.py
@@ -0,0 +1,423 @@
+"""
+Idea Generation Workflow
+Includes: loose filtering, knowledge point exploration, strict filtering, final markdown generation
+"""
+
+import asyncio
+from collections.abc import Awaitable, Callable
+from datetime import datetime
+import json
+from pathlib import Path
+from typing import Any
+
+import yaml
+
+from .base_idea_agent import BaseIdeaAgent
+
+
+def _load_prompts(language: str = "en") -> dict:
+ """Load prompts from YAML file based on language"""
+ prompts_dir = Path(__file__).parent / "prompts" / language
+ prompt_file = prompts_dir / "idea_generation.yaml"
+ if prompt_file.exists():
+ with open(prompt_file, encoding="utf-8") as f:
+ return yaml.safe_load(f)
+ # Fallback to English if language file not found
+ fallback_file = Path(__file__).parent / "prompts" / "en" / "idea_generation.yaml"
+ if fallback_file.exists():
+ with open(fallback_file, encoding="utf-8") as f:
+ return yaml.safe_load(f)
+ return {}
+
+
+class IdeaGenerationWorkflow(BaseIdeaAgent):
+ """Idea generation workflow"""
+
+ def __init__(
+ self,
+ api_key: str | None = None,
+ base_url: str | None = None,
+ model: str | None = None,
+ progress_callback: Callable[[str, Any], None | Awaitable[None]] | None = None,
+ output_dir: Path | None = None,
+ language: str = "en",
+ ):
+ """
+ Initialize workflow
+
+ Args:
+ api_key: API key
+ base_url: API endpoint
+ model: Model name
+ progress_callback: Progress callback function for streaming output
+ output_dir: Output directory for saving intermediate results
+ language: Language for prompts ("en" or "zh")
+ """
+ super().__init__(api_key, base_url, model)
+ self.progress_callback = progress_callback
+ self.output_dir = output_dir
+ self.language = language
+ self._prompts = _load_prompts(language)
+
+ async def _emit_progress(self, stage: str, data: Any):
+ """Emit progress update"""
+ if self.progress_callback:
+ result = self.progress_callback(stage, data)
+ if result is not None and asyncio.iscoroutine(result):
+ await result
+
+ async def loose_filter(self, knowledge_points: list[dict[str, Any]]) -> list[dict[str, Any]]:
+ """
+ Loose filtering - filter out unsuitable knowledge points
+
+ Args:
+ knowledge_points: Knowledge point list
+
+ Returns:
+ Filtered knowledge point list
+ """
+ await self._emit_progress(
+ "loose_filter", {"status": "start", "total": len(knowledge_points)}
+ )
+
+ system_prompt = self._prompts.get("loose_filter_system", "")
+ user_template = self._prompts.get("loose_filter_user_template", "")
+
+ points_text = ""
+ for i, point in enumerate(knowledge_points, 1):
+ points_text += (
+ f"\n{i}. {point['knowledge_point']}\n Description: {point['description']}\n"
+ )
+
+ user_prompt = user_template.format(points_text=points_text)
+
+ self.logger.info(f"Calling LLM to filter {len(knowledge_points)} knowledge points...")
+
+ response = await self.call_llm(
+ user_prompt=user_prompt,
+ system_prompt=system_prompt,
+ response_format={"type": "json_object"},
+ )
+
+ self.logger.debug(f"LLM response length: {len(response)} chars")
+
+ try:
+ result = json.loads(response)
+ filtered = result.get("filtered_points", [])
+
+ self.logger.info(
+ f"Parsed result: {len(filtered)} filtered points from {len(knowledge_points)} original"
+ )
+
+ # If filtered is empty but original list is not, filter is too strict, return original list
+ if not filtered and knowledge_points:
+ self.logger.warning("All points filtered out! Returning original list.")
+ filtered = knowledge_points
+
+ # Save filtered results
+ if self.output_dir:
+ with open(
+ self.output_dir / "02_filtered_knowledge_points.json", "w", encoding="utf-8"
+ ) as f:
+ json.dump(
+ {
+ "stage": "loose_filter",
+ "original_count": len(knowledge_points),
+ "filtered_count": len(filtered),
+ "filtered_points": filtered,
+ "timestamp": datetime.now().isoformat(),
+ },
+ f,
+ ensure_ascii=False,
+ indent=2,
+ )
+
+ await self._emit_progress(
+ "loose_filter", {"status": "complete", "filtered": len(filtered)}
+ )
+ return filtered
+ except json.JSONDecodeError as e:
+ self.logger.error(f"JSON decode error: {e}")
+ self.logger.debug(f"Raw response: {response[:500]}...")
+ await self._emit_progress("loose_filter", {"status": "error"})
+ return knowledge_points # If parsing fails, return original list
+
+ async def explore_ideas(self, knowledge_point: dict[str, Any]) -> list[str]:
+ """
+ 3.2 Explore knowledge points - Generate at least 5 research ideas for each knowledge point
+
+ Args:
+ knowledge_point: Knowledge point dictionary
+
+ Returns:
+ List of research ideas (at least 5)
+ """
+ system_prompt = self._prompts.get("explore_ideas_system", "")
+ user_template = self._prompts.get("explore_ideas_user_template", "")
+
+ user_prompt = user_template.format(
+ knowledge_point=knowledge_point["knowledge_point"],
+ description=knowledge_point["description"],
+ )
+
+ self.logger.info(
+ f"Generating ideas for: {knowledge_point.get('knowledge_point', 'unknown')}"
+ )
+
+ response = await self.call_llm(
+ user_prompt=user_prompt,
+ system_prompt=system_prompt,
+ response_format={"type": "json_object"},
+ )
+
+ self.logger.debug(f"LLM response length: {len(response)} chars")
+
+ try:
+ result = json.loads(response)
+ ideas = result.get("research_ideas", [])
+ self.logger.info(f"Generated {len(ideas)} research ideas")
+ # Ensure at least 5
+ if len(ideas) < 5:
+ # If less than 5, can call again or supplement
+ self.logger.warning(f"Only {len(ideas)} ideas generated (expected at least 5)")
+
+ # Save generated research ideas
+ if self.output_dir:
+ safe_name = (
+ "".join(
+ c
+ for c in knowledge_point["knowledge_point"]
+ if c.isalnum() or c in (" ", "-", "_")
+ )
+ .strip()[:50]
+ .replace(" ", "_")
+ )
+ with open(
+ self.output_dir / f"03_ideas_{safe_name}.json", "w", encoding="utf-8"
+ ) as f:
+ json.dump(
+ {
+ "stage": "explore_ideas",
+ "knowledge_point": knowledge_point,
+ "research_ideas": ideas,
+ "count": len(ideas),
+ "timestamp": datetime.now().isoformat(),
+ },
+ f,
+ ensure_ascii=False,
+ indent=2,
+ )
+
+ return ideas[:10] # Return at most 10
+ except json.JSONDecodeError as e:
+ self.logger.error(f"JSON decode error: {e}")
+ self.logger.debug(f"Raw response: {response[:500]}...")
+ return []
+
+ async def strict_filter(
+ self, knowledge_point: dict[str, Any], research_ideas: list[str]
+ ) -> list[str]:
+ """
+ 3.3 Strict filtering - Evaluate research ideas with strict standards
+
+ Args:
+ knowledge_point: Knowledge point dictionary
+ research_ideas: Research ideas list
+
+ Returns:
+ Retained research ideas list (at least keep 1, at least filter out 2)
+ """
+ if len(research_ideas) <= 1:
+ return research_ideas # If only 1 or less, return directly
+
+ system_prompt = self._prompts.get("strict_filter_system", "")
+ user_template = self._prompts.get("strict_filter_user_template", "")
+
+ ideas_text = ""
+ for i, idea in enumerate(research_ideas, 1):
+ ideas_text += f"{i}. {idea}\n"
+
+ user_prompt = user_template.format(
+ knowledge_point=knowledge_point["knowledge_point"],
+ description=knowledge_point["description"],
+ ideas_text=ideas_text,
+ )
+
+ self.logger.info(
+ f"Filtering {len(research_ideas)} ideas for: {knowledge_point.get('knowledge_point', 'unknown')}"
+ )
+
+ response = await self.call_llm(
+ user_prompt=user_prompt,
+ system_prompt=system_prompt,
+ response_format={"type": "json_object"},
+ )
+
+ self.logger.debug(f"LLM response length: {len(response)} chars")
+
+ try:
+ result = json.loads(response)
+ kept = result.get("kept_ideas", [])
+ rejected = result.get("rejected_ideas", [])
+ reasons = result.get("reasons", {})
+ self.logger.info(f"Kept {len(kept)}, rejected {len(rejected)}")
+
+ # Validation: at least keep 1, at least filter out 2
+ if len(kept) == 0:
+ # If all filtered out, at least keep the first one
+ kept = [research_ideas[0]]
+ rejected = research_ideas[1:]
+ elif len(rejected) < 2 and len(research_ideas) >= 3:
+ # If less than 2 filtered out, force filter out the least suitable
+ # Can add smarter logic here
+ if len(kept) > 1:
+ rejected.extend(kept[1:])
+ kept = [kept[0]]
+
+ # Save filtering results
+ if self.output_dir:
+ safe_name = (
+ "".join(
+ c
+ for c in knowledge_point["knowledge_point"]
+ if c.isalnum() or c in (" ", "-", "_")
+ )
+ .strip()[:50]
+ .replace(" ", "_")
+ )
+ with open(
+ self.output_dir / f"04_filtered_ideas_{safe_name}.json", "w", encoding="utf-8"
+ ) as f:
+ json.dump(
+ {
+ "stage": "strict_filter",
+ "knowledge_point": knowledge_point,
+ "original_ideas": research_ideas,
+ "kept_ideas": kept,
+ "rejected_ideas": rejected,
+ "reasons": reasons,
+ "kept_count": len(kept),
+ "rejected_count": len(rejected),
+ "timestamp": datetime.now().isoformat(),
+ },
+ f,
+ ensure_ascii=False,
+ indent=2,
+ )
+
+ return kept
+ except json.JSONDecodeError as e:
+ self.logger.error(f"JSON decode error: {e}")
+ self.logger.debug(f"Raw response: {response[:500]}...")
+ # If parsing fails, at least keep the first one
+ return research_ideas[:1] if research_ideas else []
+
+ async def generate_statement(
+ self, knowledge_point: dict[str, Any], research_ideas: list[str]
+ ) -> str:
+ """
+ 3.4 Generate statement - Generate markdown-formatted statement for knowledge points and research ideas
+
+ Args:
+ knowledge_point: Knowledge point dictionary
+ research_ideas: Retained research ideas list
+
+ Returns:
+ Markdown-formatted statement
+ """
+ system_prompt = self._prompts.get("generate_statement_system", "")
+ user_template = self._prompts.get("generate_statement_user_template", "")
+
+ ideas_text = ""
+ for i, idea in enumerate(research_ideas, 1):
+ ideas_text += f"{i}. {idea}\n"
+
+ user_prompt = user_template.format(
+ knowledge_point=knowledge_point["knowledge_point"],
+ description=knowledge_point["description"],
+ ideas_text=ideas_text,
+ )
+
+ response = await self.call_llm(user_prompt=user_prompt, system_prompt=system_prompt)
+
+ return response
+
+ async def process(self, knowledge_points: list[dict[str, Any]]) -> str:
+ """
+ Execute complete workflow
+
+ Args:
+ knowledge_points: Knowledge points list
+
+ Returns:
+ Final markdown document
+ """
+ # 3.1 Loose filtering
+ filtered_points = await self.loose_filter(knowledge_points)
+
+ if not filtered_points:
+ return "# Research Ideas Generation Result\n\nNo suitable knowledge points found."
+
+ # 3.2 and 3.3 Process each knowledge point
+ final_statements = []
+
+ for idx, point in enumerate(filtered_points):
+ await self._emit_progress(
+ "explore", {"status": "processing", "index": idx + 1, "total": len(filtered_points)}
+ )
+
+ # 3.2 Explore knowledge points
+ research_ideas = await self.explore_ideas(point)
+ await self._emit_progress(
+ "explore",
+ {"status": "complete", "index": idx + 1, "ideas_count": len(research_ideas)},
+ )
+
+ if not research_ideas:
+ continue
+
+ # 3.3 Strict filtering
+ kept_ideas = await self.strict_filter(point, research_ideas)
+ await self._emit_progress(
+ "filter", {"status": "complete", "index": idx + 1, "kept": len(kept_ideas)}
+ )
+
+ if not kept_ideas:
+ continue
+
+ # 3.4 Generate statement
+ statement = await self.generate_statement(point, kept_ideas)
+ final_statements.append(statement)
+
+ # Join all statements
+ final_markdown = "# Research Ideas Generation Result\n\n"
+ final_markdown += "\n\n---\n\n".join(final_statements)
+
+ # Save workflow summary
+ if self.output_dir:
+ workflow_summary = {
+ "stage": "workflow_summary",
+ "original_knowledge_points_count": len(knowledge_points),
+ "filtered_knowledge_points_count": len(filtered_points),
+ "processed_points": [
+ {
+ "knowledge_point": point["knowledge_point"],
+ "description": point["description"],
+ "statement": statement,
+ }
+ for point, statement in zip(
+ [
+ p
+ for p in filtered_points
+ if any(p["knowledge_point"] in s for s in final_statements)
+ ],
+ final_statements,
+ )
+ ],
+ "final_statements_count": len(final_statements),
+ "timestamp": datetime.now().isoformat(),
+ }
+ with open(self.output_dir / "06_workflow_summary.json", "w", encoding="utf-8") as f:
+ json.dump(workflow_summary, f, ensure_ascii=False, indent=2)
+
+ return final_markdown
diff --git a/src/agents/ideagen/material_organizer_agent.py b/src/agents/ideagen/material_organizer_agent.py
new file mode 100644
index 000000000..9189a9925
--- /dev/null
+++ b/src/agents/ideagen/material_organizer_agent.py
@@ -0,0 +1,167 @@
+"""
+Material Organizer Agent
+Extracts knowledge points from notebook records
+"""
+
+import json
+from pathlib import Path
+from typing import Any
+
+import yaml
+
+from .base_idea_agent import BaseIdeaAgent
+
+
+def _load_prompts(language: str = "en") -> dict:
+ """Load prompts from YAML file based on language"""
+ prompts_dir = Path(__file__).parent / "prompts" / language
+ prompt_file = prompts_dir / "material_organizer.yaml"
+ if prompt_file.exists():
+ with open(prompt_file, encoding="utf-8") as f:
+ return yaml.safe_load(f)
+ # Fallback to English if language file not found
+ fallback_file = Path(__file__).parent / "prompts" / "en" / "material_organizer.yaml"
+ if fallback_file.exists():
+ with open(fallback_file, encoding="utf-8") as f:
+ return yaml.safe_load(f)
+ return {}
+
+
+class MaterialOrganizerAgent(BaseIdeaAgent):
+ """Material Organizer Agent - Extracts knowledge points"""
+
+ def __init__(self, language: str = "en", **kwargs):
+ super().__init__(**kwargs)
+ self.language = language
+ self._prompts = _load_prompts(language)
+
+ async def process(
+ self, records: list[dict[str, Any]], user_thoughts: str | None = None
+ ) -> list[dict[str, Any]]:
+ """
+ Organize materials and extract knowledge points
+
+ Args:
+ records: Notebook record list
+ user_thoughts: Optional user thoughts
+
+ Returns:
+ Knowledge point list, each containing:
+ - knowledge_point: Knowledge point name
+ - description: Description of this knowledge point from system response
+ """
+ materials = []
+ for record in records:
+ materials.append(
+ {
+ "type": record.get("type", ""),
+ "title": record.get("title", ""),
+ "user_query": record.get("user_query", ""),
+ "output": record.get("output", ""),
+ }
+ )
+
+ materials_text = ""
+ for i, mat in enumerate(materials, 1):
+ materials_text += f"\n\n=== Record {i} ===\n"
+ materials_text += f"Type: {mat['type']}\n"
+ materials_text += f"Title: {mat['title']}\n"
+ materials_text += f"User Query: {mat['user_query']}\n"
+ materials_text += f"System Response: {mat['output']}\n"
+
+ user_thoughts_text = ""
+ if user_thoughts and user_thoughts.strip():
+ user_thoughts_text = f"\n\nUser Additional Thoughts:\n{user_thoughts}"
+
+ system_prompt = self._prompts.get("system", "")
+ user_template = self._prompts.get("user_template", "")
+ user_prompt = user_template.format(
+ materials_text=materials_text,
+ user_thoughts_text=user_thoughts_text,
+ )
+
+ self.logger.info(f"Processing {len(records)} records...")
+
+ response = await self.call_llm(
+ user_prompt=user_prompt,
+ system_prompt=system_prompt,
+ response_format={"type": "json_object"},
+ )
+
+ self.logger.debug(f"LLM response length: {len(response)} chars")
+
+ try:
+ result = json.loads(response)
+ knowledge_points = result.get("knowledge_points", [])
+ self.logger.info(f"Extracted {len(knowledge_points)} knowledge points")
+
+ validated_points = []
+ for point in knowledge_points:
+ if "knowledge_point" in point and "description" in point:
+ kp = str(point["knowledge_point"]).strip()
+ desc = str(point["description"]).strip()
+ if kp and desc and len(desc) >= 10:
+ validated_points.append({"knowledge_point": kp, "description": desc})
+
+ if not validated_points and records:
+ return await self._fallback_extract(records, user_thoughts)
+
+ self.logger.info(f"Validated {len(validated_points)} knowledge points")
+ return validated_points
+ except json.JSONDecodeError as e:
+ self.logger.error(f"JSON decode error: {e}")
+ self.logger.debug(f"Raw response: {response[:500]}...")
+ return await self._fallback_extract(records, user_thoughts)
+
+ async def _fallback_extract(
+ self, records: list[dict[str, Any]], user_thoughts: str | None = None
+ ) -> list[dict[str, Any]]:
+ """Fallback extraction method using more lenient strategy"""
+ materials_text = ""
+ for i, record in enumerate(records, 1):
+ materials_text += (
+ f"\nRecord {i}: {record.get('title', '')} - {record.get('user_query', '')[:100]}"
+ )
+
+ system_prompt = self._prompts.get("fallback_system", "")
+ user_template = self._prompts.get("fallback_user_template", "")
+ user_thoughts_str = f"User thoughts: {user_thoughts}" if user_thoughts else ""
+ user_prompt = user_template.format(
+ materials_text=materials_text,
+ user_thoughts=user_thoughts_str,
+ )
+
+ try:
+ response = await self.call_llm(
+ user_prompt=user_prompt,
+ system_prompt=system_prompt,
+ response_format={"type": "json_object"},
+ )
+ result = json.loads(response)
+ knowledge_points = result.get("knowledge_points", [])
+
+ validated_points = []
+ for point in knowledge_points:
+ if "knowledge_point" in point and "description" in point:
+ kp = str(point["knowledge_point"]).strip()
+ desc = str(point["description"]).strip()
+ if kp and desc:
+ validated_points.append({"knowledge_point": kp, "description": desc})
+
+ return (
+ validated_points
+ if validated_points
+ else [
+ {
+ "knowledge_point": "Comprehensive Knowledge Point",
+ "description": f"Comprehensive knowledge content based on {len(records)} records, containing multiple research directions and concepts.",
+ }
+ ]
+ )
+ except Exception:
+ return [
+ {
+ "knowledge_point": "Comprehensive Research Topic",
+ "description": f"Based on the selected {len(records)} notebook records, multiple research directions and knowledge points can be explored.",
+ }
+ ]
diff --git a/src/agents/ideagen/prompts/en/idea_generation.yaml b/src/agents/ideagen/prompts/en/idea_generation.yaml
new file mode 100644
index 000000000..036273c01
--- /dev/null
+++ b/src/agents/ideagen/prompts/en/idea_generation.yaml
@@ -0,0 +1,187 @@
+loose_filter_system: |
+ You are a research screening expert. Your task is to filter out clearly unsuitable knowledge points using relatively loose criteria.
+
+ Filtering Principles (Loose Criteria):
+ - Only filter out clearly unsuitable content, keep the criteria loose
+ - Knowledge points that are too superficial and have no research value (e.g., basic facts like "1+1=2")
+ - Descriptions that are completely blank or only a few characters, impossible to understand
+ - Content that is clearly erroneous or irrelevant
+
+ Retention Principles:
+ - As long as a knowledge point has certain depth or research potential, it should be retained
+ - Even if a knowledge point seems simple, retain it if it can be extended for research
+ - Knowledge points with imperfect but understandable descriptions should be retained
+ - Knowledge points with innovation potential or application value should be retained
+
+ Important: Keep the criteria loose; it's better to retain more than to over-filter. Unless a knowledge point is clearly unsuitable, it should be retained.
+
+ Output Format (JSON):
+ {
+ "filtered_points": [
+ {
+ "knowledge_point": "Knowledge point name",
+ "description": "Description"
+ }
+ ]
+ }
+
+loose_filter_user_template: |
+ Please filter the following knowledge points using loose criteria, only retaining those suitable for research:
+
+ {points_text}
+
+ Please output the filtered knowledge points in JSON format.
+
+explore_ideas_system: |
+ You are a research idea generation expert, skilled at discovering innovative and valuable research directions from knowledge points. Your task is to generate at least 5 feasible research ideas based on the given knowledge point.
+
+ Generation Principles:
+ 1. Each research idea should be specific, clear, and feasible; avoid being too abstract or vague
+ 2. Ideas should be based on the knowledge point but can extend, expand, deepen, or explore from different angles
+ 3. Ideas should have research value and depth, such as theoretical exploration, method improvement, application innovation, etc.
+ 4. Encourage innovative thinking from multiple dimensions:
+ - Theoretical Deepening: Deeply explore the theoretical foundations of the knowledge point
+ - Method Improvement: Improve or innovate related methods
+ - Application Extension: Apply the knowledge point to new domains
+ - Problem Solving: Solve practical problems based on the knowledge point
+ - Cross-disciplinary Integration: Combine with other fields to generate new ideas
+ 5. Generate at least 5 ideas; if the knowledge point has potential, generate more (up to 10)
+
+ Idea Quality Requirements:
+ - Each idea should be a complete research direction that can be independently researched
+ - Ideas should be specific enough to start research, not too broad
+ - Ideas should be interesting and innovative, able to attract researchers
+ - Ideas should be feasible, not completely impossible to achieve
+
+ Output Format (JSON):
+ {
+ "research_ideas": [
+ "Research idea 1 (specific description)",
+ "Research idea 2 (specific description)",
+ ...
+ ]
+ }
+
+ Important: Must generate at least 5 ideas. If the knowledge point has potential, try to generate more creative ideas.
+
+explore_ideas_user_template: |
+ Based on the following knowledge point, generate at least 5 feasible research ideas:
+
+ Knowledge Point: {knowledge_point}
+ Description: {description}
+
+ Please output research ideas in JSON format.
+
+strict_filter_system: |
+ You are a strict research review expert with extensive research experience. Your task is to evaluate whether research ideas are suitable from a researcher's perspective, using strict but fair criteria.
+
+ Evaluation Dimensions (Strict Criteria):
+ 1. Research Value: Whether the idea has academic value, innovativeness, or practical value
+ 2. Research Depth: Whether the idea is deep enough to produce meaningful research outcomes
+ 3. Feasibility: Whether the idea can be achieved within reasonable bounds, not completely impossible
+ 4. Extension Potential: Whether the idea is suitable for further extension and in-depth research
+ 5. Specificity: Whether the idea is specific and clear, not too abstract or vague
+
+ Retention Criteria (Strict):
+ - The idea must have clear research value
+ - The idea must be specific enough to start research
+ - The idea must be feasible, not completely impossible
+ - The idea must have depth, capable of producing meaningful research outcomes
+ - The idea should be interesting and innovative
+
+ Elimination Criteria (Strict):
+ - The idea is too abstract or vague to start research
+ - The idea has no research value or innovativeness at all
+ - The idea is completely infeasible, beyond reasonable bounds
+ - The idea is too superficial to produce meaningful research outcomes
+ - The idea has too little relevance to the knowledge point
+
+ Requirements:
+ 1. Must eliminate at least 2 research ideas (if there are 5 or more in total)
+ 2. Must retain at least 1 research idea
+ 3. Only retain ideas that are truly excellent, suitable for extension, with both depth and feasibility
+ 4. Even if all ideas are good, eliminate the relatively weaker ones and keep the strongest
+
+ Output Format (JSON):
+ {
+ "kept_ideas": [
+ "Retained research idea 1",
+ "Retained research idea 2",
+ ...
+ ],
+ "rejected_ideas": [
+ "Eliminated research idea 1",
+ "Eliminated research idea 2",
+ ...
+ ],
+ "reasons": {
+ "Retained research idea 1": "Retention reason (explain why this idea is excellent)",
+ "Eliminated research idea 1": "Elimination reason (explain why this idea is not good enough)",
+ ...
+ }
+ }
+
+ Important: Evaluation should be strict but fair, ensuring that retained ideas are truly excellent research directions.
+
+strict_filter_user_template: |
+ Based on the following knowledge point and research ideas, evaluate using strict criteria:
+
+ Knowledge Point: {knowledge_point}
+ Description: {description}
+
+ Research Ideas:
+ {ideas_text}
+
+ Please output the evaluation results in JSON format. Remember: must eliminate at least 2, retain at least 1.
+
+generate_statement_system: |
+ You are a research statement generation expert, skilled at writing clear, professional, and compelling research idea statements. Your task is to generate high-quality markdown-formatted statements for knowledge points and research ideas.
+
+ Writing Requirements:
+ 1. First, concisely list the knowledge point, including its core content and review
+ 2. Then, list the retained research ideas point by point, with detailed descriptions for each
+ 3. For each research idea, explain:
+ - Why this research idea was retained (research value, innovativeness, feasibility, etc.)
+ - The research direction and possible research content of this idea
+ - The potential impact or application value of this idea
+
+ Format Requirements:
+ - Use clear Markdown formatting
+ - The knowledge point review should be concise but complete
+ - Each research idea should be described in detail so readers understand its value
+ - Retention reasons should be specific and persuasive
+
+ Output Format (Markdown):
+ ## Knowledge Point Name
+
+ **Knowledge Point Review:**
+ [Brief review of the knowledge point, explaining core content and key information]
+
+ **Research Ideas:**
+
+ ### 1. [Title of Research Idea 1]
+
+ [Detailed description of research idea 1, explaining research direction, possible research content, etc.]
+
+ **Retention Reason:** [Why this research idea was retained, explaining its research value, innovativeness, feasibility, etc.]
+
+ ### 2. [Title of Research Idea 2]
+
+ [Detailed description of research idea 2]
+
+ **Retention Reason:** [Retention reason]
+
+ ...
+
+ Important: The statement should be professional, clear, and compelling, allowing readers to understand the value and potential of each research idea.
+
+generate_statement_user_template: |
+ Please generate a markdown-formatted statement for the following knowledge point and research ideas:
+
+ Knowledge Point: {knowledge_point}
+ Description: {description}
+
+ Retained Research Ideas:
+ {ideas_text}
+
+ Please generate a markdown-formatted statement.
diff --git a/src/agents/ideagen/prompts/en/material_organizer.yaml b/src/agents/ideagen/prompts/en/material_organizer.yaml
new file mode 100644
index 000000000..f53d119b6
--- /dev/null
+++ b/src/agents/ideagen/prompts/en/material_organizer.yaml
@@ -0,0 +1,69 @@
+system: |
+ You are a knowledge organization expert, skilled at identifying and extracting valuable knowledge points from learning records. Your task is to extract relatively independent knowledge points with research value from the notebook records provided by the user.
+
+ Core Tasks:
+ 1. Deeply analyze all input content (including the complete user queries and system responses)
+ 2. Identify relatively independent and in-depth knowledge points; each knowledge point should be a concept, theory, method, or topic that can be researched independently
+ 3. For each knowledge point, extract relevant core descriptions from system responses, ensuring descriptions are complete, accurate, and informative
+ 4. Pay attention to discovering implicit knowledge points, don't only focus on explicitly mentioned content
+
+ Extraction Principles:
+ - Knowledge points should have research value, such as theories, methods, applications, problems, etc.
+ - Knowledge points should be relatively independent and can be studied separately
+ - Descriptions should be based on actual content from system responses, but can be appropriately summarized and refined
+ - If one record contains multiple knowledge points, extract them separately
+ - If system response content is limited, combine user queries to understand the knowledge points
+ - Prioritize extracting knowledge points with depth and research potential
+
+ Output Requirements:
+ - Must extract at least 1 knowledge point (if the input content indeed has research value)
+ - Each knowledge point name should be concise and clear
+ - Each knowledge point description should be detailed, containing key information, at least 50 characters
+ - Output in JSON format as follows:
+ {
+ "knowledge_points": [
+ {
+ "knowledge_point": "Knowledge point name (concise and clear)",
+ "description": "Detailed description of this knowledge point from system response (at least 50 characters, containing key information)"
+ }
+ ]
+ }
+
+ Important: Even if the input content appears simple, make an effort to identify knowledge points within it. Think from multiple angles such as concepts, methods, applications, and problems.
+
+user_template: |
+ Please analyze the following notebook records and extract relatively independent knowledge points:
+
+ {materials_text}{user_thoughts_text}
+
+ Please output the extracted knowledge points in JSON format.
+
+fallback_system: |
+ You are a knowledge extraction expert. Please extract at least 1 knowledge point from the given learning records.
+
+ Even if the content appears simple, make an effort to identify knowledge points. Consider from the following angles:
+ - Concepts and theories involved
+ - Methods and techniques used
+ - Problems solved and application scenarios
+ - Directions for in-depth research
+
+ Output in JSON format:
+ {
+ "knowledge_points": [
+ {
+ "knowledge_point": "Knowledge point name",
+ "description": "Detailed description (at least 30 characters)"
+ }
+ ]
+ }
+
+ Must extract at least 1 knowledge point.
+
+fallback_user_template: |
+ Please extract knowledge points from the following records:
+
+ {materials_text}
+
+ {user_thoughts}
+
+ Please output in JSON format, must extract at least 1 knowledge point.
diff --git a/src/agents/ideagen/prompts/zh/idea_generation.yaml b/src/agents/ideagen/prompts/zh/idea_generation.yaml
new file mode 100644
index 000000000..1138ba018
--- /dev/null
+++ b/src/agents/ideagen/prompts/zh/idea_generation.yaml
@@ -0,0 +1,187 @@
+loose_filter_system: |
+ 你是一位研究筛选专家。你的任务是使用相对宽松的标准筛选掉明显不适合的知识点。
+
+ 筛选原则(宽松标准):
+ - 只筛选掉明显不适合的内容,保持标准宽松
+ - 过于浅显且没有研究价值的知识点(如"1+1=2"这样的基本事实)
+ - 描述完全空白或只有几个字符,无法理解的内容
+ - 明显错误或不相关的内容
+
+ 保留原则:
+ - 只要知识点有一定深度或研究潜力,就应该保留
+ - 即使知识点看起来简单,如果可以扩展研究,也应保留
+ - 描述不完美但可以理解的知识点应该保留
+ - 有创新潜力或应用价值的知识点应该保留
+
+ 重要:保持标准宽松;宁可多保留一些,也不要过度筛选。除非知识点明显不适合,否则应该保留。
+
+ 输出格式(JSON):
+ {
+ "filtered_points": [
+ {
+ "knowledge_point": "知识点名称",
+ "description": "描述"
+ }
+ ]
+ }
+
+loose_filter_user_template: |
+ 请使用宽松标准筛选以下知识点,只保留适合研究的:
+
+ {points_text}
+
+ 请以JSON格式输出筛选后的知识点。
+
+explore_ideas_system: |
+ 你是一位研究想法生成专家,擅长从知识点中发现创新且有价值的研究方向。你的任务是根据给定的知识点生成至少5个可行的研究想法。
+
+ 生成原则:
+ 1. 每个研究想法应该具体、清晰、可行;避免过于抽象或模糊
+ 2. 想法应基于知识点但可以延伸、扩展、深化或从不同角度探索
+ 3. 想法应具有研究价值和深度,如理论探索、方法改进、应用创新等
+ 4. 鼓励从多个维度进行创新思考:
+ - 理论深化:深入探索知识点的理论基础
+ - 方法改进:改进或创新相关方法
+ - 应用扩展:将知识点应用于新领域
+ - 问题解决:基于知识点解决实际问题
+ - 跨学科融合:与其他领域结合产生新想法
+ 5. 生成至少5个想法;如果知识点有潜力,可以生成更多(最多10个)
+
+ 想法质量要求:
+ - 每个想法应是一个完整的研究方向,可以独立研究
+ - 想法应足够具体,可以开始研究,不能太宽泛
+ - 想法应该有趣且创新,能够吸引研究者
+ - 想法应该可行,不是完全不可能实现的
+
+ 输出格式(JSON):
+ {
+ "research_ideas": [
+ "研究想法1(具体描述)",
+ "研究想法2(具体描述)",
+ ...
+ ]
+ }
+
+ 重要:必须生成至少5个想法。如果知识点有潜力,尽量生成更多创造性的想法。
+
+explore_ideas_user_template: |
+ 根据以下知识点,生成至少5个可行的研究想法:
+
+ 知识点:{knowledge_point}
+ 描述:{description}
+
+ 请以JSON格式输出研究想法。
+
+strict_filter_system: |
+ 你是一位严格的研究评审专家,具有丰富的研究经验。你的任务是从研究者的角度评估研究想法是否适合,使用严格但公平的标准。
+
+ 评估维度(严格标准):
+ 1. 研究价值:想法是否具有学术价值、创新性或实用价值
+ 2. 研究深度:想法是否足够深入,能产生有意义的研究成果
+ 3. 可行性:想法是否可以在合理范围内实现,不是完全不可能的
+ 4. 扩展潜力:想法是否适合进一步扩展和深入研究
+ 5. 具体性:想法是否具体明确,不是太抽象或模糊
+
+ 保留标准(严格):
+ - 想法必须有明确的研究价值
+ - 想法必须足够具体,可以开始研究
+ - 想法必须可行,不是完全不可能的
+ - 想法必须有深度,能产生有意义的研究成果
+ - 想法应该有趣且创新
+
+ 淘汰标准(严格):
+ - 想法太抽象或模糊,无法开始研究
+ - 想法完全没有研究价值或创新性
+ - 想法完全不可行,超出合理范围
+ - 想法太浅显,无法产生有意义的研究成果
+ - 想法与知识点关联太少
+
+ 要求:
+ 1. 必须淘汰至少2个研究想法(如果总数5个或以上)
+ 2. 必须保留至少1个研究想法
+ 3. 只保留真正优秀的、适合扩展的、既有深度又可行的想法
+ 4. 即使所有想法都不错,也要淘汰相对较弱的,保留最强的
+
+ 输出格式(JSON):
+ {
+ "kept_ideas": [
+ "保留的研究想法1",
+ "保留的研究想法2",
+ ...
+ ],
+ "rejected_ideas": [
+ "淘汰的研究想法1",
+ "淘汰的研究想法2",
+ ...
+ ],
+ "reasons": {
+ "保留的研究想法1": "保留原因(解释为什么这个想法优秀)",
+ "淘汰的研究想法1": "淘汰原因(解释为什么这个想法不够好)",
+ ...
+ }
+ }
+
+ 重要:评估应严格但公平,确保保留的想法是真正优秀的研究方向。
+
+strict_filter_user_template: |
+ 根据以下知识点和研究想法,使用严格标准进行评估:
+
+ 知识点:{knowledge_point}
+ 描述:{description}
+
+ 研究想法:
+ {ideas_text}
+
+ 请以JSON格式输出评估结果。记住:必须淘汰至少2个,保留至少1个。
+
+generate_statement_system: |
+ 你是一位研究陈述生成专家,擅长撰写清晰、专业、有说服力的研究想法陈述。你的任务是为知识点和研究想法生成高质量的markdown格式陈述。
+
+ 写作要求:
+ 1. 首先,简洁列出知识点,包括其核心内容和回顾
+ 2. 然后,逐点列出保留的研究想法,每个都有详细描述
+ 3. 对每个研究想法,解释:
+ - 为什么保留这个研究想法(研究价值、创新性、可行性等)
+ - 这个想法的研究方向和可能的研究内容
+ - 这个想法的潜在影响或应用价值
+
+ 格式要求:
+ - 使用清晰的Markdown格式
+ - 知识点回顾应简洁但完整
+ - 每个研究想法应详细描述,让读者理解其价值
+ - 保留原因应具体且有说服力
+
+ 输出格式(Markdown):
+ ## 知识点名称
+
+ **知识点回顾:**
+ [简要回顾知识点,解释核心内容和关键信息]
+
+ **研究想法:**
+
+ ### 1. [研究想法1的标题]
+
+ [研究想法1的详细描述,解释研究方向、可能的研究内容等]
+
+ **保留原因:** [为什么保留这个研究想法,解释其研究价值、创新性、可行性等]
+
+ ### 2. [研究想法2的标题]
+
+ [研究想法2的详细描述]
+
+ **保留原因:** [保留原因]
+
+ ...
+
+ 重要:陈述应专业、清晰、有说服力,让读者理解每个研究想法的价值和潜力。
+
+generate_statement_user_template: |
+ 请为以下知识点和研究想法生成markdown格式的陈述:
+
+ 知识点:{knowledge_point}
+ 描述:{description}
+
+ 保留的研究想法:
+ {ideas_text}
+
+ 请生成markdown格式的陈述。
diff --git a/src/agents/ideagen/prompts/zh/material_organizer.yaml b/src/agents/ideagen/prompts/zh/material_organizer.yaml
new file mode 100644
index 000000000..48a8f2205
--- /dev/null
+++ b/src/agents/ideagen/prompts/zh/material_organizer.yaml
@@ -0,0 +1,69 @@
+system: |
+ 你是一位知识整理专家,擅长从学习记录中识别和提取有价值的知识点。你的任务是从用户提供的笔记本记录中提取相对独立的、具有研究价值的知识点。
+
+ 核心任务:
+ 1. 深入分析所有输入内容(包括完整的用户提问和系统回答)
+ 2. 识别出相对独立且有深度的知识点;每个知识点应该是一个可以独立研究的概念、理论、方法或话题
+ 3. 对每个知识点,从系统回答中提取相关的核心描述,确保描述完整、准确、信息丰富
+ 4. 注意发现隐含的知识点,不要只关注明确提到的内容
+
+ 提取原则:
+ - 知识点应该具有研究价值,如理论、方法、应用、问题等
+ - 知识点应该相对独立,可以单独研究
+ - 描述应基于系统回答的实际内容,但可以适当总结和提炼
+ - 如果一条记录包含多个知识点,分别提取
+ - 如果系统回答内容有限,结合用户提问来理解知识点
+ - 优先提取有深度和研究潜力的知识点
+
+ 输出要求:
+ - 必须提取至少1个知识点(如果输入内容确实有研究价值)
+ - 每个知识点名称应简洁明了
+ - 每个知识点描述应详细,包含关键信息,至少50个字符
+ - 输出JSON格式如下:
+ {
+ "knowledge_points": [
+ {
+ "knowledge_point": "知识点名称(简洁明了)",
+ "description": "来自系统回答的该知识点的详细描述(至少50个字符,包含关键信息)"
+ }
+ ]
+ }
+
+ 重要:即使输入内容看起来很简单,也要努力识别其中的知识点。从概念、方法、应用、问题等多个角度思考。
+
+user_template: |
+ 请分析以下笔记本记录,提取相对独立的知识点:
+
+ {materials_text}{user_thoughts_text}
+
+ 请以JSON格式输出提取的知识点。
+
+fallback_system: |
+ 你是一位知识提取专家。请从给定的学习记录中提取至少1个知识点。
+
+ 即使内容看起来很简单,也要努力识别知识点。从以下角度考虑:
+ - 涉及的概念和理论
+ - 使用的方法和技术
+ - 解决的问题和应用场景
+ - 深入研究的方向
+
+ 输出JSON格式:
+ {
+ "knowledge_points": [
+ {
+ "knowledge_point": "知识点名称",
+ "description": "详细描述(至少30个字符)"
+ }
+ ]
+ }
+
+ 必须提取至少1个知识点。
+
+fallback_user_template: |
+ 请从以下记录中提取知识点:
+
+ {materials_text}
+
+ {user_thoughts}
+
+ 请以JSON格式输出,必须提取至少1个知识点。
diff --git a/src/agents/question/README.md b/src/agents/question/README.md
new file mode 100644
index 000000000..876a667be
--- /dev/null
+++ b/src/agents/question/README.md
@@ -0,0 +1,538 @@
+# Question Generation System
+
+Intelligent question generation system with **dual-mode architecture** supporting both knowledge base-driven custom generation and reference exam paper mimicking.
+
+## 📁 Directory Structure
+
+```
+question/
+├── __init__.py # Module exports
+├── agents/ # Agent classes
+│ ├── __init__.py
+│ ├── base_agent.py # Base agent class (ReAct paradigm)
+│ ├── generation_agent.py # Question generation agent
+│ └── validation_agent.py # Question validation agent (deprecated)
+├── tools/ # Tools and utilities
+│ ├── __init__.py
+│ ├── pdf_parser.py # PDF parsing with MinerU
+│ ├── question_extractor.py # Extract questions from exams
+│ └── exam_mimic.py # Reference-based question generation
+├── prompts/ # Bilingual prompts (YAML)
+│ ├── zh/ # Chinese prompts
+│ │ ├── generation_agent.yaml
+│ │ ├── validation_workflow.yaml
+│ │ └── coordinator.yaml
+│ └── en/ # English prompts
+│ └── (same structure)
+├── coordinator.py # Agent coordinator
+├── validation_workflow.py # Validation workflow
+├── example.py # Usage examples
+└── README.md
+```
+
+## 🚀 Core Features
+
+### Custom Mode (Knowledge Base-Driven)
+- ✅ **Intelligent Search Query Generation** - Generates configurable number of RAG queries (from `config/main.yaml`)
+- ✅ **Background Knowledge Acquisition** - Retrieves relevant knowledge using naive mode RAG
+- ✅ **Question Planning** - Creates comprehensive plan with question IDs, focuses, and types
+- ✅ **Single-Pass Validation** - Analyzes question relevance without iterative refinement
+- ✅ **Complete File Persistence** - Saves background knowledge, plan, and individual results
+
+### Mimic Mode (Reference Exam-Based)
+- ✅ **PDF Parsing** - Automatic PDF extraction using MinerU
+- ✅ **Question Extraction** - Identifies and extracts reference questions from exams
+- ✅ **Style Mimicking** - Generates similar questions based on reference structure
+- ✅ **Batch Organization** - All outputs saved to timestamped folders
+- ✅ **Progress Tracking** - Real-time updates for parsing, extracting, and generating stages
+
+### Common Features
+- ✅ **Multimodal Content Support** - Correctly parses text, equations, images, and tables
+- ✅ **Batch Question Generation** - Handles multiple questions in parallel
+- ✅ **Bilingual Prompts** - Supports both Chinese and English prompts via YAML configuration
+- ✅ **Real-time WebSocket Streaming** - Live progress updates to frontend
+
+## System Architecture
+
+### Custom Mode Architecture
+```
+User Requirement
+ ↓
+Generate RAG Queries (configurable count)
+ ↓
+Retrieve Background Knowledge (naive mode)
+ ↓
+Create Question Plan (IDs, focuses, types)
+ ↓
+For each question:
+ GenerationAgent → ValidationWorkflow
+ ↓ ↓
+ [retrieve] [analyze_relevance]
+ [generate] (single-pass, no rejection)
+ ↓
+Save: background_knowledge.json
+ question_plan.json
+ question_X_result.json
+```
+
+### Mimic Mode Architecture
+```
+PDF Upload / Parsed Directory
+ ↓
+Parse PDF with MinerU
+ ↓
+Extract Reference Questions
+ ↓
+For each reference question (parallel):
+ GenerationAgent → ValidationWorkflow
+ ↓
+Save to: mimic_YYYYMMDD_HHMMSS_{pdf_name}/
+ ├── {pdf_name}.pdf
+ ├── auto/{pdf_name}.md
+ ├── {pdf_name}_questions.json
+ └── {pdf_name}_generated_questions.json
+```
+
+## Core Components
+
+### 1. BaseAgent (Base Agent Class)
+
+Located in `agents/base_agent.py`. Implements ReAct loop: **Think → Act → Observe**
+
+### 2. QuestionGenerationAgent
+
+Located in `agents/generation_agent.py`. Generates questions based on knowledge base content or reference questions.
+
+**Available Actions** (Custom Mode):
+- `retrieve`: Retrieve relevant knowledge from knowledge base
+- `generate_question`: Generate questions based on retrieved knowledge
+- `refine_question`: Modify questions based on validation feedback
+- `submit_question`: Submit question to validation workflow
+
+**Key Changes**:
+- ❌ Removed `reject_task` action - no longer rejects tasks
+- ✅ Focuses on generation and refinement only
+
+### 3. QuestionValidationWorkflow
+
+Located in `validation_workflow.py`. Validates question quality using single-pass analysis.
+
+**Custom Mode Workflow**:
+- `retrieve` → `validate` → `analyze_relevance` → `return`
+
+**Validation Output**:
+- `decision`: "approve" (always, no rejection)
+- `relevance`: "highly_relevant" | "partially_relevant"
+- `kb_coverage`: Detailed analysis of knowledge base content tested
+- `extension_points`: Explanation of extensions beyond KB (if applicable)
+- `issues`: List of quality issues (if any)
+- `suggestions`: Improvement suggestions (for refinement)
+
+**Mimic Mode Workflow**:
+- Similar structure, but validates against reference question style and knowledge base sufficiency
+
+### 4. AgentCoordinator
+
+Located in `coordinator.py`. Manages question generation workflows for both custom and mimic modes.
+
+**Custom Mode Methods**:
+- `generate_questions_custom()`: Full pipeline from requirement text to final questions
+- `_generate_search_queries_from_text()`: Creates RAG queries (count from config)
+- `_create_question_plan()`: Generates question plan based on requirements
+- `generate_question()`: Single question generation with validation
+
+**Mimic Mode**:
+- Handled by `tools/exam_mimic.py` with coordinator for individual question generation
+
+## Usage
+
+### Custom Mode - Full Pipeline
+
+```python
+import asyncio
+from src.agents.question import AgentCoordinator
+
+async def main():
+ # Create coordinator
+ coordinator = AgentCoordinator(
+ max_rounds=10,
+ kb_name="math2211",
+ output_dir="data/user/question"
+ )
+
+ # Full pipeline from text requirement
+ result = await coordinator.generate_questions_custom(
+ requirement_text="Generate 3 medium-difficulty questions about multivariable limits",
+ difficulty="medium",
+ question_type="choice",
+ count=3
+ )
+
+ print(f"✅ Generated {result['completed']}/{result['requested']} questions")
+ for q in result['results']:
+ print(f"- {q['question']['question'][:50]}...")
+
+asyncio.run(main())
+```
+
+### Custom Mode - Single Question
+
+```python
+# Define question requirement
+requirement = {
+ "knowledge_point": "Limits and continuity of multivariable functions",
+ "difficulty": "medium",
+ "question_type": "choice",
+ "focus": "Test path-dependent limits at (0,0)"
+}
+
+# Generate single question
+result = await coordinator.generate_question(requirement)
+
+if result["success"]:
+ print(f"✅ Generated in {result['rounds']} rounds")
+ print(f"Question: {result['question']['question']}")
+ print(f"Relevance: {result['validation']['relevance']}")
+else:
+ print(f"❌ Failed: {result['error']}")
+```
+
+### Mimic Mode - PDF Upload
+
+```python
+from src.agents.question.tools.exam_mimic import mimic_exam_questions
+
+result = await mimic_exam_questions(
+ pdf_path="exams/midterm.pdf",
+ kb_name="math2211",
+ output_dir="data/user/question/mimic_papers",
+ max_questions=5
+)
+
+print(f"✅ Generated {result['successful_generations']} questions")
+print(f"Output: {result['output_file']}")
+```
+
+### Mimic Mode - Parsed Directory
+
+```python
+# If you already have MinerU parsed results
+result = await mimic_exam_questions(
+ paper_dir="data/parsed_exams/exam_20240101",
+ kb_name="math2211",
+ max_questions=None # Generate for all reference questions
+)
+```
+
+## Prompts Configuration
+
+Prompts are stored in YAML files under `prompts/` directory with bilingual support:
+
+- `prompts/en/` - English prompts
+- `prompts/zh/` - Chinese prompts
+
+Each agent loads prompts based on the `language` parameter (default: "en").
+
+### YAML Format Example
+
+```yaml
+system: |
+ You are a professional Question Generation Agent...
+
+generate: |
+ Generate a question based on the following information:
+ Requirements: {requirements}
+ Retrieved knowledge: {knowledge}
+ ...
+
+refine: |
+ Please modify the question based on validation feedback:
+ ...
+```
+
+## Configuration
+
+### Environment Variables
+
+```bash
+# LLM API Configuration
+LLM_BINDING_API_KEY=your_api_key_here
+LLM_BINDING_HOST=https://api.openai.com/v1
+LLM_MODEL=gpt-4o
+```
+
+### Configuration Files
+
+**`config/main.yaml`** - RAG query count:
+```yaml
+question:
+ rag_query_count: 3 # Number of RAG queries for background knowledge
+```
+
+**`config/agents.yaml`** - Agent parameters:
+```yaml
+question:
+ temperature: 0.7
+ max_tokens: 4000
+```
+
+## Tools
+
+### PDF Parsing (`tools/pdf_parser.py`)
+
+Uses MinerU for high-quality PDF extraction with formula and table support.
+
+```python
+from src.agents.question.tools import parse_pdf_with_mineru
+
+# Parse PDF to markdown
+success = await parse_pdf_with_mineru(
+ pdf_path="/path/to/exam.pdf",
+ output_base_dir="data/user/question/mimic_papers"
+)
+```
+
+### Question Extraction (`tools/question_extractor.py`)
+
+Extracts structured questions from parsed exam papers.
+
+```python
+from src.agents.question.tools import extract_questions_from_paper
+
+questions = await extract_questions_from_paper(
+ paper_dir="data/mimic_papers/exam_20241211",
+ output_dir="data/mimic_papers"
+)
+# Returns: [{"question_number": "1", "question_text": "...", "images": []}, ...]
+```
+
+### Exam Mimicking (`tools/exam_mimic.py`)
+
+Complete pipeline for reference-based question generation.
+
+```python
+from src.agents.question.tools import mimic_exam_questions
+
+result = await mimic_exam_questions(
+ pdf_path="exams/midterm.pdf", # Or use paper_dir for parsed
+ kb_name="math2211",
+ output_dir="data/user/question/mimic_papers",
+ max_questions=5,
+ ws_callback=None # Optional: async callback for progress updates
+)
+```
+
+## Return Format
+
+### Custom Mode - Single Question
+
+```python
+{
+ "success": True,
+ "question": {
+ "question_type": "choice",
+ "question": "Question content",
+ "options": {"A": "...", "B": "...", "C": "...", "D": "..."},
+ "correct_answer": "A",
+ "explanation": "Detailed explanation",
+ "knowledge_point": "Topic name"
+ },
+ "validation": {
+ "decision": "approve", # Always approve, no rejection
+ "relevance": "highly_relevant", # or "partially_relevant"
+ "kb_coverage": "This question tests...", # For highly relevant
+ "extension_points": "This question extends...", # For partially relevant
+ "issues": [], # Quality issues if any
+ "suggestions": [] # Improvement suggestions
+ },
+ "rounds": 1 # Number of generation rounds (typically 1-2)
+}
+```
+
+### Custom Mode - Batch Generation
+
+```python
+{
+ "completed": 3,
+ "requested": 3,
+ "failed": 0,
+ "results": [
+ {
+ "question": {...},
+ "validation": {...},
+ "rounds": 1
+ },
+ ...
+ ]
+}
+```
+
+### Mimic Mode - Output
+
+```python
+{
+ "reference_paper": "exam_name",
+ "kb_name": "math2211",
+ "total_reference_questions": 5,
+ "successful_generations": 5,
+ "failed_generations": 0,
+ "generated_questions": [
+ {
+ "success": True,
+ "reference_question_number": "1",
+ "reference_question_text": "Original question...",
+ "generated_question": {...},
+ "validation": {...},
+ "rounds": 2
+ },
+ ...
+ ],
+ "output_file": "data/user/question/mimic_papers/mimic_20241211_120000_exam/..."
+}
+```
+
+## Output Files
+
+### Custom Mode Directory Structure
+
+```
+data/user/question/custom_YYYYMMDD_HHMMSS/
+├── background_knowledge.json # RAG retrieval results
+│ {
+│ "queries": ["query1", "query2", "query3"],
+│ "knowledge": {
+│ "query1": {"chunks": [...], "entities": [...], "relations": [...]},
+│ ...
+│ }
+│ }
+│
+├── question_plan.json # Question planning
+│ {
+│ "focuses": [
+│ {"id": "q_1", "focus": "...", "type": "choice"},
+│ {"id": "q_2", "focus": "...", "type": "written"},
+│ ...
+│ ]
+│ }
+│
+├── question_1_result.json # Individual question + validation
+├── question_2_result.json
+└── ...
+```
+
+### Mimic Mode Directory Structure
+
+```
+data/user/question/mimic_papers/
+└── mimic_YYYYMMDD_HHMMSS_{pdf_name}/
+ ├── {pdf_name}.pdf # Original PDF
+ ├── auto/{pdf_name}.md # MinerU parsed markdown
+ ├── {pdf_name}_YYYYMMDD_HHMMSS_questions.json # Extracted reference questions
+ │ {
+ │ "total_questions": 4,
+ │ "questions": [
+ │ {"question_number": "1", "question_text": "...", "images": []},
+ │ ...
+ │ ]
+ │ }
+ │
+ └── {pdf_name}_YYYYMMDD_HHMMSS_generated_questions.json # Generated questions
+ {
+ "reference_paper": "...",
+ "kb_name": "...",
+ "total_reference_questions": 4,
+ "successful_generations": 4,
+ "generated_questions": [
+ {
+ "reference_question_text": "...",
+ "generated_question": {...},
+ "validation": {...}
+ },
+ ...
+ ]
+ }
+```
+
+## Key Changes from Previous Version
+
+### ✅ What's New
+
+1. **Dual-Mode Architecture**
+ - Custom mode: Knowledge base-driven generation
+ - Mimic mode: Reference exam paper mimicking
+
+2. **Simplified Validation**
+ - Single-pass validation (no iterative refinement)
+ - Always approves questions (no rejection)
+ - Analyzes relevance: `highly_relevant` vs `partially_relevant`
+
+3. **Enhanced File Persistence**
+ - All intermediate files saved (background knowledge, plan)
+ - Mimic mode: Timestamped batch folders
+ - Complete traceability for debugging
+
+4. **Configurable RAG Queries**
+ - `rag_query_count` in `config/main.yaml`
+ - Previously hardcoded to 3
+
+5. **Real-time Progress Tracking**
+ - WebSocket streaming for live updates
+ - Mimic mode stages: uploading → parsing → extracting → generating
+
+### ❌ What's Removed
+
+1. **Task Rejection Logic**
+ - Removed `reject_task` action from generation agent
+ - Questions always proceed to validation
+ - Validation analyzes relevance instead of rejecting
+
+2. **Iterative Refinement**
+ - No multi-round validation loop
+ - Single-pass generation + validation
+ - Reduces LLM calls and cost
+
+3. **Standalone Validation Agent**
+ - Merged into `ValidationWorkflow`
+ - Simplified architecture
+
+## Migration Notes
+
+If upgrading from the old structure:
+
+**File Structure Changes:**
+- `base_agent.py` → `agents/base_agent.py`
+- `question_generation_agent.py` → `agents/generation_agent.py`
+- `question_validation_agent.py` → `agents/validation_agent.py` (deprecated)
+- `question_tools/retrieve.py` → Removed (use RAG tool directly)
+- `parse_pdf_with_mineru.py` → `tools/pdf_parser.py`
+- `extract_questions_from_paper.py` → `tools/question_extractor.py`
+- `mimic_exam_paper.py` → `tools/exam_mimic.py`
+- `question_validation_workflow.py` → `validation_workflow.py`
+
+**Import Path Updates:**
+```python
+# Old
+from .base_agent import BaseAgent
+from .question_tools import retrieve
+
+# New
+from .agents import BaseAgent
+from src.tools import rag_search # Use RAG tool directly
+```
+
+**API Changes:**
+```python
+# Old - with rejection handling
+result = await coordinator.generate_question(requirement)
+if result.get("error") == "task_rejected":
+ print("Agent rejected task")
+
+# New - always generates, check relevance
+result = await coordinator.generate_question(requirement)
+if result["success"]:
+ relevance = result["validation"]["relevance"]
+ if relevance == "highly_relevant":
+ print(result["validation"]["kb_coverage"])
+ else:
+ print(result["validation"]["extension_points"])
+```
diff --git a/src/agents/question/__init__.py b/src/agents/question/__init__.py
new file mode 100644
index 000000000..7bc729959
--- /dev/null
+++ b/src/agents/question/__init__.py
@@ -0,0 +1,28 @@
+"""
+Agent-based Question Generation System
+
+This is an autonomous question generation system based on the ReAct (Reasoning + Acting) paradigm.
+Two independent agents collaborate to complete question generation and validation.
+"""
+
+from .agents import (
+ Action,
+ BaseAgent,
+ Message,
+ Observation,
+ QuestionGenerationAgent,
+ QuestionValidationAgent,
+)
+from .coordinator import AgentCoordinator
+from .validation_workflow import QuestionValidationWorkflow
+
+__all__ = [
+ "BaseAgent",
+ "Action",
+ "Observation",
+ "Message",
+ "QuestionGenerationAgent",
+ "QuestionValidationAgent",
+ "QuestionValidationWorkflow",
+ "AgentCoordinator",
+]
diff --git a/src/agents/question/agents/__init__.py b/src/agents/question/agents/__init__.py
new file mode 100644
index 000000000..cbe1c9469
--- /dev/null
+++ b/src/agents/question/agents/__init__.py
@@ -0,0 +1,17 @@
+"""
+Question Generation Agents
+Agent modules for question generation and validation
+"""
+
+from .base_agent import Action, BaseAgent, Message, Observation
+from .generation_agent import QuestionGenerationAgent
+from .validation_agent import QuestionValidationAgent
+
+__all__ = [
+ "BaseAgent",
+ "Action",
+ "Observation",
+ "Message",
+ "QuestionGenerationAgent",
+ "QuestionValidationAgent",
+]
diff --git a/src/agents/question/agents/base_agent.py b/src/agents/question/agents/base_agent.py
new file mode 100644
index 000000000..1dc493fd6
--- /dev/null
+++ b/src/agents/question/agents/base_agent.py
@@ -0,0 +1,523 @@
+#!/usr/bin/env python
+"""
+Base Agent class - Implements the ReAct (Reasoning + Acting) paradigm.
+"""
+
+from abc import ABC, abstractmethod
+from collections.abc import Callable
+import json
+import os
+from pathlib import Path
+import sys
+from typing import Any
+
+from dotenv import load_dotenv
+from openai import AsyncOpenAI
+
+# Load environment variables
+load_dotenv(override=False)
+
+# Add project root for imports
+project_root = Path(__file__).parent.parent.parent.parent.parent
+sys.path.insert(0, str(project_root))
+
+from src.core.core import get_agent_params
+from src.core.logging import get_logger
+
+# Module logger
+_logger = get_logger("QuestionAgent")
+
+
+class Action:
+ """Represents an Agent action"""
+
+ def __init__(self, name: str, **params):
+ self.name = name
+ self.params = params
+
+ def __repr__(self):
+ params_str = ", ".join([f"{k}={v}" for k, v in self.params.items()])
+ return f"Action({self.name}, {params_str})"
+
+
+class Observation:
+ """Represents the observation result of an action"""
+
+ def __init__(self, success: bool, result: Any, message: str = ""):
+ self.success = success
+ self.result = result
+ self.message = message
+
+ def __repr__(self):
+ return f"Observation(success={self.success}, message={self.message})"
+
+
+class Message:
+ """Message passed between agents"""
+
+ def __init__(self, from_agent: str, to_agent: str, message_type: str, content: dict[str, Any]):
+ self.from_agent = from_agent
+ self.to_agent = to_agent
+ self.message_type = message_type
+ self.content = content
+
+ def __repr__(self):
+ return f"Message({self.from_agent} -> {self.to_agent}: {self.message_type})"
+
+
+class BaseAgent(ABC):
+ """
+ Base Agent class implementing ReAct paradigm
+
+ Subclasses need to implement:
+ - get_available_actions(): Return available action list
+ - execute_action(): Execute specific action
+ - get_system_prompt(): Return system prompt
+ """
+
+ def __init__(
+ self,
+ agent_name: str,
+ api_key: str | None = None,
+ base_url: str | None = None,
+ model: str | None = None,
+ max_iterations: int = 10,
+ kb_name: str | None = None,
+ token_stats_callback: Callable | None = None,
+ language: str = "en",
+ ):
+ self.agent_name = agent_name
+ self.max_iterations = max_iterations
+ self.kb_name = kb_name
+ self.token_stats_callback = token_stats_callback
+ self.language = language
+
+ # Load agent parameters from unified config (agents.yaml)
+ self._agent_params = get_agent_params("question")
+
+ if not api_key:
+ api_key = os.getenv("LLM_BINDING_API_KEY")
+ if not base_url:
+ base_url = os.getenv("LLM_BINDING_HOST")
+
+ if model is None:
+ model = os.getenv("LLM_MODEL", "gpt-4o")
+ self.model = model
+
+ self.client = AsyncOpenAI(api_key=api_key, base_url=base_url)
+ self.api_key = api_key
+ self.base_url = base_url
+
+ self.thought_history: list[str] = []
+ self.action_history: list[Action] = []
+ self.observation_history: list[Observation] = []
+ self.retrieved_knowledge: list[dict[str, Any]] = []
+
+ self.inbox: list[Message] = []
+
+ @abstractmethod
+ def get_available_actions(self) -> list[dict[str, str]]:
+ """
+ Return available action list
+
+ Returns:
+ List[Dict]: [{"name": "action_name", "description": "action_desc", "parameters": "param_desc"}, ...]
+ """
+
+ @abstractmethod
+ async def execute_action(self, action: Action) -> Observation:
+ """
+ Execute specific action
+
+ Args:
+ action: Action to execute
+
+ Returns:
+ Observation: Observation result of the action
+ """
+
+ @abstractmethod
+ def get_system_prompt(self) -> str:
+ """
+ Return system prompt
+
+ Returns:
+ str: System prompt
+ """
+
+ def receive_message(self, message: Message):
+ """Receive message from other Agent."""
+ self.inbox.append(message)
+ _logger.debug(f"[{self.agent_name}] Received message: {message}")
+
+ def format_history(self) -> str:
+ """Format history"""
+ if not self.thought_history:
+ return "(No history)"
+
+ history_parts = []
+
+ recent_count = min(3, len(self.action_history))
+ if recent_count > 0:
+ history_parts.append("🔥 **Recent Actions** (Must read! Avoid repeating actions)")
+ history_parts.append("=" * 60)
+ for i in range(len(self.action_history) - recent_count, len(self.action_history)):
+ action = self.action_history[i]
+ obs = self.observation_history[i] if i < len(self.observation_history) else None
+ status = "✅ Success" if (obs and obs.success) else "❌ Failed"
+
+ history_parts.append(f" [{i + 1}] Action: {action.name} → {status}")
+ if action.params:
+ history_parts.append(
+ f" Params: {json.dumps(action.params, ensure_ascii=False)}"
+ )
+ if obs and obs.message:
+ history_parts.append(f" Result: {obs.message}")
+ history_parts.append(
+ "⚠️ Please decide next step based on recent actions, avoid repeating the same actions!"
+ )
+ history_parts.append("=" * 60 + "\n")
+
+ if self.retrieved_knowledge:
+ history_parts.append("📚 **Retrieved Knowledge Summary** (No need to retrieve again)")
+ history_parts.append("=" * 60)
+ for i, k in enumerate(self.retrieved_knowledge, 1):
+ query = k.get("query", "N/A")
+ num_entities = len(k.get("entities", []))
+ num_relations = len(k.get("relations", []))
+ num_text = len(k.get("text_chunks", []))
+ num_multimodal = len(k.get("multimodal_chunks", []))
+ history_parts.append(
+ f' {i}. Query: "{query}" → '
+ f"{num_entities} entities, {num_relations} relations, "
+ f"{num_text} text chunks, {num_multimodal} multimodal content"
+ )
+ history_parts.append("=" * 60 + "\n")
+
+ if len(self.thought_history) > 0:
+ history_parts.append("📜 **Complete History**")
+ history_parts.append("-" * 60)
+ for i in range(len(self.thought_history)):
+ history_parts.append(f"\nRound {i + 1}:")
+ history_parts.append(f"Thought: {self.thought_history[i]}")
+
+ if i < len(self.action_history):
+ action = self.action_history[i]
+ history_parts.append(f"Action: {action.name}")
+ if action.params:
+ history_parts.append(
+ f" Params: {json.dumps(action.params, ensure_ascii=False)}"
+ )
+
+ if i < len(self.observation_history):
+ obs = self.observation_history[i]
+ status = "✅ Success" if obs.success else "❌ Failed"
+ history_parts.append(f"Observation: {status}")
+ if obs.message:
+ history_parts.append(f" Message: {obs.message}")
+ history_parts.append("-" * 60)
+
+ return "\n".join(history_parts)
+
+ def format_inbox(self) -> str:
+ """Format inbox"""
+ if not self.inbox:
+ return "(Inbox is empty)"
+
+ inbox_parts = []
+ for msg in self.inbox:
+ inbox_parts.append(f"- From {msg.from_agent}: {msg.message_type}")
+ inbox_parts.append(
+ f" Content: {json.dumps(msg.content, ensure_ascii=False, indent=2)}"
+ )
+
+ return "\n".join(inbox_parts)
+
+ async def think(self, task: str, context: dict[str, Any] = None) -> dict[str, Any]:
+ """
+ Think about next action
+
+ Args:
+ task: Current task description
+ context: Additional context information
+
+ Returns:
+ Dict: {"thought": str, "action": str, "parameters": Dict}
+ """
+ system_prompt = self.get_system_prompt()
+
+ actions_desc = "\n".join(
+ [
+ f"- **{a['name']}**: {a['description']}\n Parameters: {a['parameters']}"
+ for a in self.get_available_actions()
+ ]
+ )
+
+ # Build context description
+ context_info = ""
+ if context:
+ # Check if it's a new round iteration
+ round_num = context.get("round_num")
+ is_new_round = context.get("is_new_round", False)
+
+ if round_num and round_num > 1:
+ context_info = (
+ f"\n{'=' * 60}\n⚠️ Important note: This is round {round_num} iteration\n"
+ )
+ if is_new_round:
+ context_info += "- Work in history was for previous version of question/task\n"
+ context_info += (
+ "- Now received new content, need to re-execute complete workflow\n"
+ )
+ context_info += "- Can reference retrieved knowledge from history, but don't skip necessary steps\n"
+ context_info += "- Special note: Even if validated/generated before, need to re-process now\n"
+ context_info += f"{'=' * 60}\n"
+
+ context_info += (
+ f"\nCurrent context:\n{json.dumps(context, ensure_ascii=False, indent=2)}\n"
+ )
+
+ user_prompt = f"""Current task: {task}
+{context_info}
+Inbox:
+{self.format_inbox()}
+
+History:
+{self.format_history()}
+
+Available actions:
+{actions_desc}
+
+Please think and decide the next action.
+
+Output JSON format:
+{{
+ "thought": "your thinking process",
+ "action": "action name",
+ "parameters": {{"parameter_name": "parameter_value"}}
+}}
+
+⚠️ **Important notes**:
+1. **Must read history**: Check "Recent actions" section to understand what you just did
+2. **Avoid duplicate actions**: If you just successfully executed an action, don't execute the same action again!
+3. **Logical flow**: Based on recent action results, choose reasonable next action
+ - Example: retrieve → generate → submit, not generate → generate
+4. If inbox has messages, process messages first
+5. History can be referenced, but if it's a new round, must re-execute key steps
+"""
+
+ response = await self.client.chat.completions.create(
+ model=self.model,
+ messages=[
+ {"role": "system", "content": system_prompt},
+ {"role": "user", "content": user_prompt},
+ ],
+ temperature=self._agent_params["temperature"],
+ max_tokens=self._agent_params["max_tokens"],
+ response_format={"type": "json_object"},
+ )
+
+ # Extract response content
+ response_content = response.choices[0].message.content
+
+ # Update token statistics if callback is available
+ input_tokens = 0
+ output_tokens = 0
+ cost = 0.0
+ if hasattr(response, "usage") and response.usage:
+ input_tokens = response.usage.prompt_tokens
+ output_tokens = response.usage.completion_tokens
+ cost = input_tokens * 0.00000015 + output_tokens * 0.0000006
+ if self.token_stats_callback:
+ self.token_stats_callback(
+ input_tokens=input_tokens, output_tokens=output_tokens, model=self.model
+ )
+
+ # Log LLM call with detailed information
+ _logger.log_llm_call(
+ model=self.model,
+ stage="think",
+ system_prompt=system_prompt,
+ user_prompt=user_prompt,
+ response=response_content,
+ agent_name=self.agent_name,
+ input_tokens=input_tokens,
+ output_tokens=output_tokens,
+ cost=cost,
+ level="DEBUG",
+ )
+
+ result = json.loads(response_content)
+
+ # Record thought
+ thought = result.get("thought", "")
+ self.thought_history.append(thought)
+
+ _logger.debug(f"[{self.agent_name}] Thinking: {thought[:100]}...")
+
+ return result
+
+ async def act(self, action_name: str, parameters: dict[str, Any]) -> Observation:
+ """
+ Execute an action
+
+ Args:
+ action_name: Action name
+ parameters: Action parameters
+
+ Returns:
+ Observation: Observation result
+ """
+ action = Action(action_name, **parameters)
+ self.action_history.append(action)
+
+ _logger.info(f"[{self.agent_name}] Action: {action_name}")
+ if parameters:
+ _logger.debug(f" Parameters: {json.dumps(parameters, ensure_ascii=False)[:100]}")
+
+ observation = await self.execute_action(action)
+ self.observation_history.append(observation)
+
+ if observation.success:
+ _logger.debug(f"[{self.agent_name}] Observation: Success")
+ else:
+ _logger.warning(f"[{self.agent_name}] Observation: Failed")
+ if observation.message:
+ _logger.debug(f" Message: {observation.message[:100]}")
+
+ # Print detailed information about action results
+ if observation.success and observation.result:
+ self._print_result(action_name, observation.result)
+
+ return observation
+
+ def _print_result(self, action_name: str, result: Any):
+ """Log action result details."""
+ try:
+ if action_name == "retrieve":
+ # Retrieval action result
+ if isinstance(result, dict):
+ entities = result.get("entities", [])
+ relations = result.get("relations", [])
+ text_chunks = result.get("text_chunks", [])
+ multimodal_chunks = result.get("multimodal_chunks", [])
+
+ _logger.debug(
+ f" Result: {len(entities)} entities, {len(relations)} relations, {len(text_chunks)} text chunks, {len(multimodal_chunks)} multimodal items"
+ )
+
+ elif action_name == "generate_question":
+ # Generate question result
+ if isinstance(result, dict):
+ q_type = result.get("question_type", "N/A")
+ _logger.debug(f" Result: Generated {q_type} type question")
+
+ elif action_name == "refine_question":
+ # Refine question result
+ if isinstance(result, dict):
+ q_type = result.get("question_type", "N/A")
+ _logger.debug(f" Result: Refined {q_type} type question")
+
+ elif action_name == "validate":
+ # Validation result
+ if isinstance(result, dict):
+ decision = result.get("decision", "N/A")
+ issues = result.get("issues", [])
+ _logger.debug(
+ f" Result: Validation decision = {decision}, {len(issues)} issues"
+ )
+
+ elif action_name == "reject_task":
+ # Task rejection result
+ if isinstance(result, dict):
+ reason = result.get("reason", "N/A")
+ _logger.info(f" Result: Task rejected - {reason[:100]}")
+
+ elif action_name in [
+ "submit_question",
+ "request_modification",
+ "request_regeneration",
+ "approve_question",
+ ]:
+ # Message sending actions
+ _logger.debug(" Result: Message sent")
+
+ # Other actions
+ elif isinstance(result, dict):
+ _logger.debug(f" Result: {json.dumps(result, ensure_ascii=False)[:80]}...")
+ elif isinstance(result, str):
+ _logger.debug(f" Result: {result[:80]}...")
+
+ except Exception:
+ # Log failure should not affect main flow
+ pass
+
+ async def run(
+ self,
+ task: str,
+ context: dict[str, Any] = None,
+ send_message_callback: Callable | None = None,
+ ) -> dict[str, Any]:
+ """
+ Run the main loop of the Agent (think-act-observe)
+
+ Args:
+ task: Task description
+ context: Initial context
+ send_message_callback: Callback function for sending messages
+
+ Returns:
+ Dict: Execution result
+ """
+ _logger.info(f"[{self.agent_name}] Starting task execution")
+ _logger.debug(f" Task: {task[:80]}...")
+
+ self.send_message = send_message_callback
+
+ for iteration in range(self.max_iterations):
+ _logger.info(
+ f"[{self.agent_name}] ReAct iteration {iteration + 1}/{self.max_iterations}"
+ )
+
+ # Think
+ decision = await self.think(task, context)
+
+ # Act
+ action_name = decision.get("action")
+ parameters = decision.get("parameters", {})
+
+ observation = await self.act(action_name, parameters)
+
+ # Check if submitted (for QuestionGenerationAgent)
+ if hasattr(self, "submitted") and self.submitted:
+ _logger.success(f"[{self.agent_name}] Question submitted, task completed")
+ return {"success": True, "result": observation.result, "iterations": iteration + 1}
+
+ # Check if completed
+ # These actions indicate the Agent has completed the current stage
+ terminal_actions = [
+ "submit_question", # Generation agent submits question
+ "approve_question", # Validation agent approves question
+ "request_modification", # Validation agent requests modification
+ "request_regeneration", # Validation agent requests regeneration
+ "reject_task", # Generation agent rejects task
+ "finish", # Generic completion flag
+ ]
+
+ if action_name in terminal_actions:
+ _logger.success(f"[{self.agent_name}] Task completed")
+ return {"success": True, "result": observation.result, "iterations": iteration + 1}
+
+ _logger.warning(f"[{self.agent_name}] Max iterations reached")
+ return {
+ "success": False,
+ "error": "Max iterations reached",
+ "iterations": self.max_iterations,
+ }
+
+ def reset(self):
+ """Reset Agent state"""
+ self.thought_history.clear()
+ self.action_history.clear()
+ self.observation_history.clear()
+ self.inbox.clear()
diff --git a/src/agents/question/agents/generation_agent.py b/src/agents/question/agents/generation_agent.py
new file mode 100644
index 000000000..083848019
--- /dev/null
+++ b/src/agents/question/agents/generation_agent.py
@@ -0,0 +1,360 @@
+#!/usr/bin/env python
+"""
+Question Generation Agent - responsible for creating and refining questions.
+"""
+
+import json
+from pathlib import Path
+import sys
+from typing import Any
+
+import yaml
+
+# Add project root to sys.path
+project_root = Path(__file__).parent.parent.parent.parent.parent # OpenTutor root
+sys.path.insert(0, str(project_root))
+
+from src.core.core import load_config_with_main
+from src.core.logging import get_logger
+from src.tools.rag_tool import rag_search
+
+from .base_agent import Action, BaseAgent, Message, Observation
+
+# Module logger
+_logger = get_logger("QuestionGenerationAgent")
+
+
+def _load_prompts(language: str = "en") -> dict:
+ """Load prompts from YAML file based on language"""
+ prompts_dir = Path(__file__).parent.parent / "prompts" / language
+ prompt_file = prompts_dir / "generation_agent.yaml"
+ if prompt_file.exists():
+ with open(prompt_file, encoding="utf-8") as f:
+ return yaml.safe_load(f)
+ # Fallback to English if language file not found
+ fallback_file = Path(__file__).parent.parent / "prompts" / "en" / "generation_agent.yaml"
+ if fallback_file.exists():
+ with open(fallback_file, encoding="utf-8") as f:
+ return yaml.safe_load(f)
+ return {}
+
+
+class QuestionGenerationAgent(BaseAgent):
+ """Question generation agent"""
+
+ def __init__(self, language: str = "en", **kwargs):
+ super().__init__(agent_name="QuestionGenerationAgent", language=language, **kwargs)
+
+ # Load prompts
+ self._prompts = _load_prompts(language)
+
+ # Load config for RAG settings
+ self._config = load_config_with_main("question_config.yaml", project_root)
+
+ # State
+ self.current_requirement = None
+ self.current_question = None
+ self.retrieved_knowledge = [] # Retrieved knowledge
+ self.submitted = False # Whether a question has been submitted
+
+ def reset(self):
+ """Reset agent state, including custom fields."""
+ super().reset()
+ self.current_requirement = None
+ self.current_question = None
+ self.retrieved_knowledge = []
+ self.submitted = False
+
+ def get_system_prompt(self) -> str:
+ return self._prompts.get("system", "")
+
+ def get_available_actions(self) -> list[dict[str, str]]:
+ """Return available actions for the agent."""
+ return [
+ {
+ "name": "retrieve",
+ "description": "Retrieve relevant knowledge from the knowledge base",
+ "parameters": "query (str): search query",
+ },
+ {
+ "name": "generate_question",
+ "description": "Generate a new question based on retrieved knowledge",
+ "parameters": "none",
+ },
+ {
+ "name": "refine_question",
+ "description": "Refine the question according to validation feedback",
+ "parameters": "none",
+ },
+ {
+ "name": "submit_question",
+ "description": "Submit the current question to the Validation Agent",
+ "parameters": "none",
+ },
+ ]
+
+ async def execute_action(self, action: Action) -> Observation:
+ """Execute concrete actions."""
+ try:
+ if action.name == "retrieve":
+ return await self._action_retrieve(action.params)
+
+ if action.name == "generate_question":
+ return await self._action_generate_question()
+
+ if action.name == "refine_question":
+ return await self._action_refine_question()
+
+ if action.name == "submit_question":
+ return await self._action_submit_question()
+
+ return Observation(success=False, result=None, message=f"Unknown action: {action.name}")
+
+ except Exception as e:
+ return Observation(
+ success=False, result=None, message=f"Action execution failed: {e!s}"
+ )
+
+ async def _action_retrieve(self, params: dict[str, Any]) -> Observation:
+ """Retrieve knowledge from the KB."""
+ query = params.get("query", "")
+
+ if not query:
+ return Observation(success=False, result=None, message="Search query cannot be empty")
+
+ # Get RAG mode from config
+ question_cfg = self._config.get("question", {})
+ rag_mode = question_cfg.get("rag_mode", "hybrid")
+
+ # Use unified RAG tool
+ result = await rag_search(
+ query=query,
+ kb_name=self.kb_name,
+ mode=rag_mode,
+ only_need_context=True,
+ )
+
+ answer = result.get("answer", "")
+
+ # Save retrieved knowledge
+ self.retrieved_knowledge.append(
+ {
+ "query": query,
+ "answer": answer,
+ }
+ )
+
+ # Summarize result
+ answer_len = len(answer) if answer else 0
+ summary = f"Retrieved context with {answer_len} characters for query: {query[:50]}..."
+
+ return Observation(success=True, result={"answer": answer}, message=summary)
+
+ async def _action_generate_question(self) -> Observation:
+ """Generate a question."""
+ if not self.retrieved_knowledge:
+ return Observation(
+ success=False, result=None, message="Run retrieve before generating a question"
+ )
+
+ # Format retrieved knowledge
+ knowledge_parts = []
+ for k in self.retrieved_knowledge:
+ knowledge_parts.append(f"=== Query: {k['query']} ===")
+ answer = k.get("answer", "")
+ if answer:
+ # Truncate very long contexts
+ if len(answer) > 3000:
+ answer = answer[:3000] + "...[truncated]"
+ knowledge_parts.append(answer)
+ knowledge_parts.append("")
+
+ knowledge_str = "\n".join(knowledge_parts)
+
+ # Check whether a reference question exists
+ reference_question = self.current_requirement.get("reference_question")
+
+ # Call LLM to generate the question
+ if reference_question:
+ # Use reference-aware prompt
+ prompt_template = self._prompts.get("generate_with_reference", "")
+ prompt = prompt_template.format(
+ reference_question=reference_question,
+ requirements=json.dumps(self.current_requirement, ensure_ascii=False, indent=2),
+ knowledge=knowledge_str,
+ )
+ else:
+ # Use standard prompt
+ prompt_template = self._prompts.get("generate", "")
+ prompt = prompt_template.format(
+ requirements=json.dumps(self.current_requirement, ensure_ascii=False, indent=2),
+ knowledge=knowledge_str,
+ )
+
+ response = await self.client.chat.completions.create(
+ model=self.model,
+ messages=[
+ {"role": "system", "content": "You are a professional question designer"},
+ {"role": "user", "content": prompt},
+ ],
+ temperature=self._agent_params["temperature"],
+ max_tokens=self._agent_params["max_tokens"],
+ response_format={"type": "json_object"},
+ )
+
+ # Extract response content
+ response_content = response.choices[0].message.content
+
+ # Update token statistics if callback is available
+ input_tokens = 0
+ output_tokens = 0
+ cost = 0.0
+ if hasattr(response, "usage") and response.usage:
+ input_tokens = response.usage.prompt_tokens
+ output_tokens = response.usage.completion_tokens
+ cost = input_tokens * 0.00000015 + output_tokens * 0.0000006
+ if self.token_stats_callback:
+ self.token_stats_callback(
+ input_tokens=input_tokens, output_tokens=output_tokens, model=self.model
+ )
+
+ # Log LLM call with detailed information
+ _logger.log_llm_call(
+ model=self.model,
+ stage="generate_question",
+ system_prompt="You are a professional question designer",
+ user_prompt=prompt,
+ response=response_content,
+ agent_name="QuestionGenerationAgent",
+ input_tokens=input_tokens,
+ output_tokens=output_tokens,
+ cost=cost,
+ level="DEBUG",
+ )
+
+ question = json.loads(response_content)
+ self.current_question = question
+
+ # Automatically submit after generation
+ submit_result = await self._action_submit_question()
+ self.submitted = True # Mark as submitted
+
+ # Return the submission result to stop the loop
+ return submit_result
+
+ async def _action_refine_question(self) -> Observation:
+ """Refine the question."""
+ if not self.current_question:
+ return Observation(
+ success=False, result=None, message="No question available for refinement"
+ )
+
+ # Get feedback from inbox
+ feedback_msg = None
+ for msg in self.inbox:
+ if msg.message_type in ["request_modification", "request_regeneration"]:
+ feedback_msg = msg
+ break
+
+ if not feedback_msg:
+ return Observation(success=False, result=None, message="No validation feedback found")
+
+ # Format retrieved knowledge
+ knowledge_parts = []
+ for k in self.retrieved_knowledge:
+ knowledge_parts.append(f"=== Query: {k['query']} ===")
+ answer = k.get("answer", "")
+ if answer:
+ # Truncate very long contexts
+ if len(answer) > 3000:
+ answer = answer[:3000] + "...[truncated]"
+ knowledge_parts.append(answer)
+ knowledge_parts.append("")
+ knowledge_str = "\n".join(knowledge_parts)
+
+ # Call LLM to refine the question
+ prompt_template = self._prompts.get("refine", "")
+ prompt = prompt_template.format(
+ original_question=json.dumps(self.current_question, ensure_ascii=False, indent=2),
+ feedback=json.dumps(feedback_msg.content, ensure_ascii=False, indent=2),
+ knowledge=knowledge_str,
+ )
+
+ response = await self.client.chat.completions.create(
+ model=self.model,
+ messages=[
+ {"role": "system", "content": "You are a professional question designer"},
+ {"role": "user", "content": prompt},
+ ],
+ temperature=self._agent_params["temperature"],
+ max_tokens=self._agent_params["max_tokens"],
+ response_format={"type": "json_object"},
+ )
+
+ # Extract response content
+ response_content = response.choices[0].message.content
+
+ # Update token statistics if callback is available
+ input_tokens = 0
+ output_tokens = 0
+ cost = 0.0
+ if hasattr(response, "usage") and response.usage:
+ input_tokens = response.usage.prompt_tokens
+ output_tokens = response.usage.completion_tokens
+ cost = input_tokens * 0.00000015 + output_tokens * 0.0000006
+ if self.token_stats_callback:
+ self.token_stats_callback(
+ input_tokens=input_tokens, output_tokens=output_tokens, model=self.model
+ )
+
+ # Log LLM call with detailed information
+ _logger.log_llm_call(
+ model=self.model,
+ stage="refine_question",
+ system_prompt="You are a professional question designer",
+ user_prompt=prompt,
+ response=response_content,
+ agent_name="QuestionGenerationAgent",
+ input_tokens=input_tokens,
+ output_tokens=output_tokens,
+ cost=cost,
+ level="DEBUG",
+ )
+
+ question = json.loads(response_content)
+ self.current_question = question
+
+ # Remove the processed feedback message
+ self.inbox.remove(feedback_msg)
+
+ # Automatically submit after refinement
+ submit_result = await self._action_submit_question()
+ self.submitted = True # Mark as submitted
+
+ # Return submission result to stop the loop
+ return submit_result
+
+ async def _action_submit_question(self) -> Observation:
+ """Submit the current question to validation."""
+ if not self.current_question:
+ return Observation(success=False, result=None, message="There is no question to submit")
+
+ # Send validation request
+ if hasattr(self, "send_message") and self.send_message:
+ message = Message(
+ from_agent=self.agent_name,
+ to_agent="QuestionValidationAgent",
+ message_type="validate_request",
+ content={"question": self.current_question},
+ )
+ await self.send_message(message)
+
+ return Observation(
+ success=True,
+ result=self.current_question,
+ message="Question submitted to Validation Agent",
+ )
+
+ def set_requirement(self, requirement: dict[str, Any]):
+ """Set the current generation requirement"""
+ self.current_requirement = requirement
diff --git a/src/agents/question/agents/validation_agent.py b/src/agents/question/agents/validation_agent.py
new file mode 100644
index 000000000..35a9334fa
--- /dev/null
+++ b/src/agents/question/agents/validation_agent.py
@@ -0,0 +1,317 @@
+#!/usr/bin/env python
+"""
+Validation Agent - Responsible for validating question rigor and correctness
+"""
+
+import json
+from pathlib import Path
+import sys
+from typing import Any
+
+import yaml
+
+project_root = Path(__file__).parent.parent.parent.parent.parent
+sys.path.insert(0, str(project_root))
+
+from src.core.core import load_config_with_main
+from src.core.logging import get_logger
+from src.tools.rag_tool import rag_search
+
+from .base_agent import Action, BaseAgent, Message, Observation
+
+# Module logger
+_logger = get_logger("QuestionValidationAgent")
+
+
+def _load_prompts(language: str = "en") -> dict:
+ """Load prompts from YAML file based on language"""
+ prompts_dir = Path(__file__).parent.parent / "prompts" / language
+ prompt_file = prompts_dir / "validation_agent.yaml"
+ if prompt_file.exists():
+ with open(prompt_file, encoding="utf-8") as f:
+ return yaml.safe_load(f)
+ # Fallback to English if language file not found
+ fallback_file = Path(__file__).parent.parent / "prompts" / "en" / "validation_agent.yaml"
+ if fallback_file.exists():
+ with open(fallback_file, encoding="utf-8") as f:
+ return yaml.safe_load(f)
+ return {}
+
+
+class QuestionValidationAgent(BaseAgent):
+ """Validation Agent"""
+
+ def __init__(self, language: str = "en", **kwargs):
+ super().__init__(agent_name="QuestionValidationAgent", language=language, **kwargs)
+
+ # Load prompts
+ self._prompts = _load_prompts(language)
+
+ # Load config for RAG settings
+ self._config = load_config_with_main("question_config.yaml", project_root)
+
+ self.current_question = None
+ self.validation_result = None
+
+ def get_system_prompt(self) -> str:
+ return self._prompts.get("system", "")
+
+ def get_available_actions(self) -> list[dict[str, str]]:
+ return [
+ {
+ "name": "retrieve",
+ "description": "Retrieve knowledge from knowledge base for validation",
+ "parameters": "query (str): Retrieval query",
+ },
+ {
+ "name": "validate",
+ "description": "Validate question rigor and correctness",
+ "parameters": "None",
+ },
+ {
+ "name": "request_modification",
+ "description": "Request question generation agent to modify question",
+ "parameters": "None",
+ },
+ {
+ "name": "request_regeneration",
+ "description": "Request question generation agent to regenerate question",
+ "parameters": "None",
+ },
+ {
+ "name": "approve_question",
+ "description": "Validation passed, output final question",
+ "parameters": "None",
+ },
+ ]
+
+ async def execute_action(self, action: Action) -> Observation:
+ """Execute specific action"""
+ try:
+ if action.name == "retrieve":
+ return await self._action_retrieve(action.params)
+
+ if action.name == "validate":
+ return await self._action_validate()
+
+ if action.name == "request_modification":
+ return await self._action_request_modification()
+
+ if action.name == "request_regeneration":
+ return await self._action_request_regeneration()
+
+ if action.name == "approve_question":
+ return await self._action_approve_question()
+
+ return Observation(success=False, result=None, message=f"Unknown action: {action.name}")
+
+ except Exception as e:
+ return Observation(
+ success=False, result=None, message=f"Action execution failed: {e!s}"
+ )
+
+ async def _action_retrieve(self, params: dict[str, Any]) -> Observation:
+ """Retrieve validation knowledge"""
+ query = params.get("query", "")
+
+ if not query:
+ return Observation(
+ success=False, result=None, message="Retrieval query cannot be empty"
+ )
+
+ # Get RAG mode from config
+ question_cfg = self._config.get("question", {})
+ rag_mode = question_cfg.get("rag_mode", "hybrid")
+
+ result = await rag_search(
+ query=query,
+ kb_name=self.kb_name,
+ mode=rag_mode,
+ only_need_context=True,
+ )
+
+ answer = result.get("answer", "")
+
+ self.retrieved_knowledge.append(
+ {
+ "query": query,
+ "answer": answer,
+ }
+ )
+
+ answer_len = len(answer) if answer else 0
+ summary = f"Retrieved context with {answer_len} characters for query: {query[:50]}..."
+
+ return Observation(success=True, result={"answer": answer}, message=summary)
+
+ async def _action_validate(self) -> Observation:
+ """Validate question"""
+ if not self.current_question:
+ return Observation(success=False, result=None, message="No question to validate")
+
+ knowledge_parts = []
+ for k in self.retrieved_knowledge:
+ knowledge_parts.append(f"=== Query: {k['query']} ===")
+ answer = k.get("answer", "")
+ if answer:
+ # Truncate very long contexts
+ if len(answer) > 3000:
+ answer = answer[:3000] + "...[truncated]"
+ knowledge_parts.append(answer)
+ knowledge_parts.append("")
+
+ validation_knowledge_str = (
+ "\n".join(knowledge_parts) if knowledge_parts else "No validation knowledge retrieved"
+ )
+
+ prompt_template = self._prompts.get("validate", "")
+ prompt = prompt_template.format(
+ question=json.dumps(self.current_question, ensure_ascii=False, indent=2),
+ validation_knowledge=validation_knowledge_str,
+ )
+
+ response = await self.client.chat.completions.create(
+ model=self.model,
+ messages=[
+ {"role": "system", "content": "You are a strict question validation expert"},
+ {"role": "user", "content": prompt},
+ ],
+ temperature=self._agent_params["temperature"],
+ max_tokens=self._agent_params["max_tokens"],
+ response_format={"type": "json_object"},
+ )
+
+ result = json.loads(response.choices[0].message.content)
+ self.validation_result = result
+
+ # Ensure issues and suggestions are lists
+ issues = result.get("issues", [])
+ if not isinstance(issues, list):
+ _logger.warning(f"Issues is not a list (type: {type(issues)}), converting...")
+ if isinstance(issues, dict):
+ issues = [issues]
+ else:
+ issues = []
+ result["issues"] = issues
+
+ suggestions = result.get("suggestions", [])
+ if not isinstance(suggestions, list):
+ _logger.warning(f"Suggestions is not a list (type: {type(suggestions)}), converting...")
+ if isinstance(suggestions, dict):
+ suggestions = [suggestions]
+ else:
+ suggestions = []
+ result["suggestions"] = suggestions
+
+ decision = result.get("decision")
+ issues_count = len(issues)
+
+ return Observation(
+ success=True,
+ result=result,
+ message=f"Validation decision: {decision}, found {issues_count} issues",
+ )
+
+ async def _action_request_modification(self) -> Observation:
+ """Request question modification"""
+ if not self.validation_result:
+ return Observation(
+ success=False,
+ result=None,
+ message="Error: Must execute validate action first to get validation result. Please execute validate to validate the question!",
+ )
+
+ decision = self.validation_result.get("decision")
+ if decision != "request_modification":
+ return Observation(
+ success=False,
+ result=None,
+ message=f"Error: validate decision is '{decision}', should not execute request_modification. Please execute corresponding action based on validation decision!",
+ )
+
+ if hasattr(self, "send_message") and self.send_message:
+ message = Message(
+ from_agent=self.agent_name,
+ to_agent="QuestionGenerationAgent",
+ message_type="request_modification",
+ content={
+ "issues": self.validation_result.get("issues", []),
+ "suggestions": self.validation_result.get("suggestions", []),
+ "reasoning": self.validation_result.get("reasoning", ""),
+ },
+ )
+ await self.send_message(message)
+
+ return Observation(
+ success=True,
+ result=self.validation_result,
+ message="Modification request sent to question generation agent",
+ )
+
+ async def _action_request_regeneration(self) -> Observation:
+ """Request question regeneration"""
+ if not self.validation_result:
+ return Observation(
+ success=False,
+ result=None,
+ message="Error: Must execute validate action first to get validation result. Please execute validate to validate the question!",
+ )
+
+ decision = self.validation_result.get("decision")
+ if decision != "request_regeneration":
+ return Observation(
+ success=False,
+ result=None,
+ message=f"Error: validate decision is '{decision}', should not execute request_regeneration.",
+ )
+
+ if hasattr(self, "send_message") and self.send_message:
+ message = Message(
+ from_agent=self.agent_name,
+ to_agent="QuestionGenerationAgent",
+ message_type="request_regeneration",
+ content={
+ "issues": self.validation_result.get("issues", []),
+ "suggestions": self.validation_result.get("suggestions", []),
+ "reasoning": self.validation_result.get("reasoning", ""),
+ },
+ )
+ await self.send_message(message)
+
+ return Observation(
+ success=True,
+ result=self.validation_result,
+ message="Regeneration request sent to question generation agent",
+ )
+
+ async def _action_approve_question(self) -> Observation:
+ """Validation passed, output final question"""
+ if not self.current_question:
+ return Observation(
+ success=False,
+ result=None,
+ message="Error: No question to approve. Please get question from inbox first.",
+ )
+
+ if not self.validation_result:
+ return Observation(
+ success=False,
+ result=None,
+ message="Error: Must execute validate action first to get validation result, then can approve. Please execute validate action to validate the question!",
+ )
+
+ decision = self.validation_result.get("decision")
+ if decision != "approve":
+ return Observation(
+ success=False,
+ result=None,
+ message=f"Error: validate decision is '{decision}', cannot execute approve_question. Should execute corresponding action.",
+ )
+
+ final_result = {
+ "question": self.current_question,
+ "validation": self.validation_result,
+ "status": "approved",
+ }
+
+ return Observation(success=True, result=final_result, message="Question validation passed!")
diff --git a/src/agents/question/coordinator.py b/src/agents/question/coordinator.py
new file mode 100644
index 000000000..df663df69
--- /dev/null
+++ b/src/agents/question/coordinator.py
@@ -0,0 +1,2137 @@
+#!/usr/bin/env python
+"""
+Agent coordinator responsible for managing collaboration between the question-generation agent
+and the validation workflow.
+"""
+
+import asyncio
+from collections.abc import Callable
+import copy
+import json
+from pathlib import Path
+import sys
+from typing import Any
+
+from .agents import Message, QuestionGenerationAgent
+from .validation_workflow import QuestionValidationWorkflow
+
+# Add project root for imports
+project_root = Path(__file__).parent.parent.parent.parent
+sys.path.insert(0, str(project_root))
+
+from src.core.logging import Logger, get_logger
+from src.tools.rag_tool import rag_search
+
+
+def ensure_list(value: Any, default: list | None = None) -> list:
+ """
+ Ensure a value is a list, converting if necessary.
+
+ Args:
+ value: Value to check/convert
+ default: Default value to return if conversion fails (default: [])
+
+ Returns:
+ List: A list representation of the value
+ """
+ if default is None:
+ default = []
+
+ if isinstance(value, list):
+ return value
+ if isinstance(value, dict):
+ # If it's a dict, try to extract values
+ return list(value.values()) if value else default
+ if isinstance(value, (str, int, float)):
+ # If it's a single value, wrap in list
+ return [value]
+ if value is None:
+ return default
+ # Try to convert to list
+ try:
+ return list(value)
+ except (TypeError, ValueError):
+ return default
+
+
+def ensure_dict(value: Any, default: dict | None = None) -> dict:
+ """
+ Ensure a value is a dict, converting if necessary.
+
+ Args:
+ value: Value to check/convert
+ default: Default value to return if conversion fails (default: {})
+
+ Returns:
+ Dict: A dict representation of the value
+ """
+ if default is None:
+ default = {}
+
+ if isinstance(value, dict):
+ return value
+ if value is None:
+ return default
+ # Cannot safely convert non-dict to dict
+ return default
+
+
+class AgentCoordinator:
+ """
+ Coordinate interactions between QuestionGenerationAgent and QuestionValidationWorkflow.
+ """
+
+ def __init__(
+ self,
+ api_key: str | None = None,
+ base_url: str | None = None,
+ max_rounds: int = 10,
+ kb_name: str | None = None,
+ output_dir: str | None = None,
+ ):
+ """
+ Initialize the coordinator.
+ """
+ self.max_rounds = max_rounds
+ self.kb_name = kb_name
+ self.output_dir = output_dir
+
+ # Load configuration (with main.yaml merge) first
+ project_root = Path(__file__).parent.parent.parent.parent
+ from src.core.core import load_config_with_main
+
+ self.config = load_config_with_main("question_config.yaml", project_root)
+
+ # Initialize logger (from config)
+ log_dir = self.config.get("paths", {}).get("user_log_dir") or self.config.get(
+ "logging", {}
+ ).get("log_dir")
+ self.logger: Logger = get_logger("QuestionGen", log_dir=log_dir)
+
+ # Override max_rounds from config if available
+ question_cfg = self.config.get("question", {})
+ if isinstance(question_cfg, dict) and "max_rounds" in question_cfg:
+ self.max_rounds = question_cfg["max_rounds"]
+
+ # Get parallel generation config from question section
+ self.rag_query_count = question_cfg.get("rag_query_count", 3)
+ self.max_parallel_questions = question_cfg.get("max_parallel_questions", 3)
+
+ # Store API credentials for creating multiple agents
+ self._api_key = api_key
+ self._base_url = base_url
+
+ # Get config for generation agent
+ gen_agent_config = self.config.get("agents", {}).get("question_generation", {})
+ max_gen_iterations = gen_agent_config.get("max_iterations", 5)
+
+ # Instantiate question-generation agent
+ self.question_agent = QuestionGenerationAgent(
+ api_key=api_key,
+ base_url=base_url,
+ max_iterations=max_gen_iterations,
+ kb_name=kb_name,
+ token_stats_callback=self.update_token_stats,
+ )
+
+ # Instantiate validation workflow (fixed pipeline)
+ self.validation_workflow = QuestionValidationWorkflow(
+ api_key=api_key,
+ base_url=base_url,
+ kb_name=kb_name,
+ token_stats_callback=self.update_token_stats,
+ )
+
+ # Message queue
+ self.message_queue = asyncio.Queue()
+ self._logging_suppressed = False
+
+ # Token tracking
+ self.token_stats = {
+ "model": "gpt-4o-mini",
+ "calls": 0,
+ "tokens": 0,
+ "input_tokens": 0,
+ "output_tokens": 0,
+ "cost": 0.0,
+ }
+
+ # Agent status tracking
+ self.agent_status = {
+ "QuestionGenerationAgent": "pending",
+ "ValidationWorkflow": "pending",
+ "RetrievalTool": "pending",
+ }
+
+ # WebSocket callback for streaming updates
+ self._ws_callback: Callable | None = None
+
+ def set_ws_callback(self, callback: Callable):
+ """Set WebSocket callback for streaming updates to frontend."""
+ self._ws_callback = callback
+
+ async def _send_ws_update(self, update_type: str, data: dict[str, Any]):
+ """Send update via WebSocket callback if available."""
+ if self._ws_callback:
+ try:
+ await self._ws_callback({"type": update_type, **data})
+ except Exception as e:
+ self.logger.debug(f"Failed to send WS update: {e}")
+
+ def _update_agent_status(self, agent: str, status: str):
+ """Update agent status and notify frontend."""
+ self.agent_status[agent] = status
+ asyncio.create_task(
+ self._send_ws_update(
+ "agent_status", {"agent": agent, "status": status, "all_agents": self.agent_status}
+ )
+ )
+
+ def update_token_stats(self, input_tokens: int = 0, output_tokens: int = 0, model: str = None):
+ """
+ Update token statistics. Can be called by external components.
+
+ Args:
+ input_tokens: Number of input tokens
+ output_tokens: Number of output tokens
+ model: Model name (optional, will update if provided)
+ """
+ self.token_stats["calls"] += 1
+ self.token_stats["input_tokens"] += input_tokens
+ self.token_stats["output_tokens"] += output_tokens
+ self.token_stats["tokens"] = (
+ self.token_stats["input_tokens"] + self.token_stats["output_tokens"]
+ )
+ if model:
+ self.token_stats["model"] = model
+
+ # Estimate cost (simplified pricing)
+ # gpt-4o-mini: $0.15/1M input, $0.60/1M output
+ self.token_stats["cost"] = (
+ self.token_stats["input_tokens"] * 0.00000015
+ + self.token_stats["output_tokens"] * 0.0000006
+ )
+
+ asyncio.create_task(self._send_ws_update("token_stats", {"stats": self.token_stats}))
+
+ def _update_token_stats(self, input_tokens: int = 0, output_tokens: int = 0, model: str = None):
+ """Internal alias for backwards compatibility."""
+ self.update_token_stats(input_tokens, output_tokens, model)
+
+ async def send_message(self, message: Message):
+ """Send a message to the destination agent."""
+ await self.message_queue.put(message)
+
+ async def deliver_messages(self):
+ """Deliver queued messages."""
+ while not self.message_queue.empty():
+ message = await self.message_queue.get()
+
+ if message.to_agent == "QuestionGenerationAgent":
+ self.question_agent.receive_message(message)
+
+ def _suppress_logging(self):
+ if self._logging_suppressed:
+ return
+ import logging
+
+ logging.basicConfig(level=logging.ERROR, force=True)
+ for logger_name in [
+ "lightrag",
+ "raganything",
+ "nano-vectordb",
+ "openai",
+ "httpx",
+ "httpcore",
+ ]:
+ logging.getLogger(logger_name).setLevel(logging.ERROR)
+ logging.getLogger(logger_name).propagate = False
+ self._logging_suppressed = True
+
+ async def _call_llm(
+ self,
+ system_prompt: str,
+ user_prompt: str,
+ response_format: dict[str, Any] | None = None,
+ stage: str = "",
+ ):
+ """Utility wrapper around the generation agent's LLM client."""
+ client = self.question_agent.client
+ model = self.question_agent.model
+
+ kwargs = {
+ "model": model,
+ "messages": [
+ {"role": "system", "content": system_prompt},
+ {"role": "user", "content": user_prompt},
+ ],
+ "temperature": 0.2,
+ }
+ if response_format:
+ kwargs["response_format"] = response_format
+
+ response = await client.chat.completions.create(**kwargs)
+
+ # Extract response content
+ response_content = response.choices[0].message.content
+
+ # Track token usage
+ input_tokens = 0
+ output_tokens = 0
+ cost = 0.0
+ if hasattr(response, "usage") and response.usage:
+ input_tokens = response.usage.prompt_tokens
+ output_tokens = response.usage.completion_tokens
+ cost = input_tokens * 0.00000015 + output_tokens * 0.0000006
+ self._update_token_stats(
+ input_tokens=input_tokens, output_tokens=output_tokens, model=model
+ )
+
+ # Log LLM call with detailed information
+ self.logger.log_llm_call(
+ model=model,
+ stage=stage or "coordinator_call",
+ system_prompt=system_prompt,
+ user_prompt=user_prompt,
+ response=response_content,
+ agent_name="Coordinator",
+ input_tokens=input_tokens,
+ output_tokens=output_tokens,
+ cost=cost,
+ level="DEBUG",
+ )
+
+ return response_content
+
+ async def _generate_search_queries(
+ self, base_requirement: dict[str, Any], num_queries: int
+ ) -> list[str]:
+ """Backwards compatibility helper when a structured requirement already exists."""
+ text = json.dumps(base_requirement, ensure_ascii=False, indent=2)
+ return await self._generate_search_queries_from_text(text, num_queries)
+
+ async def _generate_search_queries_from_text(
+ self, requirement_text: str, num_queries: int
+ ) -> list[str]:
+ """Use LLM to produce semantic search queries directly from natural-language text."""
+ system_prompt = (
+ "【Role】You are a knowledge base retrieval assistant, preparing for question generation.\n"
+ "\n"
+ "【Current Task】Generate knowledge point retrieval queries to find theoretical explanations, definitions, and theorems in the knowledge base.\n"
+ "⚠️ Key: You are not generating questions now! You are looking for theoretical knowledge needed for question generation!\n"
+ "\n"
+ "【Output Rules】\n"
+ "1. Only output pure knowledge point names (theorem names, concept names, method names)\n"
+ "2. Each query should be 2-5 words\n"
+ "3. Do not include functions, numerical values, or calculation tasks\n"
+ "4. Do not use questions or task descriptions\n"
+ )
+
+ user_prompt = (
+ f"The user's question generation requirement is:\n{requirement_text}\n\n"
+ f"Please extract {num_queries} pure knowledge point names from it for knowledge base retrieval.\n\n"
+ "Correct examples:\n"
+ "✅ Taylor theorem\n"
+ "✅ Lagrange multipliers \n"
+ "✅ critical points\n\n"
+ "Incorrect examples (do not generate):\n"
+ "❌ Apply Taylor's Theorem to approximate f(x,y)=... (This is a question)\n"
+ "❌ Find and classify critical points (This is a task)\n"
+ "❌ Use Lagrange multipliers to find maximum (This is an instruction)\n\n"
+ f'Return in JSON format: {{"queries": ["knowledge point 1", "knowledge point 2", ...]}}, containing exactly {num_queries} knowledge point names.'
+ )
+
+ try:
+ content = await self._call_llm(system_prompt=system_prompt, user_prompt=user_prompt)
+ data = json.loads(content)
+
+ # Ensure queries is a list
+ queries_raw = data.get("queries", [])
+ if not isinstance(queries_raw, list):
+ self.logger.warning(
+ f"Queries is not a list (type: {type(queries_raw)}), converting..."
+ )
+ if isinstance(queries_raw, dict):
+ # If it's a dict, try to extract values or convert to list
+ queries_raw = list(queries_raw.values()) if queries_raw else []
+ elif isinstance(queries_raw, str):
+ queries_raw = [queries_raw]
+ else:
+ queries_raw = []
+
+ queries = [q.strip() for q in queries_raw if q and q.strip()]
+ except Exception as e:
+ self.logger.warning(f"Failed to generate search queries: {e}")
+ queries = []
+ if not queries:
+ queries = [requirement_text[:50]]
+ return queries[:num_queries]
+
+ async def _single_rag_search(self, query: str) -> dict[str, Any]:
+ """Execute a single RAG search and return the raw answer."""
+ question_cfg = self.config.get("question", {})
+ rag_mode = question_cfg.get("rag_mode", "hybrid")
+
+ result = await rag_search(
+ query=query,
+ kb_name=self.kb_name,
+ mode=rag_mode,
+ only_need_context=True,
+ )
+ return {
+ "query": query,
+ "answer": result.get("answer", ""),
+ "mode": result.get("mode", rag_mode),
+ }
+
+ async def _gather_retrieval_context(self, queries: list[str]) -> list[dict[str, Any]]:
+ """Run retrieval for each query in parallel and collect the raw contexts."""
+ self._update_agent_status("RetrievalTool", "running")
+ self.logger.info(f"Retrieving knowledge for {len(queries)} queries...")
+
+ # Execute all queries in parallel
+ tasks = [self._single_rag_search(query) for query in queries]
+ results = await asyncio.gather(*tasks, return_exceptions=True)
+
+ retrievals = []
+ for i, result in enumerate(results):
+ query = queries[i]
+ if isinstance(result, Exception):
+ self.logger.warning(f"Retrieval failed for query '{query}': {result}")
+ continue
+
+ self.logger.debug(f" → Query: {query[:50]}... (retrieved)")
+ retrievals.append(
+ {
+ "query": query,
+ "answer": result.get("answer", ""),
+ }
+ )
+
+ self._update_agent_status("RetrievalTool", "done")
+ return retrievals
+
+ def _summarize_retrievals(self, retrievals: list[dict[str, Any]]) -> str:
+ """Turn retrieval objects into a digest for the LLM."""
+ lines = []
+ for item in retrievals:
+ lines.append(f"=== Query: {item['query']} ===")
+ answer = item.get("answer", "")
+ if answer:
+ # Truncate very long answers
+ if len(answer) > 2000:
+ answer = answer[:2000] + "...[truncated]"
+ lines.append(answer)
+ lines.append("")
+ return "\n".join(lines) if lines else "No retrieval context available."
+
+ def _save_question_result(
+ self,
+ question: dict[str, Any],
+ requirement: dict[str, Any],
+ validation: dict[str, Any],
+ round_num: int,
+ extended: bool = False,
+ ) -> str | None:
+ """
+ Save a single question result to disk.
+
+ Args:
+ question: The generated question dict
+ requirement: The requirement dict (contains knowledge_point, difficulty, etc.)
+ validation: The validation result dict
+ round_num: Number of rounds taken
+ extended: Whether this is an extended question
+
+ Returns:
+ The output directory path if saved successfully, None otherwise
+ """
+ if not self.output_dir:
+ return None
+
+ from datetime import datetime
+
+ try:
+ # Create timestamped subdirectory
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
+ output_path = Path(self.output_dir) / f"question_{timestamp}"
+ output_path.mkdir(parents=True, exist_ok=True)
+
+ # Build result structure
+ result = {
+ "success": True,
+ "question": question,
+ "validation": validation,
+ "rounds": round_num,
+ }
+ if extended:
+ result["extended"] = True
+
+ # Save result.json
+ with open(output_path / "result.json", "w", encoding="utf-8") as f:
+ json.dump(result, f, indent=2, ensure_ascii=False)
+
+ # Build question.md
+ validation_status = "Extended" if extended else "Approved"
+ md_content = f"""# Generated Question
+
+**Knowledge point**: {requirement.get("knowledge_point", question.get("knowledge_point", "N/A"))}
+**Difficulty**: {requirement.get("difficulty", "N/A")}
+**Type**: {requirement.get("question_type", question.get("question_type", "N/A"))}
+
+---
+
+## Question
+{question.get("question", "")}
+
+"""
+ if question.get("options"):
+ md_content += "## Options\n"
+ for key, value in question.get("options", {}).items():
+ md_content += f"- **{key}**: {value}\n"
+ md_content += "\n"
+
+ md_content += f"""
+## Answer
+{question.get("correct_answer", "")}
+
+## Explanation
+{question.get("explanation", "")}
+
+---
+**Validation**: {validation_status} after {round_num} round(s)
+"""
+ with open(output_path / "question.md", "w", encoding="utf-8") as f:
+ f.write(md_content)
+
+ self.logger.info(f"Question saved to: {output_path}")
+ return str(output_path)
+
+ except Exception as e:
+ self.logger.warning(f"Failed to save question artifacts: {e}")
+ return None
+
+ async def _check_retrieval_relevance(
+ self, requirement_text: str, knowledge_summary: str
+ ) -> bool:
+ """Use LLM to determine whether retrieval results match the user's request."""
+ system_prompt = (
+ "You evaluate whether retrieved knowledge is relevant to a user's request. "
+ 'Respond in JSON with key "relevant" (true/false) and optional "reason".'
+ )
+ user_prompt = (
+ f"User request:\n{requirement_text}\n\n"
+ f"Retrieved knowledge summary:\n{knowledge_summary}\n\n"
+ "Is the retrieved knowledge substantively relevant to the request?"
+ )
+ try:
+ content = await self._call_llm(system_prompt=system_prompt, user_prompt=user_prompt)
+ parsed = json.loads(content)
+ return bool(parsed.get("relevant"))
+ except Exception as e:
+ self.logger.warning(f"Failed to check retrieval relevance: {e}")
+ return False
+
+ async def _generate_child_requirements(
+ self, base_requirement: dict[str, Any], knowledge_summary: str, num_questions: int
+ ) -> list[dict[str, Any]]:
+ """Ask LLM to break the base requirement into multiple sub-requirements."""
+ system_prompt = (
+ "You are a curriculum designer. Given a base requirement and knowledge summary, "
+ "create distinct sub-requirements that all test the SAME knowledge point. "
+ "Each sub-requirement must describe a unique scenario and reasoning flow. "
+ 'Output JSON with key "requirements" (array of length requested) where each item has: '
+ '"title", "question_type", "difficulty", "additional_requirements".'
+ )
+ user_prompt = (
+ f"Base requirement:\n{json.dumps(base_requirement, ensure_ascii=False, indent=2)}\n\n"
+ f"Knowledge summary:\n{knowledge_summary}\n\n"
+ f"Generate exactly {num_questions} sub-requirements in JSON."
+ )
+ try:
+ content = await self._call_llm(system_prompt=system_prompt, user_prompt=user_prompt)
+ parsed = json.loads(content)
+
+ # Ensure requirements is a list
+ requirements_raw = parsed.get("requirements", [])
+ if not isinstance(requirements_raw, list):
+ self.logger.warning(
+ f"Requirements is not a list (type: {type(requirements_raw)}), converting..."
+ )
+ if isinstance(requirements_raw, dict):
+ # If it's a dict, try to extract values or convert to list
+ requirements_raw = list(requirements_raw.values()) if requirements_raw else []
+ else:
+ requirements_raw = []
+
+ requirements = requirements_raw
+ except Exception as e:
+ self.logger.warning(f"Failed to generate sub-requirements: {e}")
+ requirements = []
+ return requirements[:num_questions]
+
+ async def _interpret_requirement_text(self, requirement_text: str) -> dict[str, Any]:
+ """Convert a natural-language request into structured requirement fields."""
+ system_prompt = (
+ "You are an instruction parser for an exam-question generator. "
+ "Given a natural-language request, extract the core knowledge point, "
+ "difficulty (easy/medium/hard), preferred question type (choice/written), "
+ "and additional requirements. Return JSON with keys: "
+ '"knowledge_point", "difficulty", "question_type", "additional_requirements".'
+ )
+ user_prompt = f"Requirement:\n{requirement_text}\n\nReturn JSON only."
+ try:
+ content = await self._call_llm(system_prompt=system_prompt, user_prompt=user_prompt)
+ parsed = json.loads(content)
+ except Exception as e:
+ self.logger.warning(f"Failed to interpret requirement text: {e}")
+ parsed = {}
+
+ knowledge_point = parsed.get("knowledge_point") or requirement_text[:60]
+ difficulty = (parsed.get("difficulty") or "medium").lower()
+ if difficulty not in {"easy", "medium", "hard"}:
+ difficulty = "medium"
+ question_type = (parsed.get("question_type") or "written").lower()
+ if question_type not in {"choice", "written"}:
+ question_type = "written"
+
+ additional_requirements = parsed.get("additional_requirements") or requirement_text
+
+ return {
+ "knowledge_point": knowledge_point,
+ "difficulty": difficulty,
+ "question_type": question_type,
+ "additional_requirements": additional_requirements,
+ }
+
+ async def generate_question(self, requirement: dict[str, Any]) -> dict[str, Any]:
+ """
+ Full workflow for generating and validating a question.
+ """
+ # Reset agent status for this question
+ self.agent_status = {
+ "QuestionGenerationAgent": "pending",
+ "ValidationWorkflow": "pending",
+ "RetrievalTool": "pending",
+ }
+
+ self.logger.section("Question Generation Workflow")
+ self.logger.info("Workflow started")
+ self.logger.info(f"Knowledge point: {requirement.get('knowledge_point')}")
+ self.logger.info(f"Difficulty: {requirement.get('difficulty')}")
+ self.logger.info(f"Question type: {requirement.get('question_type')}")
+
+ # Send progress update
+ await self._send_ws_update(
+ "progress", {"stage": "generating", "progress": {"status": "initializing"}}
+ )
+
+ # If this is a batch sub-requirement, show specific info
+ batch_index = requirement.get("batch_index")
+ additional_req = requirement.get("additional_requirements", "")
+ if batch_index and additional_req:
+ lines = additional_req.split("\n")
+ for line in lines:
+ if line.startswith("[Auto-derived sub requirement"):
+ title_part = line.split(":", 1)[1].strip().rstrip("]") if ":" in line else ""
+ self.logger.info(f"Sub-requirement: {title_part}")
+ break
+
+ # Ensure noisy loggers are silenced
+ self._suppress_logging()
+
+ # Provide requirement to the generation agent
+ self.question_agent.set_requirement(requirement)
+
+ for round_num in range(1, self.max_rounds + 1):
+ self.logger.separator()
+ self.logger.stage(f"Round {round_num}/{self.max_rounds}")
+
+ # Send progress update
+ await self._send_ws_update(
+ "progress",
+ {
+ "stage": "generating",
+ "progress": {"round": round_num, "max_rounds": self.max_rounds},
+ },
+ )
+
+ self.logger.info("Stage 1: QuestionGenerationAgent starting...")
+ self.logger.debug(f" Knowledge point: {requirement.get('knowledge_point', 'N/A')}")
+ self.logger.debug(f" Difficulty: {requirement.get('difficulty', 'N/A')}")
+ self._update_agent_status("QuestionGenerationAgent", "running")
+
+ # Register message callback
+ self.question_agent.send_message = self.send_message
+
+ # Reset submission flag for the new round
+ self.question_agent.submitted = False
+
+ # Build task description and context
+ if round_num == 1:
+ task = f"Generate a question that satisfies the requirement: {requirement.get('knowledge_point')}"
+ agent_context = {
+ "requirement": requirement,
+ "round_num": round_num,
+ "is_new_round": False,
+ }
+ else:
+ task = "Revise the question based on validation feedback"
+ agent_context = {
+ "requirement": requirement,
+ "round_num": round_num,
+ "is_new_round": True, # Notify the agent that a fresh round is starting
+ }
+
+ # Execute the question-generation agent
+ question_result = await self.question_agent.run(
+ task=task, context=agent_context, send_message_callback=self.send_message
+ )
+
+ if not question_result.get("success"):
+ self._update_agent_status("QuestionGenerationAgent", "error")
+ return {
+ "success": False,
+ "error": "question_agent_execution_failed",
+ "details": question_result,
+ }
+
+ # Check for rejections FIRST (before checking if submitted)
+ result_data = question_result.get("result")
+ if isinstance(result_data, dict) and result_data.get("task_rejected"):
+ self.logger.separator()
+ self.logger.warning("Question generation rejected")
+ self._update_agent_status("QuestionGenerationAgent", "error")
+ return {
+ "success": False,
+ "error": "task_rejected",
+ "reason": result_data.get(
+ "reason", "Required knowledge is missing from the knowledge base."
+ ),
+ "message": "QuestionGenerationAgent rejected this task because the knowledge base lacks the required content.",
+ }
+
+ # Ensure the agent submitted a question
+ if self.question_agent.submitted:
+ self.logger.success("QuestionGenerationAgent submitted a question")
+ self._update_agent_status("QuestionGenerationAgent", "done")
+ else:
+ self.logger.warning(
+ "QuestionGenerationAgent did not submit a question; moving to next round"
+ )
+ continue
+
+ # Retrieve the submitted question from the queue (before delivering messages)
+ question = None
+ messages_to_deliver = []
+ while not self.message_queue.empty():
+ msg = await self.message_queue.get()
+ if msg.message_type == "validate_request":
+ question = msg.content.get("question")
+ else:
+ messages_to_deliver.append(msg)
+
+ # Return non-question messages to the queue
+ for msg in messages_to_deliver:
+ await self.message_queue.put(msg)
+
+ # Deliver other pending messages
+ await self.deliver_messages()
+
+ if not question:
+ self.logger.warning("QuestionGenerationAgent did not submit a question")
+ continue
+
+ self.logger.success("Question submitted for validation")
+
+ self.logger.info("Stage 2: Validation workflow starting...")
+ self.logger.debug(f" Validating question: {question.get('question', '')[:60]}...")
+ self._update_agent_status("ValidationWorkflow", "running")
+
+ # Send progress update
+ await self._send_ws_update(
+ "progress", {"stage": "validating", "progress": {"round": round_num}}
+ )
+
+ # Attach knowledge point for validation retrieval
+ question["knowledge_point"] = requirement.get("knowledge_point", "")
+
+ # Execute validation workflow (retrieve → validate → return)
+ # Pass reference question for innovation check
+ reference_question = requirement.get("reference_question")
+ validation_result = await self.validation_workflow.validate(
+ question, reference_question
+ )
+
+ # Evaluate validation decision
+ decision = validation_result.get("decision")
+
+ if decision == "approve":
+ self.logger.separator()
+ self.logger.success("Question approved by validation")
+ self._update_agent_status("ValidationWorkflow", "done")
+
+ # Validate validation_result structure before building result
+ issues = validation_result.get("issues", [])
+ suggestions = validation_result.get("suggestions", [])
+
+ # Log types for debugging
+ self.logger.debug(
+ f"Validation result - issues type: {type(issues)}, suggestions type: {type(suggestions)}"
+ )
+
+ # Ensure issues and suggestions are lists
+ if not isinstance(issues, list):
+ self.logger.warning(
+ f"Issues is not a list (type: {type(issues)}), converting..."
+ )
+ if isinstance(issues, dict):
+ issues = [issues]
+ else:
+ issues = []
+
+ if not isinstance(suggestions, list):
+ self.logger.warning(
+ f"Suggestions is not a list (type: {type(suggestions)}), converting..."
+ )
+ if isinstance(suggestions, dict):
+ suggestions = [suggestions]
+ else:
+ suggestions = []
+
+ result = {
+ "success": True,
+ "question": question,
+ "validation": {
+ "decision": decision,
+ "issues": issues,
+ "suggestions": suggestions,
+ "reasoning": validation_result.get("reasoning", ""),
+ },
+ "rounds": round_num,
+ }
+
+ # Log final result structure
+ self.logger.debug(
+ f"Result structure - validation.issues type: {type(result['validation']['issues'])}, validation.suggestions type: {type(result['validation']['suggestions'])}"
+ )
+
+ # Persist results if output_dir is provided
+ if self.output_dir:
+ from datetime import datetime
+ import json
+ from pathlib import Path
+
+ try:
+ # timestamped subdirectory
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
+ output_path = Path(self.output_dir) / f"question_{timestamp}"
+ output_path.mkdir(parents=True, exist_ok=True)
+
+ # result JSON
+ with open(output_path / "result.json", "w", encoding="utf-8") as f:
+ json.dump(result, f, indent=2, ensure_ascii=False)
+
+ # question markdown
+ md_content = f"""# Generated Question
+
+**Knowledge point**: {requirement.get("knowledge_point")}
+**Difficulty**: {requirement.get("difficulty")}
+**Type**: {requirement.get("question_type")}
+
+---
+
+## Question
+{question.get("question")}
+
+"""
+ if question.get("options"):
+ md_content += "## Options\n"
+ for key, value in question.get("options", {}).items():
+ md_content += f"- **{key}**: {value}\n"
+ md_content += "\n"
+
+ md_content += f"""
+## Answer
+{question.get("correct_answer")}
+
+## Explanation
+{question.get("explanation")}
+
+---
+**Validation**: Approved after {round_num} round(s)
+"""
+ with open(output_path / "question.md", "w", encoding="utf-8") as f:
+ f.write(md_content)
+
+ self.logger.info(f"Results saved to: {output_path}")
+ result["output_dir"] = str(output_path)
+
+ except Exception as e:
+ self.logger.warning(f"Failed to save artifacts: {e}")
+
+ return result
+
+ # Handle modification/regeneration decisions
+ if decision in ["request_modification", "request_regeneration"]:
+ self.logger.info(f"Validation decision: {decision}")
+ self.logger.debug(f"Issues: {validation_result.get('issues')}")
+ self.logger.debug(f"Suggestions: {validation_result.get('suggestions')}")
+ self._update_agent_status("ValidationWorkflow", "pending")
+
+ # Send feedback back to the question agent
+ message = Message(
+ from_agent="QuestionValidationWorkflow",
+ to_agent="QuestionGenerationAgent",
+ message_type=decision,
+ content={
+ "issues": validation_result.get("issues", []),
+ "suggestions": validation_result.get("suggestions", []),
+ "reasoning": validation_result.get("reasoning", ""),
+ },
+ )
+ self.question_agent.receive_message(message)
+
+ # Continue to next round
+ continue
+
+ self.logger.warning(f"Unknown validation decision: {decision}")
+ continue
+
+ self.logger.separator()
+ self.logger.warning(f"Maximum rounds reached ({self.max_rounds})")
+
+ # Return as extended question instead of failure
+ last_question = self.question_agent.current_question
+ if last_question:
+ # Get extension analysis from validation workflow
+ # Build shared context from retrieved knowledge
+ shared_context = ""
+ if hasattr(self.question_agent, "retrieved_knowledge"):
+ for k in self.question_agent.retrieved_knowledge:
+ shared_context += f"{k.get('answer', '')}\n\n"
+
+ extension_analysis = await self.validation_workflow.analyze_extension(
+ last_question, shared_context
+ )
+
+ self.logger.info("Question marked as extended (beyond KB scope)")
+ return {
+ "success": True,
+ "question": last_question,
+ "validation": {
+ "decision": "extended",
+ "reasoning": extension_analysis.get("reasoning", ""),
+ "kb_connection": extension_analysis.get("kb_connection", ""),
+ "extended_aspect": extension_analysis.get("extended_aspect", ""),
+ },
+ "rounds": self.max_rounds,
+ "extended": True,
+ }
+ else:
+ return {
+ "success": False,
+ "error": f"Maximum rounds reached ({self.max_rounds}) without generating a question",
+ "last_question": None,
+ }
+
+ async def generate_multiple_questions(
+ self,
+ base_requirement: dict[str, Any],
+ num_questions: int,
+ precomputed_queries: list[str] | None = None,
+ precomputed_retrievals: list[dict[str, Any]] | None = None,
+ precomputed_summary: str | None = None,
+ ) -> dict[str, Any]:
+ """
+ Generate multiple questions based on a single high-level requirement.
+ """
+ if num_questions <= 0:
+ raise ValueError("num_questions must be greater than zero")
+
+ self._suppress_logging()
+
+ # Step 1: plan retrieval queries and gather context
+ queries = precomputed_queries or await self._generate_search_queries(
+ base_requirement, max(3, num_questions)
+ )
+ retrievals = precomputed_retrievals or await self._gather_retrieval_context(queries)
+ knowledge_summary = precomputed_summary or self._summarize_retrievals(retrievals)
+
+ if (
+ not retrievals
+ or not knowledge_summary
+ or knowledge_summary.strip() == "No retrieval context available."
+ ):
+ return {
+ "success": False,
+ "error": "knowledge_not_found",
+ "message": "Knowledge base does not contain relevant information for the request.",
+ }
+
+ # Step 2: ask LLM to produce sub-requirements
+ child_requirements = await self._generate_child_requirements(
+ base_requirement, knowledge_summary, num_questions
+ )
+
+ if not child_requirements:
+ # Fallback: simple numbered variants
+ child_requirements = [
+ {
+ "title": f"Variant #{idx}",
+ "question_type": base_requirement.get("question_type"),
+ "difficulty": base_requirement.get("difficulty"),
+ "additional_requirements": f"Create a distinct scenario #{idx} using the same knowledge point.",
+ }
+ for idx in range(1, num_questions + 1)
+ ]
+
+ results: list[dict[str, Any]] = []
+ failures: list[dict[str, Any]] = []
+
+ self.logger.section(f"Batch Generation: {num_questions} question(s)")
+
+ for idx in range(1, num_questions + 1):
+ self.logger.separator("-")
+ self.logger.stage(f"Generating variant #{idx}/{num_questions}")
+
+ # Send progress update
+ await self._send_ws_update(
+ "progress",
+ {"stage": "generating", "progress": {"current": idx, "total": num_questions}},
+ )
+
+ # Clear Agent history, ensure each question is independent
+ self.question_agent.reset()
+
+ requirement_variant = copy.deepcopy(base_requirement)
+ child_req = child_requirements[idx - 1] if idx - 1 < len(child_requirements) else {}
+
+ if child_req.get("question_type"):
+ requirement_variant["question_type"] = child_req["question_type"]
+ if child_req.get("difficulty"):
+ requirement_variant["difficulty"] = child_req["difficulty"]
+
+ existing_extra = requirement_variant.get("additional_requirements", "").strip()
+ child_extra = child_req.get("additional_requirements", "").strip()
+ title = child_req.get("title", f"Variant #{idx}")
+
+ directive = (
+ f"[Auto-derived sub requirement #{idx}: {title}]\n"
+ "Maintain the exact same core knowledge point(s) as the base requirement.\n"
+ "Use the retrieved knowledge summary to shape the scenario.\n"
+ "Ensure the scenario and reasoning steps are distinct from other variants.\n"
+ f"{child_extra}"
+ )
+
+ combined_requirements = "\n\n".join(
+ part for part in [existing_extra, directive] if part
+ )
+ requirement_variant["additional_requirements"] = combined_requirements
+ requirement_variant["batch_index"] = idx
+
+ result = await self.generate_question(requirement_variant)
+
+ if result.get("success"):
+ results.append(result)
+ else:
+ failures.append(
+ {"index": idx, "error": result.get("error"), "reason": result.get("reason")}
+ )
+ # If any child requirement fails (e.g., due to knowledge issues), stop the batch early
+ self.logger.error(f"Batch aborted due to failure while generating variant #{idx}")
+ break
+
+ summary = {
+ "success": len(results) == num_questions and len(failures) == 0,
+ "requested": num_questions,
+ "completed": len(results),
+ "failed": len(failures),
+ "search_queries": queries,
+ "knowledge_summary": knowledge_summary,
+ "child_requirements": child_requirements,
+ "results": results,
+ "failures": failures,
+ }
+
+ # Persist batch results if output_dir is provided
+ if self.output_dir:
+ try:
+ from datetime import datetime
+
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
+ out_path = Path(self.output_dir)
+ out_path.mkdir(parents=True, exist_ok=True)
+ batch_file = out_path / f"batch_{timestamp}.json"
+ with open(batch_file, "w", encoding="utf-8") as f:
+ json.dump(summary, f, indent=2, ensure_ascii=False)
+ summary["output_file"] = str(batch_file)
+ self.logger.info(f"Batch results saved to: {batch_file}")
+ except Exception as e:
+ self.logger.warning(f"Failed to save batch results: {e}")
+
+ self.logger.section("Batch Generation Summary")
+ self.logger.info(f"Requested : {num_questions}")
+ self.logger.info(f"Completed : {len(results)}")
+ self.logger.info(f"Failed : {len(failures)}")
+
+ return summary
+
+ async def generate_questions_from_prompt(
+ self, requirement_text: str, num_questions: int
+ ) -> dict[str, Any]:
+ """
+ Entry point for users supplying only natural-language requirements.
+ """
+ self._suppress_logging()
+
+ queries = await self._generate_search_queries_from_text(
+ requirement_text, max(3, num_questions)
+ )
+ retrievals = await self._gather_retrieval_context(queries)
+ knowledge_summary = self._summarize_retrievals(retrievals)
+
+ # Check if any content was retrieved
+ has_content = any(retrieval.get("answer", "").strip() for retrieval in retrievals)
+
+ if not has_content:
+ return {
+ "success": False,
+ "error": "knowledge_not_found",
+ "message": "Knowledge base does not contain relevant information for the request.",
+ "search_queries": queries,
+ "knowledge_summary": knowledge_summary,
+ }
+
+ relevant = await self._check_retrieval_relevance(requirement_text, knowledge_summary)
+ if not relevant:
+ return {
+ "success": False,
+ "error": "knowledge_not_found",
+ "message": "Knowledge base appears unrelated to the requested topic.",
+ "search_queries": queries,
+ "knowledge_summary": knowledge_summary,
+ }
+
+ base_requirement = await self._interpret_requirement_text(requirement_text)
+ return await self.generate_multiple_questions(
+ base_requirement,
+ num_questions,
+ precomputed_queries=queries,
+ precomputed_retrievals=retrievals,
+ precomputed_summary=knowledge_summary,
+ )
+
+ async def _plan_sub_focuses(
+ self,
+ base_requirement: dict[str, Any],
+ shared_context: str,
+ num_questions: int,
+ ) -> list[dict[str, Any]]:
+ """Plan distinct sub-focuses for each question in one LLM call."""
+ system_prompt = (
+ "You are an educational content planner. Given a base requirement and knowledge context, "
+ "create distinct sub-focuses for generating multiple questions on the SAME topic. "
+ "Each sub-focus should describe a unique angle, scenario, or aspect to test. "
+ 'Output JSON with key "focuses" containing an array of objects, each with: '
+ '"id" (string like "q_1"), "focus" (string describing the specific angle), '
+ '"scenario_hint" (brief scenario suggestion).'
+ )
+ user_prompt = (
+ f"Base requirement:\n{json.dumps(base_requirement, ensure_ascii=False, indent=2)}\n\n"
+ f"Available knowledge context:\n{shared_context[:3000]}...\n\n"
+ f"Generate exactly {num_questions} distinct sub-focuses in JSON."
+ )
+ try:
+ content = await self._call_llm(
+ system_prompt=system_prompt, user_prompt=user_prompt, stage="plan_sub_focuses"
+ )
+ parsed = json.loads(content)
+ focuses = parsed.get("focuses", [])
+ if not isinstance(focuses, list):
+ focuses = []
+ except Exception as e:
+ self.logger.warning(f"Failed to plan sub-focuses: {e}")
+ focuses = []
+
+ # Fallback: create simple numbered focuses
+ if len(focuses) < num_questions:
+ for i in range(len(focuses), num_questions):
+ focuses.append(
+ {
+ "id": f"q_{i + 1}",
+ "focus": f"Variant {i + 1}: Different scenario using the same knowledge point",
+ "scenario_hint": f"Create a distinct problem #{i + 1}",
+ }
+ )
+
+ return focuses[:num_questions]
+
+ async def _generate_single_question_with_context(
+ self,
+ question_id: str,
+ base_requirement: dict[str, Any],
+ focus: dict[str, Any],
+ shared_context: str,
+ full_plan: list[dict[str, Any]],
+ semaphore: asyncio.Semaphore,
+ ) -> dict[str, Any]:
+ """Generate a single question with shared context and full plan awareness."""
+ async with semaphore:
+ try:
+ # Send progress update
+ await self._send_ws_update(
+ "question_update",
+ {
+ "question_id": question_id,
+ "status": "generating",
+ "focus": focus.get("focus", ""),
+ },
+ )
+
+ # Create a fresh agent for this question
+ gen_agent_config = self.config.get("agents", {}).get("question_generation", {})
+ max_gen_iterations = gen_agent_config.get("max_iterations", 5)
+
+ question_agent = QuestionGenerationAgent(
+ api_key=self._api_key,
+ base_url=self._base_url,
+ max_iterations=max_gen_iterations,
+ kb_name=self.kb_name,
+ token_stats_callback=self.update_token_stats,
+ )
+
+ # Build requirement with focus and plan awareness
+ requirement_variant = copy.deepcopy(base_requirement)
+
+ # Build plan summary to prevent duplication
+ other_focuses = [f for f in full_plan if f.get("id") != question_id]
+ plan_summary = "\n".join(
+ [f"- {f.get('id')}: {f.get('focus', 'N/A')}" for f in other_focuses]
+ )
+
+ focus_directive = (
+ f"[Question {question_id}]\n"
+ f"Focus: {focus.get('focus', 'Generate a question')}\n"
+ f"Scenario hint: {focus.get('scenario_hint', '')}\n\n"
+ "IMPORTANT: The following focuses are assigned to OTHER questions in this batch. "
+ "You MUST create a question that is DISTINCT from these:\n"
+ f"{plan_summary}\n\n"
+ "Use the provided knowledge context to ensure accuracy."
+ )
+
+ existing_extra = requirement_variant.get("additional_requirements", "").strip()
+ requirement_variant["additional_requirements"] = "\n\n".join(
+ filter(None, [existing_extra, focus_directive])
+ )
+ requirement_variant["batch_index"] = question_id
+ requirement_variant["_shared_context"] = shared_context
+
+ # Set up the agent
+ question_agent.set_requirement(requirement_variant)
+
+ # Pre-populate retrieved knowledge with shared context
+ question_agent.retrieved_knowledge = [
+ {
+ "query": "shared_batch_context",
+ "answer": shared_context,
+ }
+ ]
+
+ # Create message queue for this agent
+ local_queue = asyncio.Queue()
+
+ async def local_send_message(msg):
+ await local_queue.put(msg)
+
+ question_agent.send_message = local_send_message
+
+ # Run generation loop
+ for round_num in range(1, self.max_rounds + 1):
+ await self._send_ws_update(
+ "question_update",
+ {"question_id": question_id, "status": "generating", "round": round_num},
+ )
+
+ question_agent.submitted = False
+ task = f"Generate a question based on the focus: {focus.get('focus', '')}"
+
+ if round_num > 1:
+ task = "Revise the question based on validation feedback"
+
+ question_result = await question_agent.run(
+ task=task,
+ context={"requirement": requirement_variant, "round_num": round_num},
+ send_message_callback=local_send_message,
+ )
+
+ if not question_result.get("success"):
+ continue
+
+ # Check for rejection
+ result_data = question_result.get("result")
+ if isinstance(result_data, dict) and result_data.get("task_rejected"):
+ return {
+ "success": False,
+ "question_id": question_id,
+ "error": "task_rejected",
+ "reason": result_data.get("reason", "Knowledge missing"),
+ }
+
+ if not question_agent.submitted:
+ continue
+
+ # Get submitted question from queue
+ question = None
+ while not local_queue.empty():
+ msg = await local_queue.get()
+ if msg.message_type == "validate_request":
+ question = msg.content.get("question")
+
+ if not question:
+ continue
+
+ # Validate
+ await self._send_ws_update(
+ "question_update",
+ {"question_id": question_id, "status": "validating", "round": round_num},
+ )
+
+ question["knowledge_point"] = base_requirement.get("knowledge_point", "")
+ reference_question = base_requirement.get("reference_question")
+ validation_result = await self.validation_workflow.validate(
+ question, reference_question
+ )
+
+ decision = validation_result.get("decision")
+
+ if decision == "approve":
+ await self._send_ws_update(
+ "question_update", {"question_id": question_id, "status": "done"}
+ )
+
+ # Save question to disk
+ output_dir = self._save_question_result(
+ question=question,
+ requirement=base_requirement,
+ validation=validation_result,
+ round_num=round_num,
+ extended=False,
+ )
+
+ result = {
+ "success": True,
+ "question_id": question_id,
+ "question": question,
+ "validation": validation_result,
+ "rounds": round_num,
+ "focus": focus,
+ }
+ if output_dir:
+ result["output_dir"] = output_dir
+ return result
+
+ # Send feedback for next round
+ if decision in ["request_modification", "request_regeneration"]:
+ message = Message(
+ from_agent="QuestionValidationWorkflow",
+ to_agent="QuestionGenerationAgent",
+ message_type=decision,
+ content={
+ "issues": validation_result.get("issues", []),
+ "suggestions": validation_result.get("suggestions", []),
+ "reasoning": validation_result.get("reasoning", ""),
+ },
+ )
+ question_agent.receive_message(message)
+
+ # Max rounds reached - return as extended question instead of failure
+ last_question = question_agent.current_question
+ if last_question:
+ # Get extension analysis from validation workflow
+ extension_analysis = await self.validation_workflow.analyze_extension(
+ last_question, shared_context
+ )
+
+ await self._send_ws_update(
+ "question_update",
+ {"question_id": question_id, "status": "done", "extended": True},
+ )
+
+ validation = {
+ "decision": "extended",
+ "reasoning": extension_analysis.get("reasoning", ""),
+ "kb_connection": extension_analysis.get("kb_connection", ""),
+ "extended_aspect": extension_analysis.get("extended_aspect", ""),
+ }
+
+ # Save extended question to disk
+ output_dir = self._save_question_result(
+ question=last_question,
+ requirement=base_requirement,
+ validation=validation,
+ round_num=self.max_rounds,
+ extended=True,
+ )
+
+ result = {
+ "success": True,
+ "question_id": question_id,
+ "question": last_question,
+ "validation": validation,
+ "rounds": self.max_rounds,
+ "focus": focus,
+ "extended": True,
+ }
+ if output_dir:
+ result["output_dir"] = output_dir
+ return result
+ else:
+ # No question was generated at all
+ await self._send_ws_update(
+ "question_update", {"question_id": question_id, "status": "error"}
+ )
+ return {
+ "success": False,
+ "question_id": question_id,
+ "error": f"Max rounds ({self.max_rounds}) reached without generating a question",
+ }
+
+ except Exception as e:
+ self.logger.error(f"Error generating question {question_id}: {e}")
+ await self._send_ws_update(
+ "question_update", {"question_id": question_id, "status": "error"}
+ )
+ return {
+ "success": False,
+ "question_id": question_id,
+ "error": str(e),
+ }
+
+ async def generate_questions_parallel(
+ self,
+ base_requirement: dict[str, Any],
+ num_questions: int,
+ ) -> dict[str, Any]:
+ """
+ Generate multiple questions in parallel with shared context.
+
+ New flow:
+ 1. Split user input into N RAG queries
+ 2. Run RAG queries in parallel
+ 3. Merge results into shared context
+ 4. Plan sub-focuses for all questions at once
+ 5. Generate questions in parallel (with semaphore control)
+ """
+ if num_questions <= 0:
+ raise ValueError("num_questions must be greater than zero")
+
+ self._suppress_logging()
+
+ # Send initial progress
+ await self._send_ws_update(
+ "progress",
+ {
+ "stage": "planning",
+ "progress": {"status": "splitting_queries"},
+ "total": num_questions,
+ },
+ )
+
+ # Step 1: Split into RAG queries
+ self.logger.section(f"Parallel Generation: {num_questions} question(s)")
+ self.logger.info("Step 1: Splitting into RAG queries...")
+
+ queries = await self._generate_search_queries(base_requirement, self.rag_query_count)
+ self.logger.info(f"Generated {len(queries)} search queries")
+
+ # Step 2: Run RAG queries in parallel
+ await self._send_ws_update(
+ "progress",
+ {"stage": "researching", "progress": {"status": "retrieving"}, "queries": queries},
+ )
+ self.logger.info("Step 2: Retrieving knowledge in parallel...")
+
+ retrievals = await self._gather_retrieval_context(queries)
+
+ # Step 3: Merge into shared context
+ shared_context = self._summarize_retrievals(retrievals)
+
+ # Check if we have any content
+ has_content = any(r.get("answer", "").strip() for r in retrievals)
+ if not has_content:
+ return {
+ "success": False,
+ "error": "knowledge_not_found",
+ "message": "Knowledge base does not contain relevant information for the request.",
+ "search_queries": queries,
+ }
+
+ self.logger.info(f"Merged {len(retrievals)} retrieval results into shared context")
+
+ # Step 4: Plan sub-focuses
+ await self._send_ws_update(
+ "progress", {"stage": "planning", "progress": {"status": "planning_focuses"}}
+ )
+ self.logger.info("Step 3: Planning sub-focuses for all questions...")
+
+ sub_focuses = await self._plan_sub_focuses(base_requirement, shared_context, num_questions)
+ self.logger.info(f"Planned {len(sub_focuses)} sub-focuses")
+
+ # Send focuses to frontend
+ await self._send_ws_update(
+ "progress",
+ {
+ "stage": "generating",
+ "progress": {"status": "starting_parallel"},
+ "total": num_questions,
+ "focuses": sub_focuses,
+ },
+ )
+
+ # Step 5: Generate questions in parallel
+ self.logger.info(
+ f"Step 4: Generating {num_questions} questions in parallel (max {self.max_parallel_questions} concurrent)..."
+ )
+
+ semaphore = asyncio.Semaphore(self.max_parallel_questions)
+
+ tasks = [
+ self._generate_single_question_with_context(
+ question_id=focus.get("id", f"q_{i + 1}"),
+ base_requirement=base_requirement,
+ focus=focus,
+ shared_context=shared_context,
+ full_plan=sub_focuses,
+ semaphore=semaphore,
+ )
+ for i, focus in enumerate(sub_focuses)
+ ]
+
+ results = await asyncio.gather(*tasks, return_exceptions=True)
+
+ # Step 6: Aggregate results
+ successes = []
+ failures = []
+
+ for i, result in enumerate(results):
+ if isinstance(result, Exception):
+ failures.append(
+ {
+ "question_id": f"q_{i + 1}",
+ "error": str(result),
+ }
+ )
+ elif result.get("success"):
+ successes.append(result)
+ else:
+ failures.append(
+ {
+ "question_id": result.get("question_id", f"q_{i + 1}"),
+ "error": result.get("error", "Unknown error"),
+ "reason": result.get("reason", ""),
+ }
+ )
+
+ summary = {
+ "success": len(successes) == num_questions,
+ "requested": num_questions,
+ "completed": len(successes),
+ "failed": len(failures),
+ "search_queries": queries,
+ "shared_context": shared_context[:500] + "..."
+ if len(shared_context) > 500
+ else shared_context,
+ "sub_focuses": sub_focuses,
+ "results": successes,
+ "failures": failures,
+ }
+
+ # Persist results if output_dir is provided
+ if self.output_dir:
+ try:
+ from datetime import datetime
+
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
+ out_path = Path(self.output_dir)
+ out_path.mkdir(parents=True, exist_ok=True)
+ batch_file = out_path / f"parallel_batch_{timestamp}.json"
+ with open(batch_file, "w", encoding="utf-8") as f:
+ json.dump(summary, f, indent=2, ensure_ascii=False)
+ summary["output_file"] = str(batch_file)
+ self.logger.info(f"Results saved to: {batch_file}")
+ except Exception as e:
+ self.logger.warning(f"Failed to save results: {e}")
+
+ # Send completion
+ await self._send_ws_update(
+ "progress",
+ {
+ "stage": "complete",
+ "completed": len(successes),
+ "failed": len(failures),
+ "total": num_questions,
+ },
+ )
+
+ self.logger.section("Parallel Generation Summary")
+ self.logger.info(f"Requested : {num_questions}")
+ self.logger.info(f"Completed : {len(successes)}")
+ self.logger.info(f"Failed : {len(failures)}")
+
+ return summary
+
+ # =========================================================================
+ # Custom Mode Methods - New streamlined flow without iteration
+ # =========================================================================
+
+ async def _single_rag_search_naive(self, query: str) -> dict[str, Any]:
+ """Execute a single RAG search using naive mode."""
+ result = await rag_search(
+ query=query,
+ kb_name=self.kb_name,
+ mode="naive",
+ only_need_context=True,
+ )
+ return {
+ "query": query,
+ "answer": result.get("answer", ""),
+ "mode": "naive",
+ }
+
+ async def _gather_retrieval_context_naive(self, queries: list[str]) -> list[dict[str, Any]]:
+ """Run retrieval for each query in parallel using naive mode."""
+ self._update_agent_status("RetrievalTool", "running")
+ self.logger.info(
+ f"Retrieving background knowledge for {len(queries)} queries (naive mode)..."
+ )
+
+ # Execute all queries in parallel
+ tasks = [self._single_rag_search_naive(query) for query in queries]
+ results = await asyncio.gather(*tasks, return_exceptions=True)
+
+ retrievals = []
+ for i, result in enumerate(results):
+ query = queries[i]
+ if isinstance(result, Exception):
+ self.logger.warning(f"Retrieval failed for query '{query}': {result}")
+ continue
+
+ self.logger.debug(f" → Query: {query[:50]}... (retrieved)")
+ retrievals.append(
+ {
+ "query": query,
+ "answer": result.get("answer", ""),
+ }
+ )
+
+ self._update_agent_status("RetrievalTool", "done")
+ return retrievals
+
+ async def _generate_question_plan(
+ self,
+ base_requirement: dict[str, Any],
+ knowledge_summary: str,
+ num_questions: int,
+ ) -> dict[str, Any]:
+ """
+ Generate a question plan with focuses for each question.
+
+ Args:
+ base_requirement: Base requirement with knowledge_point, difficulty, question_type
+ knowledge_summary: Summary of retrieved background knowledge
+ num_questions: Number of questions to generate
+
+ Returns:
+ Plan dict with "focuses" array containing {id, focus, type} for each question
+ """
+ difficulty = base_requirement.get("difficulty", "medium")
+ question_type = base_requirement.get("question_type", "written")
+ knowledge_point = base_requirement.get("knowledge_point", "")
+
+ system_prompt = (
+ "You are an educational content planner. Given a topic, difficulty level, "
+ "question type, and background knowledge, create a structured question plan.\n\n"
+ "Each question focus should:\n"
+ "1. Test a specific aspect or angle of the knowledge point\n"
+ "2. Be distinct from other focuses (different scenarios, applications, or perspectives)\n"
+ "3. Match the specified difficulty level\n"
+ "4. Be achievable with the provided background knowledge\n\n"
+ 'Output JSON with key "focuses" containing an array of objects, each with:\n'
+ '- "id": string like "q_1", "q_2", etc.\n'
+ '- "focus": string describing what specific aspect this question will test\n'
+ '- "type": "choice" or "written" (should match the requested type)\n'
+ )
+
+ user_prompt = (
+ f"Topic/Knowledge Point: {knowledge_point}\n"
+ f"Difficulty: {difficulty}\n"
+ f"Question Type: {question_type}\n"
+ f"Number of Questions: {num_questions}\n\n"
+ f"Background Knowledge:\n{knowledge_summary[:3000]}...\n\n"
+ f"Generate exactly {num_questions} distinct question focuses in JSON format."
+ )
+
+ try:
+ content = await self._call_llm(
+ system_prompt=system_prompt, user_prompt=user_prompt, stage="generate_question_plan"
+ )
+ parsed = json.loads(content)
+ focuses = parsed.get("focuses", [])
+ if not isinstance(focuses, list):
+ focuses = []
+ except Exception as e:
+ self.logger.warning(f"Failed to generate question plan: {e}")
+ focuses = []
+
+ # Fallback: create simple numbered focuses
+ if len(focuses) < num_questions:
+ for i in range(len(focuses), num_questions):
+ focuses.append(
+ {
+ "id": f"q_{i + 1}",
+ "focus": f"Aspect {i + 1} of {knowledge_point}",
+ "type": question_type,
+ }
+ )
+
+ # Ensure all focuses have the correct type
+ for focus in focuses:
+ if "type" not in focus:
+ focus["type"] = question_type
+ if "id" not in focus:
+ focus["id"] = f"q_{focuses.index(focus) + 1}"
+
+ return {
+ "knowledge_point": knowledge_point,
+ "difficulty": difficulty,
+ "question_type": question_type,
+ "num_questions": num_questions,
+ "focuses": focuses[:num_questions],
+ }
+
+ def _save_knowledge_json(
+ self,
+ batch_dir: Path,
+ queries: list[str],
+ retrievals: list[dict[str, Any]],
+ ) -> str:
+ """Save background knowledge to knowledge.json."""
+ knowledge_data = {
+ "queries": queries,
+ "retrievals": retrievals,
+ "total_queries": len(queries),
+ "successful_retrievals": len([r for r in retrievals if r.get("answer")]),
+ }
+
+ knowledge_file = batch_dir / "knowledge.json"
+ with open(knowledge_file, "w", encoding="utf-8") as f:
+ json.dump(knowledge_data, f, indent=2, ensure_ascii=False)
+
+ self.logger.info(f"Background knowledge saved to: {knowledge_file}")
+ return str(knowledge_file)
+
+ def _save_plan_json(self, batch_dir: Path, plan: dict[str, Any]) -> str:
+ """Save question plan to plan.json."""
+ plan_file = batch_dir / "plan.json"
+ with open(plan_file, "w", encoding="utf-8") as f:
+ json.dump(plan, f, indent=2, ensure_ascii=False)
+
+ self.logger.info(f"Question plan saved to: {plan_file}")
+ return str(plan_file)
+
+ def _save_custom_question_result(
+ self,
+ batch_dir: Path,
+ question_id: str,
+ question: dict[str, Any],
+ validation: dict[str, Any],
+ focus: dict[str, Any],
+ ) -> str:
+ """Save a single question result in custom mode."""
+ question_dir = batch_dir / question_id
+ question_dir.mkdir(parents=True, exist_ok=True)
+
+ # Build result structure
+ result = {
+ "question_id": question_id,
+ "focus": focus,
+ "question": question,
+ "validation": validation,
+ }
+
+ # Save result.json
+ result_file = question_dir / "result.json"
+ with open(result_file, "w", encoding="utf-8") as f:
+ json.dump(result, f, indent=2, ensure_ascii=False)
+
+ # Build question.md
+ relevance = validation.get("relevance", "unknown")
+ kb_coverage = validation.get("kb_coverage", "")
+ extension_points = validation.get("extension_points", "")
+
+ md_content = f"""# Generated Question
+
+**Focus**: {focus.get("focus", "N/A")}
+**Type**: {focus.get("type", question.get("question_type", "N/A"))}
+
+---
+
+## Question
+{question.get("question", "")}
+
+"""
+ if question.get("options"):
+ md_content += "## Options\n"
+ for key, value in question.get("options", {}).items():
+ md_content += f"- **{key}**: {value}\n"
+ md_content += "\n"
+
+ md_content += f"""
+## Answer
+{question.get("correct_answer", "")}
+
+## Explanation
+{question.get("explanation", "")}
+
+---
+
+## Relevance Analysis
+
+**Relevance Level**: {relevance}
+
+**Knowledge Base Coverage**:
+{kb_coverage}
+"""
+ if extension_points:
+ md_content += f"""
+**Extension Points**:
+{extension_points}
+"""
+
+ md_file = question_dir / "question.md"
+ with open(md_file, "w", encoding="utf-8") as f:
+ f.write(md_content)
+
+ return str(question_dir)
+
+ async def _generate_single_question_custom(
+ self,
+ focus: dict[str, Any],
+ base_requirement: dict[str, Any],
+ knowledge_summary: str,
+ ) -> dict[str, Any]:
+ """
+ Generate a single question without iteration loop (custom mode).
+
+ Returns:
+ Dict with question data
+ """
+ question_id = focus.get("id", "q_1")
+ question_type = focus.get("type", base_requirement.get("question_type", "written"))
+ focus_text = focus.get("focus", "")
+ knowledge_point = base_requirement.get("knowledge_point", "")
+ difficulty = base_requirement.get("difficulty", "medium")
+
+ system_prompt = (
+ "You are a professional question designer. Generate a high-quality exam question "
+ "based on the provided focus and background knowledge.\n\n"
+ "Requirements:\n"
+ "1. The question must align with the specified focus\n"
+ "2. Use the background knowledge to ensure accuracy\n"
+ "3. Match the difficulty level\n"
+ "4. Provide a detailed explanation\n"
+ )
+
+ if question_type == "choice":
+ output_format = """Output JSON format:
+{
+ "question_type": "choice",
+ "question": "question content",
+ "options": {"A": "...", "B": "...", "C": "...", "D": "..."},
+ "correct_answer": "A/B/C/D",
+ "explanation": "detailed explanation"
+}"""
+ else:
+ output_format = """Output JSON format:
+{
+ "question_type": "written",
+ "question": "question content",
+ "correct_answer": "detailed answer",
+ "explanation": "detailed explanation"
+}"""
+
+ user_prompt = (
+ f"Knowledge Point: {knowledge_point}\n"
+ f"Focus: {focus_text}\n"
+ f"Difficulty: {difficulty}\n"
+ f"Question Type: {question_type}\n\n"
+ f"Background Knowledge:\n{knowledge_summary[:4000]}\n\n"
+ f"{output_format}"
+ )
+
+ try:
+ content = await self._call_llm(
+ system_prompt=system_prompt,
+ user_prompt=user_prompt,
+ stage=f"generate_question_{question_id}",
+ )
+ question = json.loads(content)
+ question["knowledge_point"] = knowledge_point
+ return {
+ "success": True,
+ "question": question,
+ }
+ except Exception as e:
+ self.logger.error(f"Failed to generate question {question_id}: {e}")
+ return {
+ "success": False,
+ "error": str(e),
+ }
+
+ async def generate_questions_custom(
+ self,
+ base_requirement: dict[str, Any],
+ num_questions: int,
+ ) -> dict[str, Any]:
+ """
+ Custom mode: Generate questions with the new streamlined flow.
+
+ Flow:
+ 1. Researching: Generate RAG queries, retrieve with naive mode, save knowledge.json
+ 2. Planning: Generate question plan, save plan.json
+ 3. Generating: For each focus, generate question + relevance analysis
+
+ Args:
+ base_requirement: Dict with knowledge_point, difficulty, question_type
+ num_questions: Number of questions to generate
+
+ Returns:
+ Summary dict with all results
+ """
+ from datetime import datetime
+
+ if num_questions <= 0:
+ raise ValueError("num_questions must be greater than zero")
+
+ self._suppress_logging()
+
+ # Create batch directory
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
+ batch_dir = Path(self.output_dir) / f"batch_{timestamp}" if self.output_dir else None
+ if batch_dir:
+ batch_dir.mkdir(parents=True, exist_ok=True)
+
+ self.logger.section(f"Custom Mode Generation: {num_questions} question(s)")
+
+ # =====================================================================
+ # Stage 1: Researching - Retrieve background knowledge
+ # =====================================================================
+ self.logger.stage("Stage 1: Researching")
+ await self._send_ws_update(
+ "progress",
+ {
+ "stage": "researching",
+ "progress": {"status": "generating_queries"},
+ "total": num_questions,
+ },
+ )
+
+ # Generate search queries
+ requirement_text = json.dumps(base_requirement, ensure_ascii=False)
+ queries = await self._generate_search_queries_from_text(
+ requirement_text, self.rag_query_count
+ )
+ self.logger.info(f"Generated {len(queries)} search queries: {queries}")
+
+ await self._send_ws_update(
+ "progress",
+ {"stage": "researching", "progress": {"status": "retrieving"}, "queries": queries},
+ )
+
+ # Retrieve using naive mode
+ retrievals = await self._gather_retrieval_context_naive(queries)
+ knowledge_summary = self._summarize_retrievals(retrievals)
+
+ # Check if we have any content
+ has_content = any(r.get("answer", "").strip() for r in retrievals)
+ if not has_content:
+ self.logger.warning("No content retrieved from knowledge base")
+ return {
+ "success": False,
+ "error": "knowledge_not_found",
+ "message": "Knowledge base does not contain relevant information for the request.",
+ "search_queries": queries,
+ }
+
+ # Save knowledge.json
+ if batch_dir:
+ self._save_knowledge_json(batch_dir, queries, retrievals)
+
+ await self._send_ws_update(
+ "progress", {"stage": "researching", "progress": {"status": "completed"}}
+ )
+ await self._send_ws_update("knowledge_saved", {"queries": queries})
+
+ # =====================================================================
+ # Stage 2: Planning - Generate question plan
+ # =====================================================================
+ self.logger.stage("Stage 2: Planning")
+ await self._send_ws_update(
+ "progress", {"stage": "planning", "progress": {"status": "creating_plan"}}
+ )
+
+ plan = await self._generate_question_plan(
+ base_requirement, knowledge_summary, num_questions
+ )
+ focuses = plan.get("focuses", [])
+ self.logger.info(f"Generated plan with {len(focuses)} focuses")
+
+ # Save plan.json
+ if batch_dir:
+ self._save_plan_json(batch_dir, plan)
+
+ await self._send_ws_update(
+ "progress",
+ {"stage": "planning", "progress": {"status": "completed"}, "focuses": focuses},
+ )
+ await self._send_ws_update("plan_ready", {"plan": plan, "focuses": focuses})
+
+ # =====================================================================
+ # Stage 3: Generating - Generate each question
+ # =====================================================================
+ self.logger.stage("Stage 3: Generating")
+ await self._send_ws_update(
+ "progress",
+ {
+ "stage": "generating",
+ "progress": {"current": 0, "total": num_questions},
+ "focuses": focuses,
+ },
+ )
+
+ results = []
+ failures = []
+
+ for idx, focus in enumerate(focuses):
+ question_id = focus.get("id", f"q_{idx + 1}")
+ self.logger.info(f"Generating question {question_id}: {focus.get('focus', '')[:50]}...")
+
+ await self._send_ws_update(
+ "question_update",
+ {
+ "question_id": question_id,
+ "status": "generating",
+ "focus": focus.get("focus", ""),
+ },
+ )
+
+ # Generate question (single pass, no iteration)
+ gen_result = await self._generate_single_question_custom(
+ focus=focus,
+ base_requirement=base_requirement,
+ knowledge_summary=knowledge_summary,
+ )
+
+ if not gen_result.get("success"):
+ self.logger.error(f"Failed to generate question {question_id}")
+ failures.append(
+ {
+ "question_id": question_id,
+ "error": gen_result.get("error", "Unknown error"),
+ }
+ )
+ await self._send_ws_update(
+ "question_update", {"question_id": question_id, "status": "error"}
+ )
+ continue
+
+ question = gen_result["question"]
+
+ # Perform relevance analysis
+ await self._send_ws_update(
+ "question_update", {"question_id": question_id, "status": "analyzing"}
+ )
+
+ validation = await self.validation_workflow.analyze_relevance(
+ question=question,
+ knowledge_summary=knowledge_summary,
+ )
+
+ # Save result
+ if batch_dir:
+ self._save_custom_question_result(
+ batch_dir=batch_dir,
+ question_id=question_id,
+ question=question,
+ validation=validation,
+ focus=focus,
+ )
+
+ result = {
+ "question_id": question_id,
+ "focus": focus,
+ "question": question,
+ "validation": validation,
+ }
+ results.append(result)
+
+ await self._send_ws_update(
+ "question_update", {"question_id": question_id, "status": "done"}
+ )
+ await self._send_ws_update(
+ "result",
+ {
+ "question_id": question_id,
+ "question": question,
+ "validation": validation,
+ "focus": focus,
+ "index": idx,
+ "rounds": 1, # Custom mode has single-pass generation
+ },
+ )
+
+ # Update progress
+ await self._send_ws_update(
+ "progress",
+ {"stage": "generating", "progress": {"current": idx + 1, "total": num_questions}},
+ )
+
+ # =====================================================================
+ # Complete
+ # =====================================================================
+ summary = {
+ "success": len(results) == num_questions,
+ "requested": num_questions,
+ "completed": len(results),
+ "failed": len(failures),
+ "search_queries": queries,
+ "plan": plan,
+ "results": results,
+ "failures": failures,
+ }
+
+ # Save summary.json
+ if batch_dir:
+ summary_file = batch_dir / "summary.json"
+ with open(summary_file, "w", encoding="utf-8") as f:
+ json.dump(summary, f, indent=2, ensure_ascii=False)
+ summary["output_dir"] = str(batch_dir)
+ self.logger.info(f"Summary saved to: {summary_file}")
+
+ await self._send_ws_update(
+ "progress",
+ {
+ "stage": "complete",
+ "completed": len(results),
+ "failed": len(failures),
+ "total": num_questions,
+ },
+ )
+
+ self.logger.section("Custom Mode Generation Summary")
+ self.logger.info(f"Requested : {num_questions}")
+ self.logger.info(f"Completed : {len(results)}")
+ self.logger.info(f"Failed : {len(failures)}")
+
+ return summary
diff --git a/src/agents/question/example.py b/src/agents/question/example.py
new file mode 100644
index 000000000..534228a36
--- /dev/null
+++ b/src/agents/question/example.py
@@ -0,0 +1,108 @@
+#!/usr/bin/env python
+"""
+Example script that demonstrates how to use the Agent coordinator.
+"""
+
+import asyncio
+import json
+import logging
+import os
+from pathlib import Path
+import sys
+
+from dotenv import load_dotenv
+
+os.environ["RAGANYTHING_VERBOSE"] = "0"
+os.environ["LIGHTRAG_VERBOSE"] = "0"
+
+logging.basicConfig(level=logging.WARNING, force=True)
+for logger_name in ["lightrag", "raganything", "nano-vectordb", "openai", "httpx", "httpcore"]:
+ logger = logging.getLogger(logger_name)
+ logger.setLevel(logging.WARNING)
+ logger.propagate = False
+
+project_root = Path(__file__).resolve().parent.parent.parent.parent.parent.parent.parent
+sys.path.insert(0, str(project_root))
+
+load_dotenv(dotenv_path=project_root / ".env", override=False)
+
+from src.agents.question import AgentCoordinator
+
+
+async def run_single_example(coordinator: AgentCoordinator):
+ """Generate a single question."""
+ requirement = {
+ "knowledge_point": "Lagrange multipliers",
+ "difficulty": "medium",
+ "question_type": "written",
+ "additional_requirements": "Focus on a computational exercise that demonstrates how to apply Lagrange multipliers.",
+ }
+
+ result = await coordinator.generate_question(requirement)
+
+ print("\n" + "=" * 80)
+ print("📊 Single-question result")
+ print("=" * 80)
+
+ if result.get("success"):
+ question = result["question"]
+ validation = result["validation"]
+
+ print(f"\n✅ Success in {result['rounds']} round(s)")
+ print(f"\nType: {question.get('question_type')}")
+ print(f"\nQuestion:\n{question.get('question')}")
+
+ if question.get("options"):
+ print("\nOptions:")
+ for key, value in question["options"].items():
+ print(f" {key}. {value}")
+
+ print(f"\nCorrect answer: {question.get('correct_answer')}")
+ print(f"\nExplanation:\n{question.get('explanation')}")
+
+ print(f"\nValidation decision: {validation.get('decision')}")
+ print(f"Validation reasoning: {validation.get('reasoning')}")
+ else:
+ error_type = result.get("error")
+ if error_type == "task_rejected":
+ print("\n🚫 Task rejected")
+ print(f"Reason: {result.get('reason')}")
+ print(
+ "\n💡 Tip: try a different knowledge point or ensure the knowledge base contains supporting material."
+ )
+ else:
+ print(f"\n❌ Failed: {error_type}")
+ if result.get("last_question"):
+ print("\nLast attempted question:")
+ print(json.dumps(result["last_question"], ensure_ascii=False, indent=2))
+ if result.get("last_validation"):
+ print("\nLast validation result:")
+ print(json.dumps(result["last_validation"], ensure_ascii=False, indent=2))
+
+
+async def run_batch_example(coordinator: AgentCoordinator):
+ """Generate multiple questions from a natural-language prompt."""
+ prompt = (
+ "Medium questions on Multivariable Functions, Limits and Continuity, and Differentiation"
+ )
+
+ batch_result = await coordinator.generate_questions_from_prompt(
+ requirement_text=prompt, num_questions=3
+ )
+
+ print("\n" + "=" * 80)
+ print("📦 Batch generation result")
+ print("=" * 80)
+ print(json.dumps(batch_result, ensure_ascii=False, indent=2))
+
+
+async def main():
+ """Entry point for the example script."""
+ coordinator = AgentCoordinator(max_rounds=10, kb_name="math2211", output_dir="./output")
+
+ # await run_single_example(coordinator)
+ await run_batch_example(coordinator)
+
+
+if __name__ == "__main__":
+ asyncio.run(main())
diff --git a/src/agents/question/prompts/en/coordinator.yaml b/src/agents/question/prompts/en/coordinator.yaml
new file mode 100644
index 000000000..536e7b6e3
--- /dev/null
+++ b/src/agents/question/prompts/en/coordinator.yaml
@@ -0,0 +1,75 @@
+generate_search_queries: |
+ system: |
+ 【Role】You are a knowledge base retrieval assistant, preparing for question generation.
+
+ 【Current Task】Generate knowledge point retrieval queries to find theoretical explanations, definitions, and theorems in the knowledge base.
+ ⚠️ Key: You are not generating questions now! You are looking for theoretical knowledge needed for question generation!
+
+ 【Output Rules】
+ 1. Only output pure knowledge point names (theorem names, concept names, method names)
+ 2. Each query should be 2-5 words
+ 3. Do not include functions, numerical values, or calculation tasks
+ 4. Do not use questions or task descriptions
+
+ user_template: |
+ The user's question generation requirement is:
+ {requirement_text}
+
+ Please extract {num_queries} pure knowledge point names from it for knowledge base retrieval.
+
+ Correct examples:
+ ✅ Taylor theorem
+ ✅ Lagrange multipliers
+ ✅ critical points
+
+ Incorrect examples (do not generate):
+ ❌ Apply Taylor's Theorem to approximate f(x,y)=... (This is a question)
+ ❌ Find and classify critical points (This is a task)
+ ❌ Use Lagrange multipliers to find maximum (This is an instruction)
+
+ Return in JSON format: {{"queries": ["knowledge point 1", "knowledge point 2", ...]}}, containing exactly {num_queries} knowledge point names.
+
+check_retrieval_relevance: |
+ system: |
+ You evaluate whether retrieved knowledge is relevant to a user's request.
+ Respond in JSON with key "relevant" (true/false) and optional "reason".
+
+ user_template: |
+ User request:
+ {requirement_text}
+
+ Retrieved knowledge summary:
+ {knowledge_summary}
+
+ Is the retrieved knowledge substantively relevant to the request?
+
+generate_child_requirements: |
+ system: |
+ You are a curriculum designer. Given a base requirement and knowledge summary,
+ create distinct sub-requirements that all test the SAME knowledge point.
+ Each sub-requirement must describe a unique scenario and reasoning flow.
+ Output JSON with key "requirements" (array of length requested) where each item has:
+ "title", "question_type", "difficulty", "additional_requirements".
+
+ user_template: |
+ Base requirement:
+ {base_requirement}
+
+ Knowledge summary:
+ {knowledge_summary}
+
+ Generate exactly {num_questions} sub-requirements in JSON.
+
+interpret_requirement_text: |
+ system: |
+ You are an instruction parser for an exam-question generator.
+ Given a natural-language request, extract the core knowledge point,
+ difficulty (easy/medium/hard), preferred question type (choice/written),
+ and additional requirements. Return JSON with keys:
+ "knowledge_point", "difficulty", "question_type", "additional_requirements".
+
+ user_template: |
+ Requirement:
+ {requirement_text}
+
+ Return JSON only.
diff --git a/src/agents/question/prompts/en/generation_agent.yaml b/src/agents/question/prompts/en/generation_agent.yaml
new file mode 100644
index 000000000..0356bc9e0
--- /dev/null
+++ b/src/agents/question/prompts/en/generation_agent.yaml
@@ -0,0 +1,110 @@
+system: |
+ You are a professional Question Generation Agent. Your responsibilities are:
+ 1. Generate high-quality questions based on requirements
+ 2. Use retrieved background knowledge to ensure accuracy
+ 3. Express knowledge in the same way as the knowledge base
+
+ **Workflow**:
+ 1. Understand question requirements (knowledge point, difficulty, question type, etc.)
+ 2. Use the provided background knowledge to generate the question
+ 3. Ensure the question is rigorous and accurate
+ 4. Submit question for relevance analysis
+
+ **Important notes**:
+ - Questions must be rigorous and accurate, based on knowledge base content
+ - Calculation problems should have substantial computation, not too simple
+ - Use the provided background knowledge as the foundation for question generation
+ - Multiple choice questions must have only one correct answer
+ - Solutions/explanations should be detailed and clear, using the same narrative style as knowledge base
+ - **Chain-of-thought discipline**:
+ - Always reason internally in a deliberate, step-by-step manner. First outline the new scenario, then plan how the solution should proceed, and finally produce the answer.
+ - Do not expose chain-of-thought text in the final JSON; keep the reasoning internal and ensure the final output is coherent and precise.
+
+generate: |
+ Generate a question based on the following information:
+
+ Requirements:
+ {requirements}
+
+ Retrieved knowledge:
+ {knowledge}
+
+ Thinking instructions:
+ - First, silently plan the scenario and reasoning steps (chain-of-thought) to ensure the question is coherent.
+ - Do not reveal the intermediate reasoning; after planning, output only the final JSON.
+
+ Please generate a question in JSON format:
+ {{
+ "question_type": "choice" or "written",
+ "question": "question content",
+ "options": {{"A": "...", "B": "...", "C": "...", "D": "..."}} # only for multiple choice
+ "correct_answer": "correct answer",
+ "explanation": "detailed explanation"
+ }}
+
+generate_with_reference: |
+ Generate a new question that draws inspiration from the following reference but is clearly distinct in scenario and reasoning:
+
+ Reference question:
+ {reference_question}
+
+ Requirements:
+ {requirements}
+
+ Retrieved knowledge:
+ {knowledge}
+
+ Requirements:
+ 1. **Maintain same core knowledge and difficulty**: Concepts being tested must stay aligned
+ 2. **Maintain the exact same knowledge scope**: Infer the primary mathematical concepts from the reference and keep them identical (e.g., if the reference focuses on planar line parametrization, remain within that topic; do NOT escalate to surfaces, directional derivatives, or unrelated advanced subjects).
+ 3. **Change the scenario/background**: Use different objects, coordinate systems, physical contexts, or story framing. Simply reusing the same geometric shape or statement with different numbers is forbidden.
+ 4. **Change the calculation process / add new reasoning steps**: Rearrange the solution steps, introduce an additional sub-question, or require an extra computation compared to the reference.
+ 5. **Change specific data and symbols**: Use new parameters, coordinate values, constants, etc.
+ 6. **Maintain overall structure**: Keep the number/type of sub-questions comparable (if the reference has multiple parts, yours can also have multiple parts, but they must not be identical).
+ 7. **Explicitly forbidden**:
+ - Only modifying numerical values or variable names
+ - Repeating the same statement with an added explanation
+ - Copying the same geometric/object setup without new twists
+ - Introducing higher-level or unrelated knowledge points that are absent from the reference
+
+ Innovation examples:
+ - ✅ Good innovation: Change the geometric object (tetrahedron→pyramid with an apex not on axes), request an extra computation (e.g., find area + volume), use a different method (e.g., projection instead of simple dot product).
+ - ❌ Insufficient innovation: Same tetrahedron on coordinate axes with identical statement, even if an explanation is added. Adding extra commentary does NOT count as innovation.
+
+ Thinking instructions:
+ - Deliberately plan the new scenario and reasoning steps step-by-step.
+ - Keep the chain-of-thought internal; only output the final JSON.
+
+ Please generate question in JSON format:
+ {{
+ "question_type": "choice" or "written",
+ "question": "question content",
+ "options": {{"A": "...", "B": "...", "C": "...", "D": "..."}} # only for multiple choice
+ "correct_answer": "correct answer",
+ "explanation": "detailed explanation"
+ }}
+
+refine: |
+ Please modify the question based on validation feedback:
+
+ Original question:
+ {original_question}
+
+ Validation feedback:
+ {feedback}
+
+ Retrieved knowledge:
+ {knowledge}
+
+ Thinking instructions:
+ - Reflect on the validation feedback step-by-step, plan the adjustments mentally, then update the question.
+ - Keep the reasoning private; only output the final JSON.
+
+ Please revise the question in JSON format:
+ {{
+ "question_type": "choice" or "written",
+ "question": "question content",
+ "options": {{"A": "...", "B": "...", "C": "...", "D": "..."}} # only for multiple choice
+ "correct_answer": "correct answer",
+ "explanation": "detailed explanation"
+ }}
diff --git a/src/agents/question/prompts/en/validation_agent.yaml b/src/agents/question/prompts/en/validation_agent.yaml
new file mode 100644
index 000000000..a034a5ff8
--- /dev/null
+++ b/src/agents/question/prompts/en/validation_agent.yaml
@@ -0,0 +1,63 @@
+system: |
+ You are a professional question validation Agent. Your responsibilities are:
+ 1. Verify the rigor and correctness of questions
+ 2. Use the retrieve tool to search the knowledge base and independently verify answers
+ 3. Based on validation results, decide: approve, request modification, or request regeneration
+
+ **Validation Criteria**:
+ 1. Is the question statement clear and unambiguous?
+ 2. Can the answer be derived from knowledge base content? (Be lenient - if core concepts are covered, it's acceptable)
+ 3. Do multiple-choice questions have only one correct answer?
+ 4. Is the explanation detailed and accurate?
+ 5. For questions involving calculations, is the answer correct?
+ 6. Does the explanation use the same narrative approach as the knowledge base?
+ 7. For knowledge points that are obviously below the knowledge base level, they may not need to appear in the knowledge base (e.g., basic arithmetic operations used in solving calculus problems)
+
+ **Important Principles**:
+ - **Questions that extend beyond KB content are valuable** - they encourage broader learning
+ - **Be lenient with validation** - if the core concepts are related, accept the question
+ - **Cannot skip the validate step and directly approve**
+
+ **Action Choices**:
+ - **Approve (approve_question)**: Use when validate result is approve
+ - **Modify (request_modification)**: Use when validate result is request_modification (for minor issues)
+ - **Regenerate (request_regeneration)**: Use ONLY when validate result is request_regeneration AND the content is completely irrelevant
+
+validate: |
+ Please validate the following question:
+
+ Question:
+ {question}
+
+ Retrieved validation knowledge:
+ {validation_knowledge}
+
+ Please perform validation and output in JSON format:
+ {{
+ "decision": "approve" or "request_modification" or "request_regeneration",
+ "issues": ["Issue 1", "Issue 2", ...], # List of discovered issues
+ "suggestions": ["Suggestion 1", "Suggestion 2", ...], # List of modification suggestions
+ "reasoning": "Detailed explanation of validation reasoning"
+ }}
+
+ Validation Points:
+ 1. **Retrieval Result Sufficiency (Lenient Judgment)**:
+ - If the retrieved knowledge covers the core concepts of the question, it is sufficient
+ - Questions that extend beyond the KB content can still be valuable for learning
+ - Only request regeneration when the content is **completely irrelevant**
+ 2. Can the answer be derived from the retrieved knowledge? (Basic knowledge can be assumed)
+ 3. Do multiple-choice questions have only one correct answer?
+ 4. Is the question statement clear?
+ 5. Is the explanation sufficient?
+ 6. If there are calculations, are the results correct?
+
+ **Validation Principles**:
+ - ✅ Be lenient: If core concepts are covered, the question should be accepted
+ - ✅ Questions extending beyond KB content are valuable - they show broader application
+ - ❌ **Only use request_regeneration for completely irrelevant content**
+ - ❌ Cannot use your own knowledge to validate; must rely on retrieved knowledge
+
+ **Decision Guidelines**:
+ - "approve": Question is valid and well-aligned with knowledge base
+ - "request_modification": Minor issues that can be fixed with adjustments
+ - "request_regeneration": ONLY when content is completely irrelevant to the knowledge base
diff --git a/src/agents/question/prompts/en/validation_workflow.yaml b/src/agents/question/prompts/en/validation_workflow.yaml
new file mode 100644
index 000000000..90c79c6a3
--- /dev/null
+++ b/src/agents/question/prompts/en/validation_workflow.yaml
@@ -0,0 +1,88 @@
+validate: |
+ Please validate the following question:
+
+ Question:
+ {question}
+
+ {reference_section}
+
+ Retrieved validation knowledge:
+ {validation_knowledge}
+
+ Please perform validation and output in JSON format:
+ {{
+ "decision": "approve" or "request_modification" or "request_regeneration",
+ "issues": ["issue1", "issue2", ...], # List of found issues
+ "suggestions": ["suggestion1", "suggestion2", ...], # List of modification suggestions
+ "reasoning": "Detailed explanation of validation reasoning"
+ }}
+
+ Validation criteria:
+ 1. **Retrieved knowledge sufficiency (lenient judgment)**:
+ - ⚠️ **Important**: Knowledge base may not contain basic/low-level knowledge points, as students are assumed to have mastered them
+ - If question involves basic knowledge (e.g. vector dot product, magnitude, basic calculus formulas), but retrieved results are more advanced content, this is **acceptable**
+ - **Judgment criterion**: Is retrieved knowledge related to the question's **core knowledge points**? If question tests application of advanced concepts and you retrieved that advanced concept, it should be accepted even without basic formulas
+ - Only request regeneration when retrieved knowledge is **completely irrelevant** or **core knowledge points don't match**
+
+ {innovation_section}
+
+ 2. **Knowledge level judgment**:
+ - If retrieved knowledge is **higher level** than basic knowledge required by question, knowledge base assumes these basics are mastered
+ - Example: Question uses vector dot product, retrieved multivariable calculus content → **acceptable** (calculus courses assume students know vectors)
+ - Example: Question tests Lagrange multipliers, retrieved Lagrange multipliers → **acceptable** (even without basic partial derivative definition)
+
+ 3. Can answer be derived from retrieved knowledge? (Consider basic knowledge may not be in knowledge base)
+ 4. Do multiple choice questions have only one correct answer?
+ 5. Is question statement clear?
+ 6. Is explanation sufficient?
+ 7. If calculation involved, is result correct?
+
+ **Validation principles**:
+ - ✅ Be lenient with basic knowledge: If question uses basic knowledge but retrieved more advanced related content, should accept
+ - ✅ Focus on core knowledge points: As long as question's core points are reflected in retrieval results, knowledge is sufficient
+ - ✅ Questions that extend beyond KB content are valuable: They encourage broader learning
+ - ❌ Still need to validate based on retrieval results: Cannot use your own knowledge, but can reasonably infer basics are mastered
+ - ❌ Only request regeneration when completely irrelevant: Only require regeneration when retrieval results are **completely unrelated** to question's core content
+
+ **Example judgments**:
+ - ✅ Accept: Question uses vector operations + retrieved linear algebra advanced content
+ - ✅ Accept: Question uses basic differentiation + retrieved multivariable calculus content
+ - ✅ Accept: Question uses trigonometric functions + retrieved complex analysis content
+ - ⚠️ Request modification (not regeneration): Question partially related but needs adjustment
+ - ❌ Request regeneration: Question tests Lagrange multipliers + retrieved probability theory content (completely irrelevant)
+
+innovation_section: |
+ **Special check for mimicking questions**:
+ - **Innovation check**: Compare the generated question with the reference question
+ - ⚠️ **Insufficient innovation** - If only numbers/symbols changed while scenario, wording, structure, and solution process remain the same, or if the generator merely adds an explanation to the same statement, you MUST return request_modification or request_regeneration.
+ - Examples of insufficient innovation:
+ * Only changed coordinates from (1,2,3) to (4,5,6), everything else same
+ * Only changed parameter from k to m, calculation process identical
+ * Only swapped numerical values, question structure completely same
+ - ⚠️ Adding explanations or extra words without changing the scenario/requirements does NOT count as innovation.
+ - ✅ **Sufficient innovation** should include:
+ * Changed geometric objects or mathematical structures
+ * Changed calculation approach or solution method
+ * Changed question scenario or context
+ * Changed what is being solved for (e.g. from angle to projection)
+ - If innovation is insufficient, add to issues: "Insufficient innovation: only data changed, scenario and process identical to reference"
+
+relevance_analysis: |
+ Analyze the relevance between the following exam question and the knowledge base content.
+
+ Question:
+ {question}
+
+ Knowledge Base Content:
+ {knowledge}
+
+ Please analyze and provide a JSON response:
+ {{
+ "relevance": "high" or "partial",
+ "kb_coverage": "Describe specifically what concepts, theories, or methods from the knowledge base this question tests.",
+ "extension_points": "If relevance is 'partial', describe what aspects extend beyond the knowledge base. Leave empty if 'high'."
+ }}
+
+ Guidelines:
+ - "high": Question can be fully answered using only the knowledge base content
+ - "partial": Question is related but requires some knowledge beyond what's provided
diff --git a/src/agents/question/prompts/zh/coordinator.yaml b/src/agents/question/prompts/zh/coordinator.yaml
new file mode 100644
index 000000000..e5e9dc070
--- /dev/null
+++ b/src/agents/question/prompts/zh/coordinator.yaml
@@ -0,0 +1,75 @@
+generate_search_queries: |
+ system: |
+ 【角色】你是一个知识库检索助手,为题目生成做准备。
+
+ 【当前任务】生成知识点检索查询,在知识库中查找理论解释、定义和定理。
+ ⚠️ 关键:你现在不是在生成题目!你是在寻找题目生成所需的理论知识!
+
+ 【输出规则】
+ 1. 只输出纯粹的知识点名称(定理名称、概念名称、方法名称)
+ 2. 每个查询应为2-5个词
+ 3. 不要包含函数、数值或计算任务
+ 4. 不要使用问题或任务描述
+
+ user_template: |
+ 用户的题目生成需求是:
+ {requirement_text}
+
+ 请从中提取{num_queries}个纯知识点名称用于知识库检索。
+
+ 正确示例:
+ ✅ 泰勒定理
+ ✅ 拉格朗日乘数法
+ ✅ 临界点
+
+ 错误示例(不要生成):
+ ❌ 应用泰勒定理近似f(x,y)=...(这是一道题目)
+ ❌ 求临界点并分类(这是一个任务)
+ ❌ 用拉格朗日乘数法求最大值(这是一条指令)
+
+ 以JSON格式返回:{{"queries": ["知识点1", "知识点2", ...]}},恰好包含{num_queries}个知识点名称。
+
+check_retrieval_relevance: |
+ system: |
+ 你评估检索到的知识是否与用户的请求相关。
+ 以JSON格式响应,包含键"relevant"(true/false)和可选的"reason"。
+
+ user_template: |
+ 用户请求:
+ {requirement_text}
+
+ 检索到的知识摘要:
+ {knowledge_summary}
+
+ 检索到的知识是否实质上与请求相关?
+
+generate_child_requirements: |
+ system: |
+ 你是一个课程设计师。给定一个基础需求和知识摘要,
+ 创建测试相同知识点的不同子需求。
+ 每个子需求必须描述独特的场景和推理流程。
+ 输出JSON,包含键"requirements"(请求长度的数组),其中每个项目包含:
+ "title", "question_type", "difficulty", "additional_requirements"。
+
+ user_template: |
+ 基础需求:
+ {base_requirement}
+
+ 知识摘要:
+ {knowledge_summary}
+
+ 以JSON格式生成恰好{num_questions}个子需求。
+
+interpret_requirement_text: |
+ system: |
+ 你是考试题目生成器的指令解析器。
+ 给定一个自然语言请求,提取核心知识点、
+ 难度(easy/medium/hard)、首选题型(choice/written)、
+ 和额外要求。返回JSON,包含键:
+ "knowledge_point", "difficulty", "question_type", "additional_requirements"。
+
+ user_template: |
+ 需求:
+ {requirement_text}
+
+ 仅返回JSON。
diff --git a/src/agents/question/prompts/zh/generation_agent.yaml b/src/agents/question/prompts/zh/generation_agent.yaml
new file mode 100644
index 000000000..904927b9e
--- /dev/null
+++ b/src/agents/question/prompts/zh/generation_agent.yaml
@@ -0,0 +1,110 @@
+system: |
+ 你是一个专业的题目生成Agent。你的职责是:
+ 1. 根据需求生成高质量的题目
+ 2. 使用检索到的背景知识确保准确性
+ 3. 以与知识库相同的方式表达知识
+
+ **工作流程**:
+ 1. 理解题目需求(知识点、难度、题型等)
+ 2. 使用提供的背景知识生成题目
+ 3. 确保题目严谨准确
+ 4. 提交题目进行相关性分析
+
+ **重要提示**:
+ - 题目必须严谨准确,基于知识库内容
+ - 计算题应有实质性的计算,不能太简单
+ - 使用提供的背景知识作为出题的基础
+ - 选择题必须只有一个正确答案
+ - 解答/解释应详细清晰,使用与知识库相同的叙述风格
+ - **思维链纪律**:
+ - 始终以深思熟虑、逐步的方式进行内部推理。首先概述新场景,然后规划解题步骤,最后产生答案。
+ - 不要在最终JSON中暴露思维链文本;保持内部推理,确保最终输出连贯准确。
+
+generate: |
+ 根据以下信息生成一道题目:
+
+ 需求:
+ {requirements}
+
+ 检索到的知识:
+ {knowledge}
+
+ 思考说明:
+ - 首先,默默规划场景和推理步骤(思维链),确保题目连贯。
+ - 不要透露中间推理过程;规划后,只输出最终的JSON。
+
+ 请以JSON格式生成题目:
+ {{
+ "question_type": "choice" 或 "written",
+ "question": "题目内容",
+ "options": {{"A": "...", "B": "...", "C": "...", "D": "..."}} # 仅选择题需要
+ "correct_answer": "正确答案",
+ "explanation": "详细解释"
+ }}
+
+generate_with_reference: |
+ 生成一道受以下参考题启发但在场景和推理上明显不同的新题目:
+
+ 参考题目:
+ {reference_question}
+
+ 需求:
+ {requirements}
+
+ 检索到的知识:
+ {knowledge}
+
+ 要求:
+ 1. **保持相同的核心知识和难度**:被测试的概念必须保持一致
+ 2. **保持完全相同的知识范围**:从参考题推断主要数学概念并保持相同(例如,如果参考题关注平面直线参数化,就保持在该主题内;不要升级到曲面、方向导数或无关的高级主题)
+ 3. **改变场景/背景**:使用不同的对象、坐标系、物理背景或故事框架。禁止简单地重用相同的几何形状或陈述,只改变数字
+ 4. **改变计算过程/添加新的推理步骤**:重新安排解题步骤,引入额外的子问题,或要求比参考题多的计算
+ 5. **改变具体数据和符号**:使用新的参数、坐标值、常数等
+ 6. **保持整体结构**:保持子问题的数量/类型相当(如果参考题有多个部分,你的也可以有多个部分,但不能完全相同)
+ 7. **明确禁止**:
+ - 仅修改数值或变量名
+ - 重复相同的陈述只是添加解释
+ - 复制相同的几何/对象设置而没有新的变化
+ - 引入参考题中没有的更高级或无关的知识点
+
+ 创新示例:
+ - ✅ 好的创新:改变几何对象(四面体→顶点不在坐标轴上的棱锥),要求额外的计算(如求面积+体积),使用不同的方法(如投影而非简单点积)
+ - ❌ 创新不足:坐标轴上相同的四面体,陈述相同,即使添加了解释。添加额外评论不算创新。
+
+ 思考说明:
+ - 深思熟虑地逐步规划新场景和推理步骤。
+ - 保持思维链内部;只输出最终的JSON。
+
+ 请以JSON格式生成题目:
+ {{
+ "question_type": "choice" 或 "written",
+ "question": "题目内容",
+ "options": {{"A": "...", "B": "...", "C": "...", "D": "..."}} # 仅选择题需要
+ "correct_answer": "正确答案",
+ "explanation": "详细解释"
+ }}
+
+refine: |
+ 请根据验证反馈修改题目:
+
+ 原题目:
+ {original_question}
+
+ 验证反馈:
+ {feedback}
+
+ 检索到的知识:
+ {knowledge}
+
+ 思考说明:
+ - 逐步反思验证反馈,在心里规划调整,然后更新题目。
+ - 保持推理私密;只输出最终的JSON。
+
+ 请以JSON格式修改题目:
+ {{
+ "question_type": "choice" 或 "written",
+ "question": "题目内容",
+ "options": {{"A": "...", "B": "...", "C": "...", "D": "..."}} # 仅选择题需要
+ "correct_answer": "正确答案",
+ "explanation": "详细解释"
+ }}
diff --git a/src/agents/question/prompts/zh/validation_agent.yaml b/src/agents/question/prompts/zh/validation_agent.yaml
new file mode 100644
index 000000000..41b93b9c6
--- /dev/null
+++ b/src/agents/question/prompts/zh/validation_agent.yaml
@@ -0,0 +1,63 @@
+system: |
+ 你是一个专业的题目验证Agent。你的职责是:
+ 1. 验证题目的严谨性和正确性
+ 2. 使用retrieve工具搜索知识库,独立验证答案
+ 3. 根据验证结果决定:通过、请求修改或请求重新生成
+
+ **验证标准**:
+ 1. 题目表述是否清晰无歧义?
+ 2. 答案是否能从知识库内容推导?(宽松判断 - 如果核心概念相关,可以接受)
+ 3. 选择题是否只有一个正确答案?
+ 4. 解释是否详细准确?
+ 5. 对于涉及计算的题目,答案是否正确?
+ 6. 解释是否使用与知识库相同的叙述方式?
+ 7. 对于明显低于知识库水平的知识点,它们可能不需要出现在知识库中(例如,解微积分问题时使用的基本算术运算)
+
+ **重要原则**:
+ - **拓展知识库内容的题目是有价值的** - 它们鼓励更广泛的学习
+ - **验证时要宽松** - 如果核心概念相关,应接受题目
+ - **不能跳过validate步骤直接通过**
+
+ **行动选择**:
+ - **通过 (approve_question)**:当validate结果是approve时使用
+ - **修改 (request_modification)**:当validate结果是request_modification时使用(针对小问题)
+ - **重新生成 (request_regeneration)**:仅当validate结果是request_regeneration且内容完全不相关时使用
+
+validate: |
+ 请验证以下题目:
+
+ 题目:
+ {question}
+
+ 检索到的验证知识:
+ {validation_knowledge}
+
+ 请进行验证并以JSON格式输出:
+ {{
+ "decision": "approve" 或 "request_modification" 或 "request_regeneration",
+ "issues": ["问题1", "问题2", ...], # 发现的问题列表
+ "suggestions": ["建议1", "建议2", ...], # 修改建议列表
+ "reasoning": "验证推理的详细说明"
+ }}
+
+ 验证要点:
+ 1. **检索结果充分性(宽松判断)**:
+ - 如果检索到的知识涵盖了题目的核心概念,就是充分的
+ - 拓展知识库内容的题目对学习仍有价值
+ - 只有当内容**完全不相关**时才请求重新生成
+ 2. 答案能否从检索到的知识推导?(可以假设基础知识已掌握)
+ 3. 选择题是否只有一个正确答案?
+ 4. 题目表述是否清晰?
+ 5. 解释是否充分?
+ 6. 如果有计算,结果是否正确?
+
+ **验证原则**:
+ - ✅ 宽松判断:如果核心概念相关,题目应被接受
+ - ✅ 拓展知识库内容的题目是有价值的 - 它们展示了更广泛的应用
+ - ❌ **只在内容完全不相关时使用request_regeneration**
+ - ❌ 不能使用自己的知识验证;必须依赖检索到的知识
+
+ **决策指南**:
+ - "approve":题目有效且与知识库对齐良好
+ - "request_modification":有小问题可以通过调整修复
+ - "request_regeneration":仅当内容与知识库完全不相关时
diff --git a/src/agents/question/prompts/zh/validation_workflow.yaml b/src/agents/question/prompts/zh/validation_workflow.yaml
new file mode 100644
index 000000000..ef8296081
--- /dev/null
+++ b/src/agents/question/prompts/zh/validation_workflow.yaml
@@ -0,0 +1,88 @@
+validate: |
+ 请验证以下题目:
+
+ 题目:
+ {question}
+
+ {reference_section}
+
+ 检索到的验证知识:
+ {validation_knowledge}
+
+ 请进行验证并以JSON格式输出:
+ {{
+ "decision": "approve" 或 "request_modification" 或 "request_regeneration",
+ "issues": ["问题1", "问题2", ...], # 发现的问题列表
+ "suggestions": ["建议1", "建议2", ...], # 修改建议列表
+ "reasoning": "验证推理的详细说明"
+ }}
+
+ 验证标准:
+ 1. **检索知识充分性(宽松判断)**:
+ - ⚠️ **重要**:知识库可能不包含基础/低级知识点,因为假设学生已经掌握
+ - 如果题目涉及基础知识(如向量点积、模、基本微积分公式),但检索结果是更高级的内容,这是**可以接受的**
+ - **判断标准**:检索到的知识是否与题目的**核心知识点**相关?如果题目测试高级概念的应用,且你检索到了该高级概念,即使没有基础公式也应该接受
+ - 只有当检索知识**完全不相关**或**核心知识点不匹配**时才返回"request_regeneration"
+
+ {innovation_section}
+
+ 2. **知识层次判断**:
+ - 如果检索到的知识**高于**题目所需的基础知识,知识库假设这些基础已经掌握
+ - 例如:题目使用向量点积,检索到多元微积分内容 → **可接受**(微积分课程假设学生了解向量)
+ - 例如:题目测试拉格朗日乘数法,检索到拉格朗日乘数法 → **可接受**(即使没有偏导数的基本定义)
+
+ 3. 答案能否从检索知识推导?(考虑基础知识可能不在知识库中)
+ 4. 选择题是否只有一个正确答案?
+ 5. 题目表述是否清晰?
+ 6. 解释是否充分?
+ 7. 如果涉及计算,结果是否正确?
+
+ **验证原则**:
+ - ✅ 对基础知识宽容:如果题目使用基础知识但检索到更高级的相关内容,应该接受
+ - ✅ 关注核心知识点:只要题目的核心知识点在检索结果中有所体现,知识就是充分的
+ - ✅ 拓展知识库内容的题目是有价值的:它们鼓励更广泛的学习
+ - ❌ 仍需基于检索结果验证:不能使用你自己的知识,但可以合理推断基础已被掌握
+ - ❌ 只在完全不相关时要求重新生成:只有当检索结果与题目核心内容**完全无关**时才要求重新生成
+
+ **判断示例**:
+ - ✅ 接受:题目使用向量运算 + 检索到线性代数高级内容
+ - ✅ 接受:题目使用基本微分 + 检索到多元微积分内容
+ - ✅ 接受:题目使用三角函数 + 检索到复分析内容
+ - ⚠️ 请求修改(非重新生成):题目部分相关但需要调整
+ - ❌ 请求重新生成:题目测试拉格朗日乘数法 + 检索到概率论内容(完全不相关)
+
+innovation_section: |
+ **仿题特别检查**:
+ - **创新检查**:比较生成的题目与参考题目
+ - ⚠️ **创新不足** - 如果仅改变数字/符号而场景、措辞、结构和解题过程保持不变,或者生成者仅对相同陈述添加解释,你必须返回request_modification或request_regeneration。
+ - 创新不足的示例:
+ * 只改变坐标从(1,2,3)到(4,5,6),其他完全相同
+ * 只改变参数从k到m,计算过程完全相同
+ * 只交换数值,题目结构完全相同
+ - ⚠️ 仅添加解释或额外文字而不改变场景/要求不算创新。
+ - ✅ **充分创新**应包括:
+ * 改变几何对象或数学结构
+ * 改变计算方法或解题方法
+ * 改变题目场景或背景
+ * 改变求解目标(如从夹角到投影)
+ - 如果创新不足,添加到issues:"创新不足:仅改变数据,场景和过程与参考题相同"
+
+relevance_analysis: |
+ 分析以下考试题目与知识库内容之间的相关性。
+
+ 题目:
+ {question}
+
+ 知识库内容:
+ {knowledge}
+
+ 请分析并以JSON格式输出:
+ {{
+ "relevance": "high" 或 "partial",
+ "kb_coverage": "具体描述这道题目考查了知识库中的哪些概念、理论或方法。",
+ "extension_points": "如果相关性为'partial',描述哪些方面延展了知识库的内容。如果为'high'则留空。"
+ }}
+
+ 判断标准:
+ - "high":题目可以完全使用知识库内容来回答
+ - "partial":题目与知识库相关,但需要一些知识库之外的知识
diff --git a/src/agents/question/tools/__init__.py b/src/agents/question/tools/__init__.py
new file mode 100644
index 000000000..b99092590
--- /dev/null
+++ b/src/agents/question/tools/__init__.py
@@ -0,0 +1,13 @@
+"""
+Question Tools - Question generation system toolset
+"""
+
+from .exam_mimic import mimic_exam_questions
+from .pdf_parser import parse_pdf_with_mineru
+from .question_extractor import extract_questions_from_paper
+
+__all__ = [
+ "parse_pdf_with_mineru",
+ "extract_questions_from_paper",
+ "mimic_exam_questions",
+]
diff --git a/src/agents/question/tools/exam_mimic.py b/src/agents/question/tools/exam_mimic.py
new file mode 100644
index 000000000..90c6b15af
--- /dev/null
+++ b/src/agents/question/tools/exam_mimic.py
@@ -0,0 +1,598 @@
+#!/usr/bin/env python
+"""
+Reference-based exam-question generation system
+
+Workflow:
+1. Parse the PDF exam (MinerU)
+2. Extract question information (LLM)
+3. Generate new questions per reference question (Agent)
+"""
+
+from __future__ import annotations
+
+import asyncio
+from datetime import datetime
+import json
+from pathlib import Path
+import sys
+from typing import TYPE_CHECKING, Any, Callable
+
+if TYPE_CHECKING:
+ from src.agents.question import AgentCoordinator
+
+# Add project root to sys.path
+project_root = Path(__file__).parent.parent.parent.parent.parent
+sys.path.insert(0, str(project_root))
+
+# Note: AgentCoordinator is imported inside functions to avoid circular import
+from src.agents.question.tools.pdf_parser import parse_pdf_with_mineru
+from src.agents.question.tools.question_extractor import extract_questions_from_paper
+
+# Type alias for WebSocket callback
+WsCallback = Callable[[str, dict[str, Any]], Any]
+
+
+async def generate_question_from_reference(
+ reference_question: dict[str, Any], coordinator: AgentCoordinator, kb_name: str
+) -> dict[str, Any]:
+ """
+ Generate a new question based on a reference entry.
+ """
+ # Build generation requirement that encodes the reference
+ requirement = {
+ "reference_question": reference_question["question_text"],
+ "has_images": len(reference_question.get("images", [])) > 0,
+ "kb_name": kb_name,
+ "allow_reject": False,
+ "additional_requirements": (
+ f"Reference question:\n{reference_question['question_text']}\n\n"
+ "Requirements:\n"
+ "1. Keep a similar difficulty level.\n"
+ "2. **Identify the core knowledge concept(s) of the reference and keep them EXACTLY the same. Do not introduce new advanced topics beyond what the reference question requires.**\n"
+ "3. **Change the scenario/objects/geometry; do not simply replace numbers or symbols.**\n"
+ "4. **Alter at least one part of the reasoning process or add a new sub-question "
+ "(e.g., extra calculation, analysis, or proof).**\n"
+ "5. Keep the problem entirely within the same mathematical scope as the reference (e.g., if the reference is planar line parametrization, you must stay within planar line parametrization and cannot escalate to surfaces or directional derivatives).\n"
+ "6. Ensure the prompt is rigorous, precise, and self-contained.\n"
+ "7. If the original problem references images, describe them in text.\n"
+ "8. Rejection is forbidden—you must complete the generation task.\n\n"
+ "Chain-of-thought guidance:\n"
+ "- Think step-by-step to plan the new scenario and reasoning before producing the final JSON.\n"
+ "- Do not reveal your reasoning; output only the final JSON."
+ ),
+ }
+
+ # Trigger generation through the coordinator
+ result = await coordinator.generate_question(requirement)
+
+ return result
+
+
+async def mimic_exam_questions(
+ pdf_path: str | None = None,
+ paper_dir: str | None = None,
+ kb_name: str = None,
+ output_dir: str | None = None,
+ max_questions: int | None = None,
+ ws_callback: WsCallback | None = None,
+) -> dict[str, Any]:
+ """
+ End-to-end orchestration for reference-based question generation.
+
+ Args:
+ pdf_path: Path to the PDF exam paper
+ paper_dir: Path to a pre-parsed exam directory
+ kb_name: Knowledge base name to use
+ output_dir: Output directory for generated questions
+ max_questions: Maximum number of questions to process
+ ws_callback: Optional async callback for WebSocket progress updates
+ Signature: async def callback(event_type: str, data: dict)
+ """
+
+ async def send_progress(event_type: str, data: dict[str, Any]):
+ """Helper to send progress updates via WebSocket callback."""
+ if ws_callback:
+ try:
+ await ws_callback(event_type, data)
+ except Exception as e:
+ print(f"WebSocket callback error: {e}")
+
+ print("=" * 80)
+ print("📚 Reference-based question generation system")
+ print("=" * 80)
+ print()
+
+ # Validate arguments
+ if not pdf_path and not paper_dir:
+ await send_progress("error", {"content": "Either pdf_path or paper_dir must be provided."})
+ return {"success": False, "error": "Either pdf_path or paper_dir must be provided."}
+
+ if pdf_path and paper_dir:
+ await send_progress("error", {"content": "pdf_path and paper_dir cannot be used together."})
+ return {
+ "success": False,
+ "error": "pdf_path and paper_dir cannot be used together. Choose only one.",
+ }
+
+ latest_dir = None
+
+ # If an already parsed exam directory is provided
+ if paper_dir:
+ await send_progress(
+ "progress",
+ {
+ "stage": "parsing",
+ "status": "locating",
+ "message": "Locating parsed exam directory...",
+ },
+ )
+
+ print("🔍 Using parsed exam directory")
+ print("-" * 80)
+
+ # Resolve relative names against reference_papers
+ paper_path = Path(paper_dir)
+
+ if not paper_path.is_absolute():
+ # Candidate locations to search (including new location)
+ project_root = Path(__file__).parent.parent.parent.parent.parent
+ possible_paths = [
+ project_root
+ / "data"
+ / "user"
+ / "question"
+ / "mimic_papers"
+ / paper_dir, # New primary location
+ Path("question_agents/reference_papers") / paper_dir, # Legacy location
+ Path("reference_papers") / paper_dir,
+ paper_path,
+ ]
+
+ latest_dir = None
+ for p in possible_paths:
+ if p.exists():
+ latest_dir = p.resolve()
+ break
+
+ if not latest_dir:
+ error_msg = f"Exam directory not found: {paper_dir}"
+ await send_progress("error", {"content": error_msg})
+ return {
+ "success": False,
+ "error": f"{error_msg}\nSearched paths: {[str(p) for p in possible_paths]}",
+ }
+ else:
+ latest_dir = paper_path.resolve()
+ if not latest_dir.exists():
+ error_msg = f"Exam directory not found: {latest_dir}"
+ await send_progress("error", {"content": error_msg})
+ return {"success": False, "error": error_msg}
+
+ # Ensure auto subdirectory exists
+ auto_dir = latest_dir / "auto"
+ if not auto_dir.exists():
+ error_msg = f"Invalid exam directory (missing auto folder): {latest_dir}"
+ await send_progress("error", {"content": error_msg})
+ return {
+ "success": False,
+ "error": error_msg,
+ }
+
+ print(f"✅ Exam directory detected: {latest_dir.name}")
+ print(f" Full path: {latest_dir}")
+ print()
+
+ await send_progress(
+ "progress",
+ {
+ "stage": "parsing",
+ "status": "complete",
+ "message": f"Using parsed exam: {latest_dir.name}",
+ },
+ )
+
+ # If a PDF is provided, parse it first
+ elif pdf_path:
+ # Stage 1: Parsing PDF
+ await send_progress(
+ "progress",
+ {"stage": "parsing", "status": "running", "message": "Parsing PDF with MinerU..."},
+ )
+
+ print("🔄 Step 1: parse the PDF exam")
+ print("-" * 80)
+
+ # Use provided output_dir or default to mimic_papers
+ project_root = Path(__file__).parent.parent.parent.parent.parent
+ if output_dir:
+ output_base = Path(output_dir)
+ else:
+ output_base = project_root / "data" / "user" / "question" / "mimic_papers"
+ output_base.mkdir(parents=True, exist_ok=True)
+
+ success = parse_pdf_with_mineru(pdf_path=pdf_path, output_base_dir=str(output_base))
+
+ if not success:
+ await send_progress("error", {"content": "Failed to parse PDF with MinerU"})
+ return {"success": False, "error": "Failed to parse PDF"}
+
+ print()
+
+ print("🔍 Step 2: locating parsed results")
+ print("-" * 80)
+
+ # Look in the new output directory (user/question/mimic_papers)
+ reference_papers_dir = output_base
+ subdirs = sorted(
+ [d for d in reference_papers_dir.iterdir() if d.is_dir()],
+ key=lambda x: x.stat().st_mtime,
+ reverse=True,
+ )
+
+ if not subdirs:
+ await send_progress("error", {"content": "No parsed outputs were found"})
+ return {"success": False, "error": "No parsed outputs were found"}
+
+ latest_dir = subdirs[0]
+ print(f"✅ Parsed folder: {latest_dir.name}")
+ print()
+
+ await send_progress(
+ "progress",
+ {
+ "stage": "parsing",
+ "status": "complete",
+ "message": f"PDF parsed successfully: {latest_dir.name}",
+ },
+ )
+
+ # Stage 2: Extract questions
+ await send_progress(
+ "progress",
+ {
+ "stage": "extracting",
+ "status": "running",
+ "message": "Extracting reference questions from exam...",
+ },
+ )
+
+ print("🔄 Step 3: extract reference questions")
+ print("-" * 80)
+
+ json_files = list(latest_dir.glob("*_questions.json"))
+
+ if json_files:
+ print(f"✅ Found existing question file: {json_files[0].name}")
+ with open(json_files[0], encoding="utf-8") as f:
+ questions_data = json.load(f)
+ else:
+ print("📄 No question file found, starting extraction...")
+ success = extract_questions_from_paper(paper_dir=str(latest_dir), output_dir=None)
+
+ if not success:
+ await send_progress("error", {"content": "Question extraction failed"})
+ return {"success": False, "error": "Question extraction failed"}
+
+ json_files = list(latest_dir.glob("*_questions.json"))
+ if not json_files:
+ await send_progress(
+ "error", {"content": "Question JSON file not found after extraction"}
+ )
+ return {"success": False, "error": "Question JSON file not found after extraction"}
+
+ with open(json_files[0], encoding="utf-8") as f:
+ questions_data = json.load(f)
+
+ reference_questions = questions_data.get("questions", [])
+
+ if max_questions:
+ reference_questions = reference_questions[:max_questions]
+
+ print(f"✅ Loaded {len(reference_questions)} reference questions")
+ print()
+
+ # Send reference questions info
+ await send_progress(
+ "progress",
+ {
+ "stage": "extracting",
+ "status": "complete",
+ "message": f"Extracted {len(reference_questions)} reference questions",
+ "total_questions": len(reference_questions),
+ "reference_questions": [
+ {
+ "number": q.get("question_number", str(i + 1)),
+ "preview": q["question_text"][:100] + "..."
+ if len(q["question_text"]) > 100
+ else q["question_text"],
+ }
+ for i, q in enumerate(reference_questions)
+ ],
+ },
+ )
+
+ # Stage 3: Generate mimic questions
+ await send_progress(
+ "progress",
+ {
+ "stage": "generating",
+ "status": "running",
+ "message": "Generating mimic questions...",
+ "current": 0,
+ "total": len(reference_questions),
+ },
+ )
+
+ print("🔄 Step 4: generate new questions from references (parallel)")
+ print("-" * 80)
+
+ # Lazy import to avoid circular import
+ from src.agents.question import AgentCoordinator
+ from src.core.core import load_config_with_main
+
+ # Load config for parallel settings
+ config = load_config_with_main("question_config.yaml", project_root)
+ question_cfg = config.get("question", {})
+ max_parallel = question_cfg.get("max_parallel_questions", 3)
+
+ print(f"📊 Processing {len(reference_questions)} questions with max {max_parallel} parallel")
+
+ # Create semaphore for parallel control
+ semaphore = asyncio.Semaphore(max_parallel)
+
+ # Track completed count
+ completed_count = 0
+ completed_lock = asyncio.Lock()
+
+ async def generate_single_mimic(ref_question: dict, index: int) -> dict:
+ """Generate a single mimic question with semaphore control."""
+ nonlocal completed_count
+
+ async with semaphore:
+ question_id = f"mimic_{index}"
+ ref_number = ref_question.get("question_number", str(index))
+
+ # Send question start update
+ await send_progress(
+ "question_update",
+ {
+ "question_id": question_id,
+ "index": index,
+ "status": "generating",
+ "reference_number": ref_number,
+ "reference_preview": ref_question["question_text"][:80] + "...",
+ },
+ )
+
+ print(f"\n📝 [{question_id}] Starting - Reference: {ref_number}")
+ print(f" Preview: {ref_question['question_text'][:80]}...")
+
+ # Create a fresh coordinator for each question
+ coordinator = AgentCoordinator(max_rounds=10, kb_name=kb_name)
+
+ try:
+ result = await generate_question_from_reference(
+ reference_question=ref_question, coordinator=coordinator, kb_name=kb_name
+ )
+
+ async with completed_lock:
+ completed_count += 1
+ current_completed = completed_count
+
+ if result.get("success"):
+ print(f"✅ [{question_id}] Generated in {result['rounds']} round(s)")
+
+ result_data = {
+ "success": True,
+ "reference_question_number": ref_number,
+ "reference_question_text": ref_question["question_text"],
+ "reference_images": ref_question.get("images", []),
+ "generated_question": result["question"],
+ "validation": result["validation"],
+ "rounds": result["rounds"],
+ }
+
+ # Send result update
+ await send_progress(
+ "result",
+ {
+ "question_id": question_id,
+ "index": index,
+ "success": True,
+ "question": result["question"],
+ "validation": result["validation"],
+ "rounds": result["rounds"],
+ "reference_question": ref_question["question_text"],
+ "current": current_completed,
+ "total": len(reference_questions),
+ },
+ )
+
+ return result_data
+ else:
+ print(f"❌ [{question_id}] Failed: {result.get('error', 'Unknown error')}")
+
+ error_data = {
+ "success": False,
+ "reference_question_number": ref_number,
+ "reference_question_text": ref_question["question_text"],
+ "error": result.get("error", "Unknown error"),
+ "reason": result.get("reason", ""),
+ }
+
+ await send_progress(
+ "question_update",
+ {
+ "question_id": question_id,
+ "index": index,
+ "status": "failed",
+ "error": result.get("error", "Unknown error"),
+ "current": current_completed,
+ "total": len(reference_questions),
+ },
+ )
+
+ return error_data
+
+ except Exception as e:
+ print(f"❌ [{question_id}] Exception: {e!s}")
+
+ async with completed_lock:
+ completed_count += 1
+ current_completed = completed_count
+
+ await send_progress(
+ "question_update",
+ {
+ "question_id": question_id,
+ "index": index,
+ "status": "failed",
+ "error": str(e),
+ "current": current_completed,
+ "total": len(reference_questions),
+ },
+ )
+
+ return {
+ "success": False,
+ "reference_question_number": ref_question.get("question_number", str(index)),
+ "reference_question_text": ref_question["question_text"],
+ "error": f"Exception: {e!s}",
+ }
+
+ # Run all mimic generations in parallel
+ tasks = [generate_single_mimic(ref_q, i) for i, ref_q in enumerate(reference_questions, 1)]
+ results = await asyncio.gather(*tasks, return_exceptions=True)
+
+ # Separate successes and failures
+ generated_questions = []
+ failed_questions = []
+
+ for result in results:
+ if isinstance(result, Exception):
+ failed_questions.append({"error": str(result)})
+ elif result.get("success"):
+ generated_questions.append(result)
+ else:
+ failed_questions.append(result)
+
+ print()
+ print("=" * 80)
+ print("📊 Generation summary")
+ print("=" * 80)
+ print(f"Reference questions: {len(reference_questions)}")
+ print(f"Successes: {len(generated_questions)}")
+ print(f"Failures: {len(failed_questions)}")
+
+ if output_dir is None:
+ output_dir = latest_dir
+ else:
+ output_dir = Path(output_dir)
+ output_dir.mkdir(parents=True, exist_ok=True)
+
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
+ output_file = output_dir / f"{latest_dir.name}_{timestamp}_generated_questions.json"
+
+ output_data = {
+ "reference_paper": latest_dir.name,
+ "kb_name": kb_name,
+ "total_reference_questions": len(reference_questions),
+ "successful_generations": len(generated_questions),
+ "failed_generations": len(failed_questions),
+ "generated_questions": generated_questions,
+ "failed_questions": failed_questions,
+ }
+
+ with open(output_file, "w", encoding="utf-8") as f:
+ json.dump(output_data, f, ensure_ascii=False, indent=2)
+
+ print(f"\n💾 Results saved to: {output_file}")
+ print()
+
+ # Send summary
+ await send_progress(
+ "summary",
+ {
+ "total_reference": len(reference_questions),
+ "successful": len(generated_questions),
+ "failed": len(failed_questions),
+ "output_file": str(output_file),
+ },
+ )
+
+ return {
+ "success": True,
+ "output_file": str(output_file),
+ "total_reference_questions": len(reference_questions),
+ "generated_questions": generated_questions,
+ "failed_questions": failed_questions,
+ }
+
+
+async def main():
+ """Command-line entry point."""
+ import argparse
+
+ parser = argparse.ArgumentParser(
+ description="Reference-based question generation CLI",
+ formatter_class=argparse.RawDescriptionHelpFormatter,
+ epilog="""
+Examples:
+ python exam_mimic.py --pdf /path/to/exam.pdf --kb math2211
+ python exam_mimic.py --paper 2211asm1 --kb math2211
+ python exam_mimic.py --paper reference_papers/2211asm1 --kb math2211
+ python exam_mimic.py --paper 2211asm1 --kb math2211 --max-questions 3
+ python exam_mimic.py --paper 2211asm1 --kb math2211 -o ./output
+ """,
+ )
+
+ # Input mode (mutually exclusive)
+ input_group = parser.add_mutually_exclusive_group(required=True)
+ input_group.add_argument(
+ "--pdf", type=str, help="Absolute path to the PDF exam (will be parsed)"
+ )
+
+ input_group.add_argument(
+ "--paper",
+ type=str,
+ help="Name of a parsed exam directory (e.g., 2211asm1) or its absolute path",
+ )
+
+ parser.add_argument("--kb", type=str, required=True, help="Knowledge base name")
+
+ parser.add_argument(
+ "-o",
+ "--output",
+ type=str,
+ default=None,
+ help="Output directory (defaults to the exam folder)",
+ )
+
+ parser.add_argument(
+ "--max-questions",
+ type=int,
+ default=None,
+ help="Maximum number of reference questions to process (testing)",
+ )
+
+ args = parser.parse_args()
+
+ # Execute the workflow
+ result = await mimic_exam_questions(
+ pdf_path=args.pdf,
+ paper_dir=args.paper,
+ kb_name=args.kb,
+ output_dir=args.output,
+ max_questions=args.max_questions,
+ )
+
+ if result["success"]:
+ print("✅ Completed!")
+ sys.exit(0)
+ else:
+ print(f"❌ Failed: {result.get('error')}")
+ sys.exit(1)
+
+
+if __name__ == "__main__":
+ asyncio.run(main())
diff --git a/src/agents/question/tools/pdf_parser.py b/src/agents/question/tools/pdf_parser.py
new file mode 100644
index 000000000..17d56aecb
--- /dev/null
+++ b/src/agents/question/tools/pdf_parser.py
@@ -0,0 +1,198 @@
+#!/usr/bin/env python
+"""
+Parse PDF files using MinerU and save results to reference_papers directory
+"""
+
+import argparse
+from datetime import datetime
+from pathlib import Path
+import shutil
+import subprocess
+import sys
+
+
+def check_mineru_installed():
+ """Check if MinerU is installed"""
+ try:
+ result = subprocess.run(
+ ["magic-pdf", "--version"], check=False, capture_output=True, text=True
+ )
+ if result.returncode == 0:
+ return "magic-pdf"
+ except FileNotFoundError:
+ pass
+
+ try:
+ result = subprocess.run(
+ ["mineru", "--version"], check=False, capture_output=True, text=True
+ )
+ if result.returncode == 0:
+ return "mineru"
+ except FileNotFoundError:
+ pass
+
+ return None
+
+
+def parse_pdf_with_mineru(pdf_path: str, output_base_dir: str = None):
+ """
+ Parse PDF file using MinerU
+
+ Args:
+ pdf_path: Path to PDF file
+ output_base_dir: Base path for output directory, defaults to reference_papers
+
+ Returns:
+ bool: Whether parsing was successful
+ """
+ mineru_cmd = check_mineru_installed()
+ if not mineru_cmd:
+ print("❌ Error: MinerU installation not detected")
+ print("Please install MinerU first:")
+ print(" pip install magic-pdf[full]")
+ print("or")
+ print(" pip install mineru")
+ print("or visit: https://github.com/opendatalab/MinerU")
+ return False
+
+ print(f"✅ Detected MinerU command: {mineru_cmd}")
+
+ pdf_path = Path(pdf_path).resolve()
+ if not pdf_path.exists():
+ print(f"❌ Error: PDF file does not exist: {pdf_path}")
+ return False
+
+ if not pdf_path.suffix.lower() == ".pdf":
+ print(f"❌ Error: File is not PDF format: {pdf_path}")
+ return False
+
+ script_dir = Path(__file__).parent.parent.parent.parent.parent
+ if output_base_dir is None:
+ output_base_dir = script_dir / "reference_papers"
+ else:
+ output_base_dir = Path(output_base_dir)
+
+ output_base_dir.mkdir(parents=True, exist_ok=True)
+
+ pdf_name = pdf_path.stem
+ output_dir = output_base_dir / pdf_name
+
+ if 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"📄 PDF file: {pdf_path}")
+ print(f"📁 Output directory: {output_dir}")
+ print("⏳ Starting parsing...")
+
+ try:
+ temp_output = output_base_dir / "temp_mineru_output"
+ temp_output.mkdir(parents=True, exist_ok=True)
+
+ cmd = [mineru_cmd, "-p", str(pdf_path), "-o", str(temp_output)]
+
+ print(f"🔧 Executing command: {' '.join(cmd)}")
+
+ result = subprocess.run(cmd, capture_output=True, text=True, check=False)
+
+ if result.returncode != 0:
+ print("❌ MinerU parsing failed:")
+ print(f"Stdout: {result.stdout}")
+ print(f"Stderr: {result.stderr}")
+ if temp_output.exists():
+ shutil.rmtree(temp_output)
+ return False
+
+ print("✅ MinerU parsing completed!")
+
+ generated_folders = list(temp_output.iterdir())
+
+ if not generated_folders:
+ print("⚠️ Warning: No generated files found in temp directory")
+ if temp_output.exists():
+ shutil.rmtree(temp_output)
+ return False
+
+ source_folder = generated_folders[0] if generated_folders[0].is_dir() else temp_output
+
+ # Create target directory and move content
+ output_dir.mkdir(parents=True, exist_ok=True)
+
+ # Move MinerU-generated content to target directory
+ if source_folder.exists() and source_folder.is_dir():
+ # If source_folder is the PDF-named directory, move its contents
+ for item in source_folder.iterdir():
+ dest_item = output_dir / item.name
+ if dest_item.exists():
+ if dest_item.is_dir():
+ shutil.rmtree(dest_item)
+ else:
+ dest_item.unlink()
+ shutil.move(str(item), str(dest_item))
+ print(f"📦 Files saved to: {output_dir}")
+ else:
+ if output_dir.exists():
+ shutil.rmtree(output_dir)
+ shutil.move(str(source_folder), str(output_dir))
+ print(f"📦 Files saved to: {output_dir}")
+
+ if temp_output.exists():
+ shutil.rmtree(temp_output)
+
+ print("\n📋 Generated files:")
+ for item in output_dir.rglob("*"):
+ if item.is_file():
+ rel_path = item.relative_to(output_dir)
+ print(f" - {rel_path}")
+
+ return True
+
+ except Exception as e:
+ print(f"❌ Error occurred during parsing: {e!s}")
+ import traceback
+
+ traceback.print_exc()
+ return False
+
+
+def main():
+ """Main function"""
+ parser = argparse.ArgumentParser(
+ description="Parse PDF files using MinerU and save results to reference_papers directory",
+ formatter_class=argparse.RawDescriptionHelpFormatter,
+ epilog="""
+Examples:
+ # Parse a single PDF file
+ python pdf_parser.py /path/to/paper.pdf
+
+ # Parse PDF and specify output directory
+ python pdf_parser.py /path/to/paper.pdf -o /custom/output/dir
+ """,
+ )
+
+ parser.add_argument("pdf_path", type=str, help="Path to PDF file")
+
+ parser.add_argument(
+ "-o",
+ "--output",
+ type=str,
+ default=None,
+ help="Base path for output directory (default: reference_papers)",
+ )
+
+ args = parser.parse_args()
+
+ success = parse_pdf_with_mineru(args.pdf_path, args.output)
+
+ if success:
+ print("\n✅ Parsing completed!")
+ sys.exit(0)
+ else:
+ print("\n❌ Parsing failed!")
+ sys.exit(1)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/src/agents/question/tools/question_extractor.py b/src/agents/question/tools/question_extractor.py
new file mode 100644
index 000000000..df1304495
--- /dev/null
+++ b/src/agents/question/tools/question_extractor.py
@@ -0,0 +1,321 @@
+#!/usr/bin/env python
+"""
+Extract question information from MinerU-parsed exam papers
+
+This script reads MinerU-parsed markdown files and content_list.json,
+uses LLM to analyze and extract all questions, including question content and related images.
+"""
+
+import argparse
+from datetime import datetime
+import json
+from pathlib import Path
+import sys
+from typing import Any
+
+project_root = Path(__file__).parent.parent.parent.parent.parent
+sys.path.insert(0, str(project_root))
+
+from openai import OpenAI
+
+from src.core.core import get_agent_params, get_llm_config
+
+
+def load_parsed_paper(paper_dir: Path) -> tuple[str | None, list[dict] | None, Path]:
+ """
+ Load MinerU-parsed exam paper files
+
+ Args:
+ paper_dir: MinerU output directory (e.g., reference_papers/paper_name_20241129/)
+
+ Returns:
+ (markdown_content, content_list, images_dir)
+ """
+ auto_dir = paper_dir / "auto"
+ if not auto_dir.exists():
+ auto_dir = paper_dir
+
+ md_files = list(auto_dir.glob("*.md"))
+ if not md_files:
+ print(f"❌ Error: No markdown file found in {auto_dir}")
+ return None, None, auto_dir / "images"
+
+ md_file = md_files[0]
+ print(f"📄 Found markdown file: {md_file.name}")
+
+ with open(md_file, encoding="utf-8") as f:
+ markdown_content = f.read()
+
+ json_files = list(auto_dir.glob("*_content_list.json"))
+ content_list = None
+ if json_files:
+ json_file = json_files[0]
+ print(f"📋 Found content_list file: {json_file.name}")
+ with open(json_file, encoding="utf-8") as f:
+ content_list = json.load(f)
+ else:
+ print("⚠️ Warning: content_list.json file not found, will use markdown content only")
+
+ images_dir = auto_dir / "images"
+ if images_dir.exists():
+ image_count = len(list(images_dir.glob("*")))
+ print(f"🖼️ Found image directory: {image_count} images")
+ else:
+ print("⚠️ Warning: images directory not found")
+
+ return markdown_content, content_list, images_dir
+
+
+def extract_questions_with_llm(
+ markdown_content: str,
+ content_list: list[dict] | None,
+ images_dir: Path,
+ api_key: str,
+ base_url: str,
+ model: str,
+) -> list[dict[str, Any]]:
+ """
+ Use LLM to analyze markdown content and extract questions
+
+ Args:
+ markdown_content: Document content in Markdown format
+ content_list: MinerU-generated content_list (optional)
+ images_dir: Image directory path
+ api_key: OpenAI API key
+ base_url: API endpoint URL
+ model: Model name
+
+ Returns:
+ Question list, each question contains:
+ {
+ "question_number": Question number,
+ "question_text": Question text content (multiple choice includes options),
+ "images": [List of relative paths to related images]
+ }
+ """
+ client = OpenAI(api_key=api_key, base_url=base_url)
+
+ image_list = []
+ if images_dir.exists():
+ for img_file in sorted(images_dir.glob("*")):
+ if img_file.suffix.lower() in [".jpg", ".jpeg", ".png", ".gif", ".webp"]:
+ image_list.append(img_file.name)
+
+ system_prompt = """You are a professional exam paper analysis assistant. Your task is to extract all question information from the provided exam paper content.
+
+Please carefully analyze the exam paper content and extract the following information for each question:
+1. Question number (e.g., "1.", "Question 1", etc.)
+2. Complete question text content (if multiple choice, include all options)
+3. Related image file names (if the question references images)
+
+For multiple choice questions, please merge the stem and all options into one complete question text, for example:
+"1. Which of the following descriptions about neural networks is correct? ()\nA. Option A content\nB. Option B content\nC. Option C content\nD. Option D content"
+
+Please return results in JSON format as follows:
+```json
+{
+ "questions": [
+ {
+ "question_number": "1",
+ "question_text": "Complete question content (including options)...",
+ "images": ["image_001.jpg", "image_002.jpg"]
+ },
+ {
+ "question_number": "2",
+ "question_text": "Complete content of another question...",
+ "images": []
+ }
+ ]
+}
+```
+
+Important Notes:
+1. Ensure all questions are extracted, do not miss any
+2. Keep the original question text, do not modify or summarize
+3. For multiple choice questions, must merge stem and options in question_text
+4. If a question has no associated images, set images field to empty array []
+5. Image file names should be actual existing file names
+6. Ensure the returned format is valid JSON
+"""
+
+ user_prompt = f"""Exam paper content (Markdown format):
+
+{markdown_content[:15000]}
+
+Available image files:
+{json.dumps(image_list, ensure_ascii=False, indent=2)}
+
+Please analyze the above exam paper content, extract all question information, and return in JSON format.
+"""
+
+ print("\n🤖 Using LLM to analyze questions...")
+ print(f"📊 Model: {model}")
+ print(f"📝 Document length: {len(markdown_content)} characters")
+ print(f"🖼️ Available images: {len(image_list)}")
+
+ # Get agent parameters from unified config
+ agent_params = get_agent_params("question")
+
+ try:
+ response = client.chat.completions.create(
+ model=model,
+ messages=[
+ {"role": "system", "content": system_prompt},
+ {"role": "user", "content": user_prompt},
+ ],
+ temperature=agent_params["temperature"],
+ max_tokens=agent_params["max_tokens"],
+ response_format={"type": "json_object"},
+ )
+
+ result_text = response.choices[0].message.content
+ result = json.loads(result_text)
+
+ questions = result.get("questions", [])
+ print(f"✅ Successfully extracted {len(questions)} questions")
+
+ return questions
+
+ except json.JSONDecodeError as e:
+ print(f"❌ JSON parsing error: {e!s}")
+ print(f"LLM response content: {result_text[:500]}...")
+ return []
+ except Exception as e:
+ print(f"❌ LLM call failed: {e!s}")
+ import traceback
+
+ traceback.print_exc()
+ return []
+
+
+def save_questions_json(questions: list[dict[str, Any]], output_dir: Path, paper_name: str) -> Path:
+ """
+ Save question information as JSON file
+
+ Args:
+ questions: Question list
+ output_dir: Output directory
+ paper_name: Paper name
+
+ Returns:
+ Saved file path
+ """
+ output_dir.mkdir(parents=True, exist_ok=True)
+
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
+
+ output_data = {
+ "paper_name": paper_name,
+ "extraction_time": datetime.now().isoformat(),
+ "total_questions": len(questions),
+ "questions": questions,
+ }
+
+ output_file = output_dir / f"{paper_name}_{timestamp}_questions.json"
+ with open(output_file, "w", encoding="utf-8") as f:
+ json.dump(output_data, f, ensure_ascii=False, indent=2)
+
+ print(f"💾 Question information saved to: {output_file.name}")
+
+ print("\n📋 Question statistics:")
+ print(f" Total questions: {len(questions)}")
+
+ questions_with_images = sum(1 for q in questions if q.get("images"))
+ print(f" Questions with images: {questions_with_images}")
+
+ return output_file
+
+
+def extract_questions_from_paper(paper_dir: str, output_dir: str | None = None) -> bool:
+ """
+ Extract questions from parsed exam paper
+
+ Args:
+ paper_dir: MinerU-parsed directory path
+ output_dir: Output directory (default: paper_dir)
+
+ Returns:
+ Whether extraction was successful
+ """
+ paper_dir = Path(paper_dir).resolve()
+ if not paper_dir.exists():
+ print(f"❌ Error: Directory does not exist: {paper_dir}")
+ return False
+
+ print(f"📁 Paper directory: {paper_dir}")
+
+ markdown_content, content_list, images_dir = load_parsed_paper(paper_dir)
+
+ if not markdown_content:
+ print("❌ Error: Unable to load paper content")
+ return False
+
+ try:
+ llm_config = get_llm_config()
+ except ValueError as e:
+ print(f"❌ {e!s}")
+ print(
+ "Tip: Please create .env file in project root and configure LLM-related environment variables"
+ )
+ return False
+
+ questions = extract_questions_with_llm(
+ markdown_content=markdown_content,
+ content_list=content_list,
+ images_dir=images_dir,
+ api_key=llm_config["api_key"],
+ base_url=llm_config["base_url"],
+ model=llm_config["model"],
+ )
+
+ if not questions:
+ print("⚠️ Warning: No questions extracted")
+ return False
+
+ if output_dir is None:
+ output_dir = paper_dir
+ else:
+ output_dir = Path(output_dir)
+
+ paper_name = paper_dir.name
+ output_file = save_questions_json(questions, output_dir, paper_name)
+
+ print("\n✅ Question extraction completed!")
+ print(f"📄 View results: {output_file}")
+
+ return True
+
+
+def main():
+ """Main function"""
+ parser = argparse.ArgumentParser(
+ description="Extract question information from MinerU-parsed exam papers",
+ formatter_class=argparse.RawDescriptionHelpFormatter,
+ epilog="""
+Examples:
+ # Extract questions from parsed exam paper directory
+ python question_extractor.py reference_papers/exam_20241129_143052
+
+ # Specify output directory
+ python question_extractor.py reference_papers/exam_20241129_143052 -o ./output
+ """,
+ )
+
+ parser.add_argument("paper_dir", type=str, help="MinerU-parsed exam paper directory path")
+
+ parser.add_argument(
+ "-o", "--output", type=str, default=None, help="Output directory (default: paper directory)"
+ )
+
+ args = parser.parse_args()
+
+ success = extract_questions_from_paper(args.paper_dir, args.output)
+
+ if success:
+ sys.exit(0)
+ else:
+ sys.exit(1)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/src/agents/question/validation_workflow.py b/src/agents/question/validation_workflow.py
new file mode 100644
index 000000000..1438f23b4
--- /dev/null
+++ b/src/agents/question/validation_workflow.py
@@ -0,0 +1,594 @@
+#!/usr/bin/env python
+"""
+Question Validation Workflow: retrieve → validate → return
+"""
+
+from collections.abc import Callable
+import json
+import os
+from pathlib import Path
+import sys
+from typing import Any
+
+from openai import AsyncOpenAI
+import yaml
+
+# Add project root to path
+project_root = Path(__file__).parent.parent.parent.parent
+sys.path.insert(0, str(project_root))
+
+from src.core.core import get_agent_params, load_config_with_main
+from src.core.logging import get_logger
+from src.tools.rag_tool import rag_search
+
+# Module logger
+logger = get_logger("QuestionValidation")
+
+
+def _load_prompts(language: str = "en") -> dict:
+ """Load prompts from YAML file based on language"""
+ prompts_dir = Path(__file__).parent / "prompts" / language
+ prompt_file = prompts_dir / "validation_workflow.yaml"
+ if prompt_file.exists():
+ with open(prompt_file, encoding="utf-8") as f:
+ return yaml.safe_load(f)
+ # Fallback to English if language file not found
+ fallback_file = Path(__file__).parent / "prompts" / "en" / "validation_workflow.yaml"
+ if fallback_file.exists():
+ with open(fallback_file, encoding="utf-8") as f:
+ return yaml.safe_load(f)
+ return {}
+
+
+class QuestionValidationWorkflow:
+ """Question validation workflow - fixed pipeline"""
+
+ def __init__(
+ self,
+ api_key: str | None = None,
+ base_url: str | None = None,
+ model: str | None = None,
+ kb_name: str | None = None,
+ token_stats_callback: Callable | None = None,
+ language: str = "en",
+ ):
+ """
+ Initialize validation workflow.
+
+ Args:
+ api_key: API key
+ base_url: API endpoint
+ model: Model name
+ kb_name: Knowledge base name
+ token_stats_callback: Callback function to update token statistics
+ language: Language for prompts ("en" or "zh")
+ """
+ # API configuration
+ if not api_key:
+ api_key = os.getenv("LLM_BINDING_API_KEY")
+ if not base_url:
+ base_url = os.getenv("LLM_BINDING_HOST")
+ if model is None:
+ model = os.getenv("LLM_MODEL", "gpt-4o")
+
+ self.client = AsyncOpenAI(api_key=api_key, base_url=base_url)
+ self.api_key = api_key
+ self.base_url = base_url
+ self.model = model
+ self.kb_name = kb_name
+ self.token_stats_callback = token_stats_callback
+ self.language = language
+
+ # Load prompts
+ self._prompts = _load_prompts(language)
+
+ # Get agent parameters from unified config
+ self._agent_params = get_agent_params("question")
+
+ # Load config for RAG settings
+ self._config = load_config_with_main("question_config.yaml", project_root)
+
+ async def validate(
+ self, question: dict[str, Any], reference_question: str | None = None
+ ) -> dict[str, Any]:
+ """
+ Validate question - fixed pipeline: retrieve → validate → return
+
+ Args:
+ question: Question content
+ {
+ "question_type": str,
+ "question": str,
+ "options": Dict (for multiple choice),
+ "correct_answer": str,
+ "explanation": str,
+ "knowledge_point": str (optional)
+ }
+
+ Returns:
+ Dict: Validation result
+ {
+ "decision": "approve" | "request_modification" | "request_regeneration",
+ "issues": List[str],
+ "suggestions": List[str],
+ "reasoning": str,
+ "retrieved_knowledge": List[Dict]
+ }
+ """
+ logger.info("Starting question validation")
+
+ # Step 1: Retrieve related knowledge
+ logger.info("Step 1/2: Retrieving validation knowledge")
+ retrieved_knowledge = await self._retrieve_knowledge(question)
+ logger.debug(f"Retrieved {len(retrieved_knowledge)} knowledge items")
+
+ # Step 2: Validate question
+ logger.info("Step 2/2: Validating question")
+ validation_result = await self._validate_question(
+ question, retrieved_knowledge, reference_question
+ )
+ logger.info(f"Validation decision: {validation_result['decision']}")
+
+ # Add retrieved knowledge to result
+ validation_result["retrieved_knowledge"] = retrieved_knowledge
+
+ logger.success("Validation completed")
+
+ return validation_result
+
+ async def _generate_retrieval_query(self, question: dict[str, Any]) -> str:
+ """Use LLM to generate retrieval query"""
+ knowledge_point = question.get("knowledge_point", "")
+ question_text = question.get("question", "")
+ options = question.get("options", {})
+ correct_answer = question.get("correct_answer", "")
+
+ prompt = f"""Analyze the following question and generate a concise retrieval query to retrieve relevant knowledge from the knowledge base to validate this question.
+
+Question information:
+- Knowledge point: {knowledge_point}
+- Question: {question_text}
+"""
+
+ if options:
+ prompt += f"- Options: {json.dumps(options, ensure_ascii=False)}\n"
+ if correct_answer:
+ prompt += f"- Answer: {correct_answer}\n"
+
+ prompt += """
+Please extract the **core knowledge points and concepts** involved in the question and generate a concise retrieval query (no more than 100 words).
+
+Requirements:
+1. Extract core mathematical/physical concepts, theorems, methods from the question
+2. If specific formulas or algorithms exist, extract key terminology
+3. Do not include specific numerical values and details from the question
+4. Query should be able to retrieve theoretical knowledge needed to validate the question
+
+Output the retrieval query directly, no additional content.
+"""
+
+ response = await self.client.chat.completions.create(
+ model=self.model,
+ messages=[
+ {"role": "system", "content": "You are a professional knowledge retrieval expert."},
+ {"role": "user", "content": prompt},
+ ],
+ temperature=0.3,
+ )
+
+ # Extract response content
+ response_content = response.choices[0].message.content.strip()
+
+ # Update token statistics if callback is available
+ input_tokens = 0
+ output_tokens = 0
+ cost = 0.0
+ if hasattr(response, "usage") and response.usage:
+ input_tokens = response.usage.prompt_tokens
+ output_tokens = response.usage.completion_tokens
+ cost = input_tokens * 0.00000015 + output_tokens * 0.0000006
+ if self.token_stats_callback:
+ self.token_stats_callback(
+ input_tokens=input_tokens, output_tokens=output_tokens, model=self.model
+ )
+
+ # Log LLM call with detailed information
+ logger.log_llm_call(
+ model=self.model,
+ stage="generate_query",
+ system_prompt="You are a professional knowledge retrieval expert.",
+ user_prompt=prompt,
+ response=response_content,
+ agent_name="QuestionValidationWorkflow",
+ input_tokens=input_tokens,
+ output_tokens=output_tokens,
+ cost=cost,
+ level="DEBUG",
+ )
+
+ return response_content
+
+ async def _retrieve_knowledge(self, question: dict[str, Any]) -> list[dict[str, Any]]:
+ """Retrieve knowledge needed for validation."""
+ # Use LLM to generate retrieval query
+ query = await self._generate_retrieval_query(question)
+
+ logger.debug(f"LLM generated query: {query[:100]}...")
+
+ # Get RAG mode from config
+ question_cfg = self._config.get("question", {})
+ rag_mode = question_cfg.get("rag_mode", "hybrid")
+
+ # Execute retrieval using unified RAG tool
+ try:
+ result = await rag_search(
+ query=query,
+ kb_name=self.kb_name,
+ mode=rag_mode,
+ only_need_context=True,
+ )
+
+ # Return retrieval results with raw answer
+ retrieved = []
+ if result and result.get("answer"):
+ retrieved.append(
+ {
+ "query": query,
+ "answer": result.get("answer", ""),
+ }
+ )
+
+ return retrieved
+
+ except Exception as e:
+ logger.warning(f"Retrieval failed: {e!s}")
+ return []
+
+ async def _validate_question(
+ self,
+ question: dict[str, Any],
+ retrieved_knowledge: list[dict[str, Any]],
+ reference_question: str = None,
+ ) -> dict[str, Any]:
+ """Validate question"""
+ knowledge_str = self._format_knowledge(retrieved_knowledge)
+
+ question_str = json.dumps(question, ensure_ascii=False, indent=2)
+
+ reference_section = ""
+ innovation_section = ""
+ if reference_question:
+ reference_section = f"""Reference question (for comparison):
+{reference_question}
+"""
+ innovation_section = self._prompts.get("innovation_section", "")
+
+ prompt_template = self._prompts.get("validate", "")
+ prompt = prompt_template.format(
+ question=question_str,
+ reference_section=reference_section,
+ innovation_section=innovation_section,
+ validation_knowledge=knowledge_str,
+ )
+
+ try:
+ response = await self.client.chat.completions.create(
+ model=self.model,
+ messages=[
+ {
+ "role": "system",
+ "content": "You are a professional question validation expert who strictly validates questions based on knowledge base content.",
+ },
+ {"role": "user", "content": prompt},
+ ],
+ temperature=self._agent_params["temperature"],
+ max_tokens=self._agent_params["max_tokens"],
+ response_format={"type": "json_object"},
+ )
+
+ # Extract response content
+ response_content = response.choices[0].message.content
+
+ # Update token statistics if callback is available
+ input_tokens = 0
+ output_tokens = 0
+ cost = 0.0
+ if hasattr(response, "usage") and response.usage:
+ input_tokens = response.usage.prompt_tokens
+ output_tokens = response.usage.completion_tokens
+ cost = input_tokens * 0.00000015 + output_tokens * 0.0000006
+ if self.token_stats_callback:
+ self.token_stats_callback(
+ input_tokens=input_tokens, output_tokens=output_tokens, model=self.model
+ )
+
+ # Log LLM call with detailed information
+ logger.log_llm_call(
+ model=self.model,
+ stage="validate",
+ system_prompt="You are a professional question validation expert who strictly validates questions based on knowledge base content.",
+ user_prompt=prompt,
+ response=response_content,
+ agent_name="QuestionValidationWorkflow",
+ input_tokens=input_tokens,
+ output_tokens=output_tokens,
+ cost=cost,
+ level="DEBUG",
+ )
+
+ result = json.loads(response_content)
+
+ # Ensure issues and suggestions are lists (handle case where LLM returns dict)
+ issues = result.get("issues", [])
+ if not isinstance(issues, list):
+ if isinstance(issues, dict):
+ # If issues is a dict, convert to list
+ issues = [issues]
+ else:
+ issues = []
+
+ suggestions = result.get("suggestions", [])
+ if not isinstance(suggestions, list):
+ if isinstance(suggestions, dict):
+ # If suggestions is a dict, convert to list
+ suggestions = [suggestions]
+ else:
+ suggestions = []
+
+ return {
+ "decision": result.get("decision", "request_regeneration"),
+ "issues": issues,
+ "suggestions": suggestions,
+ "reasoning": result.get("reasoning", ""),
+ }
+
+ except Exception as e:
+ logger.warning(f"Validation failed: {e!s}")
+ return {
+ "decision": "request_regeneration",
+ "issues": [f"Validation error: {e!s}"],
+ "suggestions": ["Please regenerate the question"],
+ "reasoning": "An error occurred during validation",
+ }
+
+ def _format_knowledge(self, retrieved_knowledge: list[dict[str, Any]]) -> str:
+ """Format retrieved knowledge."""
+ if not retrieved_knowledge:
+ return "No validation knowledge retrieved"
+
+ knowledge_parts = []
+ for k in retrieved_knowledge:
+ knowledge_parts.append(f"=== Query: {k['query']} ===")
+ answer = k.get("answer", "")
+ if answer:
+ # Truncate very long answers
+ if len(answer) > 3000:
+ answer = answer[:3000] + "...[truncated]"
+ knowledge_parts.append(answer)
+ knowledge_parts.append("")
+
+ return (
+ "\n".join(knowledge_parts) if knowledge_parts else "No validation knowledge retrieved"
+ )
+
+ async def analyze_extension(
+ self, question: dict[str, Any], shared_context: str
+ ) -> dict[str, Any]:
+ """
+ Analyze how a question extends beyond the knowledge base.
+
+ This is called when a question doesn't pass validation after max rounds,
+ to provide insights about how it relates to and extends from the KB.
+
+ Args:
+ question: The question that wasn't fully validated
+ shared_context: The shared knowledge context from RAG
+
+ Returns:
+ Dict with:
+ - kb_connection: How the question relates to the knowledge base
+ - extended_aspect: What knowledge areas the question extends to
+ - reasoning: Detailed explanation
+ """
+ logger.info("Analyzing question extension from knowledge base")
+
+ question_str = json.dumps(question, ensure_ascii=False, indent=2)
+
+ # Truncate context if too long
+ context_str = shared_context
+ if len(context_str) > 4000:
+ context_str = context_str[:4000] + "...[truncated]"
+
+ prompt = f"""Analyze how the following question relates to and extends from the knowledge base content.
+
+Question:
+{question_str}
+
+Knowledge Base Content:
+{context_str}
+
+Please analyze from the perspective of knowledge extension and provide a JSON response:
+{{
+ "kb_connection": "Describe how this question connects to the knowledge base content. What concepts, theories, or methods from the KB are relevant to this question?",
+ "extended_aspect": "Describe what knowledge areas this question extends to beyond the core KB content. What additional concepts, applications, or perspectives does it explore?",
+ "reasoning": "Provide a detailed explanation of the relationship between this question and the knowledge base, and why this extension is valuable for learning."
+}}
+
+Guidelines:
+1. Focus on the POSITIVE aspects - this is an "extended" question that goes beyond basic KB content
+2. kb_connection should identify the foundation concepts from the KB that the question builds upon
+3. extended_aspect should highlight what new learning opportunities this question provides
+4. Keep the analysis constructive and educational
+
+Output only the JSON, no additional text."""
+
+ try:
+ response = await self.client.chat.completions.create(
+ model=self.model,
+ messages=[
+ {
+ "role": "system",
+ "content": "You are an educational content analyst specializing in identifying knowledge connections and learning extensions.",
+ },
+ {"role": "user", "content": prompt},
+ ],
+ temperature=0.3,
+ response_format={"type": "json_object"},
+ )
+
+ response_content = response.choices[0].message.content
+
+ # Update token statistics
+ if hasattr(response, "usage") and response.usage:
+ input_tokens = response.usage.prompt_tokens
+ output_tokens = response.usage.completion_tokens
+ cost = input_tokens * 0.00000015 + output_tokens * 0.0000006
+ if self.token_stats_callback:
+ self.token_stats_callback(
+ input_tokens=input_tokens, output_tokens=output_tokens, model=self.model
+ )
+
+ result = json.loads(response_content)
+
+ logger.info("Extension analysis completed")
+
+ return {
+ "kb_connection": result.get("kb_connection", ""),
+ "extended_aspect": result.get("extended_aspect", ""),
+ "reasoning": result.get("reasoning", ""),
+ }
+
+ except Exception as e:
+ logger.warning(f"Extension analysis failed: {e!s}")
+ return {
+ "kb_connection": "Unable to analyze connection to knowledge base",
+ "extended_aspect": "This question explores areas beyond the core knowledge base content",
+ "reasoning": f"Analysis could not be completed: {e!s}",
+ }
+
+ async def analyze_relevance(
+ self,
+ question: dict[str, Any],
+ knowledge_summary: str,
+ ) -> dict[str, Any]:
+ """
+ Analyze the relevance between a question and the knowledge base content.
+
+ This is used in custom mode where we don't iterate - we just analyze
+ how the question relates to the knowledge base.
+
+ Args:
+ question: The generated question dict
+ knowledge_summary: Summary of background knowledge from RAG
+
+ Returns:
+ Dict with:
+ - relevance: "high" or "partial"
+ - kb_coverage: Description of what KB content the question tests
+ - extension_points: Description of any extensions (only if partial)
+ """
+ logger.info("Analyzing question relevance to knowledge base")
+
+ question_str = json.dumps(question, ensure_ascii=False, indent=2)
+
+ # Truncate context if too long
+ context_str = knowledge_summary
+ if len(context_str) > 4000:
+ context_str = context_str[:4000] + "...[truncated]"
+
+ prompt = f"""Analyze the relevance between the following exam question and the knowledge base content.
+
+Question:
+{question_str}
+
+Knowledge Base Content:
+{context_str}
+
+Please analyze and provide a JSON response with the following structure:
+{{
+ "relevance": "high" or "partial",
+ "kb_coverage": "Describe specifically what concepts, theories, or methods from the knowledge base this question tests. List the key knowledge points that are directly relevant.",
+ "extension_points": "If relevance is 'partial', describe what aspects of this question extend beyond the knowledge base content. What additional knowledge does it require? Leave empty if relevance is 'high'."
+}}
+
+Guidelines for determining relevance:
+1. "high" - The question can be fully answered using only the knowledge base content. All concepts, methods, and required knowledge are present in the KB.
+2. "partial" - The question is related to the KB content but requires some knowledge beyond what's provided. The KB serves as a foundation but the question extends to additional areas.
+
+For kb_coverage:
+- Be specific about which concepts from the KB are being tested
+- Reference the actual content from the KB where possible
+- Explain how the KB content relates to the question
+
+For extension_points (only when relevance is "partial"):
+- Identify what additional knowledge is needed
+- Explain how the question extends from the KB foundation
+- Keep the tone positive - extensions are valuable for learning
+
+Output only the JSON, no additional text."""
+
+ try:
+ response = await self.client.chat.completions.create(
+ model=self.model,
+ messages=[
+ {
+ "role": "system",
+ "content": "You are an educational content analyst specializing in analyzing the relationship between exam questions and knowledge base content.",
+ },
+ {"role": "user", "content": prompt},
+ ],
+ temperature=0.3,
+ response_format={"type": "json_object"},
+ )
+
+ response_content = response.choices[0].message.content
+
+ # Update token statistics
+ input_tokens = 0
+ output_tokens = 0
+ if hasattr(response, "usage") and response.usage:
+ input_tokens = response.usage.prompt_tokens
+ output_tokens = response.usage.completion_tokens
+ cost = input_tokens * 0.00000015 + output_tokens * 0.0000006
+ if self.token_stats_callback:
+ self.token_stats_callback(
+ input_tokens=input_tokens, output_tokens=output_tokens, model=self.model
+ )
+
+ # Log LLM call
+ logger.log_llm_call(
+ model=self.model,
+ stage="analyze_relevance",
+ system_prompt="Educational content analyst for relevance analysis",
+ user_prompt=prompt,
+ response=response_content,
+ agent_name="QuestionValidationWorkflow",
+ input_tokens=input_tokens,
+ output_tokens=output_tokens,
+ cost=input_tokens * 0.00000015 + output_tokens * 0.0000006,
+ level="DEBUG",
+ )
+
+ result = json.loads(response_content)
+
+ relevance = result.get("relevance", "partial")
+ if relevance not in ["high", "partial"]:
+ relevance = "partial"
+
+ logger.info(f"Relevance analysis completed: {relevance}")
+
+ return {
+ "relevance": relevance,
+ "kb_coverage": result.get("kb_coverage", ""),
+ "extension_points": result.get("extension_points", "")
+ if relevance == "partial"
+ else "",
+ }
+
+ except Exception as e:
+ logger.warning(f"Relevance analysis failed: {e!s}")
+ return {
+ "relevance": "partial",
+ "kb_coverage": "Unable to analyze knowledge base coverage",
+ "extension_points": f"Analysis could not be completed: {e!s}",
+ }
diff --git a/src/agents/research/README.md b/src/agents/research/README.md
new file mode 100644
index 000000000..76e77a4fd
--- /dev/null
+++ b/src/agents/research/README.md
@@ -0,0 +1,540 @@
+# 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
+
+### CLI Usage
+
+```bash
+# Quick mode (fast research, ~5-10 min)
+python src/agents/research/main.py --topic "Deep Learning Basics" --preset quick
+
+# Medium mode (balanced depth)
+python src/agents/research/main.py --topic "Transformer Architecture" --preset medium
+
+# Deep mode (thorough research)
+python src/agents/research/main.py --topic "Graph Neural Networks" --preset deep
+
+# Auto mode (agent decides depth)
+python src/agents/research/main.py --topic "Reinforcement Learning" --preset auto
+```
+
+### 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 |
+| `query_item` | Entity | Item ID (e.g., "Theorem 3.1") | Specific entity lookup |
+| `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/research/
+├── reports/
+│ ├── research_YYYYMMDD_HHMMSS.md # Final Markdown report
+│ └── research_*_metadata.json # Statistics and metadata
+└── cache/
+ └── 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: ModuleNotFoundError: research_pipeline**
+
+Run from project root:
+```bash
+python src/agents/research/main.py --topic "..." --preset quick
+```
+
+**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/agents/research/agents/__init__.py b/src/agents/research/agents/__init__.py
new file mode 100644
index 000000000..d045d649a
--- /dev/null
+++ b/src/agents/research/agents/__init__.py
@@ -0,0 +1,22 @@
+#!/usr/bin/env python
+"""
+DR-in-KG 2.0 Agents Module
+"""
+
+from .base_agent import BaseAgent
+from .decompose_agent import DecomposeAgent
+from .manager_agent import ManagerAgent
+from .note_agent import NoteAgent
+from .rephrase_agent import RephraseAgent
+from .reporting_agent import ReportingAgent
+from .research_agent import ResearchAgent
+
+__all__ = [
+ "BaseAgent",
+ "DecomposeAgent",
+ "ManagerAgent",
+ "NoteAgent",
+ "RephraseAgent",
+ "ReportingAgent",
+ "ResearchAgent",
+]
diff --git a/src/agents/research/agents/base_agent.py b/src/agents/research/agents/base_agent.py
new file mode 100644
index 000000000..e8cfd8c7d
--- /dev/null
+++ b/src/agents/research/agents/base_agent.py
@@ -0,0 +1,269 @@
+#!/usr/bin/env python
+"""
+BaseAgent 2.0 - Improved Agent base class
+Integrates env_config, prompt_loader, token_tracker, logger
+"""
+
+from abc import ABC, abstractmethod
+from pathlib import Path
+import sys
+import time
+from typing import Any
+
+import yaml
+
+# Add project root to path
+project_root = Path(__file__).parent.parent.parent.parent
+sys.path.insert(0, str(project_root))
+# Add research directory to path (for importing utils and other local modules)
+research_dir = Path(__file__).parent.parent.parent.parent
+sys.path.insert(0, str(research_dir))
+
+from lightrag.llm.openai import openai_complete_if_cache
+
+from src.core.core import get_agent_params, get_llm_config
+
+
+class BaseAgent(ABC):
+ """Improved Agent base class"""
+
+ _PROMPT_CACHE: dict[str, dict[str, Any]] = {}
+
+ def __init__(
+ self,
+ config: dict[str, Any],
+ api_key: str | None = None,
+ base_url: str | None = None,
+ agent_name: str = "base_agent",
+ ):
+ """
+ Initialize Agent
+
+ Args:
+ config: Complete configuration dictionary
+ api_key: API key (optional, prefers env_config)
+ base_url: API endpoint (optional, prefers env_config)
+ agent_name: Agent name
+ """
+ self.config = config
+ self.agent_name = agent_name
+
+ # Load agent parameters from unified config (agents.yaml)
+ self._agent_params = get_agent_params("research")
+
+ # Load LLM configuration from env_config
+ try:
+ env_llm = get_llm_config()
+ self.api_key = api_key or env_llm.get("api_key")
+ self.base_url = base_url or env_llm.get("base_url")
+ self.default_model = env_llm.get("model")
+ except ValueError as e:
+ print(f"⚠️ Environment configuration error: {e}")
+ self.api_key = api_key
+ self.base_url = base_url
+ self.default_model = "gpt-4o"
+
+ # Get Agent-specific configuration
+ self.agent_config = config.get("agents", {}).get(agent_name, {})
+ self.llm_config = config.get("llm", {})
+ self.enabled = self.agent_config.get("enabled", True)
+
+ # Load prompts
+ self.prompts = self._load_prompts()
+
+ def _load_prompts(self) -> dict[str, Any]:
+ """Load prompt definitions for current Agent"""
+ # Get language configuration (unified in config/main.yaml system.language)
+ from src.core.core import parse_language
+
+ language = self.config.get("system", {}).get("language", "zh")
+ lang_code = parse_language(language)
+
+ # Determine language directory: 'en' or 'zh' (unified language codes)
+ # Note: research module prompts may be in 'cn' directory, we support both 'zh' and 'cn' for backward compatibility
+ if lang_code == "en":
+ lang_dir = "en"
+ else:
+ # Try 'zh' first, fall back to 'cn' for backward compatibility
+ lang_dir = "zh"
+
+ # Get prompts directory: from agents/base_agent.py -> research/prompts/
+ prompts_dir = Path(__file__).parent.parent / "prompts"
+
+ # Build prompt file path: prompts/{lang_dir}/{agent_name}.yaml
+ prompt_file = prompts_dir / lang_dir / f"{self.agent_name}.yaml"
+
+ # Build cache key (include language info)
+ cache_key = f"{self.agent_name}_{lang_dir}"
+
+ if cache_key in BaseAgent._PROMPT_CACHE:
+ return BaseAgent._PROMPT_CACHE[cache_key]
+
+ # Try loading specified language version first, fall back to 'cn' if 'zh' doesn't exist (backward compatibility)
+ if not prompt_file.exists() and lang_dir == "zh":
+ # If 'zh' version doesn't exist, try 'cn' for backward compatibility
+ prompt_file = prompts_dir / "cn" / f"{self.agent_name}.yaml"
+ if prompt_file.exists():
+ lang_dir = "cn"
+ cache_key = f"{self.agent_name}_{lang_dir}"
+ else:
+ # If neither 'zh' nor 'cn' exists, fall back to 'en'
+ prompt_file = prompts_dir / "en" / f"{self.agent_name}.yaml"
+ lang_dir = "en"
+ cache_key = f"{self.agent_name}_{lang_dir}"
+ elif not prompt_file.exists() and lang_dir == "en":
+ # If English version doesn't exist, fall back to 'zh' or 'cn'
+ prompt_file = prompts_dir / "zh" / f"{self.agent_name}.yaml"
+ if prompt_file.exists():
+ lang_dir = "zh"
+ cache_key = f"{self.agent_name}_{lang_dir}"
+ else:
+ prompt_file = prompts_dir / "cn" / f"{self.agent_name}.yaml"
+ lang_dir = "cn"
+ cache_key = f"{self.agent_name}_{lang_dir}"
+ if cache_key in BaseAgent._PROMPT_CACHE:
+ return BaseAgent._PROMPT_CACHE[cache_key]
+
+ if not prompt_file.exists():
+ print(f"⚠️ Prompt file not found: {prompt_file}")
+ BaseAgent._PROMPT_CACHE[cache_key] = {}
+ return {}
+
+ try:
+ with open(prompt_file, encoding="utf-8") as f:
+ data = yaml.safe_load(f) or {}
+ except Exception as exc:
+ print(f"⚠️ Failed to load prompt file {prompt_file}: {exc}")
+ data = {}
+
+ BaseAgent._PROMPT_CACHE[cache_key] = data
+ return data
+
+ def get_prompt(self, section: str, field: str, fallback: str = "") -> str:
+ """
+ Get specified prompt template
+
+ Args:
+ section: Prompt section name
+ field: Field name
+ fallback: Default value
+
+ Returns:
+ Prompt template
+ """
+ template = self.prompts.get(section, {}).get(field)
+ return template if template is not None else fallback
+
+ def get_model(self) -> str:
+ """Get model name (only loaded from environment variables, ignore model in config file)"""
+ # If config accidentally contains model field, ignore it (can log one-time warning here)
+ return self.default_model
+
+ def get_temperature(self) -> float:
+ """Get temperature parameter from unified config (agents.yaml)"""
+ return self._agent_params["temperature"]
+
+ def get_max_tokens(self) -> int:
+ """Get maximum token count from unified config (agents.yaml)"""
+ return self._agent_params["max_tokens"]
+
+ async def call_llm(
+ self,
+ user_prompt: str,
+ system_prompt: str,
+ temperature: float | None = None,
+ model: str | None = None,
+ max_tokens: int | None = None,
+ verbose: bool = True,
+ stage: str | None = None,
+ ) -> str:
+ """
+ Unified interface for calling LLM
+
+ Args:
+ user_prompt: User prompt
+ system_prompt: System prompt
+ temperature: Temperature parameter
+ model: Model name
+ max_tokens: Maximum token count
+ verbose: Whether to print output
+ stage: Stage marker (for logging)
+
+ Returns:
+ LLM response
+ """
+ model = model or self.get_model()
+ temperature = temperature if temperature is not None else self.get_temperature()
+ max_tokens = max_tokens or self.get_max_tokens()
+
+ # Record call start time
+ start_time = time.time()
+
+ kwargs = {
+ "model": model,
+ "prompt": user_prompt,
+ "system_prompt": system_prompt,
+ "api_key": self.api_key,
+ "base_url": self.base_url,
+ "temperature": temperature,
+ }
+
+ if max_tokens:
+ kwargs["max_tokens"] = max_tokens
+
+ # Call LLM and record errors
+ response = None
+ error = None
+ try:
+ response = await openai_complete_if_cache(**kwargs)
+ except Exception as e:
+ error = e
+ # Log error
+ if hasattr(self, "logger") and self.logger:
+ self.logger.error(f"LLM call failed: {e}")
+ raise
+
+ # Calculate call duration
+ call_duration = time.time() - start_time
+
+ # Record token usage (optional)
+ try:
+ from ..utils.token_tracker import get_token_tracker
+
+ tracker = get_token_tracker()
+ tracker.add_usage(
+ agent_name=self.agent_name,
+ stage=stage or "default",
+ model=model,
+ system_prompt=system_prompt,
+ user_prompt=user_prompt,
+ response_text=response,
+ )
+ except Exception:
+ pass
+
+ # Log LLM call info
+ if hasattr(self, "logger") and self.logger:
+ self.logger.debug(f"LLM call completed: model={model}, duration={call_duration:.2f}s")
+
+ if verbose:
+ print(f"\n{'=' * 70}")
+ print(f"🤖 [{self.agent_name}] LLM Output:")
+ print(f"{'=' * 70}")
+ if len(response) > 2000:
+ print(response[:2000] + f"\n... (truncated, total length: {len(response)})")
+ else:
+ print(response)
+ print(f"{'=' * 70}\n")
+
+ return response
+
+ @abstractmethod
+ async def process(self, *args, **kwargs) -> Any:
+ """Main processing logic of Agent (must be implemented by subclasses)"""
+
+ def __repr__(self) -> str:
+ return f"{self.__class__.__name__}(name={self.agent_name}, enabled={self.enabled})"
+
+
+__all__ = ["BaseAgent"]
diff --git a/src/agents/research/agents/decompose_agent.py b/src/agents/research/agents/decompose_agent.py
new file mode 100644
index 000000000..cc625242e
--- /dev/null
+++ b/src/agents/research/agents/decompose_agent.py
@@ -0,0 +1,498 @@
+#!/usr/bin/env python
+"""
+DecomposeAgent - Topic decomposition Agent
+Responsible for decomposing topics into multiple subtopics and generating overviews for each subtopic
+"""
+
+from pathlib import Path
+import sys
+from typing import Any
+
+project_root = Path(__file__).parent.parent.parent.parent
+sys.path.insert(0, str(project_root))
+
+import json
+
+from src.agents.research.data_structures import ToolTrace
+from src.tools.rag_tool import rag_search
+
+from ..utils.json_utils import extract_json_from_text
+from .base_agent import BaseAgent
+
+
+class DecomposeAgent(BaseAgent):
+ """Topic decomposition Agent"""
+
+ def __init__(
+ self,
+ config: dict[str, Any],
+ api_key: str = None,
+ base_url: str = None,
+ kb_name: str = "ai_textbook",
+ ):
+ super().__init__(
+ config=config, api_key=api_key, base_url=base_url, agent_name="decompose_agent"
+ )
+ # Load KB and RAG mode from config, no hardcoding
+ rag_cfg = config.get("rag", {})
+ self.kb_name = rag_cfg.get("kb_name", kb_name or "ai_textbook")
+ self.rag_mode = rag_cfg.get("default_mode", "hybrid")
+
+ # Check if RAG is enabled (from researching config)
+ researching_cfg = config.get("researching", {})
+ self.enable_rag = researching_cfg.get("enable_rag_hybrid", True) or researching_cfg.get(
+ "enable_rag_naive", True
+ )
+
+ # Citation manager (will be set during process)
+ self.citation_manager = None
+
+ def set_citation_manager(self, citation_manager):
+ """Set citation manager"""
+ self.citation_manager = citation_manager
+
+ async def process(
+ self, topic: str, num_subtopics: int = 5, mode: str = "manual"
+ ) -> dict[str, Any]:
+ """
+ Decompose topic into subtopics and generate overview for each subtopic
+
+ Args:
+ topic: Main topic
+ num_subtopics: Expected number of subtopics in manual mode, or maximum limit in auto mode
+ mode: Mode, "manual" (manually specify count) or "auto" (auto-generate)
+
+ Returns:
+ Dictionary containing decomposition results
+ {
+ "main_topic": str,
+ "sub_topics": [
+ {
+ "title": str,
+ "overview": str
+ },
+ ...
+ ],
+ "total_subtopics": int,
+ "mode": str
+ }
+ """
+ print(f"\n{'=' * 70}")
+ print("🔀 DecomposeAgent - Topic Decomposition")
+ print(f"{'=' * 70}")
+ print(f"Main Topic: {topic}")
+ print(f"Mode: {mode}")
+ print(f"RAG Enabled: {self.enable_rag}")
+ if mode == "auto":
+ print(f"Max Subtopic Limit: {num_subtopics}\n")
+ else:
+ print(f"Expected Subtopic Count: {num_subtopics}\n")
+
+ # If RAG is disabled, use direct LLM generation without RAG context
+ if not self.enable_rag:
+ print("⚠️ RAG is disabled, generating subtopics directly from LLM...")
+ return await self._process_without_rag(topic, num_subtopics, mode)
+
+ if mode == "auto":
+ # Auto mode: autonomously generate subtopics
+ return await self._process_auto_mode(topic, num_subtopics)
+ # Manual mode: generate based on specified count
+ return await self._process_manual_mode(topic, num_subtopics)
+
+ async def _process_without_rag(
+ self, topic: str, num_subtopics: int, mode: str = "manual"
+ ) -> dict[str, Any]:
+ """
+ Process without RAG: directly generate subtopics from LLM based on topic.
+ Used when RAG is disabled by user.
+
+ Args:
+ topic: Main topic
+ num_subtopics: Number of subtopics to generate (exact for manual, max for auto)
+ mode: "manual" or "auto"
+
+ Returns:
+ Dictionary containing decomposition results
+ """
+ print("\n🎯 Generating subtopics directly (no RAG)...")
+
+ system_prompt = self.get_prompt(
+ "system",
+ "role",
+ "You are a research planning expert. Your task is to decompose complex topics into clear subtopics.",
+ )
+
+ user_prompt_template = self.get_prompt("process", "decompose_without_rag")
+ if not user_prompt_template:
+ raise ValueError(
+ "DecomposeAgent missing decompose_without_rag prompt, please configure process.decompose_without_rag in prompts/{lang}/decompose_agent.yaml"
+ )
+
+ # Build requirement based on mode
+ if mode == "auto":
+ decompose_requirement = f"""
+Quantity Requirements:
+Generate between 3 and {num_subtopics} subtopics based on the complexity of the topic.
+- For simple topics, generate fewer subtopics (3-4)
+- For complex topics, generate more subtopics (up to {num_subtopics})
+- Prioritize the most important and distinctive aspects of the topic
+"""
+ else:
+ decompose_requirement = f"""
+Quantity Requirements:
+Generate exactly {num_subtopics} subtopics. Please ensure exactly {num_subtopics} subtopics are generated, no more, no less.
+"""
+
+ user_prompt = user_prompt_template.format(
+ topic=topic, decompose_requirement=decompose_requirement
+ )
+
+ response = await self.call_llm(
+ user_prompt=user_prompt,
+ system_prompt=system_prompt,
+ stage="decompose_no_rag",
+ )
+
+ # Parse JSON output
+ from ..utils.json_utils import ensure_json_dict, ensure_keys, extract_json_from_text
+
+ data = extract_json_from_text(response)
+ try:
+ obj = ensure_json_dict(data)
+ ensure_keys(obj, ["sub_topics"])
+ subs = obj.get("sub_topics", [])
+ if not isinstance(subs, list):
+ raise ValueError("sub_topics must be an array")
+ # Clean and limit subtopics
+ cleaned = []
+ for it in subs[:num_subtopics]:
+ if isinstance(it, dict):
+ cleaned.append(
+ {"title": it.get("title", ""), "overview": it.get("overview", "")}
+ )
+ sub_topics = cleaned
+ except Exception:
+ sub_topics = []
+
+ print(f"✅ Generated {len(sub_topics)} subtopics (without RAG)")
+
+ return {
+ "main_topic": topic,
+ "sub_queries": [], # No sub-queries when RAG is disabled
+ "rag_context": "", # No RAG context
+ "sub_topics": sub_topics,
+ "total_subtopics": len(sub_topics),
+ "mode": f"{mode}_no_rag",
+ "rag_context_summary": "RAG disabled - subtopics generated directly from LLM",
+ }
+
+ async def _process_manual_mode(self, topic: str, num_subtopics: int) -> dict[str, Any]:
+ """Manual mode: generate subtopics based on specified count"""
+ # Step 1: Generate sub-queries
+ print("\n🔍 Step 1: Generating sub-queries...")
+ sub_queries = await self._generate_sub_queries(topic, num_subtopics)
+ print(f"✅ Generated {len(sub_queries)} sub-queries")
+
+ # Step 2: Execute RAG retrieval to get background knowledge
+ print("\n🔍 Step 2: Executing RAG retrieval...")
+ rag_contexts = {}
+ for i, query in enumerate(sub_queries, 1):
+ try:
+ result = await rag_search(query=query, kb_name=self.kb_name, mode=self.rag_mode)
+ rag_answer = result.get("answer", "")
+ rag_contexts[query] = rag_answer
+ print(f" ✓ Query {i}/{len(sub_queries)}: {query[:50]}...")
+
+ # Record citation (if citation manager is enabled)
+ if self.citation_manager:
+ # Get citation ID from CitationManager (unified ID generation)
+ citation_id = self.citation_manager.get_next_citation_id(stage="planning")
+ tool_type = f"rag_{self.rag_mode}" if self.rag_mode else "rag_hybrid"
+
+ # Create ToolTrace
+ import time
+
+ tool_id = f"plan_tool_{int(time.time() * 1000)}"
+ raw_answer_json = json.dumps(result, ensure_ascii=False)
+ trace = ToolTrace(
+ tool_id=tool_id,
+ citation_id=citation_id,
+ tool_type=tool_type,
+ query=query,
+ raw_answer=raw_answer_json,
+ summary=(
+ rag_answer[:500] if rag_answer else ""
+ ), # Use first 500 characters as summary
+ )
+
+ # Add to citation manager
+ self.citation_manager.add_citation(
+ citation_id=citation_id,
+ tool_type=tool_type,
+ tool_trace=trace,
+ raw_answer=raw_answer_json,
+ )
+ except Exception as e:
+ print(f" ✗ Query {i} failed: {e!s}")
+ rag_contexts[query] = ""
+
+ # Merge all RAG contexts
+ combined_rag_context = "\n\n".join(
+ [f"【{query}】\n{context}" for query, context in rag_contexts.items() if context]
+ )
+
+ # Step 3: Generate subtopics based on RAG background
+ print("\n🎯 Step 3: Generating subtopics...")
+ sub_topics = await self._generate_sub_topics(
+ topic=topic, rag_context=combined_rag_context, num_subtopics=num_subtopics
+ )
+
+ print(f"✅ Generated {len(sub_topics)} subtopics")
+
+ return {
+ "main_topic": topic,
+ "sub_queries": sub_queries,
+ "rag_context": combined_rag_context,
+ "sub_topics": sub_topics,
+ "total_subtopics": len(sub_topics),
+ "mode": "manual",
+ "rag_context_summary": f"Used RAG background from {len(rag_contexts)} queries",
+ }
+
+ async def _process_auto_mode(self, topic: str, max_subtopics: int) -> dict[str, Any]:
+ """Auto mode: autonomously generate subtopics based on topic and RAG context"""
+ # Step 1: First perform a broad RAG retrieval to get topic-related background knowledge
+ print("\n🔍 Step 1: Executing RAG retrieval to get background knowledge...")
+ try:
+ # Use topic itself as query to get related background
+ result = await rag_search(query=topic, kb_name=self.kb_name, mode=self.rag_mode)
+ rag_context = result.get("answer", "")
+ print(f" ✓ Retrieved background knowledge ({len(rag_context)} characters)")
+
+ # Record citation (if citation manager is enabled)
+ if self.citation_manager:
+ # Get citation ID from CitationManager (unified ID generation)
+ citation_id = self.citation_manager.get_next_citation_id(stage="planning")
+ tool_type = f"rag_{self.rag_mode}" if self.rag_mode else "rag_hybrid"
+
+ # Create ToolTrace
+ import time
+
+ tool_id = f"plan_tool_{int(time.time() * 1000)}"
+ raw_answer_json = json.dumps(result, ensure_ascii=False)
+ trace = ToolTrace(
+ tool_id=tool_id,
+ citation_id=citation_id,
+ tool_type=tool_type,
+ query=topic,
+ raw_answer=raw_answer_json,
+ summary=(
+ rag_context[:500] if rag_context else ""
+ ), # Use first 500 characters as summary
+ )
+
+ # Add to citation manager
+ self.citation_manager.add_citation(
+ citation_id=citation_id,
+ tool_type=tool_type,
+ tool_trace=trace,
+ raw_answer=raw_answer_json,
+ )
+ except Exception as e:
+ print(f" ✗ RAG retrieval failed: {e!s}")
+ rag_context = ""
+
+ # Step 2: Autonomously generate subtopics based on topic and RAG context
+ print("\n🎯 Step 2: Autonomously generating subtopics...")
+ sub_topics = await self._generate_sub_topics_auto(
+ topic=topic, rag_context=rag_context, max_subtopics=max_subtopics
+ )
+
+ print(f"✅ Autonomously generated {len(sub_topics)} subtopics")
+
+ return {
+ "main_topic": topic,
+ "sub_queries": [topic], # In auto mode, use topic itself as query
+ "rag_context": rag_context,
+ "sub_topics": sub_topics,
+ "total_subtopics": len(sub_topics),
+ "mode": "auto",
+ "rag_context_summary": "RAG background based on topic",
+ }
+
+ async def _generate_sub_topics_auto(
+ self, topic: str, rag_context: str, max_subtopics: int
+ ) -> list[dict[str, str]]:
+ """
+ Auto mode: Autonomously generate subtopics based on RAG background
+
+ Args:
+ topic: Main topic
+ rag_context: RAG background knowledge
+ max_subtopics: Maximum subtopic count limit
+
+ Returns:
+ Subtopics list
+ """
+ system_prompt = self.get_prompt("system", "role")
+ if not system_prompt:
+ raise ValueError(
+ "DecomposeAgent missing system prompt, please configure system.role in prompts/{lang}/decompose_agent.yaml"
+ )
+
+ user_prompt_template = self.get_prompt("process", "decompose")
+ if not user_prompt_template:
+ raise ValueError(
+ "DecomposeAgent missing decompose prompt, please configure process.decompose in prompts/{lang}/decompose_agent.yaml"
+ )
+
+ # Auto mode: Dynamically generate subtopics not exceeding the limit
+ decompose_requirement = f"""
+Quantity Requirements:
+Dynamically generate no more than {max_subtopics} subtopics. Please carefully analyze the background knowledge, identify core content areas related to the topic, and independently generate subtopics around the topic-related book content.
+- The number of subtopics should be reasonable, not exceeding {max_subtopics}
+- Prioritize subtopics most relevant and important to the topic
+- Ensure subtopics do not duplicate and cover different dimensions of the topic
+"""
+
+ user_prompt = user_prompt_template.format(
+ topic=topic, rag_context=rag_context, decompose_requirement=decompose_requirement
+ )
+
+ response = await self.call_llm(
+ user_prompt=user_prompt, system_prompt=system_prompt, stage="decompose"
+ )
+
+ # Parse JSON output (strict validation)
+ from ..utils.json_utils import ensure_json_dict, ensure_keys, extract_json_from_text
+
+ data = extract_json_from_text(response)
+ try:
+ obj = ensure_json_dict(data)
+ ensure_keys(obj, ["sub_topics"])
+ subs = obj.get("sub_topics", [])
+ if not isinstance(subs, list):
+ raise ValueError("sub_topics must be an array")
+ # Limit count not exceeding max_subtopics
+ cleaned = []
+ for it in subs[:max_subtopics]:
+ if isinstance(it, dict):
+ cleaned.append(
+ {"title": it.get("title", ""), "overview": it.get("overview", "")}
+ )
+ return cleaned
+ except Exception:
+ # Fallback: return empty list
+ return []
+
+ async def _generate_sub_queries(self, topic: str, num_queries: int) -> list[str]:
+ """
+ Generate sub-queries
+
+ Args:
+ topic: Main topic
+ num_queries: Expected number of queries
+
+ Returns:
+ Query list
+ """
+ system_prompt = self.get_prompt("system", "role")
+ if not system_prompt:
+ raise ValueError(
+ "DecomposeAgent missing system prompt, please configure system.role in prompts/{lang}/decompose_agent.yaml"
+ )
+
+ user_prompt_template = self.get_prompt("process", "generate_queries")
+ if not user_prompt_template:
+ raise ValueError(
+ "DecomposeAgent missing generate_queries prompt, please configure process.generate_queries in prompts/{lang}/decompose_agent.yaml"
+ )
+
+ user_prompt = user_prompt_template.format(topic=topic, num_queries=num_queries)
+
+ response = await self.call_llm(
+ user_prompt=user_prompt,
+ system_prompt=system_prompt,
+ stage="generate_queries",
+ )
+
+ from ..utils.json_utils import ensure_json_dict, ensure_keys
+
+ data = extract_json_from_text(response)
+ try:
+ obj = ensure_json_dict(data)
+ ensure_keys(obj, ["queries"])
+ queries = obj.get("queries", [])
+ if not isinstance(queries, list):
+ raise ValueError("queries must be an array")
+ return queries[:num_queries]
+ except Exception:
+ # Fallback: extract queries from text
+ lines = response.split("\n")
+ queries = [line.strip() for line in lines if line.strip() and len(line.strip()) > 3]
+ return queries[:num_queries]
+
+ async def _generate_sub_topics(
+ self, topic: str, rag_context: str, num_subtopics: int
+ ) -> list[dict[str, str]]:
+ """
+ Generate subtopics based on RAG background
+
+ Args:
+ topic: Main topic
+ rag_context: RAG background knowledge
+ num_subtopics: Expected number of subtopics
+
+ Returns:
+ Subtopics list
+ """
+ system_prompt = self.get_prompt("system", "role")
+ if not system_prompt:
+ raise ValueError(
+ "DecomposeAgent missing system prompt, please configure system.role in prompts/{lang}/decompose_agent.yaml"
+ )
+
+ user_prompt_template = self.get_prompt("process", "decompose")
+ if not user_prompt_template:
+ raise ValueError(
+ "DecomposeAgent missing decompose prompt, please configure process.decompose in prompts/{lang}/decompose_agent.yaml"
+ )
+
+ # Manual mode: Explicitly generate specified number of subtopics
+ decompose_requirement = f"""
+Quantity Requirements:
+Explicitly generate {num_subtopics} subtopics. Please ensure exactly {num_subtopics} subtopics are generated, no more, no less.
+"""
+
+ user_prompt = user_prompt_template.format(
+ topic=topic, rag_context=rag_context, decompose_requirement=decompose_requirement
+ )
+
+ response = await self.call_llm(
+ user_prompt=user_prompt, system_prompt=system_prompt, stage="decompose"
+ )
+
+ # Parse JSON output (strict validation)
+ from ..utils.json_utils import ensure_json_dict, ensure_keys, extract_json_from_text
+
+ data = extract_json_from_text(response)
+ try:
+ obj = ensure_json_dict(data)
+ ensure_keys(obj, ["sub_topics"])
+ subs = obj.get("sub_topics", [])
+ if not isinstance(subs, list):
+ raise ValueError("sub_topics must be an array")
+ # Only select required fields
+ cleaned = []
+ for it in subs[:num_subtopics]:
+ if isinstance(it, dict):
+ cleaned.append(
+ {"title": it.get("title", ""), "overview": it.get("overview", "")}
+ )
+ return cleaned
+ except Exception:
+ # Fallback: return empty list
+ return []
+
+
+__all__ = ["DecomposeAgent"]
diff --git a/src/agents/research/agents/manager_agent.py b/src/agents/research/agents/manager_agent.py
new file mode 100644
index 000000000..9d6847849
--- /dev/null
+++ b/src/agents/research/agents/manager_agent.py
@@ -0,0 +1,215 @@
+#!/usr/bin/env python
+"""
+ManagerAgent - Queue management Agent
+Responsible for managing DynamicTopicQueue state and task distribution
+"""
+
+import asyncio
+from pathlib import Path
+import sys
+from typing import Any
+
+project_root = Path(__file__).parent.parent.parent.parent
+sys.path.insert(0, str(project_root))
+
+from src.agents.research.data_structures import DynamicTopicQueue, TopicBlock
+
+from .base_agent import BaseAgent
+
+
+class ManagerAgent(BaseAgent):
+ """Queue management Agent"""
+
+ def __init__(self, config: dict[str, Any], api_key: str = None, base_url: str = None):
+ super().__init__(
+ config=config, api_key=api_key, base_url=base_url, agent_name="manager_agent"
+ )
+ self.queue: DynamicTopicQueue | None = None
+ self.primary_topic: str | None = None
+ self._lock = asyncio.Lock() # Lock for thread-safe operations in parallel mode
+
+ def set_queue(self, queue: DynamicTopicQueue) -> None:
+ """Set queue to manage"""
+ self.queue = queue
+
+ def set_primary_topic(self, topic: str | None) -> None:
+ """Update primary research topic for subsequent topic consistency judgment"""
+ self.primary_topic = (topic or "").strip() or None
+
+ def get_next_task(self) -> TopicBlock | None:
+ """
+ Get next task to research
+
+ Returns:
+ Next TopicBlock with PENDING status, returns None if none available
+ """
+ if not self.queue:
+ return None
+
+ block = self.queue.get_pending_block()
+ if block:
+ # Mark as researching
+ self.queue.mark_researching(block.block_id)
+ print(f"\n📋 ManagerAgent: Assigned task {block.block_id}")
+ print(f" Topic: {block.sub_topic}")
+
+ return block
+
+ def complete_task(self, block_id: str) -> bool:
+ """
+ Mark task as completed
+
+ Args:
+ block_id: Topic block ID
+
+ Returns:
+ Whether successfully marked
+ """
+ if not self.queue:
+ return False
+
+ success = self.queue.mark_completed(block_id)
+ if success:
+ print(f"✅ ManagerAgent: Task {block_id} completed")
+
+ return success
+
+ async def get_next_task_async(self) -> TopicBlock | None:
+ """
+ Thread-safe async version of get_next_task for parallel mode
+
+ Returns:
+ Next TopicBlock with PENDING status, returns None if none available
+ """
+ async with self._lock:
+ return self.get_next_task()
+
+ async def complete_task_async(self, block_id: str) -> bool:
+ """
+ Thread-safe async version of complete_task for parallel mode
+
+ Args:
+ block_id: Topic block ID
+
+ Returns:
+ Whether successfully marked
+ """
+ async with self._lock:
+ return self.complete_task(block_id)
+
+ async def fail_task_async(self, block_id: str, reason: str = "") -> bool:
+ """
+ Thread-safe async version of fail_task for parallel mode
+
+ Args:
+ block_id: Topic block ID
+ reason: Failure reason
+
+ Returns:
+ Whether successfully marked
+ """
+ async with self._lock:
+ return self.fail_task(block_id, reason)
+
+ async def add_new_topic_async(self, sub_topic: str, overview: str) -> TopicBlock:
+ """
+ Thread-safe async version of add_new_topic for parallel mode
+
+ Args:
+ sub_topic: Sub-topic name
+ overview: Topic overview
+
+ Returns:
+ Newly created TopicBlock
+ """
+ async with self._lock:
+ return self.add_new_topic(sub_topic, overview)
+
+ def fail_task(self, block_id: str, reason: str = "") -> bool:
+ """
+ Mark task as failed
+
+ Args:
+ block_id: Topic block ID
+ reason: Failure reason
+
+ Returns:
+ Whether successfully marked
+ """
+ if not self.queue:
+ return False
+
+ success = self.queue.mark_failed(block_id)
+ if success:
+ print(f"❌ ManagerAgent: Task {block_id} failed")
+ if reason:
+ print(f" Reason: {reason}")
+
+ return success
+
+ def add_new_topic(self, sub_topic: str, overview: str) -> TopicBlock:
+ """
+ Add new topic to queue
+
+ Args:
+ sub_topic: Sub-topic name
+ overview: Topic overview
+
+ Returns:
+ Newly created TopicBlock
+ """
+ if not self.queue:
+ raise RuntimeError("Queue not initialized")
+
+ normalized = (sub_topic or "").strip()
+ if not normalized:
+ raise ValueError("New topic title cannot be empty")
+ if self.queue.has_topic(normalized):
+ print(f"⚠️ ManagerAgent: Topic《{normalized}》already exists, skipping addition")
+ return None
+
+ block = self.queue.add_block(normalized, overview)
+ print(f"➕ ManagerAgent: Added new topic {block.block_id}")
+ print(f" Topic: {sub_topic}")
+
+ return block
+
+ def is_research_complete(self) -> bool:
+ """
+ Check if research is complete (all tasks are completed)
+
+ Returns:
+ Whether all tasks are completed
+ """
+ if not self.queue:
+ return False
+
+ return self.queue.is_all_completed()
+
+ def get_queue_status(self) -> dict[str, Any]:
+ """
+ Get queue status
+
+ Returns:
+ Queue statistics
+ """
+ if not self.queue:
+ return {}
+
+ stats = self.queue.get_statistics()
+ print("\n📊 Queue Status:")
+ print(f" Total Topics: {stats['total_blocks']}")
+ print(f" Pending: {stats['pending']}")
+ print(f" Researching: {stats['researching']}")
+ print(f" Completed: {stats['completed']}")
+ print(f" Failed: {stats['failed']}")
+ print(f" Total Tool Calls: {stats['total_tool_calls']}")
+
+ return stats
+
+ async def process(self, *args, **kwargs) -> Any:
+ """Main processing logic of Manager Agent"""
+ # Manager Agent is mainly called through other methods, no independent process method needed
+
+
+__all__ = ["ManagerAgent"]
diff --git a/src/agents/research/agents/note_agent.py b/src/agents/research/agents/note_agent.py
new file mode 100644
index 000000000..c17ed9209
--- /dev/null
+++ b/src/agents/research/agents/note_agent.py
@@ -0,0 +1,164 @@
+#!/usr/bin/env python
+"""
+NoteAgent - Recording Agent
+Responsible for information compression and summary generation, converting raw data returned by tools into usable knowledge summaries
+"""
+
+from pathlib import Path
+from string import Template
+import sys
+from typing import Any
+
+project_root = Path(__file__).parent.parent.parent.parent
+sys.path.insert(0, str(project_root))
+
+from src.agents.research.data_structures import ToolTrace
+
+from ..utils.json_utils import extract_json_from_text
+from .base_agent import BaseAgent
+
+
+class NoteAgent(BaseAgent):
+ """Recording Agent"""
+
+ def __init__(self, config: dict[str, Any], api_key: str = None, base_url: str = None):
+ super().__init__(config=config, api_key=api_key, base_url=base_url, agent_name="note_agent")
+
+ async def process(
+ self,
+ tool_type: str,
+ query: str,
+ raw_answer: str,
+ citation_id: str,
+ topic: str = "",
+ context: str = "",
+ ) -> ToolTrace:
+ """
+ Process raw data returned by tool, generate summary and create ToolTrace
+
+ Args:
+ tool_type: Tool type
+ query: Query statement
+ raw_answer: Raw answer returned by tool
+ citation_id: Citation ID (REQUIRED, must be obtained from CitationManager)
+ topic: Topic (for context)
+ context: Additional context
+
+ Returns:
+ ToolTrace object
+
+ Note:
+ citation_id must be obtained from CitationManager before calling this method.
+ Use CitationManager.get_next_citation_id() or its async variant.
+ """
+ print(f"\n{'=' * 70}")
+ print("📝 NoteAgent - Information Recording and Summary")
+ print(f"{'=' * 70}")
+ print(f"Tool: {tool_type}")
+ print(f"Query: {query}")
+ print(f"Citation ID: {citation_id}")
+ print(f"Raw Answer Length: {len(raw_answer)} characters\n")
+
+ # Generate summary
+ summary = await self._generate_summary(
+ tool_type=tool_type, query=query, raw_answer=raw_answer, topic=topic, context=context
+ )
+
+ print(f"✅ Summary generation completed ({len(summary)} characters)")
+
+ # Create ToolTrace with the provided citation ID
+ tool_id = self._generate_tool_id()
+ trace = ToolTrace(
+ tool_id=tool_id,
+ citation_id=citation_id,
+ tool_type=tool_type,
+ query=query,
+ raw_answer=raw_answer,
+ summary=summary,
+ )
+
+ return trace
+
+ @staticmethod
+ def _convert_to_template_format(template_str: str) -> str:
+ """
+ Convert {var} style placeholders to $var style for string.Template.
+ This avoids conflicts with LaTeX braces like {\rho}.
+ """
+ import re
+
+ # Only convert simple {var_name} patterns, not nested or complex ones
+ return re.sub(r"\{(\w+)\}", r"$\1", template_str)
+
+ async def _generate_summary(
+ self, tool_type: str, query: str, raw_answer: str, topic: str = "", context: str = ""
+ ) -> str:
+ """
+ Generate summary
+
+ Args:
+ tool_type: Tool type
+ query: Query statement
+ raw_answer: Raw answer
+ topic: Topic
+ context: Additional context
+
+ Returns:
+ Generated summary
+ """
+ system_prompt = self.get_prompt("system", "role")
+ if not system_prompt:
+ raise ValueError(
+ "NoteAgent missing system prompt, please configure system.role in prompts/{lang}/note_agent.yaml"
+ )
+
+ user_prompt_template = self.get_prompt("process", "generate_summary")
+ if not user_prompt_template:
+ raise ValueError(
+ "NoteAgent missing generate_summary prompt, please configure process.generate_summary in prompts/{lang}/note_agent.yaml"
+ )
+
+ # Use string.Template to avoid conflicts with LaTeX braces like {\rho}
+ # Convert {var} to $var format, then use safe_substitute
+ template_str = self._convert_to_template_format(user_prompt_template)
+ template = Template(template_str)
+ user_prompt = template.safe_substitute(
+ tool_type=tool_type,
+ query=query,
+ raw_answer=raw_answer,
+ topic=topic,
+ context=context,
+ )
+
+ response = await self.call_llm(
+ user_prompt=user_prompt,
+ system_prompt=system_prompt,
+ stage="generate_summary",
+ verbose=False,
+ )
+
+ # Parse JSON output (strict validation)
+ from ..utils.json_utils import ensure_json_dict, ensure_keys
+
+ data = extract_json_from_text(response)
+ try:
+ obj = ensure_json_dict(data)
+ ensure_keys(obj, ["summary"])
+ summary = obj.get("summary", "")
+ # Ensure summary is string type
+ if not isinstance(summary, str):
+ summary = str(summary) if summary else ""
+ return summary
+ except Exception:
+ # Fallback: directly use text prefix
+ return (response or "")[:1000]
+
+ def _generate_tool_id(self) -> str:
+ """Generate tool ID"""
+ import time
+
+ timestamp = int(time.time() * 1000)
+ return f"tool_{timestamp}"
+
+
+__all__ = ["NoteAgent"]
diff --git a/src/agents/research/agents/rephrase_agent.py b/src/agents/research/agents/rephrase_agent.py
new file mode 100644
index 000000000..98aa0c187
--- /dev/null
+++ b/src/agents/research/agents/rephrase_agent.py
@@ -0,0 +1,248 @@
+#!/usr/bin/env python
+"""
+RephraseAgent - Topic rephrasing Agent
+Responsible for rephrasing and optimizing user input
+"""
+
+from pathlib import Path
+import sys
+from typing import Any
+
+project_root = Path(__file__).parent.parent.parent.parent
+sys.path.insert(0, str(project_root))
+
+from ..utils.json_utils import extract_json_from_text
+from .base_agent import BaseAgent
+
+
+class RephraseAgent(BaseAgent):
+ """Topic rephrasing Agent"""
+
+ def __init__(self, config: dict[str, Any], api_key: str = None, base_url: str = None):
+ super().__init__(
+ config=config, api_key=api_key, base_url=base_url, agent_name="rephrase_agent"
+ )
+ # Store complete conversation history for multi-turn optimization
+ self.conversation_history: list[dict[str, Any]] = []
+
+ def reset_history(self):
+ """Reset conversation history for a new research session"""
+ self.conversation_history = []
+
+ def _format_conversation_history(self) -> str:
+ """Format conversation history for prompt"""
+ if not self.conversation_history:
+ return ""
+
+ history_parts = []
+ for entry in self.conversation_history:
+ role = entry.get("role", "unknown")
+ iteration = entry.get("iteration", 0)
+ content = entry.get("content", "")
+
+ if role == "user":
+ if iteration == 0:
+ history_parts.append(f"[User - Initial Input]\n{content}")
+ else:
+ history_parts.append(f"[User - Feedback (Round {iteration})]\n{content}")
+ elif role == "assistant":
+ topic = content.get("topic", "") if isinstance(content, dict) else str(content)
+ history_parts.append(f"[Assistant - Rephrased Topic (Round {iteration})]\n{topic}")
+
+ return "\n\n".join(history_parts)
+
+ async def process(
+ self, user_input: str, iteration: int = 0, previous_result: dict[str, Any] = None
+ ) -> dict[str, Any]:
+ """
+ Rephrase and optimize user input, supports user interaction confirmation
+ Uses complete conversation history for better context understanding
+
+ Args:
+ user_input: User's original input (first time) or feedback (subsequent iterations)
+ iteration: Iteration count (for tracking rephrasing rounds)
+ previous_result: Previous rephrasing result (for backward compatibility)
+
+ Returns:
+ Dictionary containing rephrasing results
+ {
+ "topic": str, # Optimized research topic (a clear, explicit statement)
+ "iteration": int, # Iteration count
+ }
+ """
+ print(f"\n{'=' * 70}")
+ print(f"🔄 RephraseAgent - Topic Rephrasing (Iteration {iteration})")
+ print(f"{'=' * 70}")
+
+ # Reset history for new session (iteration 0)
+ if iteration == 0:
+ self.reset_history()
+ print(f"Original Input: {user_input}\n")
+ else:
+ print(f"User Feedback: {user_input}\n")
+ print(f"Conversation History: {len(self.conversation_history)} entries\n")
+
+ # Add current user input to history
+ self.conversation_history.append(
+ {
+ "role": "user",
+ "content": user_input,
+ "iteration": iteration,
+ }
+ )
+
+ # Get system prompt
+ system_prompt = self.get_prompt("system", "role")
+ if not system_prompt:
+ raise ValueError(
+ "RephraseAgent missing system prompt, please configure system.role in prompts/{lang}/rephrase_agent.yaml"
+ )
+
+ # Get user prompt template
+ user_prompt_template = self.get_prompt("process", "rephrase")
+ if not user_prompt_template:
+ raise ValueError(
+ "RephraseAgent missing rephrase prompt, please configure process.rephrase in prompts/{lang}/rephrase_agent.yaml"
+ )
+
+ # Format conversation history for prompt
+ history_text = self._format_conversation_history()
+
+ # Format user prompt with full history
+ user_prompt = user_prompt_template.format(
+ user_input=user_input,
+ iteration=iteration,
+ conversation_history=history_text,
+ previous_result=history_text, # For backward compatibility with old templates
+ )
+
+ # Call LLM
+ response = await self.call_llm(
+ user_prompt=user_prompt, system_prompt=system_prompt, stage="rephrase"
+ )
+
+ # Parse JSON output
+ data = extract_json_from_text(response)
+ from ..utils.json_utils import ensure_json_dict, ensure_keys
+
+ try:
+ result = ensure_json_dict(data)
+ ensure_keys(result, ["topic"])
+ except Exception:
+ # Fallback: use user input or last assistant topic
+ fallback_topic = user_input
+ for entry in reversed(self.conversation_history):
+ if entry.get("role") == "assistant":
+ content = entry.get("content", {})
+ if isinstance(content, dict) and content.get("topic"):
+ fallback_topic = content["topic"]
+ break
+ result = {"topic": fallback_topic}
+
+ result["iteration"] = iteration
+
+ # Add assistant response to history
+ self.conversation_history.append(
+ {
+ "role": "assistant",
+ "content": result,
+ "iteration": iteration,
+ }
+ )
+
+ print("\n✅ Rephrasing Completed:")
+ print(f" Optimized Research Topic: {result.get('topic', '')}")
+
+ return result
+
+ async def check_user_satisfaction(
+ self, rephrase_result: dict[str, Any], user_feedback: str
+ ) -> dict[str, Any]:
+ """
+ Determine user satisfaction with rephrasing result
+
+ Args:
+ rephrase_result: Current rephrasing result
+ user_feedback: User feedback
+
+ Returns:
+ Dictionary containing judgment results
+ {
+ "user_satisfied": bool, # Whether user is satisfied
+ "should_continue": bool, # Whether to continue rephrasing
+ "interpretation": str, # Interpretation of user intent
+ "suggested_action": str # Suggested next action
+ }
+ """
+ print(f"\n{'=' * 70}")
+ print("🤔 RephraseAgent - Judging User Intent")
+ print(f"{'=' * 70}")
+ print(f"User Feedback: {user_feedback}\n")
+
+ system_prompt = self.get_prompt("system", "role")
+ if not system_prompt:
+ raise ValueError(
+ "RephraseAgent missing system prompt, please configure system.role in prompts/{lang}/rephrase_agent.yaml"
+ )
+
+ user_prompt_template = self.get_prompt("process", "check_satisfaction")
+ if not user_prompt_template:
+ raise ValueError(
+ "RephraseAgent missing check_satisfaction prompt, please configure process.check_satisfaction in prompts/{lang}/rephrase_agent.yaml"
+ )
+
+ user_prompt = user_prompt_template.format(
+ topic=rephrase_result.get("topic", ""), user_feedback=user_feedback
+ )
+
+ response = await self.call_llm(
+ user_prompt=user_prompt,
+ system_prompt=system_prompt,
+ stage="check_satisfaction",
+ verbose=False,
+ )
+
+ # Parse JSON output
+ data = extract_json_from_text(response)
+ from ..utils.json_utils import ensure_json_dict, ensure_keys
+
+ try:
+ result = ensure_json_dict(data)
+ ensure_keys(result, ["user_satisfied", "should_continue", "interpretation"])
+ except Exception:
+ # Fallback: judge based on keywords
+ feedback_lower = user_feedback.lower()
+ satisfied_keywords = ["ok", "yes", "satisfied", "good", "fine", "agree", "approved"]
+ continue_keywords = [
+ "modify",
+ "change",
+ "adjust",
+ "no",
+ "need",
+ "want",
+ "should",
+ "hope",
+ ]
+
+ user_satisfied = any(kw in feedback_lower for kw in satisfied_keywords) and not any(
+ kw in feedback_lower for kw in continue_keywords
+ )
+
+ result = {
+ "user_satisfied": user_satisfied,
+ "should_continue": not user_satisfied,
+ "interpretation": "Judged based on keywords",
+ "suggested_action": (
+ "Continue rephrasing" if not user_satisfied else "Proceed to next stage"
+ ),
+ }
+
+ print("\n📊 Judgment Result:")
+ print(f" User Satisfied: {'Yes' if result.get('user_satisfied') else 'No'}")
+ print(f" Continue Rephrasing: {'Yes' if result.get('should_continue') else 'No'}")
+ print(f" Intent Interpretation: {result.get('interpretation', '')}")
+
+ return result
+
+
+__all__ = ["RephraseAgent"]
diff --git a/src/agents/research/agents/reporting_agent.py b/src/agents/research/agents/reporting_agent.py
new file mode 100644
index 000000000..b5e4486ed
--- /dev/null
+++ b/src/agents/research/agents/reporting_agent.py
@@ -0,0 +1,1320 @@
+#!/usr/bin/env python
+"""
+ReportingAgent - Report generation Agent (DR-in-KG 2.0)
+- Deduplication and cleaning
+- Generate linear outline (introduction → sections → conclusion)
+- Write final report (prefer LLM JSON return markdown, fallback to local assembly on failure)
+- Inline citations and References anchors (based on citation_id)
+"""
+
+from __future__ import annotations
+
+from collections.abc import Callable
+from pathlib import Path
+import re
+from string import Template
+import sys
+from typing import Any
+
+project_root = Path(__file__).parent.parent.parent.parent
+sys.path.insert(0, str(project_root))
+
+from src.agents.research.data_structures import DynamicTopicQueue, TopicBlock
+
+from ..utils.json_utils import ensure_json_dict, ensure_keys, extract_json_from_text
+from .base_agent import BaseAgent
+
+
+class ReportingAgent(BaseAgent):
+ """Report generation Agent"""
+
+ @staticmethod
+ def _escape_braces(text: str) -> str:
+ """
+ Escape curly braces in text to prevent str.format() from interpreting them.
+ This is needed because JSON data may contain LaTeX formulas with braces like {L}, {x}.
+
+ Args:
+ text: Input text that may contain curly braces
+
+ Returns:
+ Text with braces escaped ({{ and }})
+ """
+ return text.replace("{", "{{").replace("}", "}}")
+
+ @staticmethod
+ def _convert_to_template_format(template_str: str) -> str:
+ """
+ Convert {var} style placeholders to $var style for string.Template.
+ This avoids conflicts with LaTeX braces like {\rho}, {L}.
+ """
+ return re.sub(r"\{(\w+)\}", r"$\1", template_str)
+
+ def _safe_format(self, template_str: str, **kwargs) -> str:
+ """
+ Safe string formatting using string.Template to avoid LaTeX brace conflicts.
+ Converts {var} to $var format, then uses safe_substitute.
+ """
+ converted = self._convert_to_template_format(template_str)
+ return Template(converted).safe_substitute(**kwargs)
+
+ def __init__(
+ self, config: dict[str, Any], api_key: str | None = None, base_url: str | None = None
+ ):
+ super().__init__(
+ config=config, api_key=api_key, base_url=base_url, agent_name="reporting_agent"
+ )
+ self.reporting_config = config.get("reporting", {})
+ self.citation_manager = None # Will be set during process
+
+ # Citation configuration: read from config, default off
+ self.enable_citation_list = self.reporting_config.get("enable_citation_list", False)
+ self.enable_inline_citations = self.reporting_config.get("enable_inline_citations", False)
+
+ def set_citation_manager(self, citation_manager):
+ """Set citation manager"""
+ self.citation_manager = citation_manager
+
+ async def process(
+ self,
+ queue: DynamicTopicQueue,
+ topic: str,
+ progress_callback: Callable[[dict[str, Any]], None] | None = None,
+ ) -> dict[str, Any]:
+ """
+ Generate final report
+ Returns:
+ {
+ "report": str,
+ "word_count": int,
+ "sections": int,
+ "citations": int
+ }
+ """
+ print(f"\n{'=' * 70}")
+ print("📄 ReportingAgent - Report Generation")
+ print(f"{'=' * 70}")
+ print(f"Topic: {topic}")
+ print(f"Topic Blocks: {len(queue.blocks)}\n")
+
+ # Store progress_callback for use in _write_report
+ self._progress_callback = progress_callback
+
+ self._notify_progress(
+ progress_callback, "reporting_started", topic=topic, total_blocks=len(queue.blocks)
+ )
+
+ # 1) Deduplication
+ print("🔄 Step 1: Deduplication and cleaning...")
+ cleaned_blocks = await self._deduplicate_blocks(queue.blocks)
+ print(f"✅ Cleaning completed: {len(cleaned_blocks)} topic blocks")
+ self._notify_progress(
+ progress_callback, "deduplicate_completed", kept_blocks=len(cleaned_blocks)
+ )
+
+ # 2) Outline
+ print("\n📋 Step 2: Generating outline...")
+ outline = await self._generate_outline(topic, cleaned_blocks)
+ print("✅ Outline generation completed")
+ self._notify_progress(
+ progress_callback, "outline_completed", sections=len(outline.get("sections", []))
+ )
+
+ # Save outline for later use
+ self._current_outline = outline
+
+ # 3) Writing
+ print("\n✍️ Step 3: Writing report...")
+ report_markdown = await self._write_report(topic, cleaned_blocks, outline)
+ print("✅ Report writing completed")
+ self._notify_progress(progress_callback, "writing_completed")
+
+ word_count = len(report_markdown)
+ sections = len(cleaned_blocks)
+ citations = sum(len(b.tool_traces) for b in cleaned_blocks)
+
+ print("\n📊 Report Statistics:")
+ print(f" Word Count: {word_count}")
+ print(f" Sections: {sections}")
+ print(f" Citations: {citations}")
+ self._notify_progress(
+ progress_callback,
+ "reporting_completed",
+ word_count=word_count,
+ sections=sections,
+ citations=citations,
+ )
+
+ result = {
+ "report": report_markdown,
+ "word_count": word_count,
+ "sections": sections,
+ "citations": citations,
+ }
+
+ # If outline has been generated, add it to result
+ if hasattr(self, "_current_outline"):
+ result["outline"] = self._current_outline
+ delattr(self, "_current_outline")
+
+ return result
+
+ async def _deduplicate_blocks(self, blocks: list[TopicBlock]) -> list[TopicBlock]:
+ if len(blocks) <= 1:
+ return blocks
+ system_prompt = self.get_prompt("system", "role")
+ if not system_prompt:
+ raise ValueError(
+ "ReportingAgent missing system prompt, please configure system.role in prompts/{lang}/reporting_agent.yaml"
+ )
+ user_prompt = self.get_prompt("process", "deduplicate")
+ if not user_prompt:
+ raise ValueError(
+ "ReportingAgent missing deduplicate prompt, please configure process.deduplicate in prompts/{lang}/reporting_agent.yaml"
+ )
+ topics_text = "\n".join(
+ [f"{i + 1}. {b.sub_topic}: {b.overview[:200]}" for i, b in enumerate(blocks)]
+ )
+ filled = self._safe_format(user_prompt, topics=topics_text, total_topics=len(blocks))
+ resp = await self.call_llm(filled, system_prompt, stage="deduplicate", verbose=False)
+ data = extract_json_from_text(resp)
+ try:
+ obj = ensure_json_dict(data)
+ ensure_keys(obj, ["keep_indices"])
+ keep_indices = obj.get("keep_indices", [])
+ return [blocks[i] for i in keep_indices if isinstance(i, int) and i < len(blocks)]
+ except Exception:
+ return blocks
+
+ async def _generate_outline(self, topic: str, blocks: list[TopicBlock]) -> dict[str, Any]:
+ """Generate report outline based on complete subtopic, overview and all tool_trace summaries
+
+ Supports three-level heading system:
+ - Level 1 (#): Report main title
+ - Level 2 (##): Main sections (Introduction, Core Sections, Conclusion)
+ - Level 3 (###): Subsections within each section
+ """
+ system_prompt = self.get_prompt("system", "role")
+ if not system_prompt:
+ raise ValueError(
+ "ReportingAgent missing system prompt, please configure system.role in prompts/{lang}/reporting_agent.yaml"
+ )
+ user_prompt = self.get_prompt("process", "generate_outline")
+ if not user_prompt:
+ raise ValueError(
+ "ReportingAgent missing generate_outline prompt, please configure process.generate_outline in prompts/{lang}/reporting_agent.yaml"
+ )
+
+ # Build complete topic information, including subtopic, overview and all tool_trace summaries
+ topics_data = []
+ for i, block in enumerate(blocks, 1):
+ topic_info = {
+ "index": i,
+ "block_id": block.block_id,
+ "sub_topic": block.sub_topic,
+ "overview": block.overview,
+ "tool_summaries": (
+ [trace.summary for trace in block.tool_traces] if block.tool_traces else []
+ ),
+ }
+ topics_data.append(topic_info)
+
+ import json as _json
+
+ topics_json = _json.dumps(topics_data, ensure_ascii=False, indent=2)
+ # Use safe_format to avoid conflicts with LaTeX braces like {\rho}, {L}
+ filled = self._safe_format(
+ user_prompt, topic=topic, topics_json=topics_json, total_topics=len(blocks)
+ )
+
+ resp = await self.call_llm(filled, system_prompt, stage="generate_outline", verbose=False)
+ data = extract_json_from_text(resp)
+ try:
+ obj = ensure_json_dict(data)
+ ensure_keys(obj, ["title", "introduction", "sections", "conclusion"])
+ # Ensure title uses markdown format (# prefix)
+ if not obj.get("title", "").startswith("#"):
+ obj["title"] = f"# {obj.get('title', topic)}"
+ # Ensure introduction and conclusion use markdown format (## prefix)
+ if obj.get("introduction") and not obj["introduction"].startswith("##"):
+ obj["introduction"] = f"## {obj['introduction']}"
+ if obj.get("conclusion") and not obj["conclusion"].startswith("##"):
+ obj["conclusion"] = f"## {obj['conclusion']}"
+
+ # Process sections to ensure proper formatting
+ for section in obj.get("sections", []):
+ # Ensure section title has ## prefix
+ if section.get("title") and not section["title"].startswith("##"):
+ section["title"] = f"## {section['title']}"
+ # Process subsections if present
+ for subsection in section.get("subsections", []):
+ if subsection.get("title") and not subsection["title"].startswith("###"):
+ subsection["title"] = f"### {subsection['title']}"
+
+ return obj
+ except Exception:
+ # Fallback to default outline with subsections
+ return self._create_default_outline(topic, blocks)
+
+ def _create_default_outline(self, topic: str, blocks: list[TopicBlock]) -> dict[str, Any]:
+ """Create a default outline with three-level heading structure"""
+ sections = []
+ for i, b in enumerate(blocks, 1):
+ section = {
+ "title": f"## {i}. {b.sub_topic}",
+ "instruction": f"Provide detailed introduction to {b.sub_topic}, including core concepts, key mechanisms, and practical applications",
+ "block_id": b.block_id,
+ "subsections": [
+ {
+ "title": f"### {i}.1 Core Concepts and Definitions",
+ "instruction": f"Explain the fundamental concepts and definitions related to {b.sub_topic}",
+ },
+ {
+ "title": f"### {i}.2 Key Mechanisms and Principles",
+ "instruction": f"Analyze the underlying mechanisms and theoretical principles of {b.sub_topic}",
+ },
+ ],
+ }
+ sections.append(section)
+
+ return {
+ "title": f"# {topic}",
+ "introduction": "## Introduction",
+ "introduction_instruction": "Present the research background, motivation, objectives, and report structure",
+ "sections": sections,
+ "conclusion": "## Conclusion and Future Directions",
+ "conclusion_instruction": "Summarize core findings, research contributions, limitations, and future directions",
+ }
+
+ def _ser_block(self, b: TopicBlock) -> dict[str, Any]:
+ """Serialize TopicBlock to dictionary, including complete tool traces
+
+ If self._citation_map is available (built by _build_citation_number_map),
+ each trace will include a ref_number field for inline citation use.
+ """
+ traces = []
+ for t in b.tool_traces:
+ cid = getattr(t, "citation_id", None) or f"CIT-{b.block_id.split('_')[-1]}-01"
+ trace_data = {
+ "citation_id": cid,
+ "tool_type": t.tool_type,
+ "query": t.query,
+ "raw_answer": t.raw_answer, # Include complete original response
+ "summary": t.summary,
+ }
+ # Add ref_number if citation map is available
+ if hasattr(self, "_citation_map") and self._citation_map:
+ ref_num = self._citation_map.get(cid, 0)
+ if ref_num > 0:
+ trace_data["ref_number"] = ref_num
+ traces.append(trace_data)
+ return {
+ "block_id": b.block_id,
+ "sub_topic": b.sub_topic,
+ "overview": b.overview,
+ "traces": traces,
+ }
+
+ def _build_citation_table(self, block: TopicBlock) -> str:
+ """Build a clear citation reference table for LLM to understand the mapping
+
+ This creates an easy-to-read table showing:
+ - Reference number to use in text (use [N] format)
+ - Tool type
+ - Query summary (truncated)
+
+ Args:
+ block: TopicBlock containing tool traces
+
+ Returns:
+ Formatted citation table string
+ """
+ if not block.tool_traces:
+ return " (No citations available for this section)"
+
+ lines = []
+ for trace in block.tool_traces:
+ cid = getattr(trace, "citation_id", None)
+ if not cid:
+ continue
+
+ ref_num = self._citation_map.get(cid, 0) if hasattr(self, "_citation_map") else 0
+ if ref_num <= 0:
+ continue
+
+ # Truncate query for readability
+ query_preview = trace.query[:60] + "..." if len(trace.query) > 60 else trace.query
+ tool_display = {
+ "rag_naive": "RAG",
+ "rag_hybrid": "Hybrid RAG",
+ "query_item": "KB Query",
+ "paper_search": "Paper",
+ "web_search": "Web",
+ "run_code": "Code",
+ }.get(trace.tool_type.lower(), trace.tool_type)
+
+ # Use clear format: cite as [N] -> source description
+ lines.append(f" - Cite as [{ref_num}] → ({tool_display}) {query_preview}")
+
+ if not lines:
+ return " (No citations available for this section)"
+
+ return "\n".join(lines)
+
+ async def _write_introduction(
+ self, topic: str, blocks: list[TopicBlock], outline: dict[str, Any]
+ ) -> str:
+ """Write report introduction section"""
+ system_prompt = self.get_prompt(
+ "system",
+ "role",
+ "You are an academic writing expert specializing in writing the introduction section of research reports.",
+ )
+ tmpl = self.get_prompt("process", "write_introduction", "")
+ if not tmpl:
+ raise ValueError(
+ "Cannot get introduction writing prompt template, report generation failed"
+ )
+
+ import json as _json
+
+ # Prepare context for introduction: overview information of all topics
+ topics_summary = []
+ for b in blocks:
+ topics_summary.append(
+ {"sub_topic": b.sub_topic, "overview": b.overview, "tool_count": len(b.tool_traces)}
+ )
+
+ # Use introduction_instruction if available, otherwise fall back to introduction title
+ intro_instruction = outline.get("introduction_instruction", "") or outline.get(
+ "introduction", ""
+ )
+
+ # Use safe_format to avoid conflicts with LaTeX braces like {\rho}, {L}
+ topics_summary_json = _json.dumps(topics_summary, ensure_ascii=False, indent=2)
+ filled = self._safe_format(
+ tmpl,
+ topic=topic,
+ introduction_instruction=intro_instruction,
+ topics_summary=topics_summary_json,
+ total_topics=len(blocks),
+ )
+
+ resp = await self.call_llm(filled, system_prompt, stage="write_introduction", verbose=False)
+ data = extract_json_from_text(resp)
+
+ try:
+ obj = ensure_json_dict(data)
+ ensure_keys(obj, ["introduction"])
+ intro = obj.get("introduction", "")
+ if isinstance(intro, str) and intro.strip():
+ return intro
+ raise ValueError("LLM returned empty or invalid introduction field")
+ except Exception as e:
+ raise ValueError(
+ f"Unable to parse LLM returned introduction content: {e!s}. Report generation failed."
+ )
+
+ async def _write_section_body(
+ self, topic: str, block: TopicBlock, section_outline: dict[str, Any]
+ ) -> str:
+ """Write main content of a single section"""
+ system_prompt = self.get_prompt(
+ "system",
+ "role",
+ "You are an academic writing expert specializing in writing chapter content for research reports.",
+ )
+ tmpl = self.get_prompt("process", "write_section_body", "")
+ if not tmpl:
+ raise ValueError("Cannot get section writing prompt template, report generation failed")
+
+ import json as _json
+
+ block_data = self._ser_block(block)
+
+ # Dynamically build citation instructions based on configuration
+ if self.enable_inline_citations:
+ # Build clear citation reference table for this block
+ citation_table = self._build_citation_table(block)
+
+ citation_instruction_template = self.get_prompt("citation", "enabled_instruction")
+ if citation_instruction_template:
+ citation_instruction = citation_instruction_template.format(
+ citation_table=citation_table
+ )
+ else:
+ # Fallback if YAML not configured
+ citation_instruction = f"**Citation Reference Table**:\n{citation_table}"
+ citation_output_hint = ", citations"
+ else:
+ citation_instruction = self.get_prompt("citation", "disabled_instruction") or ""
+ citation_output_hint = ""
+
+ # Use safe_format to avoid conflicts with LaTeX braces like {\rho}, {L}
+ block_data_json = _json.dumps(block_data, ensure_ascii=False, indent=2)
+ filled = self._safe_format(
+ tmpl,
+ topic=topic,
+ section_title=section_outline.get("title", block.sub_topic),
+ section_instruction=section_outline.get("instruction", ""),
+ block_data=block_data_json,
+ min_section_length=self.reporting_config.get("min_section_length", 500),
+ citation_instruction=citation_instruction,
+ citation_output_hint=citation_output_hint,
+ )
+
+ resp = await self.call_llm(filled, system_prompt, stage="write_section_body", verbose=False)
+ data = extract_json_from_text(resp)
+
+ try:
+ obj = ensure_json_dict(data)
+ ensure_keys(obj, ["section_content"])
+ content = obj.get("section_content", "")
+ if isinstance(content, str) and content.strip():
+ return content
+ raise ValueError("LLM returned empty or invalid section_content field")
+ except Exception as e:
+ raise ValueError(
+ f"Unable to parse LLM returned section content: {e!s}. Report generation failed."
+ )
+
+ async def _write_conclusion(
+ self, topic: str, blocks: list[TopicBlock], outline: dict[str, Any]
+ ) -> str:
+ """Write report conclusion section"""
+ system_prompt = self.get_prompt(
+ "system",
+ "role",
+ "You are an academic writing expert specializing in writing the conclusion section of research reports.",
+ )
+ tmpl = self.get_prompt("process", "write_conclusion", "")
+ if not tmpl:
+ raise ValueError(
+ "Cannot get conclusion writing prompt template, report generation failed"
+ )
+
+ import json as _json
+
+ # Prepare context for conclusion: key findings of all topics
+ topics_findings = []
+ for b in blocks:
+ findings = {
+ "sub_topic": b.sub_topic,
+ "overview": b.overview,
+ "key_findings": [
+ t.summary for t in b.tool_traces[:3]
+ ], # Top 3 key findings for each topic
+ }
+ topics_findings.append(findings)
+
+ # Use conclusion_instruction if available, otherwise fall back to conclusion title
+ conclusion_instruction = outline.get("conclusion_instruction", "") or outline.get(
+ "conclusion", ""
+ )
+
+ # Use safe_format to avoid conflicts with LaTeX braces like {\rho}, {L}
+ topics_findings_json = _json.dumps(topics_findings, ensure_ascii=False, indent=2)
+ filled = self._safe_format(
+ tmpl,
+ topic=topic,
+ conclusion_instruction=conclusion_instruction,
+ topics_findings=topics_findings_json,
+ total_topics=len(blocks),
+ )
+
+ resp = await self.call_llm(filled, system_prompt, stage="write_conclusion", verbose=False)
+ data = extract_json_from_text(resp)
+
+ try:
+ obj = ensure_json_dict(data)
+ ensure_keys(obj, ["conclusion"])
+ conclusion = obj.get("conclusion", "")
+ if isinstance(conclusion, str) and conclusion.strip():
+ return conclusion
+ raise ValueError("LLM returned empty or invalid conclusion field")
+ except Exception as e:
+ raise ValueError(
+ f"Unable to parse LLM returned conclusion content: {e!s}. Report generation failed."
+ )
+
+ def _build_citation_number_map(self, blocks: list[TopicBlock]) -> dict[str, int]:
+ """Build citation_id to reference number mapping with deduplication
+
+ This method delegates to CitationManager for unified mapping logic.
+ The mapping is built once and cached in CitationManager.
+
+ Returns:
+ Dictionary mapping citation_id (e.g., "CIT-1-01") to reference number (e.g., 1)
+ """
+ if self.citation_manager:
+ # Use CitationManager's unified mapping (single source of truth)
+ return self.citation_manager.build_ref_number_map()
+
+ # Fallback: build from blocks when no CitationManager available
+ citation_map = {}
+
+ def extract_citation_number(cit_id):
+ try:
+ if cit_id.startswith("PLAN-"):
+ num = int(cit_id.replace("PLAN-", ""))
+ return (0, 0, num)
+ parts_list = cit_id.replace("CIT-", "").split("-")
+ if len(parts_list) == 2:
+ return (1, int(parts_list[0]), int(parts_list[1]))
+ except:
+ pass
+ return (999, 999, 999)
+
+ all_citations = []
+ for block in blocks:
+ if block.tool_traces:
+ for trace in block.tool_traces:
+ citation_id = getattr(trace, "citation_id", None)
+ if citation_id and citation_id not in [c["citation_id"] for c in all_citations]:
+ all_citations.append({"citation_id": citation_id})
+
+ all_citations.sort(key=lambda x: extract_citation_number(x["citation_id"]))
+
+ for idx, cit in enumerate(all_citations, 1):
+ citation_map[cit["citation_id"]] = idx
+
+ return citation_map
+
+ def _generate_references(self, blocks: list[TopicBlock]) -> str:
+ """Generate References section"""
+ parts = ["## References\n"]
+
+ # If using CitationManager, generate from JSON file
+ if self.citation_manager:
+ return self._generate_references_from_manager(blocks)
+
+ # Otherwise use original method of extracting from blocks (backward compatible)
+ return self._generate_references_from_blocks(blocks)
+
+ def _get_citation_dedup_key(self, citation: dict, paper: dict = None) -> str:
+ """Generate unique key for citation deduplication
+
+ Args:
+ citation: The citation dict
+ paper: Optional paper dict for paper_search citations
+
+ Returns:
+ Unique string key for deduplication
+ """
+ tool_type = citation.get("tool_type", "").lower()
+
+ if tool_type == "paper_search" and paper:
+ # For papers: use title + first author (normalized)
+ title = paper.get("title", "").lower().strip()
+ authors = paper.get("authors", "").lower().strip()
+ # Extract first author if multiple
+ first_author = authors.split(",")[0].strip() if authors else ""
+ return f"paper:{title}|{first_author}"
+ elif tool_type == "paper_search":
+ # Fallback for paper_search without paper dict
+ title = citation.get("title", "").lower().strip()
+ authors = citation.get("authors", "").lower().strip()
+ first_author = authors.split(",")[0].strip() if authors else ""
+ return f"paper:{title}|{first_author}"
+ else:
+ # For RAG/web_search/etc: use tool_type + query (normalized)
+ query = citation.get("query", "").lower().strip()
+ # Use first 100 chars of query for dedup
+ return f"{tool_type}:{query[:100]}"
+
+ def _generate_references_from_manager(self, blocks: list[TopicBlock]) -> str:
+ """Generate References section from CitationManager in academic paper style
+
+ Uses CitationManager's ref_number_map to ensure consistency between
+ in-text citations and the References section.
+
+ Format:
+ - Ordered by reference number (consistent with in-text citations)
+ - Paper citations: APA format
+ - RAG/Query citations: Tool name, query, summary
+ - Web search: Tool name, query, summary + collapsible links
+ """
+ parts = ["## References\n\n"]
+
+ # Get all citations and the ref_number_map
+ all_citations = self.citation_manager.get_all_citations()
+
+ if not all_citations:
+ return "## References\n\n*No citations available.*\n"
+
+ # Get the ref_number_map from CitationManager (single source of truth)
+ ref_map = self.citation_manager.get_ref_number_map()
+
+ # Build reverse map: ref_number -> (citation_id, paper_idx or None)
+ # This groups citations by their ref_number for consistent output
+ ref_to_citations: dict[int, list[tuple[str, dict, dict | None]]] = {}
+
+ for citation_id, citation in all_citations.items():
+ tool_type = citation.get("tool_type", "").lower()
+
+ if tool_type == "paper_search":
+ papers = citation.get("papers", [])
+ if papers:
+ for paper_idx, paper in enumerate(papers):
+ # Check if this paper has a ref_number
+ paper_ref_key = f"{citation_id}-{paper_idx + 1}"
+ ref_num = ref_map.get(paper_ref_key) or ref_map.get(citation_id, 0)
+ if ref_num > 0:
+ if ref_num not in ref_to_citations:
+ ref_to_citations[ref_num] = []
+ ref_to_citations[ref_num].append((citation_id, citation, paper))
+ else:
+ ref_num = ref_map.get(citation_id, 0)
+ if ref_num > 0:
+ if ref_num not in ref_to_citations:
+ ref_to_citations[ref_num] = []
+ ref_to_citations[ref_num].append((citation_id, citation, None))
+ else:
+ ref_num = ref_map.get(citation_id, 0)
+ if ref_num > 0:
+ if ref_num not in ref_to_citations:
+ ref_to_citations[ref_num] = []
+ ref_to_citations[ref_num].append((citation_id, citation, None))
+
+ # Generate references in order of ref_number
+ for ref_num in sorted(ref_to_citations.keys()):
+ entries = ref_to_citations[ref_num]
+ if not entries:
+ continue
+
+ # Use the first entry for this ref_number (others are duplicates)
+ citation_id, citation, paper = entries[0]
+ tool_type = citation.get("tool_type", "").lower()
+
+ anchor = f"ref-{ref_num}"
+ parts.append(f'<a id="{anchor}"></a>**[{ref_num}]** ')
+
+ if tool_type == "paper_search":
+ if paper:
+ formatted = self._format_single_paper_apa(paper)
+ else:
+ formatted = self._format_paper_citation_apa(citation)
+ parts.append(formatted)
+ elif tool_type == "web_search":
+ formatted = self._format_web_search_citation(citation)
+ parts.append(formatted)
+ elif tool_type in ("rag_naive", "rag_hybrid", "query_item"):
+ formatted = self._format_rag_citation(citation)
+ parts.append(formatted)
+ elif tool_type == "run_code":
+ formatted = self._format_code_citation(citation)
+ parts.append(formatted)
+ else:
+ # Generic format
+ query = citation.get("query", "")
+ summary = citation.get("summary", "")
+ parts.append(f"**{tool_type}**\n\n")
+ parts.append(f"- **Query**: {query}\n")
+ if summary:
+ clean_summary = self._strip_markdown(summary)
+ parts.append(
+ f"- **Summary**: {clean_summary[:300]}{'...' if len(clean_summary) > 300 else ''}\n"
+ )
+
+ parts.append("\n\n")
+
+ return "".join(parts)
+
+ def _format_single_paper_apa(self, paper: dict) -> str:
+ """Format a single paper in APA style
+
+ Format: Authors (Year). *Title*. Venue. arXiv:ID. URL
+ """
+ authors = paper.get("authors", "Unknown Author")
+ year = paper.get("year", "n.d.")
+ title = paper.get("title", "Untitled")
+ url = paper.get("url", "")
+ arxiv_id = paper.get("arxiv_id", "")
+ venue = paper.get("venue", "")
+ doi = paper.get("doi", "")
+
+ # APA format
+ result = f"{authors} ({year}). *{title}*."
+ if venue:
+ result += f" {venue}."
+ if arxiv_id:
+ result += f" arXiv:{arxiv_id}."
+ if doi:
+ result += f" https://doi.org/{doi}"
+ elif url:
+ result += f" {url}"
+
+ return result
+
+ def _format_paper_citation_apa(self, citation: dict) -> str:
+ """Format paper citation in APA style (fallback for citations without papers array)
+
+ Format: Authors (Year). *Title*. Venue. arXiv:ID. URL
+ """
+ # Use top-level fields (backward compatibility)
+ authors = citation.get("authors", "Unknown Author")
+ year = citation.get("year", "n.d.")
+ title = citation.get("title", "Untitled")
+ url = citation.get("url", "")
+ arxiv_id = citation.get("arxiv_id", "")
+ venue = citation.get("venue", "")
+ doi = citation.get("doi", "")
+
+ result = f"{authors} ({year}). *{title}*."
+ if venue:
+ result += f" {venue}."
+ if arxiv_id:
+ result += f" arXiv:{arxiv_id}."
+ if doi:
+ result += f" https://doi.org/{doi}"
+ elif url:
+ result += f" {url}"
+ return result
+
+ def _format_web_search_citation(self, citation: dict) -> str:
+ """Format web search citation with collapsible links"""
+ query = citation.get("query", "")
+ summary = citation.get("summary", "")
+ web_sources = citation.get("web_sources", [])
+
+ result = "**Web Search**\n\n"
+ result += f"- **Query**: {query}\n"
+ if summary:
+ # Clean summary to avoid markdown rendering issues
+ clean_summary = self._strip_markdown(summary)
+ summary_text = clean_summary[:300] + ("..." if len(clean_summary) > 300 else "")
+ result += f"- **Summary**: {summary_text}\n"
+
+ # Add collapsible links section
+ if web_sources:
+ result += "\n<details>\n<summary>📎 Retrieved Sources ({} links)</summary>\n\n".format(
+ len(web_sources)
+ )
+ for i, source in enumerate(web_sources, 1):
+ title = source.get("title", "Untitled")
+ url = source.get("url", "")
+ snippet = source.get("snippet", "")
+ if url:
+ result += f"{i}. [{title}]({url})"
+ if snippet:
+ clean_snippet = self._strip_markdown(snippet)
+ result += f"\n > {clean_snippet[:150]}{'...' if len(clean_snippet) > 150 else ''}"
+ result += "\n\n"
+ result += "</details>"
+
+ return result
+
+ def _format_rag_citation(self, citation: dict) -> str:
+ """Format RAG/Query citation"""
+ tool_type = citation.get("tool_type", "")
+ query = citation.get("query", "")
+ summary = citation.get("summary", "")
+ kb_name = citation.get("kb_name", "")
+ sources = citation.get("sources", [])
+
+ # Tool name display
+ tool_display = {
+ "rag_naive": "RAG Retrieval",
+ "rag_hybrid": "Hybrid RAG Retrieval",
+ "query_item": "Knowledge Base Query",
+ }.get(tool_type, tool_type)
+
+ result = f"**{tool_display}**"
+ if kb_name:
+ result += f" (KB: {kb_name})"
+ result += "\n\n"
+ result += f"- **Query**: {query}\n"
+ if summary:
+ # Clean summary: remove markdown formatting to avoid rendering issues
+ clean_summary = self._strip_markdown(summary)
+ summary_text = clean_summary[:300] + ("..." if len(clean_summary) > 300 else "")
+ result += f"- **Summary**: {summary_text}\n"
+
+ # Add source documents if available
+ if sources:
+ result += "\n<details>\n<summary>📄 Source Documents ({} docs)</summary>\n\n".format(
+ len(sources)
+ )
+ for i, source in enumerate(sources, 1):
+ title = source.get("title", "") or source.get("source_file", f"Document {i}")
+ content = source.get("content_preview", "")
+ page = source.get("page", "")
+ result += f"{i}. **{title}**"
+ if page:
+ result += f" (Page {page})"
+ if content:
+ clean_content = self._strip_markdown(content)
+ result += (
+ f"\n > {clean_content[:150]}{'...' if len(clean_content) > 150 else ''}"
+ )
+ result += "\n\n"
+ result += "</details>"
+
+ return result
+
+ def _strip_markdown(self, text: str) -> str:
+ """Strip markdown formatting from text to get plain text"""
+ import re
+
+ if not text:
+ return ""
+
+ # Remove bold/italic markers
+ text = re.sub(r"\*\*([^*]+)\*\*", r"\1", text) # **bold**
+ text = re.sub(r"\*([^*]+)\*", r"\1", text) # *italic*
+ text = re.sub(r"__([^_]+)__", r"\1", text) # __bold__
+ text = re.sub(r"_([^_]+)_", r"\1", text) # _italic_
+
+ # Remove headers
+ text = re.sub(r"^#{1,6}\s+", "", text, flags=re.MULTILINE)
+
+ # Remove links but keep text
+ text = re.sub(r"\[([^\]]+)\]\([^)]+\)", r"\1", text)
+
+ # Remove inline code
+ text = re.sub(r"`([^`]+)`", r"\1", text)
+
+ # Remove bullet points
+ text = re.sub(r"^[\s]*[-*+]\s+", "", text, flags=re.MULTILINE)
+
+ # Remove numbered lists
+ text = re.sub(r"^[\s]*\d+\.\s+", "", text, flags=re.MULTILINE)
+
+ # Remove blockquotes
+ text = re.sub(r"^>\s*", "", text, flags=re.MULTILINE)
+
+ # Normalize whitespace
+ text = re.sub(r"\n{3,}", "\n\n", text)
+ text = re.sub(r" +", " ", text)
+
+ return text.strip()
+
+ def _format_code_citation(self, citation: dict) -> str:
+ """Format code execution citation"""
+ query = citation.get("query", "") # This is usually the code
+ summary = citation.get("summary", "")
+
+ result = "**Code Execution**\n\n"
+ if query:
+ # Truncate long code
+ code_preview = query[:300] + ("..." if len(query) > 300 else "")
+ result += f"- **Code**: `{code_preview}`\n"
+ if summary:
+ summary_text = summary[:300] + ("..." if len(summary) > 300 else "")
+ result += f"- **Result**: {summary_text}\n"
+
+ return result
+
+ def _generate_references_from_blocks(self, blocks: list[TopicBlock]) -> str:
+ """Generate References section from blocks (backward compatible, academic paper style)"""
+ parts = ["## References\n\n"]
+
+ # Collect all citations
+ all_citations = []
+ for block in blocks:
+ if block.tool_traces:
+ for trace in block.tool_traces:
+ citation_id = (
+ getattr(trace, "citation_id", None)
+ or f"CIT-{block.block_id.split('_')[-1]}-01"
+ )
+ all_citations.append(
+ {"citation_id": citation_id, "block": block, "trace": trace}
+ )
+
+ if not all_citations:
+ return "## References\n\n*No citations available.*\n"
+
+ # Sort by citation_id (extract numeric parts for sorting)
+ def extract_citation_number(cit_id):
+ try:
+ if cit_id.startswith("PLAN-"):
+ num = int(cit_id.replace("PLAN-", ""))
+ return (0, 0, num)
+ # CIT-X-XX format
+ parts_list = cit_id.replace("CIT-", "").split("-")
+ if len(parts_list) == 2:
+ return (1, int(parts_list[0]), int(parts_list[1]))
+ except:
+ pass
+ return (999, 999, 999)
+
+ all_citations.sort(key=lambda x: extract_citation_number(x["citation_id"]))
+
+ # Generate numbered references in academic paper style
+ # Using simple ref-N anchor format for clickable inline citations
+ for idx, cit in enumerate(all_citations, 1):
+ trace = cit["trace"]
+ citation_id = cit["citation_id"]
+
+ # Use simple ref-N anchor format (consistent with _generate_references_from_manager)
+ anchor = f"ref-{idx}"
+ tool_type = trace.tool_type.lower() if trace.tool_type else ""
+
+ # Tool name display
+ tool_display = {
+ "rag_naive": "RAG Retrieval",
+ "rag_hybrid": "Hybrid RAG Retrieval",
+ "query_item": "Knowledge Base Query",
+ "paper_search": "Paper Search",
+ "web_search": "Web Search",
+ "run_code": "Code Execution",
+ }.get(tool_type, tool_type)
+
+ parts.append(f'<a id="{anchor}"></a>**[{idx}]** **{tool_display}**\n\n')
+ parts.append(f"- **Query**: {trace.query}\n")
+ if trace.summary:
+ summary_text = trace.summary[:500] + ("..." if len(trace.summary) > 500 else "")
+ parts.append(f"- **Summary**: {summary_text}\n")
+ parts.append("\n")
+
+ return "".join(parts)
+
+ def _convert_citation_format(self, text: str) -> str:
+ """
+ Convert various citation formats to clickable [[N]](#ref-N) format.
+
+ Handles:
+ - [N] format (simple number in brackets)
+ - [ref=N] format (from citation table)
+
+ Args:
+ text: Text with citations in various formats
+
+ Returns:
+ Text with [[N]](#ref-N) clickable citations
+ """
+ import re
+
+ # Get valid ref_numbers from the citation map
+ valid_refs = set()
+ if hasattr(self, "_citation_map") and self._citation_map:
+ valid_refs = set(self._citation_map.values())
+
+ def replace_citation(match):
+ # Get the number from the match
+ ref_num = match.group(1)
+
+ # Only convert if it's a valid ref_number
+ try:
+ num = int(ref_num)
+ if num in valid_refs:
+ return f"[[{ref_num}]](#ref-{ref_num})"
+ except ValueError:
+ pass
+
+ # Return unchanged if not a valid reference
+ return match.group(0)
+
+ # First, convert [ref=N] format to clickable format
+ # Pattern: [ref=N] where N is a number
+ ref_pattern = r"\[ref=(\d+)\]"
+ text = re.sub(ref_pattern, replace_citation, text)
+
+ # Then, convert simple [N] format (but NOT already converted [[N]])
+ # Pattern to match [N] where N is a number, but NOT already in [[N]] format
+ # Use negative lookbehind and lookahead to avoid matching [[N]] or [N](#ref-N)
+ simple_pattern = r"(?<!\[)\[(\d+)\](?!\(#ref-)"
+ text = re.sub(simple_pattern, replace_citation, text)
+
+ return text
+
+ def _validate_and_fix_citations(self, text: str) -> tuple[str, dict]:
+ """
+ Validate citations in text and fix invalid ones.
+
+ Args:
+ text: Text with citations
+
+ Returns:
+ Tuple of (fixed_text, validation_result)
+ """
+ import re
+
+ # Get valid ref_numbers
+ valid_refs = set()
+ if hasattr(self, "_citation_map") and self._citation_map:
+ valid_refs = set(self._citation_map.values())
+
+ # Find all citations in [[N]](#ref-N) format
+ pattern = r"\[\[(\d+)\]\]\(#ref-\d+\)"
+ found_citations = re.findall(pattern, text)
+
+ valid = []
+ invalid = []
+
+ for ref in found_citations:
+ try:
+ num = int(ref)
+ if num in valid_refs:
+ valid.append(num)
+ else:
+ invalid.append(num)
+ except ValueError:
+ invalid.append(ref)
+
+ # Remove invalid citations
+ if invalid:
+
+ def remove_invalid(match):
+ ref_num = match.group(1)
+ try:
+ num = int(ref_num)
+ if num not in valid_refs:
+ return "" # Remove invalid citation
+ except ValueError:
+ return ""
+ return match.group(0)
+
+ text = re.sub(pattern, remove_invalid, text)
+
+ validation_result = {
+ "valid_citations": valid,
+ "invalid_citations": invalid,
+ "is_valid": len(invalid) == 0,
+ "total_found": len(found_citations),
+ }
+
+ return text, validation_result
+
+ async def _write_report(
+ self, topic: str, blocks: list[TopicBlock], outline: dict[str, Any]
+ ) -> str:
+ """Write complete report using step-by-step method with three-level heading support"""
+ parts = []
+
+ # Build citation number map before writing (for consistent ref_number in traces)
+ if self.enable_inline_citations:
+ self._citation_map = self._build_citation_number_map(blocks)
+ print(f" 📋 Built citation map with {len(self._citation_map)} entries")
+ else:
+ self._citation_map = {}
+
+ # 1. Add main title (from outline, or use topic if not available)
+ title = outline.get("title", f"# {topic}")
+ if not title.startswith("#"):
+ title = f"# {title}"
+ parts.append(f"{title}\n\n")
+
+ # 2. Write introduction
+ print(" 📝 Writing introduction...")
+ self._notify_progress(
+ getattr(self, "_progress_callback", None),
+ "writing_section",
+ current_section="Introduction",
+ section_index=0,
+ total_sections=len(outline.get("sections", [])) + 2, # +2 for intro and conclusion
+ )
+ introduction = await self._write_introduction(topic, blocks, outline)
+ # Get introduction title from outline, or use default if not available
+ intro_title = outline.get("introduction", "## Introduction")
+ if not intro_title.startswith("##"):
+ intro_title = f"## {intro_title}"
+ parts.append(f"{intro_title}\n\n")
+ parts.append(introduction)
+ parts.append("\n\n")
+
+ # 3. Write each section with subsection support
+ sections = outline.get("sections", [])
+ for i, section in enumerate(sections, 1):
+ block_id = section.get("block_id")
+ block = next((b for b in blocks if b.block_id == block_id), None)
+ if not block:
+ print(
+ f" ⚠️ Warning: Cannot find topic block with block_id={block_id}, skipping this section"
+ )
+ continue
+
+ section_title = section.get("title", block.sub_topic)
+ # Clean section title for display (remove markdown markers)
+ display_title = section_title.replace("##", "").strip()
+ print(f" 📝 Writing section {i}/{len(sections)}: {section_title}...")
+ self._notify_progress(
+ getattr(self, "_progress_callback", None),
+ "writing_section",
+ current_section=display_title,
+ section_index=i, # 1-based, after introduction
+ total_sections=len(sections) + 2, # +2 for intro and conclusion
+ )
+
+ # Check if section has subsections defined in outline
+ subsections = section.get("subsections", [])
+
+ if subsections:
+ # Write section with explicit subsection structure
+ section_content = await self._write_section_with_subsections(
+ topic, block, section, subsections
+ )
+ else:
+ # Write section normally (LLM will generate its own subsection structure)
+ section_content = await self._write_section_body(topic, block, section)
+
+ # Section content already includes ## level title, append directly
+ parts.append(section_content)
+ parts.append("\n\n")
+
+ # 4. Write conclusion
+ print(" 📝 Writing conclusion...")
+ total_sections = len(sections) + 2
+ self._notify_progress(
+ getattr(self, "_progress_callback", None),
+ "writing_section",
+ current_section="Conclusion",
+ section_index=total_sections - 1, # Last section
+ total_sections=total_sections,
+ )
+ conclusion = await self._write_conclusion(topic, blocks, outline)
+ # Get conclusion title from outline, or use default if not available
+ conclusion_title = outline.get("conclusion", "## Conclusion")
+ if not conclusion_title.startswith("##"):
+ conclusion_title = f"## {conclusion_title}"
+ parts.append(f"{conclusion_title}\n\n")
+ parts.append(conclusion)
+ parts.append("\n\n")
+
+ # 5. Generate References based on configuration
+ if self.enable_citation_list:
+ print(" 📝 Generating citation list...")
+ references = self._generate_references(blocks)
+ parts.append(references)
+ else:
+ print(" ℹ️ Citation list disabled, skipping generation")
+
+ # Combine all parts
+ report = "".join(parts)
+
+ # 6. Post-process citations (convert [N] to [[N]](#ref-N) format)
+ if self.enable_inline_citations:
+ print(" 🔗 Converting citation format...")
+ report = self._convert_citation_format(report)
+
+ # Validate and fix invalid citations
+ print(" ✓ Validating citations...")
+ report, validation = self._validate_and_fix_citations(report)
+
+ if not validation["is_valid"]:
+ print(
+ f" ⚠️ Removed {len(validation['invalid_citations'])} invalid citations: {validation['invalid_citations']}"
+ )
+ else:
+ print(f" ✓ All {validation['total_found']} citations are valid")
+
+ return report
+
+ async def _write_section_with_subsections(
+ self,
+ topic: str,
+ block: TopicBlock,
+ section: dict[str, Any],
+ subsections: list[dict[str, Any]],
+ ) -> str:
+ """Write a section that has explicitly defined subsections in the outline
+
+ This method writes the section as a whole, passing subsection structure to the LLM
+ to guide the content organization while maintaining coherence.
+ """
+ import json as _json
+
+ # Enhance section instruction with subsection information
+ subsection_info = []
+ for j, sub in enumerate(subsections, 1):
+ subsection_info.append(
+ {
+ "title": sub.get("title", f"### Subsection {j}"),
+ "instruction": sub.get("instruction", ""),
+ }
+ )
+
+ # Create enhanced section data with subsection guidance
+ enhanced_section = {
+ "title": section.get("title", block.sub_topic),
+ "instruction": section.get("instruction", ""),
+ "subsection_structure": subsection_info,
+ }
+
+ # Prepare block data with subsection hints
+ block_data = self._ser_block(block)
+ block_data["expected_subsections"] = subsection_info
+
+ system_prompt = self.get_prompt(
+ "system",
+ "role",
+ "You are an academic writing expert specializing in writing comprehensive research report sections with structured subsections.",
+ )
+ tmpl = self.get_prompt("process", "write_section_body", "")
+ if not tmpl:
+ raise ValueError("Cannot get section writing prompt template, report generation failed")
+
+ # Build enhanced instruction including subsection structure
+ section_instruction = section.get("instruction", "")
+ if subsection_info:
+ subsection_guide = "\n\n**Expected subsection structure:**\n"
+ for sub in subsection_info:
+ subsection_guide += f"- {sub['title']}: {sub['instruction']}\n"
+ section_instruction += subsection_guide
+
+ # Dynamically build citation instructions based on configuration
+ if self.enable_inline_citations:
+ # Build clear citation reference table for this block
+ citation_table = self._build_citation_table(block)
+
+ citation_instruction_template = self.get_prompt("citation", "enabled_instruction")
+ if citation_instruction_template:
+ citation_instruction = citation_instruction_template.format(
+ citation_table=citation_table
+ )
+ else:
+ # Fallback if YAML not configured
+ citation_instruction = f"**Citation Reference Table**:\n{citation_table}"
+ citation_output_hint = ", citations"
+ else:
+ citation_instruction = self.get_prompt("citation", "disabled_instruction") or ""
+ citation_output_hint = ""
+
+ # Use safe_format to avoid conflicts with LaTeX braces like {\rho}, {L}
+ block_data_json = _json.dumps(block_data, ensure_ascii=False, indent=2)
+ filled = self._safe_format(
+ tmpl,
+ topic=topic,
+ section_title=section.get("title", block.sub_topic),
+ section_instruction=section_instruction,
+ block_data=block_data_json,
+ min_section_length=self.reporting_config.get("min_section_length", 800),
+ citation_instruction=citation_instruction,
+ citation_output_hint=citation_output_hint,
+ )
+
+ resp = await self.call_llm(
+ filled,
+ system_prompt,
+ stage="write_section_with_subsections",
+ verbose=False,
+ )
+ data = extract_json_from_text(resp)
+
+ try:
+ obj = ensure_json_dict(data)
+ ensure_keys(obj, ["section_content"])
+ content = obj.get("section_content", "")
+ if isinstance(content, str) and content.strip():
+ return content
+ raise ValueError("LLM returned empty or invalid section_content field")
+ except Exception as e:
+ raise ValueError(
+ f"Unable to parse LLM returned section content: {e!s}. Report generation failed."
+ )
+
+ def _notify_progress(
+ self, callback: Callable[[dict[str, Any]], None] | None, status: str, **payload: Any
+ ) -> None:
+ if not callback:
+ return
+ event = {"status": status}
+ event.update({k: v for k, v in payload.items() if v is not None})
+ try:
+ callback(event)
+ except Exception:
+ pass
+
+
+__all__ = ["ReportingAgent"]
diff --git a/src/agents/research/agents/research_agent.py b/src/agents/research/agents/research_agent.py
new file mode 100644
index 000000000..688a3d461
--- /dev/null
+++ b/src/agents/research/agents/research_agent.py
@@ -0,0 +1,700 @@
+#!/usr/bin/env python
+"""
+ResearchAgent - Research Agent
+Responsible for executing research logic and tool call decisions
+"""
+
+from collections.abc import Awaitable, Callable
+from pathlib import Path
+import re
+from string import Template
+import sys
+from typing import Any
+
+project_root = Path(__file__).parent.parent.parent.parent
+sys.path.insert(0, str(project_root))
+
+from src.agents.research.data_structures import DynamicTopicQueue, TopicBlock
+
+from ..utils.json_utils import extract_json_from_text
+from .base_agent import BaseAgent
+
+
+class ResearchAgent(BaseAgent):
+ """Research Agent"""
+
+ def __init__(self, config: dict[str, Any], api_key: str = None, base_url: str = None):
+ super().__init__(
+ config=config, api_key=api_key, base_url=base_url, agent_name="research_agent"
+ )
+ self.researching_config = config.get("researching", {})
+ self.max_iterations = self.researching_config.get("max_iterations", 5)
+ # Iteration mode: "fixed" (must explore all iterations) or "flexible" (can stop early)
+ # In "fixed" mode, agent should be more conservative about declaring knowledge sufficient
+ # In "flexible" mode (auto), agent can stop early when knowledge is truly sufficient
+ self.iteration_mode = self.researching_config.get("iteration_mode", "fixed")
+ # Tool availability configuration
+ self.enable_rag = self.researching_config.get(
+ "enable_rag_hybrid", True
+ ) or self.researching_config.get("enable_rag_naive", True)
+ # Web search: global switch (tools.web_search.enabled) has higher priority
+ # Only enabled when both global switch and module switch are True
+ tools_web_search_enabled = (
+ config.get("tools", {}).get("web_search", {}).get("enabled", True)
+ )
+ research_web_search_enabled = self.researching_config.get("enable_web_search", False)
+ self.enable_web_search = tools_web_search_enabled and research_web_search_enabled
+ self.enable_paper_search = self.researching_config.get("enable_paper_search", False)
+ self.enable_run_code = self.researching_config.get("enable_run_code", True)
+ # Store enabled tools list for prompt generation
+ self.enabled_tools = self.researching_config.get("enabled_tools", ["RAG"])
+
+ @staticmethod
+ def _convert_to_template_format(template_str: str) -> str:
+ """
+ Convert {var} style placeholders to $var style for string.Template.
+ This avoids conflicts with LaTeX braces like {\rho}.
+ """
+ # Only convert simple {var_name} patterns, not nested or complex ones
+ return re.sub(r"\{(\w+)\}", r"$\1", template_str)
+
+ def _safe_format(self, template_str: str, **kwargs) -> str:
+ """
+ Safe string formatting using string.Template to avoid LaTeX brace conflicts.
+ """
+ converted = self._convert_to_template_format(template_str)
+ return Template(converted).safe_substitute(**kwargs)
+
+ def _generate_available_tools_text(self) -> str:
+ """
+ Generate available tools list based on enabled_tools configuration
+
+ Returns:
+ Available tools text for prompt
+ """
+ tools = []
+ if self.enable_rag:
+ tools.append(
+ "- rag_hybrid: Hybrid RAG retrieval (knowledge base) | Query format: Natural language"
+ )
+ tools.append(
+ "- rag_naive: Basic RAG retrieval (knowledge base) | Query format: Natural language"
+ )
+ tools.append(
+ "- query_item: Entity/item query (e.g., Theorem 3.1, Fig 2.1) | Query format: Entry number"
+ )
+ if self.enable_paper_search:
+ tools.append(
+ "- paper_search: Academic paper search | Query format: 3-5 English keywords, space-separated"
+ )
+ if self.enable_web_search:
+ tools.append(
+ "- web_search: Web search for latest information | Query format: Natural language"
+ )
+ if self.enable_run_code:
+ tools.append(
+ "- run_code: Code execution for calculation/visualization | Query format: Python code"
+ )
+
+ if not tools:
+ tools.append(
+ "- rag_hybrid: Hybrid RAG retrieval (default) | Query format: Natural language"
+ )
+
+ return "\n".join(tools)
+
+ def _generate_tool_phase_guidance(self) -> str:
+ """
+ Generate phased tool selection guidance based on enabled tools.
+ Only includes guidance for tools that are actually enabled.
+
+ Returns:
+ Tool phase guidance text for prompt
+ """
+ # Determine which tool categories are enabled
+ has_rag = self.enable_rag
+ has_paper = self.enable_paper_search
+ has_web = self.enable_web_search
+ has_code = self.enable_run_code
+
+ # Build phase guidance dynamically based on enabled tools
+ guidance_parts = []
+
+ # Phase 1: Basic exploration (always includes RAG if enabled)
+ phase1_tools = []
+ if has_rag:
+ phase1_tools.append(
+ "- `rag_hybrid`: Get comprehensive information, core concepts, mechanism principles"
+ )
+ phase1_tools.append("- `rag_naive`: Query specific definitions, precise formulas")
+ phase1_tools.append(
+ "- `query_item`: Get content with specific entry numbers (if known)"
+ )
+
+ if phase1_tools:
+ guidance_parts.append(f"""**Phase 1: Basic Exploration (early iterations)**
+Focus on building foundational knowledge:
+{chr(10).join(phase1_tools)}""")
+
+ # Phase 2: Deep mining (introduce external tools if enabled)
+ phase2_tools = []
+ if has_rag:
+ phase2_tools.append(
+ "- Continue using `rag_hybrid` to explore different angles (applications, relationships, comparisons)"
+ )
+ if has_paper:
+ phase2_tools.append(
+ "- `paper_search`: Get cutting-edge academic research (if topic involves academic fields)"
+ )
+ if has_web:
+ phase2_tools.append("- `web_search`: Get practical application cases, industry trends")
+
+ if phase2_tools:
+ guidance_parts.append(f"""**Phase 2: Deep Mining (middle iterations)**
+Deep dive and expand knowledge:
+{chr(10).join(phase2_tools)}""")
+
+ # Phase 3: Completion (all available external tools)
+ phase3_tools = []
+ if has_paper:
+ phase3_tools.append(
+ "- `paper_search`: Cutting-edge research, specific methods, experimental results"
+ )
+ if has_web:
+ phase3_tools.append(
+ "- `web_search`: Latest developments, practical cases, industry applications"
+ )
+ if has_code:
+ phase3_tools.append(
+ "- `run_code`: Algorithm verification, numerical calculation, visualization"
+ )
+
+ if phase3_tools:
+ guidance_parts.append(f"""**Phase 3: Completion and Supplement (late iterations)**
+Fill gaps and expand horizons:
+{chr(10).join(phase3_tools)}""")
+
+ # If no external tools enabled, add a note
+ if not has_paper and not has_web:
+ guidance_parts.append("""**Note**: Only knowledge base tools (RAG) are available.
+Focus on thoroughly exploring the knowledge base from multiple angles.""")
+
+ return "\n\n".join(guidance_parts)
+
+ def _generate_research_depth_guidance(self, iteration: int, used_tools: list[str]) -> str:
+ """
+ Generate research depth guidance based on iteration, used tools, and iteration_mode
+
+ Args:
+ iteration: Current iteration number
+ used_tools: List of tools already used
+
+ Returns:
+ Research depth guidance text
+ """
+ # Determine research phase based on max_iterations
+ early_threshold = max(2, self.max_iterations // 3)
+ middle_threshold = max(4, self.max_iterations * 2 // 3)
+
+ if iteration <= early_threshold:
+ phase = "early"
+ phase_desc = f"Early Stage (Iteration 1-{early_threshold})"
+ guidance = "Focus on building foundational knowledge using RAG/knowledge base tools."
+ elif iteration <= middle_threshold:
+ phase = "middle"
+ phase_desc = f"Middle Stage (Iteration {early_threshold + 1}-{middle_threshold})"
+ if self.enable_paper_search or self.enable_web_search:
+ guidance = "Consider using Paper/Web search to add academic depth and real-time information."
+ else:
+ guidance = "Deepen knowledge coverage, explore different angles of the topic."
+ else:
+ phase = "late"
+ phase_desc = f"Late Stage (Iteration {middle_threshold + 1}+)"
+ guidance = "Fill knowledge gaps, ensure completeness before concluding."
+
+ # Tool diversity analysis
+ unique_tools = set(used_tools)
+ available_tools = []
+ if self.enable_rag and not any(
+ t in unique_tools for t in ["rag_hybrid", "rag_naive", "query_item"]
+ ):
+ available_tools.append("RAG tools (rag_hybrid/rag_naive/query_item)")
+ if self.enable_paper_search and "paper_search" not in unique_tools:
+ available_tools.append("paper_search")
+ if self.enable_web_search and "web_search" not in unique_tools:
+ available_tools.append("web_search")
+
+ diversity_hint = ""
+ if available_tools and phase != "early":
+ diversity_hint = f"\n**Tool Diversity Suggestion**: Consider using unexplored tools: {', '.join(available_tools)}"
+
+ # Iteration mode specific guidance
+ if self.iteration_mode == "flexible":
+ # Auto/flexible mode: agent can decide when to stop
+ mode_guidance = """
+**Iteration Mode: FLEXIBLE (Auto)**
+You have autonomy to decide when knowledge is sufficient. You may stop early if:
+- Core concepts are well covered from multiple angles
+- Key questions about the topic have been addressed
+- Further iterations would only add marginal value
+However, ensure you have made meaningful exploration before concluding."""
+ else:
+ # Fixed mode: more conservative about stopping
+ mode_guidance = """
+**Iteration Mode: FIXED**
+This mode requires thorough exploration. Be CONSERVATIVE about declaring knowledge sufficient:
+- In early iterations (first third), rarely conclude sufficiency
+- In middle iterations, require strong evidence of comprehensive coverage
+- Only in late iterations, conclude if truly comprehensive"""
+
+ return f"""
+**Research Phase Guidance** ({phase_desc}):
+{guidance}
+
+Current iteration: {iteration}/{self.max_iterations}
+Tools already used: {", ".join(used_tools) if used_tools else "None"}
+{diversity_hint}
+{mode_guidance}
+"""
+
+ def _generate_online_search_instruction(self) -> str:
+ """
+ Generate online search guidance instructions from YAML config
+
+ Returns:
+ Online search guidance text, returns empty string if not enabled
+ """
+ if not self.enable_web_search and not self.enable_paper_search:
+ return ""
+
+ if self.enable_web_search and self.enable_paper_search:
+ instruction = self.get_prompt("guidance", "online_search_both")
+ if instruction:
+ return instruction
+ elif self.enable_web_search:
+ instruction = self.get_prompt("guidance", "online_search_web_only")
+ if instruction:
+ return instruction
+ elif self.enable_paper_search:
+ instruction = self.get_prompt("guidance", "online_search_paper_only")
+ if instruction:
+ return instruction
+
+ return ""
+
+ def _generate_iteration_mode_criteria(self, iteration: int) -> str:
+ """
+ Generate iteration mode specific criteria for sufficiency check from YAML config
+
+ Args:
+ iteration: Current iteration number
+
+ Returns:
+ Iteration mode criteria text
+ """
+ # Calculate early threshold
+ early_threshold = max(2, self.max_iterations // 3)
+
+ if self.iteration_mode == "flexible":
+ criteria = self.get_prompt("guidance", "iteration_mode_flexible")
+ if criteria:
+ return criteria
+ # Fallback if YAML not configured
+ return "- **FLEXIBLE mode (Auto)**: You have autonomy to decide sufficiency."
+ else:
+ criteria = self.get_prompt("guidance", "iteration_mode_fixed")
+ if criteria:
+ return criteria.format(early_threshold=early_threshold)
+ # Fallback if YAML not configured
+ return f"- **FIXED mode**: Be CONSERVATIVE about declaring sufficiency. Early threshold: {early_threshold}"
+
+ async def check_sufficiency(
+ self,
+ topic: str,
+ overview: str,
+ current_knowledge: str,
+ iteration: int,
+ used_tools: list[str] | None = None,
+ ) -> dict[str, Any]:
+ system_prompt = self.get_prompt("system", "role")
+ if not system_prompt:
+ raise ValueError(
+ "ResearchAgent missing system prompt, please configure system.role in prompts/{lang}/research_agent.yaml"
+ )
+ user_prompt_template = self.get_prompt("process", "check_sufficiency")
+ if not user_prompt_template:
+ raise ValueError(
+ "ResearchAgent missing check_sufficiency prompt, please configure process.check_sufficiency in prompts/{lang}/research_agent.yaml"
+ )
+
+ # Generate online search guidance (if web_search or paper_search is enabled)
+ online_search_instruction = self._generate_online_search_instruction()
+
+ # Generate research depth guidance
+ research_depth_guidance = self._generate_research_depth_guidance(
+ iteration, used_tools or []
+ )
+
+ # Generate iteration mode specific criteria
+ iteration_mode_criteria = self._generate_iteration_mode_criteria(iteration)
+
+ # Use safe_format to avoid conflicts with LaTeX braces like {\rho}
+ user_prompt = self._safe_format(
+ user_prompt_template,
+ topic=topic,
+ overview=overview,
+ current_knowledge=current_knowledge if current_knowledge else "(None)",
+ iteration=iteration,
+ max_iterations=self.max_iterations,
+ online_search_instruction=online_search_instruction,
+ research_depth_guidance=research_depth_guidance,
+ iteration_mode_criteria=iteration_mode_criteria,
+ )
+ response = await self.call_llm(
+ user_prompt=user_prompt,
+ system_prompt=system_prompt,
+ stage="check_sufficiency",
+ verbose=False,
+ )
+ from ..utils.json_utils import ensure_json_dict, ensure_keys
+
+ data = extract_json_from_text(response)
+ obj = ensure_json_dict(data)
+ ensure_keys(obj, ["is_sufficient", "reason"])
+ return obj
+
+ async def generate_query_plan(
+ self,
+ topic: str,
+ overview: str,
+ current_knowledge: str,
+ iteration: int,
+ existing_topics: list[str] | None = None,
+ used_tools: list[str] | None = None,
+ ) -> dict[str, Any]:
+ system_prompt = self.get_prompt("system", "role")
+ if not system_prompt:
+ raise ValueError(
+ "ResearchAgent missing system prompt, please configure system.role in prompts/{lang}/research_agent.yaml"
+ )
+ user_prompt_template = self.get_prompt("process", "generate_query_plan")
+ if not user_prompt_template:
+ raise ValueError(
+ "ResearchAgent missing generate_query_plan prompt, please configure process.generate_query_plan in prompts/{lang}/research_agent.yaml"
+ )
+ topics_text = "(No other topics)"
+ if existing_topics:
+ topics_text = "\n".join([f"- {t}" for t in existing_topics])
+
+ # Generate available tools list based on configuration (only enabled tools)
+ available_tools_text = self._generate_available_tools_text()
+
+ # Generate tool phase guidance based on enabled tools
+ tool_phase_guidance = self._generate_tool_phase_guidance()
+
+ # Generate research depth guidance
+ research_depth_guidance = self._generate_research_depth_guidance(
+ iteration, used_tools or []
+ )
+
+ # Use safe_format to avoid conflicts with LaTeX braces like {\rho}
+ user_prompt = self._safe_format(
+ user_prompt_template,
+ topic=topic,
+ overview=overview,
+ current_knowledge=current_knowledge[:2000] if current_knowledge else "(None)",
+ iteration=iteration,
+ max_iterations=self.max_iterations,
+ existing_topics=topics_text,
+ available_tools=available_tools_text,
+ tool_phase_guidance=tool_phase_guidance,
+ research_depth_guidance=research_depth_guidance,
+ )
+ response = await self.call_llm(
+ user_prompt=user_prompt,
+ system_prompt=system_prompt,
+ stage="generate_query_plan",
+ verbose=False,
+ )
+ from ..utils.json_utils import ensure_json_dict, ensure_keys
+
+ data = extract_json_from_text(response)
+ obj = ensure_json_dict(data)
+ ensure_keys(obj, ["query", "tool_type", "rationale"])
+ return obj
+
+ async def process(
+ self,
+ topic_block: TopicBlock,
+ call_tool_callback: Callable[[str, str], Awaitable[str]],
+ note_agent,
+ citation_manager,
+ queue: DynamicTopicQueue,
+ manager_agent,
+ config: dict[str, Any],
+ progress_callback: Callable[[str, Any], None] | None = None,
+ ) -> dict[str, Any]:
+ """
+ Execute research for a single topic block (complete multi-round retrieval loop)
+
+ Args:
+ topic_block: Topic block to research
+ call_tool_callback: Tool call callback function (tool_type, query) -> raw_answer
+ note_agent: NoteAgent instance for generating summaries
+ citation_manager: CitationManager instance for managing citations
+ queue: DynamicTopicQueue instance for getting existing topic list
+ manager_agent: ManagerAgent instance for adding new topics
+ config: Configuration dictionary for getting parameters
+ progress_callback: Optional callback for iteration progress (event_type, **data)
+
+ Returns:
+ Research result
+ {
+ "block_id": str,
+ "iterations": int,
+ "final_knowledge": str,
+ "tools_used": List[str],
+ "queries_used": List[dict],
+ "status": str
+ }
+ """
+ block_id_prefix = f"[{topic_block.block_id}]"
+ print(f"\n{block_id_prefix} {'=' * 70}")
+ print(f"{block_id_prefix} 🔬 ResearchAgent - Executing Research")
+ print(f"{block_id_prefix} {'=' * 70}")
+ print(f"{block_id_prefix} Topic: {topic_block.sub_topic}")
+ print(f"{block_id_prefix} Overview: {topic_block.overview}")
+ print(
+ f"{block_id_prefix} Max iterations: {self.max_iterations}, Mode: {self.iteration_mode}\n"
+ )
+
+ iteration = 0
+ current_knowledge = ""
+ tools_used = []
+ queries_used = [] # Track all queries for progress display
+
+ # Helper to send progress updates
+ def send_progress(event_type: str, **data):
+ if progress_callback:
+ try:
+ progress_callback(event_type, **data)
+ except Exception:
+ pass # Ignore callback errors
+
+ while iteration < self.max_iterations:
+ iteration += 1
+ print(f"{block_id_prefix} \n【Iteration {iteration}/{self.max_iterations}】")
+
+ # Send iteration started progress
+ send_progress(
+ "iteration_started",
+ iteration=iteration,
+ max_iterations=self.max_iterations,
+ tools_used=tools_used.copy(),
+ )
+
+ # Step 1: Check if knowledge is sufficient
+ send_progress(
+ "checking_sufficiency", iteration=iteration, max_iterations=self.max_iterations
+ )
+ suff = await self.check_sufficiency(
+ topic=topic_block.sub_topic,
+ overview=topic_block.overview,
+ current_knowledge=current_knowledge,
+ iteration=iteration,
+ used_tools=tools_used,
+ )
+
+ if suff.get("is_sufficient", False):
+ print(
+ f"{block_id_prefix} ✓ Current topic is sufficient, ending research for this topic"
+ )
+ send_progress(
+ "knowledge_sufficient",
+ iteration=iteration,
+ max_iterations=self.max_iterations,
+ reason=suff.get("reason", ""),
+ )
+ break
+
+ # Step 2: Generate query plan
+ send_progress(
+ "generating_query", iteration=iteration, max_iterations=self.max_iterations
+ )
+ plan = await self.generate_query_plan(
+ topic=topic_block.sub_topic,
+ overview=topic_block.overview,
+ current_knowledge=current_knowledge,
+ iteration=iteration,
+ existing_topics=queue.list_topics(),
+ used_tools=tools_used,
+ )
+
+ # Dynamic splitting: if new topic is discovered, add to queue tail
+ new_topic = plan.get("new_sub_topic")
+ new_overview = plan.get("new_overview")
+ new_topic_score = float(plan.get("new_topic_score") or 0)
+ should_add_new_topic = plan.get("should_add_new_topic")
+ min_score = config.get("researching", {}).get("new_topic_min_score", 0.75)
+ new_topic_reason = plan.get("new_topic_reason")
+
+ if isinstance(new_topic, str) and new_topic.strip():
+ trimmed_topic = new_topic.strip()
+ if should_add_new_topic is False:
+ print(
+ f"{block_id_prefix} ↩️ LLM determined not to add new topic《{trimmed_topic}》, skipping"
+ )
+ elif new_topic_score < min_score:
+ print(
+ f"{block_id_prefix} ↩️ New topic《{trimmed_topic}》score {new_topic_score:.2f} below threshold {min_score:.2f}, skipping"
+ )
+ else:
+ # Support both sync and async manager_agent
+ import inspect
+
+ add_topic_method = getattr(manager_agent, "add_new_topic")
+ if inspect.iscoroutinefunction(add_topic_method):
+ added = await add_topic_method(trimmed_topic, new_overview or "")
+ else:
+ added = manager_agent.add_new_topic(trimmed_topic, new_overview or "")
+ if added:
+ print(f"{block_id_prefix} ➕ Added new topic《{trimmed_topic}》to queue")
+ send_progress(
+ "new_topic_added",
+ iteration=iteration,
+ max_iterations=self.max_iterations,
+ new_topic=trimmed_topic,
+ new_overview=new_overview or "",
+ )
+ if new_topic_reason:
+ print(f"{block_id_prefix} Reason: {new_topic_reason}")
+
+ query = plan.get("query", "").strip()
+ tool_type = plan.get("tool_type", "rag_hybrid")
+ rationale = plan.get("rationale", "")
+
+ if not query:
+ print(f"{block_id_prefix} ⚠️ Generated query is empty, skipping this iteration")
+ send_progress(
+ "query_empty", iteration=iteration, max_iterations=self.max_iterations
+ )
+ continue
+
+ # Track this query
+ query_info = {
+ "query": query,
+ "tool_type": tool_type,
+ "rationale": rationale,
+ "iteration": iteration,
+ }
+ queries_used.append(query_info)
+
+ # Send progress before tool call
+ send_progress(
+ "tool_calling",
+ iteration=iteration,
+ max_iterations=self.max_iterations,
+ tool_type=tool_type,
+ query=query,
+ rationale=rationale,
+ )
+
+ # Step 3: Call tool
+ raw_answer = await call_tool_callback(tool_type, query)
+
+ # Send progress after tool call
+ send_progress(
+ "tool_completed",
+ iteration=iteration,
+ max_iterations=self.max_iterations,
+ tool_type=tool_type,
+ query=query,
+ )
+
+ # Step 4: Get citation ID from CitationManager (unified ID generation)
+ send_progress(
+ "processing_notes", iteration=iteration, max_iterations=self.max_iterations
+ )
+
+ # Get citation_id from CitationManager - support both sync and async
+ import inspect
+
+ if hasattr(
+ citation_manager, "get_next_citation_id_async"
+ ) and inspect.iscoroutinefunction(
+ getattr(citation_manager, "get_next_citation_id_async", None)
+ ):
+ citation_id = await citation_manager.get_next_citation_id_async(
+ stage="research", block_id=topic_block.block_id
+ )
+ else:
+ citation_id = citation_manager.get_next_citation_id(
+ stage="research", block_id=topic_block.block_id
+ )
+
+ # Step 5: NoteAgent records summary with the citation ID
+ trace = await note_agent.process(
+ tool_type=tool_type,
+ query=query,
+ raw_answer=raw_answer,
+ citation_id=citation_id,
+ topic=topic_block.sub_topic,
+ context=current_knowledge,
+ )
+ topic_block.add_tool_trace(trace)
+
+ # Step 6: Add citation information to citation manager
+ # Support both sync and async citation_manager
+ if hasattr(citation_manager, "add_citation") and callable(
+ getattr(citation_manager, "add_citation", None)
+ ):
+ add_citation_method = getattr(citation_manager, "add_citation")
+ if inspect.iscoroutinefunction(add_citation_method):
+ await add_citation_method(
+ citation_id=citation_id,
+ tool_type=tool_type,
+ tool_trace=trace,
+ raw_answer=raw_answer,
+ )
+ else:
+ citation_manager.add_citation(
+ citation_id=citation_id,
+ tool_type=tool_type,
+ tool_trace=trace,
+ raw_answer=raw_answer,
+ )
+ else:
+ # Fallback to sync version
+ citation_manager.add_citation(
+ citation_id=citation_id,
+ tool_type=tool_type,
+ tool_trace=trace,
+ raw_answer=raw_answer,
+ )
+
+ # Step 7: Update knowledge (accumulate summaries)
+ current_knowledge = (current_knowledge + "\n" + trace.summary).strip()
+ topic_block.iteration_count = iteration
+ tools_used.append(tool_type)
+
+ # Send iteration completed progress
+ send_progress(
+ "iteration_completed",
+ iteration=iteration,
+ max_iterations=self.max_iterations,
+ tool_type=tool_type,
+ query=query,
+ tools_used=tools_used.copy(),
+ )
+
+ return {
+ "block_id": topic_block.block_id,
+ "iterations": iteration,
+ "final_knowledge": current_knowledge,
+ "tools_used": tools_used,
+ "queries_used": queries_used,
+ "status": "completed" if iteration < self.max_iterations else "max_iterations_reached",
+ }
+
+
+__all__ = ["ResearchAgent"]
diff --git a/src/agents/research/data_structures.py b/src/agents/research/data_structures.py
new file mode 100644
index 000000000..b114bc689
--- /dev/null
+++ b/src/agents/research/data_structures.py
@@ -0,0 +1,450 @@
+#!/usr/bin/env python
+"""
+DR-in-KG 2.0 Core Data Structures
+Includes: TopicBlock, ToolTrace, DynamicTopicQueue
+"""
+
+from dataclasses import asdict, dataclass, field
+from datetime import datetime
+from enum import Enum
+import json
+from pathlib import Path
+from typing import Any
+
+
+class TopicStatus(Enum):
+ """Topic block status enumeration"""
+
+ PENDING = "pending" # Pending research
+ RESEARCHING = "researching" # Researching
+ COMPLETED = "completed" # Completed
+ FAILED = "failed" # Failed
+
+
+class ToolType(Enum):
+ """Tool type enumeration"""
+
+ RAG_NAIVE = "rag_naive"
+ RAG_HYBRID = "rag_hybrid"
+ QUERY_ITEM = "query_item"
+ PAPER_SEARCH = "paper_search"
+ RUN_CODE = "run_code"
+ WEB_SEARCH = "web_search"
+
+
+# Default max size for raw_answer (50KB)
+DEFAULT_RAW_ANSWER_MAX_SIZE = 50 * 1024
+
+
+@dataclass
+class ToolTrace:
+ """
+ Tool trace - Records complete loop of a single tool call
+ """
+
+ tool_id: str # Unique identifier (e.g., "tool_1", "tool_2")
+ citation_id: str # Citation ID (for report citations and anchors, e.g., CIT-1-01)
+ tool_type: str # Tool type (rag_naive, web_search, etc.)
+ query: str # Query statement issued
+ raw_answer: str # Raw detailed result returned by tool (may be truncated)
+ summary: str # Core summary generated by Note Agent
+ timestamp: str = field(default_factory=lambda: datetime.now().isoformat())
+ raw_answer_truncated: bool = field(default=False) # Whether raw_answer was truncated
+ raw_answer_original_size: int = field(default=0) # Original size before truncation
+
+ def __post_init__(self):
+ """Post-initialization to handle raw_answer size limit"""
+ if self.raw_answer_original_size == 0:
+ self.raw_answer_original_size = len(self.raw_answer)
+
+ # Truncate if needed
+ if len(self.raw_answer) > DEFAULT_RAW_ANSWER_MAX_SIZE:
+ self.raw_answer = self._truncate_raw_answer(
+ self.raw_answer, DEFAULT_RAW_ANSWER_MAX_SIZE
+ )
+ self.raw_answer_truncated = True
+
+ @staticmethod
+ def _truncate_raw_answer(raw_answer: str, max_size: int) -> str:
+ """
+ Truncate raw_answer while trying to preserve valid JSON structure
+
+ Args:
+ raw_answer: Original raw answer string
+ max_size: Maximum size in bytes
+
+ Returns:
+ Truncated string
+ """
+ if len(raw_answer) <= max_size:
+ return raw_answer
+
+ # Try to parse as JSON and truncate intelligently
+ try:
+ data = json.loads(raw_answer)
+
+ # If it's a dict with common RAG response fields, truncate content fields
+ if isinstance(data, dict):
+ # Truncate long content fields
+ content_fields = ["answer", "content", "text", "chunks", "documents"]
+ for field_name in content_fields:
+ if field_name in data:
+ if (
+ isinstance(data[field_name], str)
+ and len(data[field_name]) > max_size // 2
+ ):
+ data[field_name] = data[field_name][: max_size // 2] + "... [truncated]"
+ elif isinstance(data[field_name], list):
+ # Keep only first few items
+ data[field_name] = data[field_name][:3]
+ if data[field_name]:
+ data[field_name].append({"note": "... additional items truncated"})
+
+ truncated = json.dumps(data, ensure_ascii=False)
+ if len(truncated) <= max_size:
+ return truncated
+ except (json.JSONDecodeError, TypeError):
+ pass
+
+ # Fallback: simple truncation with marker
+ truncation_marker = "\n... [content truncated, original size: {} bytes]".format(
+ len(raw_answer)
+ )
+ return raw_answer[: max_size - len(truncation_marker)] + truncation_marker
+
+ def to_dict(self) -> dict[str, Any]:
+ """Convert to dictionary"""
+ return asdict(self)
+
+ @classmethod
+ def from_dict(cls, data: dict[str, Any]) -> "ToolTrace":
+ """Create from dictionary"""
+ # Handle backward compatibility - old data may not have new fields
+ if "raw_answer_truncated" not in data:
+ data["raw_answer_truncated"] = False
+ if "raw_answer_original_size" not in data:
+ data["raw_answer_original_size"] = len(data.get("raw_answer", ""))
+ return cls(**data)
+
+ @classmethod
+ def create_with_size_limit(
+ cls,
+ tool_id: str,
+ citation_id: str,
+ tool_type: str,
+ query: str,
+ raw_answer: str,
+ summary: str,
+ max_size: int = DEFAULT_RAW_ANSWER_MAX_SIZE,
+ ) -> "ToolTrace":
+ """
+ Create a ToolTrace with explicit size limit
+
+ Args:
+ tool_id: Tool ID
+ citation_id: Citation ID
+ tool_type: Tool type
+ query: Query string
+ raw_answer: Raw answer (will be truncated if needed)
+ summary: Summary
+ max_size: Maximum size for raw_answer
+
+ Returns:
+ ToolTrace instance
+ """
+ original_size = len(raw_answer)
+ truncated = len(raw_answer) > max_size
+
+ if truncated:
+ raw_answer = cls._truncate_raw_answer(raw_answer, max_size)
+
+ return cls(
+ tool_id=tool_id,
+ citation_id=citation_id,
+ tool_type=tool_type,
+ query=query,
+ raw_answer=raw_answer,
+ summary=summary,
+ raw_answer_truncated=truncated,
+ raw_answer_original_size=original_size,
+ )
+
+
+@dataclass
+class TopicBlock:
+ """
+ Topic block - Minimum scheduling unit in queue
+ """
+
+ block_id: str # Unique identifier (e.g., "block_1", "block_2")
+ sub_topic: str # Sub-topic name
+ overview: str # Topic overview/background
+ status: TopicStatus = TopicStatus.PENDING # Topic status
+ tool_traces: list[ToolTrace] = field(default_factory=list) # Tool call trace list
+ iteration_count: int = 0 # Current iteration count
+ created_at: str = field(default_factory=lambda: datetime.now().isoformat())
+ updated_at: str = field(default_factory=lambda: datetime.now().isoformat())
+ metadata: dict[str, Any] = field(default_factory=dict) # Additional metadata
+
+ def add_tool_trace(self, trace: ToolTrace) -> None:
+ """Add tool trace"""
+ self.tool_traces.append(trace)
+ self.updated_at = datetime.now().isoformat()
+
+ def get_latest_trace(self) -> ToolTrace | None:
+ """Get latest tool trace"""
+ return self.tool_traces[-1] if self.tool_traces else None
+
+ def get_all_summaries(self) -> str:
+ """Get concatenated summaries of all tool traces"""
+ if not self.tool_traces:
+ return ""
+ return "\n".join([f"[{trace.tool_type}] {trace.summary}" for trace in self.tool_traces])
+
+ def to_dict(self) -> dict[str, Any]:
+ """Convert to dictionary"""
+ data = asdict(self)
+ data["status"] = self.status.value
+ data["tool_traces"] = [trace.to_dict() for trace in self.tool_traces]
+ return data
+
+ @classmethod
+ def from_dict(cls, data: dict[str, Any]) -> "TopicBlock":
+ """Create from dictionary"""
+ data_copy = data.copy()
+ if isinstance(data_copy.get("status"), str):
+ data_copy["status"] = TopicStatus(data_copy["status"])
+ if "tool_traces" in data_copy:
+ data_copy["tool_traces"] = [
+ ToolTrace.from_dict(t) if isinstance(t, dict) else t
+ for t in data_copy["tool_traces"]
+ ]
+ return cls(**data_copy)
+
+
+class DynamicTopicQueue:
+ """
+ Dynamic topic queue - Core memory and scheduling center of the system
+ """
+
+ def __init__(
+ self, research_id: str, max_length: int | None = None, state_file: str | None = None
+ ):
+ """
+ Initialize queue
+
+ Args:
+ research_id: Research task ID
+ max_length: Maximum queue length (None means unlimited)
+ state_file: Auto-persistence file path
+ """
+ self.research_id = research_id
+ self.blocks: list[TopicBlock] = []
+ self.block_counter = 0
+ self.created_at = datetime.now().isoformat()
+ self.max_length = max_length if isinstance(max_length, int) and max_length > 0 else None
+ self.state_file = state_file
+
+ def set_state_file(self, filepath: str | None) -> None:
+ """Set queue auto-persistence file"""
+ self.state_file = filepath
+ self._auto_save()
+
+ @staticmethod
+ def _normalize_topic(text: str) -> str:
+ return (text or "").strip().lower()
+
+ def add_block(self, sub_topic: str, overview: str) -> TopicBlock:
+ """
+ Add new topic block to the end of queue
+
+ Args:
+ sub_topic: Sub-topic name
+ overview: Topic overview
+
+ Returns:
+ Created TopicBlock
+ """
+ if self.max_length and len(self.blocks) >= self.max_length:
+ raise RuntimeError(
+ f"Queue has reached maximum capacity ({self.max_length}), cannot add new topic."
+ )
+ self.block_counter += 1
+ block_id = f"block_{self.block_counter}"
+ block = TopicBlock(block_id=block_id, sub_topic=sub_topic, overview=overview)
+ self.blocks.append(block)
+ self._auto_save()
+ return block
+
+ def has_topic(self, sub_topic: str) -> bool:
+ """Check if topic already exists (case-insensitive, ignoring leading/trailing spaces)"""
+ target = self._normalize_topic(sub_topic)
+ if not target:
+ return False
+ return any(self._normalize_topic(b.sub_topic) == target for b in self.blocks)
+
+ def list_topics(self) -> list[str]:
+ """List all current topic titles"""
+ return [b.sub_topic for b in self.blocks]
+
+ def get_pending_block(self) -> TopicBlock | None:
+ """
+ Get first pending topic block
+
+ Returns:
+ First TopicBlock with PENDING status, or None if not found
+ """
+ for block in self.blocks:
+ if block.status == TopicStatus.PENDING:
+ return block
+ return None
+
+ def get_block_by_id(self, block_id: str) -> TopicBlock | None:
+ """
+ Get topic block by ID
+
+ Args:
+ block_id: Topic block ID
+
+ Returns:
+ Corresponding TopicBlock, or None if not found
+ """
+ for block in self.blocks:
+ if block.block_id == block_id:
+ return block
+ return None
+
+ def mark_researching(self, block_id: str) -> bool:
+ """
+ Mark topic block as researching
+
+ Args:
+ block_id: Topic block ID
+
+ Returns:
+ Whether marking was successful
+ """
+ block = self.get_block_by_id(block_id)
+ if block:
+ block.status = TopicStatus.RESEARCHING
+ block.updated_at = datetime.now().isoformat()
+ self._auto_save()
+ return True
+ return False
+
+ def mark_completed(self, block_id: str) -> bool:
+ """
+ Mark topic block as completed
+
+ Args:
+ block_id: Topic block ID
+
+ Returns:
+ Whether marking was successful
+ """
+ block = self.get_block_by_id(block_id)
+ if block:
+ block.status = TopicStatus.COMPLETED
+ block.updated_at = datetime.now().isoformat()
+ self._auto_save()
+ return True
+ return False
+
+ def mark_failed(self, block_id: str) -> bool:
+ """
+ Mark topic block as failed
+
+ Args:
+ block_id: Topic block ID
+
+ Returns:
+ Whether marking was successful
+ """
+ block = self.get_block_by_id(block_id)
+ if block:
+ block.status = TopicStatus.FAILED
+ block.updated_at = datetime.now().isoformat()
+ self._auto_save()
+ return True
+ return False
+
+ def get_all_completed_blocks(self) -> list[TopicBlock]:
+ """Get all completed topic blocks"""
+ return [b for b in self.blocks if b.status == TopicStatus.COMPLETED]
+
+ def get_all_pending_blocks(self) -> list[TopicBlock]:
+ """Get all pending topic blocks"""
+ return [b for b in self.blocks if b.status == TopicStatus.PENDING]
+
+ def is_all_completed(self) -> bool:
+ """Check if all topic blocks are completed"""
+ if not self.blocks:
+ return False
+ return all(b.status == TopicStatus.COMPLETED for b in self.blocks)
+
+ def get_statistics(self) -> dict[str, Any]:
+ """Get queue statistics"""
+ return {
+ "total_blocks": len(self.blocks),
+ "pending": len(self.get_all_pending_blocks()),
+ "researching": len([b for b in self.blocks if b.status == TopicStatus.RESEARCHING]),
+ "completed": len(self.get_all_completed_blocks()),
+ "failed": len([b for b in self.blocks if b.status == TopicStatus.FAILED]),
+ "total_tool_calls": sum(len(b.tool_traces) for b in self.blocks),
+ }
+
+ def to_dict(self) -> dict[str, Any]:
+ """Convert to dictionary"""
+ return {
+ "research_id": self.research_id,
+ "created_at": self.created_at,
+ "blocks": [b.to_dict() for b in self.blocks],
+ "statistics": self.get_statistics(),
+ }
+
+ @classmethod
+ def from_dict(cls, data: dict[str, Any]) -> "DynamicTopicQueue":
+ """Create from dictionary"""
+ queue = cls(data["research_id"])
+ queue.created_at = data.get("created_at", queue.created_at)
+ for block_data in data.get("blocks", []):
+ block = TopicBlock.from_dict(block_data)
+ queue.blocks.append(block)
+ # Update counter
+ if block.block_id.startswith("block_"):
+ try:
+ block_num = int(block.block_id.split("_")[1])
+ queue.block_counter = max(queue.block_counter, block_num)
+ except (ValueError, IndexError):
+ pass
+ return queue
+
+ def save_to_json(self, filepath: str) -> None:
+ """Save queue to JSON file"""
+ Path(filepath).parent.mkdir(parents=True, exist_ok=True)
+ with open(filepath, "w", encoding="utf-8") as f:
+ json.dump(self.to_dict(), f, ensure_ascii=False, indent=2)
+
+ def _auto_save(self) -> None:
+ """Auto-save if state_file is set"""
+ if self.state_file:
+ try:
+ self.save_to_json(self.state_file)
+ except Exception as exc:
+ print(f"⚠️ Failed to save queue progress: {exc}")
+
+ @classmethod
+ def load_from_json(cls, filepath: str) -> "DynamicTopicQueue":
+ """Load queue from JSON file"""
+ with open(filepath, encoding="utf-8") as f:
+ data = json.load(f)
+ return cls.from_dict(data)
+
+
+__all__ = [
+ "DynamicTopicQueue",
+ "ToolTrace",
+ "ToolType",
+ "TopicBlock",
+ "TopicStatus",
+]
diff --git a/src/agents/research/main.py b/src/agents/research/main.py
new file mode 100644
index 000000000..e7b0531f6
--- /dev/null
+++ b/src/agents/research/main.py
@@ -0,0 +1,187 @@
+#!/usr/bin/env python
+"""
+DR-in-KG 2.0 - Main Entry
+Deep research system based on dynamic topic queue
+
+Usage:
+ python main.py --topic "Research Topic" [--preset quick/standard/deep]
+"""
+
+import argparse
+import asyncio
+from pathlib import Path
+import sys
+
+from dotenv import load_dotenv
+import yaml
+
+from src.agents.research.research_pipeline import ResearchPipeline
+from src.core.core import get_llm_config
+
+
+def load_config(config_path: str = None, preset: str = None) -> dict:
+ """
+ Load configuration file (with main.yaml merge)
+
+ Args:
+ config_path: Configuration file path (default: config/research_config.yaml)
+ preset: Preset mode (quick/standard/deep)
+
+ Returns:
+ Configuration dictionary (merged with main.yaml)
+ """
+ if config_path is None:
+ project_root = Path(__file__).parent.parent.parent.parent
+ from src.core.core import load_config_with_main
+
+ config = load_config_with_main("research_config.yaml", project_root)
+ else:
+ # If custom config path provided, load it directly (for backward compatibility)
+ config_file = Path(config_path)
+ if not config_file.exists():
+ raise FileNotFoundError(f"Configuration file not found: {config_file}")
+ with open(config_file, encoding="utf-8") as f:
+ config = yaml.safe_load(f) or {}
+
+ # Apply preset
+ if preset and "presets" in config and preset in config["presets"]:
+ print(f"✓ Applied preset configuration: {preset}")
+ preset_config = config["presets"][preset]
+ for key, value in preset_config.items():
+ if key in config and isinstance(value, dict):
+ config[key].update(value)
+
+ return config
+
+
+def display_config(config: dict):
+ """Display current configuration"""
+ print("\n" + "=" * 70)
+ print("📋 Current Configuration")
+ print("=" * 70)
+
+ planning = config.get("planning", {})
+ researching = config.get("researching", {})
+ reporting = config.get("reporting", {})
+
+ print("【Planning Configuration】")
+ print(f" Initial subtopics: {planning.get('decompose', {}).get('initial_subtopics', 5)}")
+ print(f" Max subtopics: {planning.get('decompose', {}).get('max_subtopics', 10)}")
+
+ print("\n【Researching Configuration】")
+ print(f" Max iterations: {researching.get('max_iterations', 5)}")
+ print(f" Research mode: {researching.get('research_mode', 'deep')}")
+ print(" Enabled tools:")
+ print(f" - RAG: {researching.get('enable_rag_hybrid', True)}")
+ print(f" - Web Search: {researching.get('enable_web_search', True)}")
+ print(f" - Paper Search: {researching.get('enable_paper_search', True)}")
+
+ print("\n【Reporting Configuration】")
+ print(f" Min section length: {reporting.get('min_section_length', 500)} characters")
+ print(f" Enable topic deduplication: {reporting.get('enable_deduplication', True)}")
+
+ print("=" * 70 + "\n")
+
+
+async def main():
+ """Main function"""
+ # Parse command line arguments
+ parser = argparse.ArgumentParser(
+ description="DR-in-KG 2.0 - Deep research system based on dynamic topic queue",
+ formatter_class=argparse.RawDescriptionHelpFormatter,
+ epilog="""
+Examples:
+ # Quick mode
+ python main.py --topic "Deep Learning Basics" --preset quick
+
+ # Standard mode
+ python main.py --topic "Transformer Architecture" --preset standard
+
+ # Deep mode
+ python main.py --topic "Graph Neural Networks" --preset deep
+ """,
+ )
+
+ parser.add_argument("--topic", type=str, required=True, help="Research topic")
+
+ parser.add_argument(
+ "--config",
+ type=str,
+ default="config.yaml",
+ help="Configuration file path (default: config.yaml)",
+ )
+
+ parser.add_argument(
+ "--preset",
+ type=str,
+ choices=["quick", "standard", "deep"],
+ help="Preset configuration (quick: fast, standard: standard, deep: deep)",
+ )
+
+ parser.add_argument("--output-dir", type=str, help="Output directory (overrides config file)")
+
+ args = parser.parse_args()
+
+ # Load environment variables
+ load_dotenv()
+
+ # Check API configuration
+ try:
+ llm_config = get_llm_config()
+ except ValueError as e:
+ print(f"❌ Error: {e}")
+ print("Please configure in .env or OpenTutor.env file:")
+ print(" LLM_MODEL=gpt-4o")
+ print(" LLM_BINDING_API_KEY=your_api_key_here")
+ print(" LLM_BINDING_HOST=https://api.openai.com/v1")
+ sys.exit(1)
+
+ # Load configuration
+ try:
+ config = load_config(args.config, args.preset)
+ except Exception as e:
+ print(f"❌ Failed to load configuration: {e!s}")
+ sys.exit(1)
+
+ # Override configuration (command line arguments take priority)
+ if args.output_dir:
+ config["system"]["output_base_dir"] = args.output_dir
+ config["system"]["reports_dir"] = args.output_dir
+
+ # Display configuration
+ display_config(config)
+
+ # Create research pipeline
+ pipeline = ResearchPipeline(
+ config=config, api_key=llm_config["api_key"], base_url=llm_config["base_url"]
+ )
+
+ # Execute research
+ try:
+ result = await pipeline.run(topic=args.topic)
+
+ print("\n" + "=" * 70)
+ print("✅ Research completed!")
+ print("=" * 70)
+ print(f"Research ID: {result['research_id']}")
+ print(f"Topic: {result['topic']}")
+ print(f"Final Report: {result['final_report_path']}")
+ print("=" * 70 + "\n")
+
+ except KeyboardInterrupt:
+ print("\n\n⚠️ Research interrupted by user")
+ sys.exit(0)
+ except Exception as e:
+ print(f"\n\n❌ Research failed: {e!s}")
+ import traceback
+
+ traceback.print_exc()
+ sys.exit(1)
+
+
+if __name__ == "__main__":
+ # Windows compatibility
+ if sys.platform == "win32":
+ asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
+
+ asyncio.run(main())
diff --git a/src/agents/research/prompts/cn/decompose_agent.yaml b/src/agents/research/prompts/cn/decompose_agent.yaml
new file mode 100644
index 000000000..d3f967ccf
--- /dev/null
+++ b/src/agents/research/prompts/cn/decompose_agent.yaml
@@ -0,0 +1,89 @@
+# DecomposeAgent 提示词配置
+
+system:
+ role: |
+ 你是一个研究规划专家,负责将复杂话题分解为逻辑清晰、互不重复的子话题体系。
+
+process:
+ generate_queries: |
+ 为以下话题生成 {num_queries} 个搜索查询。仅输出 JSON 对象:
+
+ 话题: {topic}
+
+ 要求:
+ 1. 每个查询 1-3 个关键词,简洁且具代表性
+ 2. 覆盖话题的不同维度,确保多样性
+ 3. 查询之间避免重复
+
+ 输出 JSON:
+ {{
+ "queries": ["查询1", "查询2", ...]
+ }}
+
+ decompose: |
+ 基于以下信息将话题分解为子话题。仅输出 JSON 对象:
+
+ 主话题: {topic}
+
+ 背景知识(来自RAG检索):
+ {rag_context}
+
+ {decompose_requirement}
+
+ **分解步骤:**
+
+ 1. **分析背景知识**:识别核心概念、关键理论和重要内容
+
+ 2. **识别研究维度**:确定各维度的研究重点,确保维度间互补
+
+ 3. **生成子话题**:
+ - 基于背景知识中的实际内容
+ - 各子话题逻辑关联但不重复
+ - 覆盖主题的主要方面
+
+ 4. **完善描述**:
+ - title:简洁明确,表达子话题核心
+ - overview:2-3句话,说明内容、重要性和研究价值
+
+ 输出 JSON:
+ {{
+ "sub_topics": [
+ {{
+ "title": "子话题标题",
+ "overview": "详细概览,说明内容、重点和研究价值"
+ }}
+ ]
+ }}
+
+ decompose_without_rag: |
+ 将以下研究话题分解为清晰、结构化的子话题。仅输出 JSON 对象:
+
+ 主话题: {topic}
+
+ {decompose_requirement}
+
+ **分解步骤(无RAG上下文):**
+
+ 1. **识别关键方面**:基于你的知识,识别该话题的关键方面和维度
+
+ 2. **生成子话题**:
+ - 每个子话题应覆盖主话题的不同方面
+ - 子话题之间应有逻辑关系但不重叠或重复
+ - 确保子话题共同形成完整的研究框架
+
+ 3. **完善描述**:
+ - title:简洁明确,表达子话题的核心重点
+ - overview:2-3句话说明:
+ - 该子话题涵盖的内容
+ - 为什么它对理解主话题很重要
+ - 需要探索的关键概念或领域
+
+ 输出 JSON:
+ {{
+ "sub_topics": [
+ {{
+ "title": "子话题标题(简洁明确)",
+ "overview": "详细概览(2-3句话说明重要性、范围和关键领域)"
+ }}
+ ]
+ }}
diff --git a/src/agents/research/prompts/cn/manager_agent.yaml b/src/agents/research/prompts/cn/manager_agent.yaml
new file mode 100644
index 000000000..7825f13a4
--- /dev/null
+++ b/src/agents/research/prompts/cn/manager_agent.yaml
@@ -0,0 +1,24 @@
+# ManagerAgent 提示词配置
+
+system:
+ role: |
+ 你是一个任务调度专家,负责管理动态话题队列的状态和任务派发。
+
+process:
+ decide_next: |
+ 根据队列状态决定下一步操作。仅输出 JSON 对象:
+
+ 队列统计:
+ total={total}, pending={pending}, researching={researching}, completed={completed}, failed={failed}
+
+ **决策规则:**
+ - 有 pending → action: "dispatch",选择队头 block_id
+ - 无 pending 且 researching=0 → action: "finish"
+ - 其他情况 → action: "wait"
+
+ 输出 JSON:
+ {{
+ "action": "dispatch|finish|wait",
+ "block_id": "(dispatch时必填)",
+ "reason": "简要理由"
+ }}
diff --git a/src/agents/research/prompts/cn/note_agent.yaml b/src/agents/research/prompts/cn/note_agent.yaml
new file mode 100644
index 000000000..332d9c12f
--- /dev/null
+++ b/src/agents/research/prompts/cn/note_agent.yaml
@@ -0,0 +1,121 @@
+# NoteAgent 提示词配置 - 深度信息提取与结构化摘要
+# 设计目标:从工具输出中提取丰富的结构化信息,为高质量报告生成提供素材
+
+system:
+ role: |
+ 你是一位信息提取与知识整理专家,负责从各类工具输出中提炼关键信息,生成结构化、可复用的高质量摘要。
+
+ **核心能力**:
+ 1. **多模态信息识别**:能够识别并保留公式、表格、代码、数据等结构化元素
+ 2. **层次化提取**:区分核心信息、支撑信息和背景信息
+ 3. **知识关联**:识别概念间的关系和依赖
+ 4. **学术规范**:保持术语准确性和引用完整性
+
+ **重要格式要求**:
+ - 所有输出必须严格遵循 JSON 格式
+ - 只输出有效的 JSON 对象,不要包含任何额外的文本、解释或代码块标记
+ - JSON 必须可以被直接解析,不能包含注释或格式错误
+ - 如果输出中包含文本内容,请将其作为 JSON 字符串值,并正确转义特殊字符
+
+process:
+ generate_summary: |
+ 从以下工具输出中提取关键信息并生成结构化摘要。
+
+ **重要:你必须只输出一个有效的 JSON 对象,不要包含任何其他文本、解释或代码块标记。**
+
+ 工具类型: {tool_type}
+ 查询: {query}
+ 话题: {topic}
+ 上下文: {context}
+
+ 原始输出:
+ {raw_answer}
+
+ **深度提取框架**:
+
+ ## 第一步:内容类型识别
+
+ 识别原始输出中包含的信息类型:
+ - □ 概念定义(术语、定义、解释)
+ - □ 数学公式(方程、定理、推导)
+ - □ 数据表格(对比、参数、统计)
+ - □ 算法/代码(伪代码、实现、示例)
+ - □ 流程/架构(步骤、流程、系统结构)
+ - □ 案例/实例(应用场景、实验结果)
+ - □ 引用/来源(论文、作者、出处)
+
+ ## 第二步:分层信息提取
+
+ 1. **核心层**(必须提取):
+ - 直接回答查询的关键信息
+ - 重要定义、公式、结论
+ - 核心数据和关键发现
+
+ 2. **支撑层**(选择性提取):
+ - 推导过程和论证逻辑
+ - 实验方法和验证数据
+ - 对比分析和优缺点
+
+ 3. **背景层**(简要提及):
+ - 历史演进和发展脉络
+ - 相关工作和参考文献
+ - 适用条件和局限性
+
+ ## 第三步:结构化信息保留
+
+ **必须保留原始格式的元素**:
+
+ 1. **数学公式**:
+ - 行内公式保留为 `$...$` 格式
+ - 独立公式保留为 `$$...$$` 格式
+ - 示例:`$E = mc^2$` 或 `$$\\nabla \\cdot E = \\frac{\\rho}{\\epsilon_0}$$`
+
+ 2. **表格数据**:
+ - 转换为 Markdown 表格格式
+ - 保留表头和关键数据行
+ - 示例:`| 方法 | 准确率 | 效率 |\\n|---|---|---|\\n| A | 95% | 快 |`
+
+ 3. **代码片段**:
+ - 保留关键算法或示例代码
+ - 使用代码块格式并标注语言
+ - 示例:`\\`\\`\\`python\\ndef func():\\n pass\\n\\`\\`\\``
+
+ 4. **列表结构**:
+ - 保留步骤、要点等列表
+ - 使用 `1. 2. 3.` 或 `- - -` 格式
+
+ ## 第四步:生成结构化摘要
+
+ **摘要要求**:
+ - 长度:300-600字(视信息密度调整)
+ - 结构:按逻辑主题组织,而非按原文顺序
+ - 完整性:摘要应能独立阅读,无需参考原始输出
+ - 准确性:保持术语和数值的准确性
+
+ **输出格式要求(严格遵循):**
+ - 只输出 JSON 对象,不要使用 ```json 代码块包裹
+ - 不要添加任何解释性文字
+ - JSON 字符串中的特殊字符(如引号、换行符、反斜杠)必须正确转义
+ - 确保 JSON 格式完全有效,可以直接被 json.loads() 解析
+
+ 输出示例(仅作为格式参考,不要复制内容):
+ {{
+ "summary": "结构化摘要内容(包含保留的公式、表格等元素)",
+ "key_elements": {{
+ "definitions": ["定义1", "定义2"],
+ "formulas": ["$公式1$", "$$公式2$$"],
+ "data_points": ["数据1", "数据2"],
+ "methods": ["方法1", "方法2"]
+ }},
+ "content_type": ["concept", "formula", "data"],
+ "confidence": 0.85,
+ "source_quality": "high/medium/low"
+ }}
+
+ **关键原则**:
+ 1. 优先保留可量化、可验证的信息
+ 2. 公式和代码必须完整保留,不要简化
+ 3. 表格数据转换为 Markdown 格式
+ 4. 标注信息来源的可信度
+
+ **现在请直接输出 JSON 对象,不要包含任何其他内容。**
diff --git a/src/agents/research/prompts/cn/rephrase_agent.yaml b/src/agents/research/prompts/cn/rephrase_agent.yaml
new file mode 100644
index 000000000..96f87079c
--- /dev/null
+++ b/src/agents/research/prompts/cn/rephrase_agent.yaml
@@ -0,0 +1,58 @@
+# RephraseAgent 提示词配置
+
+system:
+ role: |
+ 你是一个研究话题优化专家,负责将用户的研究需求转化为清晰、具体、可执行的研究主题。
+
+process:
+ rephrase: |
+ 对以下用户输入进行分析和优化。仅输出 JSON 对象:
+
+ 用户输入: {user_input}
+ 迭代次数: {iteration}
+ {previous_result}
+
+ **优化维度:**
+
+ 1. **研究主题**:转化为清晰、具体、可研究的话题
+ 2. **研究重点**:识别核心问题和关键要素
+ 3. **研究范围**:明确边界,界定深度和广度
+ 4. **优化理由**:说明优化依据和逻辑
+
+ 基于以上思考,生成一段主题突出、重点明确、范围清晰的研究目标,长度不超过用户输入的两倍。
+
+ 输出 JSON:
+ {{
+ "topic": "一段清晰、完整的研究主题描述"
+ }}
+
+ 要求:
+ 1. topic 必须是连贯的文字,能独立表达完整信息
+ 2. iteration = 0 时,给出合理的聚焦和优化
+ 3. iteration > 0 时,根据用户反馈调整
+
+ check_satisfaction: |
+ 分析用户对重写结果的反馈。仅输出 JSON 对象:
+
+ 当前结果:
+ - 话题: {topic}
+
+ 用户反馈: {user_feedback}
+
+ **判断维度:**
+ 1. 用户是否明确表达满意/不满意
+ 2. 是否提出具体修改要求
+ 3. 反馈是肯定性还是否定性
+
+ 输出 JSON:
+ {{
+ "user_satisfied": true/false,
+ "should_continue": true/false,
+ "interpretation": "对用户意图的解读",
+ "suggested_action": "建议的下一步行动"
+ }}
+
+ 判断标准:
+ - 满意、同意、可以、好的 → user_satisfied = true, should_continue = false
+ - 要求修改或提出意见 → user_satisfied = false, should_continue = true
+ - 反馈模糊 → 倾向继续优化
diff --git a/src/agents/research/prompts/cn/reporting_agent.yaml b/src/agents/research/prompts/cn/reporting_agent.yaml
new file mode 100644
index 000000000..abbe04ec8
--- /dev/null
+++ b/src/agents/research/prompts/cn/reporting_agent.yaml
@@ -0,0 +1,380 @@
+# ReportingAgent 提示词配置 - 深度研究报告生成
+# 设计目标:生成元素丰富、逻辑连贯、内容翔实的学术级深度研究报告
+
+# 引用指令模板
+citation:
+ enabled_instruction: |
+ **引用要求(重要)**:
+ - 格式:使用 `[N]` 格式,其中 N 是下表中的参考编号
+ - 只使用引用参考表中的参考编号 - 不要编造编号!
+ - 将引用放在使用该来源信息的句子或论述末尾
+ - 不要添加参考文献部分 - 它将自动生成
+
+ **引用参考表**(使用这些确切编号):
+ {citation_table}
+
+ **示例**:
+ - "根据最新研究 [5],该方法实现了..."
+ - "这种方法已在多项研究中得到验证 [3][7]。"
+
+ disabled_instruction: |
+ **引用要求**:
+ - 不要在文本中添加任何行内引用,如 [1]、[[1]] 或 [N]
+ - 不要在末尾添加参考文献部分 - 参考文献将单独处理
+ - 专注于内容综合,不使用引用标记
+
+system:
+ role: |
+ 你是一位顶级学术写作与内容整合专家,擅长将复杂的研究成果转化为结构清晰、论述深刻的专业报告。你的报告应具备以下特质:
+
+ **核心写作理念**:
+ 1. **深度优于广度**:宁可深入剖析少数关键点,也不泛泛而谈
+ 2. **论证优于陈述**:每个观点都应有充分的证据、推理或实例支撑
+ 3. **结构化呈现**:善用公式、表格、流程图、代码等多种元素增强表达力
+ 4. **学术严谨性**:准确引用来源,区分事实与推断,承认局限性
+
+ **重要格式要求**:
+ - 所有输出必须严格遵循 JSON 格式
+ - 只输出有效的 JSON 对象,不要包含任何额外的文本、解释或代码块标记
+ - JSON 必须可以被直接解析,不能包含注释或格式错误
+ - 如果输出中包含 Markdown 内容,请将其作为 JSON 字符串值,并正确转义特殊字符
+
+process:
+ deduplicate: |
+ 分析以下话题列表,识别重复或高度相似的话题。
+
+ **重要:你必须只输出一个有效的 JSON 对象,不要包含任何其他文本、解释或代码块标记。**
+
+ 话题列表:
+ {topics}
+
+ 总话题数:{total_topics}
+
+ **分析步骤:**
+ 1. 理解每个话题的核心内容和研究视角
+ 2. 识别语义重复或高度相似的话题(注意:视角不同的同一概念不算重复)
+ 3. 选择最具代表性、内容最丰富的话题保留
+
+ **输出格式要求(严格遵循):**
+ - 只输出 JSON 对象,不要使用 ```json 代码块包裹
+ - 不要添加任何解释性文字
+ - 确保 JSON 格式完全有效,可以直接被解析
+
+ 输出示例(仅作为格式参考,不要复制内容):
+ {{
+ "duplicates": [{{"indices": [0, 3], "reason": "语义重复:两者都讨论XX的基本原理"}}],
+ "keep_indices": [0, 1, 2, 4],
+ "summary": "保留了4个互补性话题,覆盖理论基础、技术实现、应用场景和前沿发展"
+ }}
+
+ **现在请直接输出 JSON 对象,不要包含任何其他内容。**
+
+ generate_outline: |
+ 为以下研究生成结构化的三级标题体系大纲。
+
+ **重要:你必须只输出一个有效的 JSON 对象,不要包含任何其他文本、解释或代码块标记。**
+
+ 研究主题:{topic}
+
+ 研究话题(包含subtopic、overview和tool_summaries):
+ {topics_json}
+
+ 总话题数:{total_topics}
+
+ **大纲设计原则**:
+
+ 1. **三级标题体系**:
+ - 一级标题(#):报告总标题
+ - 二级标题(##):主要章节(引言、核心章节1-N、结论)
+ - 三级标题(###):章节内的子主题
+ - 四级标题(####):细分内容(可选,用于复杂章节)
+
+ 2. **逻辑结构设计**:
+ - 识别话题间的逻辑关系:层次、依赖、并列、递进、对比
+ - 按认知规律排序:概念→原理→方法→应用→评估→展望
+ - 确保章节间有明确的过渡逻辑
+
+ 3. **章节设计指南**:
+ - 每个主章节应有明确的研究问题或目标
+ - 子章节应覆盖该主题的核心维度
+ - instruction 应指明需要涵盖的关键要素和呈现方式
+
+ **输出格式要求(严格遵循):**
+ - 只输出 JSON 对象,不要使用 ```json 代码块包裹
+ - 不要添加任何解释性文字
+
+ 输出示例(仅作为格式参考,不要复制内容):
+ {{
+ "title": "# 报告总标题:精确表达研究主题",
+ "introduction": "## 引言",
+ "introduction_instruction": "阐述研究背景、问题动机、研究目标和报告结构",
+ "sections": [
+ {{
+ "title": "## 1. 第一主章节标题",
+ "instruction": "本章重点阐述...需要包含原理推导和关键公式",
+ "block_id": "block_1",
+ "subsections": [
+ {{
+ "title": "### 1.1 子章节标题",
+ "instruction": "详细说明...建议使用表格对比"
+ }},
+ {{
+ "title": "### 1.2 子章节标题",
+ "instruction": "分析...建议使用流程图展示"
+ }}
+ ]
+ }}
+ ],
+ "conclusion": "## 结论与展望",
+ "conclusion_instruction": "总结核心发现、研究贡献、局限性和未来方向"
+ }}
+
+ **现在请直接输出 JSON 对象,不要包含任何其他内容。**
+
+ write_introduction: |
+ 撰写研究报告的引言部分。
+
+ **重要:你必须只输出一个有效的 JSON 对象,不要包含任何其他文本、解释或代码块标记。**
+
+ 研究主题:{topic}
+ 引言指导:{introduction_instruction}
+ 研究话题概览:{topics_summary}
+ 总话题数:{total_topics}
+
+ **引言写作框架**(400-600字):
+
+ 1. **开篇立意**(第1段):
+ - 从宏观背景或重要趋势切入
+ - 引出研究领域的核心挑战或机遇
+ - 点明研究的必要性和紧迫性
+
+ 2. **问题聚焦**(第2段):
+ - 明确本研究要解决的具体问题
+ - 阐述现有方法或认知的不足
+ - 引出研究的核心目标
+
+ 3. **研究范围**(第3段):
+ - 概述研究涵盖的主要维度
+ - 说明各部分之间的逻辑关系
+ - 预告核心发现或贡献(可选)
+
+ 4. **结构导引**(第4段):
+ - 简要介绍报告各章节的组织安排
+ - 帮助读者建立阅读预期
+
+ **写作要求**:
+ - 使用学术化但不晦涩的语言
+ - 每段有明确的主题句
+ - 段落间有自然过渡
+ - 不要使用章节标题,直接写正文内容
+
+ **输出格式要求(严格遵循):**
+ - 只输出 JSON 对象,不要使用 ```json 代码块包裹
+ - JSON 字符串中的特殊字符(如引号、换行符)必须正确转义
+
+ 输出示例:
+ {{
+ "introduction": "完整的引言内容(Markdown格式,不含标题,400-600字)"
+ }}
+
+ **现在请直接输出 JSON 对象,不要包含任何其他内容。**
+
+ write_section_body: |
+ 基于研究数据撰写深度章节内容。
+
+ **重要:你必须只输出一个有效的 JSON 对象,不要包含任何其他文本、解释或代码块标记。**
+
+ 研究主题: {topic}
+ 章节标题: {section_title}
+ 写作指导: {section_instruction}
+ 数据源: {block_data}
+
+ **深度写作框架**:
+
+ ## 第一步:素材深度解析
+
+ 1. **信息分级处理**:
+ - **核心层**:关键定义、核心公式、主要结论 → 必须完整呈现
+ - **支撑层**:推导过程、实验数据、案例分析 → 选择性深入
+ - **背景层**:历史沿革、相关工作 → 简要提及
+
+ 2. **信息可信度评估**:
+ - 优先采信:peer-reviewed论文 > 权威教材 > 技术文档 > 网络资源
+ - 冲突处理:标注不同观点,或选择最新/最权威来源
+
+ ## 第二步:结构化组织
+
+ **三级标题体系**(必须遵循):
+ - 本章节使用 `##` 作为主标题
+ - 使用 `###` 组织子主题(2-4个为宜)
+ - 复杂子主题可使用 `####` 进一步细分
+
+ **逻辑架构模式**(选择最适合的一种):
+ - **演绎式**:原理→推论→应用→验证
+ - **归纳式**:现象→分析→规律→理论
+ - **对比式**:方法A vs 方法B → 优劣分析 → 适用场景
+ - **问题导向式**:问题→现有方案→局限性→改进思路
+
+ ## 第三步:多模态元素运用
+
+ **必须根据内容特点选择性使用以下元素**:
+
+ 1. **数学公式**(LaTeX格式):
+ - 行内公式:`$E = mc^2$`
+ - 独立公式块:
+ ```
+ $$
+ \mathcal{L} = \sum_{i=1}^{n} \ell(y_i, f(x_i)) + \lambda \Omega(f)
+ $$
+ ```
+ - 适用:定义、定理、推导、优化目标等
+
+ 2. **表格**(Markdown格式):
+ - 适用:多维度对比、参数配置、实验结果、分类汇总
+ - 格式示例:
+ ```
+ | 方法 | 准确率 | 效率 | 适用场景 |
+ |------|--------|------|----------|
+ | A | 95% | 快 | 实时系统 |
+ | B | 98% | 慢 | 离线分析 |
+ ```
+
+ 3. **流程图**(Mermaid格式):
+ - 适用:算法流程、系统架构、决策逻辑、数据流向
+ - 格式示例:
+ ```mermaid
+ graph TD
+ A[输入] --> B{{处理}}
+ B --> C[输出]
+ ```
+
+ 4. **代码块**:
+ - 适用:算法实现、配置示例、API调用
+ - 必须标注语言类型(python/javascript/sql等)
+
+ 5. **列表与层级**:
+ - 有序列表:步骤、排名、优先级
+ - 无序列表:特点、要素、选项
+ - 嵌套列表:层级关系、分类体系
+
+ ## 第四步:学术写作规范
+ {citation_instruction}
+
+ 1. **深度转述**:
+ - 避免直接复制,用学术语言重组表达
+ - 示例转换:
+ - 原:「X方法效果好」
+ - 改:「实验结果表明,X方法在Y指标上取得了显著提升,相较基线方法提高了Z%」
+
+ 2. **论证完整性**:
+ - 每个核心观点都应有:论点 → 论据 → 论证 → 小结
+ - 适当使用过渡句连接段落
+
+ 3. **专业术语处理**:
+ - 首次出现时给出定义或解释
+ - 可使用「术语(英文原文)」格式
+
+ **输出格式要求(严格遵循):**
+ - 只输出 JSON 对象,不要使用 ```json 代码块包裹
+ - JSON 字符串中的换行符应使用 \n 转义
+ - 确保 JSON 格式完全有效
+
+ 输出示例:
+ {{
+ "section_content": "## 章节标题\n\n开篇段落...\n\n### 1.1 子章节标题\n\n内容...\n\n### 1.2 子章节标题\n\n内容...{citation_output_hint}"
+ }}
+
+ **字数要求**:每个章节至少800字,内容翔实、论述充分
+
+ **现在请直接输出 JSON 对象,不要包含任何其他内容。**
+
+ write_conclusion: |
+ 撰写研究报告的结论部分。
+
+ **重要:你必须只输出一个有效的 JSON 对象,不要包含任何其他文本、解释或代码块标记。**
+
+ 研究主题:{topic}
+ 结论指导:{conclusion_instruction}
+ 关键发现:{topics_findings}
+ 总话题数:{total_topics}
+
+ **结论写作框架**(500-700字):
+
+ 1. **研究回顾与核心发现**(第1-2段):
+ - 简要回顾研究问题和方法
+ - 系统总结各章节的核心发现
+ - 归纳形成整体性结论
+
+ 2. **研究贡献与价值**(第3段):
+ - **理论贡献**:对领域认知的推进
+ - **方法贡献**:新方法、新框架、新工具
+ - **实践价值**:对实际应用的指导意义
+
+ 3. **局限性与反思**(第4段):
+ - 诚实指出研究的局限性
+ - 说明数据、方法或范围的约束
+ - 提示结论的适用边界
+
+ 4. **未来展望**(第5段):
+ - 指出待解决的开放问题
+ - 提出有价值的研究方向
+ - 展望领域发展趋势
+
+ **写作要求**:
+ - 结论应有高度概括性,避免重复正文细节
+ - 体现批判性思维,不回避局限性
+ - 展望应具体可行,不泛泛而谈
+ - 不要使用章节标题,直接写正文内容
+
+ **输出格式要求(严格遵循):**
+ - 只输出 JSON 对象,不要使用 ```json 代码块包裹
+ - JSON 字符串中的特殊字符必须正确转义
+
+ 输出示例:
+ {{
+ "conclusion": "完整的结论内容(Markdown格式,不含标题,500-700字)"
+ }}
+
+ **现在请直接输出 JSON 对象,不要包含任何其他内容。**
+
+ # 新增:子章节写作提示词(用于三级标题内容)
+ write_subsection: |
+ 基于父章节上下文,撰写子章节内容。
+
+ **重要:你必须只输出一个有效的 JSON 对象,不要包含任何其他文本、解释或代码块标记。**
+
+ 研究主题: {topic}
+ 父章节标题: {parent_section_title}
+ 子章节标题: {subsection_title}
+ 写作指导: {subsection_instruction}
+ 相关数据: {subsection_data}
+
+ **写作要求**:
+
+ 1. **内容定位**:
+ - 聚焦子章节的具体主题
+ - 与父章节保持逻辑连贯
+ - 避免与其他子章节内容重复
+
+ 2. **深度要求**:
+ - 提供具体的技术细节或案例分析
+ - 适当使用公式、表格、图表等元素
+ - 论述要有理有据
+
+ 3. **格式规范**:
+ - 使用 `###` 作为子章节标题
+ - 可使用 `####` 进一步细分(可选)
+ - 段落清晰,逻辑分明
+
+ **输出格式要求(严格遵循):**
+ - 只输出 JSON 对象
+ - JSON 字符串中的换行符应使用 \n 转义
+
+ 输出示例:
+ {{
+ "subsection_content": "### 子章节标题\n\n内容...\n\n#### 细分主题(可选)\n\n内容..."
+ }}
+
+ **字数要求**:每个子章节300-500字
+
+ **现在请直接输出 JSON 对象,不要包含任何其他内容。**
diff --git a/src/agents/research/prompts/cn/research_agent.yaml b/src/agents/research/prompts/cn/research_agent.yaml
new file mode 100644
index 000000000..ba75036f8
--- /dev/null
+++ b/src/agents/research/prompts/cn/research_agent.yaml
@@ -0,0 +1,173 @@
+# ResearchAgent 提示词配置
+
+system:
+ role: |
+ 你是一个基于知识库的深度研究策略专家,负责系统性地从知识库中挖掘与话题相关的内容,并根据需要拓展到外部资源。
+
+# 动态内容的指导模板
+guidance:
+ # 当 web_search 和 paper_search 都启用时的在线搜索指导
+ online_search_both: |
+ **在线搜索评估指导(web_search 和 paper_search 已启用)**:
+
+ 在评估知识充足性时,除了评估知识库内容覆盖度外,还需要考虑:
+
+ 1. **内容时效性评估**:
+ - 当前知识是否包含最新发展、行业趋势和应用案例?
+ - 是否需要补充最新背景信息和当前应用状态?
+ - 知识库内容是否可能过时,需要最新信息补充?
+
+ 2. **知识扩展评估**:
+ - 知识是否已从基础知识库内容扩展到最新发展?
+ - 是否通过 web_search 补充了实时背景、行业案例和最新应用?
+ - 是否通过 paper_search 补充了前沿学术研究、最新理论进展和具体研究工作?
+
+ 3. **研究完整性评估**:
+ - 如果话题涉及前沿研究或最新发展,是否通过在线搜索补充了相关内容?
+ - 是否形成了从知识库基础到最新发展的完整知识链?
+
+ 判断标准:
+ - 如果知识库内容已充分探索 且 已通过在线搜索补充必要的实时信息/前沿研究,则视为充足
+ - 如果知识库内容已充分探索 但 缺少必要的实时信息/前沿研究补充,则视为不充足
+ - 如果知识库内容尚未充分探索,优先继续探索知识库,暂时忽略在线搜索
+
+ # 当只启用 web_search 时的在线搜索指导
+ online_search_web_only: |
+ **在线搜索评估指导(web_search 已启用)**:
+
+ 在评估知识充足性时,除了评估知识库内容覆盖度外,还需要考虑:
+
+ 1. **内容时效性评估**:
+ - 当前知识是否包含最新发展、行业趋势和应用案例?
+ - 是否需要补充最新背景信息和当前应用状态?
+ - 知识库内容是否可能过时,需要最新信息补充?
+
+ 2. **知识扩展评估**:
+ - 知识是否已从基础知识库内容扩展到最新发展?
+ - 是否通过 web_search 补充了实时背景、行业案例和最新应用?
+
+ 判断标准:
+ - 如果知识库内容已充分探索 且 已通过 web_search 补充必要的实时信息,则视为充足
+ - 如果知识库内容已充分探索 但 缺少必要的实时信息补充,则视为不充足
+ - 如果知识库内容尚未充分探索,优先继续探索知识库,暂时忽略 web_search
+
+ # 当只启用 paper_search 时的在线搜索指导
+ online_search_paper_only: |
+ **在线搜索评估指导(paper_search 已启用)**:
+
+ 在评估知识充足性时,除了评估知识库内容覆盖度外,还需要考虑:
+
+ 1. **前沿研究评估**:
+ - 当前知识是否包含相关前沿学术研究和最新理论进展?
+ - 是否需要补充具体研究工作、最新方法和最新发现?
+ - 知识库内容是否缺乏前沿研究视角?
+
+ 2. **知识扩展评估**:
+ - 知识是否已从基础知识库内容扩展到前沿研究?
+ - 是否通过 paper_search 补充了前沿学术研究、最新理论进展和具体研究工作?
+
+ 判断标准:
+ - 如果知识库内容已充分探索 且 已通过 paper_search 补充必要的前沿研究,则视为充足
+ - 如果知识库内容已充分探索 但 缺少必要的前沿研究补充,则视为不充足
+ - 如果知识库内容尚未充分探索,优先继续探索知识库,暂时忽略 paper_search
+
+ # 灵活模式的迭代模式标准
+ iteration_mode_flexible: |
+ - **灵活模式(自动)**:你有自主权决定充足性。
+ - 如果知识确实全面,你可以提前得出充足结论
+ - 但仍需确保在得出结论前核心方面已被覆盖
+ - 质量优于数量:关注有意义的覆盖,而非迭代次数
+
+ # 固定模式的迭代模式标准
+ iteration_mode_fixed: |
+ - **固定模式**:在宣布充足性时要保守。
+ - 在早期迭代(1-{early_threshold}):很少得出充足结论,继续探索
+ - 在中期迭代:需要有力证据证明全面覆盖
+ - 仅在后期迭代({early_threshold}+):如果确实全面,才考虑充足
+ - 目标是彻底探索,而非快速完成
+
+process:
+ check_sufficiency: |
+ 判断以下话题的当前知识是否充足。仅输出 JSON 对象:
+
+ 话题: {topic}
+ 话题概览: {overview}
+ 当前知识: {current_knowledge}
+ 迭代次数: {iteration}
+ {online_search_instruction}
+ {research_depth_guidance}
+ {iteration_mode_criteria}
+
+ **重要原则:深度优先于广度**
+
+ 你必须严格、系统地评估当前知识是否真正达到了"深度研究"的标准,而非仅仅"表面覆盖"。
+
+ **评估步骤:**
+
+ 1. **明确核心要素**(至少评估以下6个维度):
+ - □ 概念定义:是否有清晰、完整的定义?
+ - □ 核心原理:是否深入解释了工作机制、推导过程?
+ - □ 关键公式/算法:是否包含具体的数学表达或算法步骤?
+ - □ 应用场景:是否有具体的应用案例或实例分析?
+ - □ 关联关系:是否探索了与其他概念/领域的联系?
+ - □ 局限与发展:是否讨论了局限性、挑战或前沿发展?
+
+ 2. **严格评估覆盖情况**:
+ - 统计已覆盖维度数量(至少需要覆盖4个以上维度)
+ - 评估每个维度的深度(表面提及 vs 深入分析)
+ - 识别关键遗漏(哪些维度完全未涉及或深度不足)
+
+ 3. **判断充足性标准**:
+ - **充足**(is_sufficient=true):满足以下**全部**条件
+ ① 至少覆盖5个核心维度
+ ② 每个已覆盖维度都有实质内容(非仅提及)
+ ③ 迭代次数 ≥ 3(确保已进行多轮探索)
+ - **不充足**(is_sufficient=false):任一条件不满足
+
+ 输出 JSON:
+ {{
+ "is_sufficient": true/false,
+ "covered_dimensions": ["已覆盖的维度列表"],
+ "missing_dimensions": ["缺失或深度不足的维度列表"],
+ "coverage_score": 0.0-1.0,
+ "reason": "判断理由(具体说明覆盖情况和判断依据)"
+ }}
+
+ generate_query_plan: |
+ 知识不充分时,制定下一步查询计划。仅输出 JSON 对象:
+
+ 话题: {topic}
+ 话题概览: {overview}
+ 当前知识: {current_knowledge}
+ 迭代次数: {iteration}
+ 已存在话题:
+ {existing_topics}
+
+ **可用工具列表(只能使用以下工具)**:
+ {available_tools}
+
+ {tool_phase_guidance}
+
+ **查询设计原则**:
+ 1. **重要**:只能从上方"可用工具列表"中选择工具,不要使用未列出的工具
+ 2. 每次查询应针对一个具体的知识缺口
+ 3. 避免与当前知识中已有内容重复
+ 4. 查询应具体、可执行(避免过于宽泛)
+ 5. 如果使用 paper_search,必须使用英文关键词
+
+ **新话题评估**:仅当发现与主题高度相关且与现有话题完全不同的重要分支时,才建议添加新话题(score ≥ 0.85)
+
+ 输出 JSON:
+ {{
+ "query": "具体查询语句",
+ "tool_type": "从可用工具列表中选择",
+ "target_dimension": "本次查询针对的知识维度",
+ "rationale": "工具选择理由和查询目标",
+ "parallel": false,
+ "fallback": ["rag_hybrid", "rag_naive"],
+ "should_add_new_topic": false,
+ "new_sub_topic": null,
+ "new_overview": null,
+ "new_topic_reason": null,
+ "new_topic_score": 0.0
+ }}
diff --git a/src/agents/research/prompts/en/decompose_agent.yaml b/src/agents/research/prompts/en/decompose_agent.yaml
new file mode 100644
index 000000000..8e511ea0d
--- /dev/null
+++ b/src/agents/research/prompts/en/decompose_agent.yaml
@@ -0,0 +1,89 @@
+# DecomposeAgent Prompt Configuration (English)
+
+system:
+ role: |
+ You are a research planning expert, responsible for decomposing complex topics into logically clear, non-overlapping subtopic systems.
+
+process:
+ generate_queries: |
+ Generate {num_queries} search queries for the following topic. Only output JSON object:
+
+ Topic: {topic}
+
+ Requirements:
+ 1. Each query 1-3 keywords, concise and representative
+ 2. Cover different dimensions of the topic to ensure diversity
+ 3. Avoid duplication between queries
+
+ Output JSON:
+ {{
+ "queries": ["Query 1", "Query 2", ...]
+ }}
+
+ decompose: |
+ Decompose the topic into subtopics based on the following information. Only output JSON object:
+
+ Main Topic: {topic}
+
+ Background Knowledge (from RAG retrieval):
+ {rag_context}
+
+ {decompose_requirement}
+
+ **Decomposition Steps:**
+
+ 1. **Analyze Background Knowledge**: Identify core concepts, key theories, and important content
+
+ 2. **Identify Research Dimensions**: Determine research focus for each dimension, ensure dimensions are complementary
+
+ 3. **Generate Subtopics**:
+ - Based on actual content in background knowledge
+ - Subtopics are logically related but not duplicated
+ - Cover main aspects of the theme
+
+ 4. **Refine Descriptions**:
+ - title: Concise and clear, expressing the core of the subtopic
+ - overview: 2-3 sentences, explaining content, importance, and research value
+
+ Output JSON:
+ {{
+ "sub_topics": [
+ {{
+ "title": "Subtopic Title",
+ "overview": "Detailed overview, explaining content, focus, and research value"
+ }}
+ ]
+ }}
+
+ decompose_without_rag: |
+ Decompose the following research topic into clear, well-structured subtopics. Only output JSON object:
+
+ Main Topic: {topic}
+
+ {decompose_requirement}
+
+ **Decomposition Steps (Without RAG Context):**
+
+ 1. **Identify Key Aspects**: Based on your knowledge, identify the key aspects and dimensions of this topic
+
+ 2. **Generate Subtopics**:
+ - Each subtopic should cover a distinct aspect of the main topic
+ - Subtopics should have logical relationships but not overlap or duplicate
+ - Ensure subtopics together form a comprehensive research framework
+
+ 3. **Refine Descriptions**:
+ - title: Concise and clear, expressing the core focus of the subtopic
+ - overview: 2-3 sentences explaining:
+ - What this subtopic covers
+ - Why it's important for understanding the main topic
+ - Key concepts or areas to explore
+
+ Output JSON:
+ {{
+ "sub_topics": [
+ {{
+ "title": "Subtopic title (concise and clear)",
+ "overview": "Detailed overview (2-3 sentences explaining importance, scope, and key areas)"
+ }}
+ ]
+ }}
diff --git a/src/agents/research/prompts/en/manager_agent.yaml b/src/agents/research/prompts/en/manager_agent.yaml
new file mode 100644
index 000000000..40895525e
--- /dev/null
+++ b/src/agents/research/prompts/en/manager_agent.yaml
@@ -0,0 +1,24 @@
+# ManagerAgent Prompt Configuration (English)
+
+system:
+ role: |
+ You are a task scheduling expert, responsible for managing the state of dynamic topic queues and task dispatching.
+
+process:
+ decide_next: |
+ Decide the next operation based on queue status. Only output JSON object:
+
+ Queue Statistics:
+ total={total}, pending={pending}, researching={researching}, completed={completed}, failed={failed}
+
+ **Decision Rules:**
+ - If there are pending → action: "dispatch", select the head block_id
+ - If no pending and researching=0 → action: "finish"
+ - Otherwise → action: "wait"
+
+ Output JSON:
+ {{
+ "action": "dispatch|finish|wait",
+ "block_id": "(required when dispatch)",
+ "reason": "Brief reason"
+ }}
diff --git a/src/agents/research/prompts/en/note_agent.yaml b/src/agents/research/prompts/en/note_agent.yaml
new file mode 100644
index 000000000..cab989fd9
--- /dev/null
+++ b/src/agents/research/prompts/en/note_agent.yaml
@@ -0,0 +1,121 @@
+# NoteAgent Prompt Configuration - Deep Information Extraction and Structured Summary
+# Design Goal: Extract rich structured information from tool outputs to provide materials for high-quality report generation
+
+system:
+ role: |
+ You are an information extraction and knowledge organization expert, responsible for extracting key information from various tool outputs and generating structured, reusable high-quality summaries.
+
+ **Core Capabilities**:
+ 1. **Multimodal Information Recognition**: Ability to identify and preserve formulas, tables, code, data, and other structured elements
+ 2. **Hierarchical Extraction**: Distinguish core information, supporting information, and background information
+ 3. **Knowledge Association**: Identify relationships and dependencies between concepts
+ 4. **Academic Standards**: Maintain terminology accuracy and citation completeness
+
+ **Important Format Requirements**:
+ - All outputs must strictly follow JSON format
+ - Only output valid JSON objects, do not include any additional text, explanations, or code block markers
+ - JSON must be directly parseable, cannot contain comments or format errors
+ - If the output contains text content, include it as a JSON string value and properly escape special characters
+
+process:
+ generate_summary: |
+ Extract key information from the following tool output and generate a structured summary.
+
+ **Important: You must only output a valid JSON object, do not include any other text, explanations, or code block markers.**
+
+ Tool Type: {tool_type}
+ Query: {query}
+ Topic: {topic}
+ Context: {context}
+
+ Raw Output:
+ {raw_answer}
+
+ **Deep Extraction Framework**:
+
+ ## Step 1: Content Type Identification
+
+ Identify information types contained in the raw output:
+ - □ Concept Definitions (terms, definitions, explanations)
+ - □ Mathematical Formulas (equations, theorems, derivations)
+ - □ Data Tables (comparisons, parameters, statistics)
+ - □ Algorithms/Code (pseudocode, implementations, examples)
+ - □ Processes/Architectures (steps, workflows, system structures)
+ - □ Cases/Examples (application scenarios, experimental results)
+ - □ Citations/Sources (papers, authors, references)
+
+ ## Step 2: Hierarchical Information Extraction
+
+ 1. **Core Layer** (Must Extract):
+ - Key information directly answering the query
+ - Important definitions, formulas, conclusions
+ - Core data and key findings
+
+ 2. **Supporting Layer** (Selective Extraction):
+ - Derivation processes and argumentation logic
+ - Experimental methods and validation data
+ - Comparative analysis and pros/cons
+
+ 3. **Background Layer** (Brief Mention):
+ - Historical evolution and development trajectory
+ - Related work and references
+ - Applicable conditions and limitations
+
+ ## Step 3: Structured Information Preservation
+
+ **Elements that MUST preserve original format**:
+
+ 1. **Mathematical Formulas**:
+ - Inline formulas: preserve as `$...$` format
+ - Block formulas: preserve as `$$...$$` format
+ - Example: `$E = mc^2$` or `$$\\nabla \\cdot E = \\frac{\\rho}{\\epsilon_0}$$`
+
+ 2. **Table Data**:
+ - Convert to Markdown table format
+ - Preserve headers and key data rows
+ - Example: `| Method | Accuracy | Efficiency |\\n|---|---|---|\\n| A | 95% | Fast |`
+
+ 3. **Code Snippets**:
+ - Preserve key algorithms or example code
+ - Use code block format with language annotation
+ - Example: `\\`\\`\\`python\\ndef func():\\n pass\\n\\`\\`\\``
+
+ 4. **List Structures**:
+ - Preserve steps, key points, and other lists
+ - Use `1. 2. 3.` or `- - -` format
+
+ ## Step 4: Generate Structured Summary
+
+ **Summary Requirements**:
+ - Length: 300-600 words (adjust based on information density)
+ - Structure: Organize by logical themes, not original text order
+ - Completeness: Summary should be independently readable without referring to raw output
+ - Accuracy: Maintain accuracy of terminology and numerical values
+
+ **Output Format Requirements (Strictly Follow):**
+ - Only output JSON object, do not use ```json code block wrapper
+ - Do not add any explanatory text
+ - Special characters in JSON strings (such as quotes, newlines, backslashes) must be properly escaped
+ - Ensure JSON format is completely valid and can be directly parsed by json.loads()
+
+ Output Example (for format reference only, do not copy content):
+ {{
+ "summary": "Structured summary content (including preserved formulas, tables, and other elements)",
+ "key_elements": {{
+ "definitions": ["definition1", "definition2"],
+ "formulas": ["$formula1$", "$$formula2$$"],
+ "data_points": ["data1", "data2"],
+ "methods": ["method1", "method2"]
+ }},
+ "content_type": ["concept", "formula", "data"],
+ "confidence": 0.85,
+ "source_quality": "high/medium/low"
+ }}
+
+ **Key Principles**:
+ 1. Prioritize quantifiable, verifiable information
+ 2. Formulas and code must be preserved completely, do not simplify
+ 3. Convert table data to Markdown format
+ 4. Annotate credibility of information sources
+
+ **Now directly output the JSON object, do not include any other content.**
diff --git a/src/agents/research/prompts/en/rephrase_agent.yaml b/src/agents/research/prompts/en/rephrase_agent.yaml
new file mode 100644
index 000000000..8097e2845
--- /dev/null
+++ b/src/agents/research/prompts/en/rephrase_agent.yaml
@@ -0,0 +1,58 @@
+# RephraseAgent Prompt Configuration (English)
+
+system:
+ role: |
+ You are a research topic optimization expert, responsible for transforming user research needs into clear, specific, and executable research topics.
+
+process:
+ rephrase: |
+ Analyze and optimize the following user input. Only output JSON object:
+
+ User Input: {user_input}
+ Iteration Count: {iteration}
+ {previous_result}
+
+ **Optimization Dimensions:**
+
+ 1. **Research Topic**: Transform into a clear, specific, researchable topic
+ 2. **Research Focus**: Identify core issues and key elements
+ 3. **Research Scope**: Clarify boundaries, define depth and breadth
+ 4. **Optimization Rationale**: Explain optimization basis and logic
+
+ Based on the above considerations, generate a research objective with prominent theme, clear focus, and well-defined scope, with length not exceeding twice the user input.
+
+ Output JSON:
+ {{
+ "topic": "A clear, complete research topic description"
+ }}
+
+ Requirements:
+ 1. topic must be coherent text that can independently express complete information
+ 2. When iteration = 0, provide reasonable focus and optimization
+ 3. When iteration > 0, adjust based on user feedback
+
+ check_satisfaction: |
+ Analyze user feedback on the rephrasing result. Only output JSON object:
+
+ Current Result:
+ - Topic: {topic}
+
+ User Feedback: {user_feedback}
+
+ **Judgment Dimensions:**
+ 1. Whether the user explicitly expresses satisfaction/dissatisfaction
+ 2. Whether specific modification requirements are proposed
+ 3. Whether feedback is positive or negative
+
+ Output JSON:
+ {{
+ "user_satisfied": true/false,
+ "should_continue": true/false,
+ "interpretation": "Interpretation of user intent",
+ "suggested_action": "Suggested next action"
+ }}
+
+ Judgment Criteria:
+ - Satisfied, agree, okay, good → user_satisfied = true, should_continue = false
+ - Request modification or raise opinions → user_satisfied = false, should_continue = true
+ - Ambiguous feedback → tend to continue optimization
diff --git a/src/agents/research/prompts/en/reporting_agent.yaml b/src/agents/research/prompts/en/reporting_agent.yaml
new file mode 100644
index 000000000..af0a31a8e
--- /dev/null
+++ b/src/agents/research/prompts/en/reporting_agent.yaml
@@ -0,0 +1,380 @@
+# ReportingAgent Prompt Configuration - Deep Research Report Generation
+# Design Goal: Generate rich, coherent, and comprehensive academic-level deep research reports
+
+# Citation instruction templates
+citation:
+ enabled_instruction: |
+ **Citation Requirements (CRITICAL)**:
+ - Format: Use `[N]` format where N is the reference number from the table below
+ - ONLY use reference numbers from the Citation Reference Table - do NOT invent numbers!
+ - Place citations at the end of sentences or claims that use information from that source
+ - DO NOT add a References section - it will be generated automatically
+
+ **Citation Reference Table** (use these exact numbers):
+ {citation_table}
+
+ **Examples**:
+ - "According to recent research [5], the method achieves..."
+ - "This approach has been validated in multiple studies [3][7]."
+
+ disabled_instruction: |
+ **Citation Requirements**:
+ - DO NOT add any inline citations like [1], [[1]], or [N] in the text
+ - DO NOT add a References section at the end - references will be handled separately
+ - Focus on content synthesis without citation markers
+
+system:
+ role: |
+ You are a top-tier academic writing and content integration expert, skilled at transforming complex research findings into well-structured, insightful professional reports. Your reports should exhibit the following qualities:
+
+ **Core Writing Philosophy**:
+ 1. **Depth over Breadth**: Better to deeply analyze a few key points than to superficially cover many
+ 2. **Argumentation over Statement**: Every point should be supported by evidence, reasoning, or examples
+ 3. **Structured Presentation**: Use formulas, tables, flowcharts, code, and other elements to enhance expression
+ 4. **Academic Rigor**: Accurately cite sources, distinguish facts from inferences, acknowledge limitations
+
+ **Important Format Requirements**:
+ - All outputs must strictly follow JSON format
+ - Only output valid JSON objects, do not include any additional text, explanations, or code block markers
+ - JSON must be directly parseable, cannot contain comments or format errors
+ - If the output contains Markdown content, include it as a JSON string value and properly escape special characters
+
+process:
+ deduplicate: |
+ Analyze the following topic list and identify duplicate or highly similar topics.
+
+ **Important: You must only output a valid JSON object, do not include any other text, explanations, or code block markers.**
+
+ Topic List:
+ {topics}
+
+ Total Topics: {total_topics}
+
+ **Analysis Steps:**
+ 1. Understand the core content and research perspective of each topic
+ 2. Identify semantically duplicate or highly similar topics (Note: same concept with different perspectives is NOT duplication)
+ 3. Keep the most representative and content-rich topics
+
+ **Output Format Requirements (Strictly Follow):**
+ - Only output JSON object, do not use ```json code block wrapper
+ - Do not add any explanatory text
+ - Ensure JSON format is completely valid and can be directly parsed
+
+ Output Example (for format reference only, do not copy content):
+ {{
+ "duplicates": [{{"indices": [0, 3], "reason": "Semantic duplication: both discuss basic principles of XX"}}],
+ "keep_indices": [0, 1, 2, 4],
+ "summary": "Kept 4 complementary topics covering theoretical foundations, technical implementation, application scenarios, and frontier developments"
+ }}
+
+ **Now directly output the JSON object, do not include any other content.**
+
+ generate_outline: |
+ Generate a structured three-level heading system outline for the following research.
+
+ **Important: You must only output a valid JSON object, do not include any other text, explanations, or code block markers.**
+
+ Research Topic: {topic}
+
+ Research Topics (including subtopic, overview, and tool_summaries):
+ {topics_json}
+
+ Total Topics: {total_topics}
+
+ **Outline Design Principles**:
+
+ 1. **Three-Level Heading System**:
+ - Level 1 (#): Report main title
+ - Level 2 (##): Major sections (Introduction, Core Sections 1-N, Conclusion)
+ - Level 3 (###): Subsections within each section
+ - Level 4 (####): Further subdivisions (optional, for complex sections)
+
+ 2. **Logical Structure Design**:
+ - Identify logical relationships between topics: hierarchy, dependency, parallel, progression, comparison
+ - Order by cognitive flow: Concept → Principles → Methods → Applications → Evaluation → Outlook
+ - Ensure clear transition logic between sections
+
+ 3. **Section Design Guidelines**:
+ - Each main section should have a clear research question or objective
+ - Subsections should cover core dimensions of the topic
+ - Instructions should specify key elements to include and presentation approach
+
+ **Output Format Requirements (Strictly Follow):**
+ - Only output JSON object, do not use ```json code block wrapper
+ - Do not add any explanatory text
+
+ Output Example (for format reference only, do not copy content):
+ {{
+ "title": "# Report Main Title: Precisely Express Research Topic",
+ "introduction": "## Introduction",
+ "introduction_instruction": "Present research background, problem motivation, research objectives, and report structure",
+ "sections": [
+ {{
+ "title": "## 1. First Main Section Title",
+ "instruction": "This section focuses on... should include principle derivation and key formulas",
+ "block_id": "block_1",
+ "subsections": [
+ {{
+ "title": "### 1.1 Subsection Title",
+ "instruction": "Explain in detail... recommend using comparison tables"
+ }},
+ {{
+ "title": "### 1.2 Subsection Title",
+ "instruction": "Analyze... recommend using flowcharts"
+ }}
+ ]
+ }}
+ ],
+ "conclusion": "## Conclusion and Future Directions",
+ "conclusion_instruction": "Summarize core findings, research contributions, limitations, and future directions"
+ }}
+
+ **Now directly output the JSON object, do not include any other content.**
+
+ write_introduction: |
+ Write the introduction section of the research report.
+
+ **Important: You must only output a valid JSON object, do not include any other text, explanations, or code block markers.**
+
+ Research Topic: {topic}
+ Introduction Guidance: {introduction_instruction}
+ Research Topics Overview: {topics_summary}
+ Total Topics: {total_topics}
+
+ **Introduction Writing Framework** (400-600 words):
+
+ 1. **Opening Statement** (Paragraph 1):
+ - Start from macro background or important trends
+ - Introduce core challenges or opportunities in the research field
+ - Highlight the necessity and urgency of the research
+
+ 2. **Problem Focus** (Paragraph 2):
+ - Clearly state the specific problems this research addresses
+ - Explain limitations of existing methods or understanding
+ - Introduce core research objectives
+
+ 3. **Research Scope** (Paragraph 3):
+ - Outline the main dimensions covered by the research
+ - Explain the logical relationships between different parts
+ - Preview core findings or contributions (optional)
+
+ 4. **Structure Guide** (Paragraph 4):
+ - Briefly introduce the organization of report sections
+ - Help readers build reading expectations
+
+ **Writing Requirements**:
+ - Use academic but accessible language
+ - Each paragraph should have a clear topic sentence
+ - Natural transitions between paragraphs
+ - Do not use section headings, write body content directly
+
+ **Output Format Requirements (Strictly Follow):**
+ - Only output JSON object, do not use ```json code block wrapper
+ - Special characters in JSON strings (such as quotes, newlines) must be properly escaped
+
+ Output Example:
+ {{
+ "introduction": "Complete introduction content (Markdown format, without heading, 400-600 words)"
+ }}
+
+ **Now directly output the JSON object, do not include any other content.**
+
+ write_section_body: |
+ Write in-depth section content based on research data.
+
+ **Important: You must only output a valid JSON object, do not include any other text, explanations, or code block markers.**
+
+ Research Topic: {topic}
+ Section Title: {section_title}
+ Writing Guidance: {section_instruction}
+ Data Source: {block_data}
+
+ **Deep Writing Framework**:
+
+ ## Step 1: In-Depth Material Analysis
+
+ 1. **Information Classification**:
+ - **Core Layer**: Key definitions, core formulas, main conclusions → Must present completely
+ - **Supporting Layer**: Derivation processes, experimental data, case analyses → Selectively elaborate
+ - **Background Layer**: Historical evolution, related work → Briefly mention
+
+ 2. **Information Credibility Assessment**:
+ - Priority: peer-reviewed papers > authoritative textbooks > technical documentation > web resources
+ - Conflict handling: Note different viewpoints, or choose most recent/authoritative source
+
+ ## Step 2: Structured Organization
+
+ **Three-Level Heading System** (Must Follow):
+ - Use `##` as the main section heading
+ - Use `###` to organize sub-topics (2-4 is ideal)
+ - Complex sub-topics can use `####` for further subdivision
+
+ **Logical Architecture Patterns** (Choose the most suitable one):
+ - **Deductive**: Principles → Corollaries → Applications → Validation
+ - **Inductive**: Phenomena → Analysis → Patterns → Theory
+ - **Comparative**: Method A vs Method B → Pros/Cons Analysis → Applicable Scenarios
+ - **Problem-Oriented**: Problem → Existing Solutions → Limitations → Improvement Ideas
+
+ ## Step 3: Multi-Modal Element Usage
+
+ **Must selectively use the following elements based on content characteristics**:
+
+ 1. **Mathematical Formulas** (LaTeX format):
+ - Inline formula: `$E = mc^2$`
+ - Block formula:
+ ```
+ $$
+ \mathcal{L} = \sum_{i=1}^{n} \ell(y_i, f(x_i)) + \lambda \Omega(f)
+ $$
+ ```
+ - Applicable: definitions, theorems, derivations, optimization objectives, etc.
+
+ 2. **Tables** (Markdown format):
+ - Applicable: multi-dimensional comparisons, parameter configurations, experimental results, classification summaries
+ - Format example:
+ ```
+ | Method | Accuracy | Efficiency | Use Case |
+ |--------|----------|------------|----------|
+ | A | 95% | Fast | Real-time systems |
+ | B | 98% | Slow | Offline analysis |
+ ```
+
+ 3. **Flowcharts** (Mermaid format):
+ - Applicable: algorithm flows, system architectures, decision logic, data flows
+ - Format example:
+ ```mermaid
+ graph TD
+ A[Input] --> B{{Processing}}
+ B --> C[Output]
+ ```
+
+ 4. **Code Blocks**:
+ - Applicable: algorithm implementations, configuration examples, API calls
+ - Must specify language type (python/javascript/sql, etc.)
+
+ 5. **Lists and Hierarchy**:
+ - Ordered lists: steps, rankings, priorities
+ - Unordered lists: features, elements, options
+ - Nested lists: hierarchical relationships, classification systems
+
+ ## Step 4: Academic Writing Standards
+ {citation_instruction}
+
+ 1. **Deep Paraphrasing**:
+ - Avoid direct copying, reorganize with academic language
+ - Example transformation:
+ - Original: "Method X works well"
+ - Revised: "Experimental results demonstrate that Method X achieves significant improvement in metric Y, with a Z% increase over the baseline approach"
+
+ 2. **Argument Completeness**:
+ - Each core point should have: Claim → Evidence → Analysis → Summary
+ - Use appropriate transition sentences to connect paragraphs
+
+ 3. **Technical Terminology Handling**:
+ - Provide definition or explanation when first mentioned
+ - Can use "term (original English)" format
+
+ **Output Format Requirements (Strictly Follow):**
+ - Only output JSON object, do not use ```json code block wrapper
+ - Newlines in JSON strings should use \n escape
+ - Ensure JSON format is completely valid
+
+ Output Example:
+ {{
+ "section_content": "## Section Title\n\nOpening paragraph...\n\n### 1.1 Subsection Title\n\nContent...\n\n### 1.2 Subsection Title\n\nContent...{citation_output_hint}"
+ }}
+
+ **Word Count Requirement**: Each section should be at least 800 words, with comprehensive and thorough discussion
+
+ **Now directly output the JSON object, do not include any other content.**
+
+ write_conclusion: |
+ Write the conclusion section of the research report.
+
+ **Important: You must only output a valid JSON object, do not include any other text, explanations, or code block markers.**
+
+ Research Topic: {topic}
+ Conclusion Guidance: {conclusion_instruction}
+ Key Findings: {topics_findings}
+ Total Topics: {total_topics}
+
+ **Conclusion Writing Framework** (500-700 words):
+
+ 1. **Research Review and Core Findings** (Paragraphs 1-2):
+ - Briefly review research questions and methods
+ - Systematically summarize core findings from each chapter
+ - Synthesize into overall conclusions
+
+ 2. **Research Contributions and Value** (Paragraph 3):
+ - **Theoretical Contributions**: Advances in domain understanding
+ - **Methodological Contributions**: New methods, frameworks, or tools
+ - **Practical Value**: Guidance for real-world applications
+
+ 3. **Limitations and Reflections** (Paragraph 4):
+ - Honestly point out research limitations
+ - Explain constraints of data, methods, or scope
+ - Indicate boundaries of conclusion applicability
+
+ 4. **Future Outlook** (Paragraph 5):
+ - Identify open problems to be solved
+ - Propose valuable research directions
+ - Outlook on field development trends
+
+ **Writing Requirements**:
+ - Conclusion should be highly summarized, avoid repeating text details
+ - Demonstrate critical thinking, do not avoid limitations
+ - Outlook should be specific and feasible, not generic
+ - Do not use section headings, write body content directly
+
+ **Output Format Requirements (Strictly Follow):**
+ - Only output JSON object, do not use ```json code block wrapper
+ - Special characters in JSON strings must be properly escaped
+
+ Output Example:
+ {{
+ "conclusion": "Complete conclusion content (Markdown format, without heading, 500-700 words)"
+ }}
+
+ **Now directly output the JSON object, do not include any other content.**
+
+ # New: Subsection writing prompt (for Level 3 heading content)
+ write_subsection: |
+ Write subsection content based on parent section context.
+
+ **Important: You must only output a valid JSON object, do not include any other text, explanations, or code block markers.**
+
+ Research Topic: {topic}
+ Parent Section Title: {parent_section_title}
+ Subsection Title: {subsection_title}
+ Writing Guidance: {subsection_instruction}
+ Related Data: {subsection_data}
+
+ **Writing Requirements**:
+
+ 1. **Content Positioning**:
+ - Focus on the specific topic of the subsection
+ - Maintain logical coherence with the parent section
+ - Avoid content overlap with other subsections
+
+ 2. **Depth Requirements**:
+ - Provide specific technical details or case analyses
+ - Appropriately use formulas, tables, charts, and other elements
+ - Arguments should be well-reasoned and evidence-based
+
+ 3. **Format Standards**:
+ - Use `###` as subsection heading
+ - Can use `####` for further subdivision (optional)
+ - Clear paragraphs with distinct logic
+
+ **Output Format Requirements (Strictly Follow):**
+ - Only output JSON object
+ - Newlines in JSON strings should use \n escape
+
+ Output Example:
+ {{
+ "subsection_content": "### Subsection Title\n\nContent...\n\n#### Sub-topic (optional)\n\nContent..."
+ }}
+
+ **Word Count Requirement**: Each subsection should be 300-500 words
+
+ **Now directly output the JSON object, do not include any other content.**
diff --git a/src/agents/research/prompts/en/research_agent.yaml b/src/agents/research/prompts/en/research_agent.yaml
new file mode 100644
index 000000000..c9789518d
--- /dev/null
+++ b/src/agents/research/prompts/en/research_agent.yaml
@@ -0,0 +1,173 @@
+# ResearchAgent Prompt Configuration (English)
+
+system:
+ role: |
+ You are a knowledge base-based deep research strategy expert, responsible for systematically mining content related to topics from the knowledge base and expanding to external resources as needed.
+
+# Guidance templates for dynamic content
+guidance:
+ # Online search instruction when both web_search and paper_search are enabled
+ online_search_both: |
+ **Online Search Evaluation Guidance (web_search and paper_search enabled)**:
+
+ When evaluating knowledge sufficiency, in addition to assessing knowledge base content coverage, you also need to consider:
+
+ 1. **Content Timeliness Assessment**:
+ - Does current knowledge include the latest developments, industry trends, and application cases?
+ - Is it necessary to supplement the latest background information and current application status?
+ - Might the knowledge base content be outdated and need latest information supplements?
+
+ 2. **Knowledge Extension Assessment**:
+ - Has the knowledge been extended from basic knowledge base content to include the latest developments?
+ - Has real-time background, industry cases, and latest applications been supplemented through web_search?
+ - Has cutting-edge academic research, latest theoretical advances, and specific research work been supplemented through paper_search?
+
+ 3. **Research Completeness Assessment**:
+ - If the topic involves cutting-edge research or latest developments, has relevant content been supplemented through online search?
+ - Has a complete knowledge chain from knowledge base fundamentals to latest developments been formed?
+
+ Judgment Criteria:
+ - If knowledge base content has been fully explored AND necessary real-time information/cutting-edge research has been supplemented through online search, consider it sufficient
+ - If knowledge base content has been fully explored BUT lacks necessary real-time information/cutting-edge research supplements, consider it insufficient
+ - If knowledge base content has not been fully explored, prioritize continuing to explore the knowledge base, temporarily ignoring online search
+
+ # Online search instruction when only web_search is enabled
+ online_search_web_only: |
+ **Online Search Evaluation Guidance (web_search enabled)**:
+
+ When evaluating knowledge sufficiency, in addition to assessing knowledge base content coverage, you also need to consider:
+
+ 1. **Content Timeliness Assessment**:
+ - Does current knowledge include the latest developments, industry trends, and application cases?
+ - Is it necessary to supplement the latest background information and current application status?
+ - Might the knowledge base content be outdated and need latest information supplements?
+
+ 2. **Knowledge Extension Assessment**:
+ - Has the knowledge been extended from basic knowledge base content to include the latest developments?
+ - Has real-time background, industry cases, and latest applications been supplemented through web_search?
+
+ Judgment Criteria:
+ - If knowledge base content has been fully explored AND necessary real-time information has been supplemented through web_search, consider it sufficient
+ - If knowledge base content has been fully explored BUT lacks necessary real-time information supplements, consider it insufficient
+ - If knowledge base content has not been fully explored, prioritize continuing to explore the knowledge base, temporarily ignoring web_search
+
+ # Online search instruction when only paper_search is enabled
+ online_search_paper_only: |
+ **Online Search Evaluation Guidance (paper_search enabled)**:
+
+ When evaluating knowledge sufficiency, in addition to assessing knowledge base content coverage, you also need to consider:
+
+ 1. **Cutting-edge Research Assessment**:
+ - Does current knowledge include relevant cutting-edge academic research and latest theoretical advances?
+ - Is it necessary to supplement specific research work, latest methods, and latest discoveries?
+ - Does the knowledge base content lack cutting-edge research perspectives?
+
+ 2. **Knowledge Extension Assessment**:
+ - Has the knowledge been extended from basic knowledge base content to include cutting-edge research?
+ - Has cutting-edge academic research, latest theoretical advances, and specific research work been supplemented through paper_search?
+
+ Judgment Criteria:
+ - If knowledge base content has been fully explored AND necessary cutting-edge research has been supplemented through paper_search, consider it sufficient
+ - If knowledge base content has been fully explored BUT lacks necessary cutting-edge research supplements, consider it insufficient
+ - If knowledge base content has not been fully explored, prioritize continuing to explore the knowledge base, temporarily ignoring paper_search
+
+ # Iteration mode criteria for flexible mode
+ iteration_mode_flexible: |
+ - **FLEXIBLE mode (Auto)**: You have autonomy to decide sufficiency.
+ - You MAY conclude sufficiency earlier if knowledge is genuinely comprehensive
+ - Still ensure core aspects are covered before concluding
+ - Quality over quantity: focus on meaningful coverage, not iteration count
+
+ # Iteration mode criteria for fixed mode
+ iteration_mode_fixed: |
+ - **FIXED mode**: Be CONSERVATIVE about declaring sufficiency.
+ - In early iterations (1-{early_threshold}): Rarely conclude sufficiency. Continue exploring.
+ - In middle iterations: Require strong evidence of comprehensive coverage.
+ - Only in late iterations ({early_threshold}+): Consider sufficiency if truly comprehensive.
+ - The goal is thorough exploration, not quick completion.
+
+process:
+ check_sufficiency: |
+ Determine whether the current knowledge for the following topic is sufficient. Only output JSON object:
+
+ Topic: {topic}
+ Topic Overview: {overview}
+ Current Knowledge: {current_knowledge}
+ Iteration Count: {iteration}
+ {online_search_instruction}
+ {research_depth_guidance}
+ {iteration_mode_criteria}
+
+ **Important Principle: Depth over Breadth**
+
+ You must strictly and systematically evaluate whether the current knowledge truly meets the "deep research" standard, not just "surface coverage".
+
+ **Evaluation Steps:**
+
+ 1. **Identify Core Elements** (evaluate at least the following 6 dimensions):
+ - □ Concept Definition: Is there a clear, complete definition?
+ - □ Core Principles: Is the working mechanism, derivation process deeply explained?
+ - □ Key Formulas/Algorithms: Does it include specific mathematical expressions or algorithm steps?
+ - □ Application Scenarios: Are there specific application cases or instance analyses?
+ - □ Relationships: Are connections with other concepts/fields explored?
+ - □ Limitations and Development: Are limitations, challenges, or cutting-edge developments discussed?
+
+ 2. **Strictly Evaluate Coverage**:
+ - Count the number of covered dimensions (at least 4 dimensions need to be covered)
+ - Evaluate the depth of each dimension (surface mention vs. in-depth analysis)
+ - Identify key omissions (which dimensions are completely unaddressed or insufficiently deep)
+
+ 3. **Determine Sufficiency Criteria**:
+ - **Sufficient** (is_sufficient=true): Meets all of the following conditions
+ ① At least 5 core dimensions covered
+ ② Each covered dimension has substantial content (not just mentioned)
+ ③ Iteration count ≥ 3 (ensuring multiple rounds of exploration)
+ - **Insufficient** (is_sufficient=false): Any condition not met
+
+ Output JSON:
+ {{
+ "is_sufficient": true/false,
+ "covered_dimensions": ["List of covered dimensions"],
+ "missing_dimensions": ["List of missing or insufficiently deep dimensions"],
+ "coverage_score": 0.0-1.0,
+ "reason": "Judgment reason (specifically explain coverage and judgment basis)"
+ }}
+
+ generate_query_plan: |
+ When knowledge is insufficient, formulate the next query plan. Only output JSON object:
+
+ Topic: {topic}
+ Topic Overview: {overview}
+ Current Knowledge: {current_knowledge}
+ Iteration Count: {iteration}
+ Existing Topics:
+ {existing_topics}
+
+ **Available Tools (ONLY use these tools)**:
+ {available_tools}
+
+ {tool_phase_guidance}
+
+ **Query Design Principles**:
+ 1. **IMPORTANT**: Only select from the Available Tools listed above. Do not use tools that are not available.
+ 2. Each query should target a specific knowledge gap
+ 3. Avoid duplication with existing content in current knowledge
+ 4. Queries should be specific and executable (avoid being too broad)
+ 5. If using paper_search, must use English keywords
+
+ **New Topic Evaluation**: Only suggest adding a new topic when discovering an important branch highly related to the theme and completely different from existing topics (score ≥ 0.85)
+
+ Output JSON:
+ {{
+ "query": "Specific query statement",
+ "tool_type": "Select from Available Tools above",
+ "target_dimension": "Knowledge dimension targeted by this query",
+ "rationale": "Tool selection reason and query objective",
+ "parallel": false,
+ "fallback": ["rag_hybrid", "rag_naive"],
+ "should_add_new_topic": false,
+ "new_sub_topic": null,
+ "new_overview": null,
+ "new_topic_reason": null,
+ "new_topic_score": 0.0
+ }}
diff --git a/src/agents/research/research_pipeline.py b/src/agents/research/research_pipeline.py
new file mode 100644
index 000000000..be1aabe2f
--- /dev/null
+++ b/src/agents/research/research_pipeline.py
@@ -0,0 +1,1293 @@
+#!/usr/bin/env python
+"""
+ResearchPipeline 2.0 - Research workflow based on dynamic topic queue
+Coordinates three stages: Planning -> Researching -> Reporting
+"""
+
+import asyncio
+from datetime import datetime
+import json
+from pathlib import Path
+import sys
+from typing import Any, Callable
+
+
+def _get_project_root() -> Path:
+ """
+ Get project root directory robustly by looking for marker files.
+ Works regardless of how the script is invoked.
+ """
+ # Start from current file's directory
+ current = Path(__file__).resolve().parent
+
+ # Walk up looking for project markers (pyproject.toml, requirements.txt, or src/ directory)
+ markers = ["pyproject.toml", "requirements.txt", ".git"]
+
+ for _ in range(10): # Limit to 10 levels up
+ for marker in markers:
+ if (current / marker).exists():
+ return current
+ parent = current.parent
+ if parent == current: # Reached filesystem root
+ break
+ current = parent
+
+ # Fallback: use relative path from this file
+ # This file is at: src/agents/research/research_pipeline.py
+ # So project root is: ../../../
+ return Path(__file__).resolve().parent.parent.parent.parent
+
+
+# Get project root
+PROJECT_ROOT = _get_project_root()
+
+# Add project root to path for imports
+sys.path.insert(0, str(PROJECT_ROOT))
+
+from src.agents.research.agents import (
+ DecomposeAgent,
+ ManagerAgent,
+ NoteAgent,
+ RephraseAgent,
+ ReportingAgent,
+ ResearchAgent,
+)
+from src.agents.research.data_structures import DynamicTopicQueue
+from src.agents.research.utils.citation_manager import CitationManager
+from src.core.logging import get_logger
+from src.tools.code_executor import run_code
+from src.tools.paper_search_tool import PaperSearchTool
+from src.tools.query_item_tool import query_numbered_item
+from src.tools.rag_tool import rag_search
+from src.tools.web_search import web_search
+
+
+class ResearchPipeline:
+ """DR-in-KG 2.0 Research workflow"""
+
+ def __init__(
+ self,
+ config: dict[str, Any],
+ api_key: str,
+ base_url: str,
+ research_id: str | None = None,
+ kb_name: str | None = None,
+ progress_callback: Callable | None = None,
+ ):
+ """
+ Initialize research workflow
+
+ Args:
+ config: Configuration dictionary
+ api_key: API key
+ base_url: API endpoint
+ research_id: Research task ID (optional)
+ kb_name: Knowledge base name (optional, if provided overrides config file setting)
+ progress_callback: Progress callback function (optional), signature: callback(event: Dict[str, Any])
+ """
+ self.config = config
+ self.progress_callback = progress_callback
+
+ # If kb_name is provided, override config
+ if kb_name is not None:
+ if "rag" not in self.config:
+ self.config["rag"] = {}
+ self.config["rag"]["kb_name"] = kb_name
+ self.api_key = api_key
+ self.base_url = base_url
+ self.input_topic: str | None = None
+ self.optimized_topic: str | None = None
+
+ # Generate research ID
+ if research_id is None:
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
+ self.research_id = f"research_{timestamp}"
+ else:
+ self.research_id = research_id
+
+ # Set directories
+ system_config = config.get("system", {})
+ self.cache_dir = Path(system_config.get("output_base_dir", "./cache")) / self.research_id
+ self.reports_dir = Path(system_config.get("reports_dir", "./reports"))
+
+ # Create directories
+ self.cache_dir.mkdir(parents=True, exist_ok=True)
+ self.reports_dir.mkdir(parents=True, exist_ok=True)
+ self.plan_progress_file = self.cache_dir / "planning_progress.json"
+ self.report_progress_file = self.cache_dir / "reporting_progress.json"
+ self.queue_progress_file = self.cache_dir / "queue_progress.json"
+ self._stage_events: dict[str, list[dict[str, Any]]] = {
+ "planning": [],
+ "reporting": [],
+ }
+
+ # Initialize queue
+ queue_cfg = config.get("queue", {})
+ self.queue = DynamicTopicQueue(
+ self.research_id,
+ max_length=queue_cfg.get("max_length"),
+ state_file=str(self.queue_progress_file),
+ )
+
+ # Initialize unified logging system (must be before _init_agents)
+ self._init_logger()
+
+ # Initialize Agents
+ self.agents = {}
+ self._init_agents()
+
+ # Tool instances
+ self._paper_tool: PaperSearchTool | None = None
+
+ # Citation manager
+ self.citation_manager = CitationManager(self.research_id, self.cache_dir)
+
+ # Lock for thread-safe progress file writing in parallel mode
+ import threading
+
+ self._progress_file_lock = threading.Lock()
+
+ def _init_logger(self):
+ """Initialize unified logging system"""
+ # Get log_dir from config paths (user_log_dir from main.yaml)
+ log_dir = self.config.get("paths", {}).get("user_log_dir") or self.config.get(
+ "logging", {}
+ ).get("log_dir")
+
+ self.logger = get_logger(name="Research", log_dir=log_dir)
+ self.logger.success("Logger initialized")
+
+ def _init_agents(self):
+ """Initialize all Agents"""
+ if self.logger:
+ self.logger.info("Initializing Agents...")
+
+ self.agents = {
+ "rephrase": RephraseAgent(self.config, self.api_key, self.base_url),
+ "decompose": DecomposeAgent(self.config, self.api_key, self.base_url),
+ "manager": ManagerAgent(self.config, self.api_key, self.base_url),
+ "research": ResearchAgent(self.config, self.api_key, self.base_url),
+ "note": NoteAgent(self.config, self.api_key, self.base_url),
+ "reporting": ReportingAgent(self.config, self.api_key, self.base_url),
+ }
+
+ # Set Manager's queue
+ self.agents["manager"].set_queue(self.queue)
+
+ if self.logger:
+ self.logger.success(f"Initialized {len(self.agents)} Agents")
+
+ async def _call_tool_with_timeout(
+ self, coro, timeout: float = 60.0, tool_name: str = "tool"
+ ) -> Any:
+ """
+ Execute a coroutine with timeout support
+
+ Args:
+ coro: Coroutine to execute
+ timeout: Timeout in seconds (default 60s)
+ tool_name: Name of the tool for logging
+
+ Returns:
+ Result of the coroutine
+
+ Raises:
+ asyncio.TimeoutError: If timeout exceeded
+ """
+ try:
+ return await asyncio.wait_for(coro, timeout=timeout)
+ except asyncio.TimeoutError:
+ self.logger.warning(f"Tool {tool_name} timed out after {timeout}s")
+ raise
+
+ async def _call_tool_with_retry(
+ self,
+ tool_func,
+ *args,
+ max_retries: int = 2,
+ timeout: float = 60.0,
+ tool_name: str = "tool",
+ **kwargs,
+ ) -> Any:
+ """
+ Call a tool function with retry and timeout support
+
+ Args:
+ tool_func: Tool function to call
+ *args: Positional arguments for the function
+ max_retries: Maximum number of retries (default 2)
+ timeout: Timeout per attempt in seconds (default 60s)
+ tool_name: Name of the tool for logging
+ **kwargs: Keyword arguments for the function
+
+ Returns:
+ Result of the tool function
+ """
+ last_error = None
+
+ for attempt in range(max_retries + 1):
+ try:
+ if asyncio.iscoroutinefunction(tool_func):
+ result = await self._call_tool_with_timeout(
+ tool_func(*args, **kwargs), timeout=timeout, tool_name=tool_name
+ )
+ else:
+ # For sync functions, run in executor
+ import functools
+
+ loop = asyncio.get_event_loop()
+ result = await asyncio.wait_for(
+ loop.run_in_executor(None, functools.partial(tool_func, *args, **kwargs)),
+ timeout=timeout,
+ )
+ return result
+ except asyncio.TimeoutError as e:
+ last_error = e
+ if attempt < max_retries:
+ self.logger.warning(
+ f"Tool {tool_name} attempt {attempt + 1} timed out, retrying..."
+ )
+ await asyncio.sleep(1) # Brief pause before retry
+ except Exception as e:
+ last_error = e
+ if attempt < max_retries:
+ self.logger.warning(
+ f"Tool {tool_name} attempt {attempt + 1} failed: {e}, retrying..."
+ )
+ await asyncio.sleep(1)
+
+ # All retries exhausted
+ self.logger.error(f"Tool {tool_name} failed after {max_retries + 1} attempts: {last_error}")
+ raise last_error if last_error else RuntimeError(f"{tool_name} failed")
+
+ async def _call_tool(self, tool_type: str, query: str) -> str:
+ """Call tool and return raw string answer (JSON string or text)"""
+ tool_type = (tool_type or "").lower()
+
+ # Get timeout and retry settings from config
+ tool_config = self.config.get("researching", {})
+ default_timeout = tool_config.get("tool_timeout", 60)
+ max_retries = tool_config.get("tool_max_retries", 2)
+
+ try:
+ if tool_type in ("rag_hybrid", "rag_naive", "rag"):
+ rag_cfg = self.config.get("rag", {})
+ kb_name = rag_cfg.get("kb_name", "DE-all")
+ default_mode = rag_cfg.get("default_mode", "hybrid")
+ fallback_mode = rag_cfg.get("fallback_mode", "naive")
+ if tool_type == "rag_hybrid":
+ mode = "hybrid"
+ elif tool_type == "rag_naive":
+ mode = "naive"
+ else:
+ mode = default_mode
+ try:
+ res = await self._call_tool_with_retry(
+ rag_search,
+ query=query,
+ kb_name=kb_name,
+ mode=mode,
+ max_retries=max_retries,
+ timeout=default_timeout,
+ tool_name=f"rag_search({mode})",
+ )
+ except Exception:
+ # Retry with fallback mode
+ res = await self._call_tool_with_retry(
+ rag_search,
+ query=query,
+ kb_name=kb_name,
+ mode=fallback_mode,
+ max_retries=1,
+ timeout=default_timeout,
+ tool_name=f"rag_search({fallback_mode})",
+ )
+ return json.dumps(res, ensure_ascii=False)
+
+ if tool_type == "web_search":
+ res = await self._call_tool_with_retry(
+ web_search,
+ query=query,
+ output_dir=str(self.cache_dir),
+ max_retries=max_retries,
+ timeout=default_timeout,
+ tool_name="web_search",
+ )
+ return json.dumps(res, ensure_ascii=False)
+
+ if tool_type == "query_item":
+ kb_name = self.config.get("rag", {}).get("kb_name", "ai_textbook")
+ res = await self._call_tool_with_retry(
+ query_numbered_item,
+ identifier=query,
+ kb_name=kb_name,
+ max_retries=max_retries,
+ timeout=default_timeout,
+ tool_name="query_item",
+ )
+ return json.dumps(res, ensure_ascii=False)
+
+ if tool_type == "paper_search":
+ if self._paper_tool is None:
+ self._paper_tool = PaperSearchTool()
+ years_limit = self.config.get("researching", {}).get("paper_search_years_limit", 3)
+ papers = await self._call_tool_with_retry(
+ self._paper_tool.search_papers,
+ query=query,
+ max_results=3,
+ years_limit=years_limit,
+ max_retries=max_retries,
+ timeout=default_timeout,
+ tool_name="paper_search",
+ )
+ return json.dumps({"papers": papers}, ensure_ascii=False)
+
+ if tool_type == "run_code":
+ # Code execution has its own internal timeout (10s), wrapper timeout is 30s
+ result = await self._call_tool_with_retry(
+ run_code,
+ language="python",
+ code=query,
+ max_retries=1,
+ timeout=30, # Wrapper timeout
+ tool_name="run_code",
+ )
+ return json.dumps(result, ensure_ascii=False)
+
+ # Default fallback to RAG hybrid
+ kb_name = self.config.get("rag", {}).get("kb_name", "ai_textbook")
+ res = await self._call_tool_with_retry(
+ rag_search,
+ query=query,
+ kb_name=kb_name,
+ mode="hybrid",
+ max_retries=max_retries,
+ timeout=default_timeout,
+ tool_name="rag_search(hybrid)",
+ )
+ return json.dumps(res, ensure_ascii=False)
+ except Exception as e:
+ return json.dumps(
+ {"status": "failed", "error": str(e), "tool": tool_type, "query": query},
+ ensure_ascii=False,
+ )
+
+ async def run(self, topic: str) -> dict[str, Any]:
+ """
+ Execute complete research workflow
+
+ Args:
+ topic: Research topic
+
+ Returns:
+ Research result
+ """
+ if self.logger:
+ self.logger.section("DR-in-KG 2.0 - Deep Research System Based on Dynamic Topic Queue")
+ self.logger.info(f"Research Topic: {topic}")
+ self.logger.info(f"Research ID: {self.research_id}")
+ self.input_topic = topic
+
+ try:
+ # ========== Phase 1: Planning (Planning and Initialization) ==========
+ self.logger.info("\n" + "█" * 70)
+ self.logger.info("█ Phase 1: Planning - Planning and Initialization")
+ self.logger.info("█" * 70)
+
+ optimized_topic = await self._phase1_planning(topic)
+
+ # ========== Phase 2: Researching (Dynamic Research Loop) ==========
+ self.logger.info("\n" + "█" * 70)
+ self.logger.info("█ Phase 2: Researching - Dynamic Research Loop")
+ self.logger.info("█" * 70)
+
+ await self._phase2_researching()
+
+ # ========== Phase 3: Reporting (Report Generation) ==========
+ self.logger.info("\n" + "█" * 70)
+ self.logger.info("█ Phase 3: Reporting - Report Generation")
+ self.logger.info("█" * 70)
+
+ report_result = await self._phase3_reporting(optimized_topic)
+
+ # ========== Save Results ==========
+ self.logger.info("\n" + "█" * 70)
+ self.logger.info("█ Save Results")
+ self.logger.info("█" * 70 + "\n")
+
+ report_file = self.reports_dir / f"{self.research_id}.md"
+ with open(report_file, "w", encoding="utf-8") as f:
+ f.write(report_result["report"])
+ self.logger.success(f"Final Report: {report_file}")
+
+ # Save queue
+ queue_file = self.cache_dir / "queue.json"
+ self.queue.save_to_json(str(queue_file))
+ self.logger.success(f"Queue Data: {queue_file}")
+
+ # Save outline (if exists)
+ if "outline" in report_result:
+ outline_file = self.cache_dir / "outline.json"
+ with open(outline_file, "w", encoding="utf-8") as f:
+ json.dump(report_result["outline"], f, ensure_ascii=False, indent=2)
+ self.logger.success(f"Report Outline: {outline_file}")
+
+ # Save metadata
+ metadata = {
+ "research_id": self.research_id,
+ "topic": topic,
+ "optimized_topic": optimized_topic,
+ "statistics": self.queue.get_statistics(),
+ "report_word_count": report_result["word_count"],
+ "completed_at": datetime.now().isoformat(),
+ }
+
+ metadata_file = self.reports_dir / f"{self.research_id}_metadata.json"
+ with open(metadata_file, "w", encoding="utf-8") as f:
+ json.dump(metadata, f, ensure_ascii=False, indent=2)
+ self.logger.success(f"Metadata: {metadata_file}")
+
+ # ===== Token Cost Statistics =====
+ try:
+ from src.agents.research.utils.token_tracker import get_token_tracker
+
+ tracker = get_token_tracker()
+ cost_summary = tracker.format_summary()
+ self.logger.info(cost_summary)
+ cost_file = self.cache_dir / "token_cost_summary.json"
+ tracker.save(str(cost_file))
+ self.logger.success(f"Cost statistics saved: {cost_file}")
+ except Exception as _e:
+ self.logger.warning(f"Cost statistics failed: {_e}")
+
+ self.logger.info("\n" + "=" * 70)
+ self.logger.success("Research Completed!")
+ self.logger.info("=" * 70)
+ self.logger.info(f"Research ID: {self.research_id}")
+ self.logger.info(f"Topic: {topic}")
+ self.logger.info(f"Final Report: {report_file}")
+ self.logger.info(f"Report Word Count: {report_result['word_count']}")
+ self.logger.info(f"Topic Blocks: {len(self.queue.blocks)}")
+ self.logger.info("=" * 70 + "\n")
+
+ return {
+ "research_id": self.research_id,
+ "topic": topic,
+ "final_report_path": str(report_file),
+ "metadata": metadata,
+ }
+
+ except KeyboardInterrupt:
+ self.logger.warning("\n\n⚠️ Research interrupted by user")
+ sys.exit(0)
+ except Exception as e:
+ self.logger.error(f"\n\n❌ Research failed: {e!s}")
+ import traceback
+
+ self.logger.error(traceback.format_exc())
+ raise
+
+ async def _phase1_planning(self, topic: str) -> str:
+ """
+ Phase 1: Planning and Initialization
+
+ Args:
+ topic: User input topic
+
+ Returns:
+ Optimized topic
+ """
+ self._log_progress("planning", "planning_started", user_topic=topic)
+
+ # Check if topic rephrasing is enabled
+ rephrase_config = self.config.get("planning", {}).get("rephrase", {})
+ rephrase_enabled = rephrase_config.get("enabled", True)
+
+ if rephrase_enabled:
+ self.logger.info("\n【Step 1】Topic Rephrasing...")
+
+ # Use RephraseAgent to optimize topic (supports user interaction)
+ max_iterations = rephrase_config.get("max_iterations", 3)
+
+ rephrase_result = None
+ iteration = 0
+ user_feedback = None # Initialize user feedback variable
+
+ # Check if running in frontend mode (has progress_callback)
+ # In frontend mode, skip interactive input loop - user controls via frontend UI
+ is_frontend_mode = self.progress_callback is not None
+
+ while iteration < max_iterations:
+ # Execute rephrasing
+ if iteration == 0:
+ rephrase_result = await self.agents["rephrase"].process(
+ topic, iteration=iteration
+ )
+ # Continue rephrasing based on user feedback
+ elif user_feedback:
+ rephrase_result = await self.agents["rephrase"].process(
+ user_feedback, iteration=iteration, previous_result=rephrase_result
+ )
+ else:
+ # If no feedback, use previous result
+ break
+
+ iteration += 1
+
+ # In frontend mode, only do one iteration and exit
+ # User will control further iterations via frontend UI (/optimize_topic API)
+ if is_frontend_mode:
+ self.logger.info(f"\n{'=' * 70}")
+ self.logger.info("📋 Rephrase Result (Frontend Mode):")
+ self.logger.info(f"{'=' * 70}")
+ self.logger.info(
+ f"Optimized Research Topic: {rephrase_result.get('topic', '')}"
+ )
+ self.logger.info(f"{'=' * 70}")
+ self.logger.success(
+ "Frontend mode: Using current result, proceeding to next stage"
+ )
+ break
+
+ # CLI mode: Ask user opinion (unless max iterations reached)
+ if iteration < max_iterations:
+ self.logger.info(f"\n{'=' * 70}")
+ self.logger.info("📋 Current Rephrasing Result:")
+ self.logger.info(f"{'=' * 70}")
+ self.logger.info(
+ f"Optimized Research Topic: {rephrase_result.get('topic', '')}"
+ )
+ self.logger.info(f"{'=' * 70}")
+ self.logger.info("\n💬 Are you satisfied with this rephrasing result?")
+ self.logger.info(
+ " - Enter 'satisfied', 'ok', etc. to indicate satisfaction, will proceed to next stage"
+ )
+ self.logger.info(
+ " - Enter specific modification suggestions, will continue optimizing based on your feedback"
+ )
+ self.logger.info(" - Press Enter directly to use current result")
+
+ user_input = input("\nYour choice: ").strip()
+
+ if not user_input:
+ self.logger.success("Using current result, proceeding to next stage")
+ break
+
+ # Determine user intent
+ satisfaction = await self.agents["rephrase"].check_user_satisfaction(
+ rephrase_result, user_input
+ )
+
+ if satisfaction.get("user_satisfied", False):
+ self.logger.success("User satisfied, proceeding to next stage")
+ break
+
+ if not satisfaction.get("should_continue", True):
+ self.logger.success("Proceeding to next stage")
+ break
+
+ # Continue iteration, use user input as feedback
+ user_feedback = user_input
+
+ # Ensure there is a result
+ if rephrase_result is None:
+ rephrase_result = {"topic": topic}
+
+ optimized_topic = rephrase_result.get("topic", topic)
+ self._log_progress(
+ "planning",
+ "rephrase_completed",
+ optimized_topic=optimized_topic,
+ iterations=iteration,
+ )
+ else:
+ self.logger.info("\n【Step 1】Topic Rephrasing (disabled, skipping)...")
+ optimized_topic = topic
+ self._log_progress(
+ "planning",
+ "rephrase_skipped",
+ optimized_topic=optimized_topic,
+ reason="rephrase feature disabled",
+ )
+
+ self.optimized_topic = optimized_topic
+
+ self.logger.info("\n【Step 2】Topic Decomposition...")
+
+ # Use DecomposeAgent to decompose topic
+ decompose_config = self.config.get("planning", {}).get("decompose", {})
+ mode = decompose_config.get("mode", "manual")
+
+ if mode == "auto":
+ # Auto mode: use auto_max_subtopics as limit
+ num_subtopics = decompose_config.get(
+ "auto_max_subtopics", decompose_config.get("initial_subtopics", 5)
+ )
+ self.logger.info(f"📌 Using Auto mode, max subtopics: {num_subtopics}")
+ else:
+ # Manual mode: use initial_subtopics
+ num_subtopics = decompose_config.get("initial_subtopics", 5)
+ self.logger.info(f"📌 Using Manual mode, expected subtopics: {num_subtopics}")
+
+ self._log_progress(
+ "planning", "decompose_started", requested_subtopics=num_subtopics, mode=mode
+ )
+
+ # Set citation manager to DecomposeAgent
+ self.agents["decompose"].set_citation_manager(self.citation_manager)
+
+ decompose_result = await self.agents["decompose"].process(
+ topic=optimized_topic, num_subtopics=num_subtopics, mode=mode
+ )
+ self._log_progress(
+ "planning",
+ "decompose_completed",
+ generated_subtopics=decompose_result.get("total_subtopics", 0),
+ rag_context_length=len(decompose_result.get("rag_context", "") or ""),
+ )
+
+ # Save Planning stage results (includes sub_queries / rag_context / sub_topics)
+ try:
+ step1_path = self.cache_dir / "step1_planning.json"
+ with open(step1_path, "w", encoding="utf-8") as f:
+ json.dump(
+ {
+ "main_topic": optimized_topic,
+ "sub_queries": decompose_result.get("sub_queries", []),
+ "rag_context": decompose_result.get("rag_context", ""),
+ "sub_topics": decompose_result.get("sub_topics", []),
+ "total_subtopics": decompose_result.get("total_subtopics", 0),
+ "timestamp": datetime.now().isoformat(),
+ },
+ f,
+ ensure_ascii=False,
+ indent=2,
+ )
+ self.logger.success(f"Planning stage data saved: {step1_path}")
+ except Exception as _e:
+ self.logger.warning(f"Failed to save Planning stage data: {_e}")
+
+ # Add subtopics to queue
+ self.logger.info("\n【Step 3】Initializing Queue...")
+ for sub_topic_data in decompose_result.get("sub_topics", []):
+ title = (sub_topic_data.get("title") or "").strip()
+ overview = sub_topic_data.get("overview", "")
+ if not title:
+ continue
+ try:
+ block = self.queue.add_block(sub_topic=title, overview=overview)
+ self._log_progress(
+ "planning",
+ "queue_seeded",
+ block_id=block.block_id,
+ sub_topic=block.sub_topic,
+ total_blocks=len(self.queue.blocks),
+ )
+ except RuntimeError as err:
+ self._log_progress(
+ "planning", "queue_capacity_reached", error=str(err), attempted_topic=title
+ )
+ self.logger.warning(
+ f"Queue reached capacity limit, stopping addition of initial topics: {err}"
+ )
+ break
+
+ stats = self.queue.get_statistics()
+ self._log_progress("planning", "planning_completed", total_blocks=stats["total_blocks"])
+ self.logger.success("\nPhase 1 Completed:")
+ self.logger.info(f" - Optimized Topic: {optimized_topic}")
+ self.logger.info(f" - Subtopic Count: {stats['total_blocks']}")
+ self.agents["manager"].set_primary_topic(optimized_topic)
+
+ return optimized_topic
+
+ async def _phase2_researching(self):
+ """
+ Phase 2: Dynamic Research Loop
+ Routes to series or parallel execution based on configuration
+ """
+ execution_mode = self.config.get("researching", {}).get("execution_mode", "series")
+
+ if execution_mode == "parallel":
+ await self._phase2_researching_parallel()
+ else:
+ await self._phase2_researching_series()
+
+ async def _phase2_researching_series(self):
+ """
+ Phase 2: Dynamic Research Loop (Series Mode - Original Implementation)
+ """
+ # Initialize researching stage event list
+ if "researching" not in self._stage_events:
+ self._stage_events["researching"] = []
+
+ manager = self.agents["manager"]
+ research = self.agents["research"]
+
+ total_blocks = len(self.queue.blocks)
+ completed_blocks = 0
+
+ self._log_researching_progress(
+ "researching_started", total_blocks=total_blocks, execution_mode="series"
+ )
+
+ while not manager.is_research_complete():
+ # Get next task to research
+ block = manager.get_next_task()
+ if not block:
+ break
+
+ self._log_researching_progress(
+ "block_started",
+ block_id=block.block_id,
+ sub_topic=block.sub_topic,
+ current_block=completed_blocks + 1,
+ total_blocks=total_blocks,
+ )
+
+ # Create iteration progress callback for this block
+ iteration_callback = self._create_iteration_progress_callback(
+ block_id=block.block_id,
+ sub_topic=block.sub_topic,
+ execution_mode="series",
+ current_block=completed_blocks + 1,
+ total_blocks=total_blocks,
+ )
+
+ # Execute research loop (unified handling by ResearchAgent.process)
+ result = await research.process(
+ topic_block=block,
+ call_tool_callback=self._call_tool,
+ note_agent=self.agents["note"],
+ citation_manager=self.citation_manager,
+ queue=self.queue,
+ manager_agent=manager,
+ config=self.config,
+ progress_callback=iteration_callback,
+ )
+
+ # Mark as completed
+ manager.complete_task(block.block_id)
+ completed_blocks += 1
+
+ # Update total_blocks in case new topics were added
+ total_blocks = len(self.queue.blocks)
+
+ self._log_researching_progress(
+ "block_completed",
+ block_id=block.block_id,
+ sub_topic=block.sub_topic,
+ iterations=result.get("iterations", 0),
+ tools_used=result.get("tools_used", []),
+ queries_used=result.get("queries_used", []),
+ current_block=completed_blocks,
+ total_blocks=total_blocks,
+ )
+
+ # Display statistics
+ manager.get_queue_status()
+
+ stats = self.queue.get_statistics()
+ self._log_researching_progress(
+ "researching_completed",
+ completed_blocks=stats["completed"],
+ total_tool_calls=stats["total_tool_calls"],
+ )
+
+ self.logger.success("\nPhase 2 Completed:")
+ self.logger.info(f" - Completed Topics: {stats['completed']}")
+ self.logger.info(f" - Total Tool Calls: {stats['total_tool_calls']}")
+
+ async def _phase2_researching_parallel(self):
+ """
+ Phase 2: Dynamic Research Loop (Parallel Mode)
+ Executes multiple topic blocks in parallel with concurrency limit
+ """
+ # Initialize researching stage event list
+ if "researching" not in self._stage_events:
+ self._stage_events["researching"] = []
+
+ manager = self.agents["manager"]
+ research = self.agents["research"]
+
+ # Get configuration
+ max_parallel = self.config.get("researching", {}).get("max_parallel_topics", 5)
+ semaphore = asyncio.Semaphore(max_parallel)
+
+ # Get all pending blocks at the start
+ from src.agents.research.data_structures import TopicStatus
+
+ pending_blocks = [b for b in self.queue.blocks if b.status == TopicStatus.PENDING]
+ total_blocks = len(self.queue.blocks)
+
+ self.logger.info(
+ f"\n🚀 Starting parallel research mode (max {max_parallel} concurrent topics)"
+ )
+ self._log_researching_progress(
+ "researching_started",
+ total_blocks=total_blocks,
+ execution_mode="parallel",
+ max_parallel=max_parallel,
+ initial_pending=len(pending_blocks),
+ )
+
+ # Track completed blocks
+ completed_count = {"value": 0} # Use dict to allow modification in nested function
+
+ # Create async wrappers for thread-safe operations in parallel mode
+ class AsyncCitationManagerWrapper:
+ """Wrapper to use async citation manager methods in parallel mode"""
+
+ def __init__(self, cm):
+ self._cm = cm
+
+ async def add_citation(self, citation_id, tool_type, tool_trace, raw_answer):
+ return await self._cm.add_citation_async(
+ citation_id, tool_type, tool_trace, raw_answer
+ )
+
+ def __getattr__(self, name):
+ # Forward other attributes to original citation_manager
+ return getattr(self._cm, name)
+
+ class AsyncManagerAgentWrapper:
+ """Wrapper to use async manager agent methods in parallel mode"""
+
+ def __init__(self, ma):
+ self._ma = ma
+
+ async def add_new_topic(self, sub_topic, overview):
+ return await self._ma.add_new_topic_async(sub_topic, overview)
+
+ def __getattr__(self, name):
+ # Forward other attributes to original manager_agent
+ return getattr(self._ma, name)
+
+ async_citation_manager = AsyncCitationManagerWrapper(self.citation_manager)
+ async_manager_agent = AsyncManagerAgentWrapper(manager)
+
+ # Track active tasks for parallel progress display
+ active_tasks: dict[str, dict[str, Any]] = {} # block_id -> task info
+ active_tasks_lock = asyncio.Lock()
+
+ async def update_active_task(block_id: str, info: dict[str, Any] | None):
+ """Update active task info (thread-safe)"""
+ async with active_tasks_lock:
+ if info is None:
+ active_tasks.pop(block_id, None)
+ else:
+ active_tasks[block_id] = info
+ # Send parallel status update
+ self._log_researching_progress(
+ "parallel_status_update",
+ active_tasks=list(active_tasks.values()),
+ active_count=len(active_tasks),
+ completed_count=completed_count["value"],
+ total_blocks=total_blocks,
+ )
+
+ async def research_single_block(block: Any) -> dict[str, Any] | None:
+ """
+ Research a single topic block with semaphore control
+
+ Args:
+ block: TopicBlock to research
+
+ Returns:
+ Research result or None if failed
+ """
+ async with semaphore:
+ try:
+ # Mark as researching (thread-safe)
+ async with manager._lock:
+ # Refresh block status from queue
+ current_block = self.queue.get_block_by_id(block.block_id)
+ if current_block and current_block.status == TopicStatus.PENDING:
+ self.queue.mark_researching(block.block_id)
+
+ # Add to active tasks
+ await update_active_task(
+ block.block_id,
+ {
+ "block_id": block.block_id,
+ "sub_topic": block.sub_topic,
+ "status": "starting",
+ "iteration": 0,
+ "current_tool": None,
+ "current_query": None,
+ },
+ )
+
+ self._log_researching_progress(
+ "block_started",
+ block_id=block.block_id,
+ sub_topic=block.sub_topic,
+ execution_mode="parallel",
+ active_count=len(active_tasks),
+ )
+
+ if self.logger:
+ self.logger.info(
+ f"\n[{block.block_id}] 🔍 Starting research: {block.sub_topic}"
+ )
+
+ # Get max_iterations from config for this closure
+ config_max_iterations = self.config.get("researching", {}).get(
+ "max_iterations", 5
+ )
+
+ # Create iteration callback for parallel mode
+ def parallel_iteration_callback(event_type: str, **data):
+ """Handle iteration progress in parallel mode"""
+ # Update active task info
+ task_info = {
+ "block_id": block.block_id,
+ "sub_topic": block.sub_topic,
+ "status": event_type,
+ "iteration": data.get("iteration", 0),
+ "max_iterations": data.get("max_iterations", config_max_iterations),
+ "current_tool": data.get("tool_type"),
+ "current_query": data.get("query"),
+ "tools_used": data.get("tools_used", []),
+ }
+ # Schedule async update
+ asyncio.create_task(update_active_task(block.block_id, task_info))
+
+ # Also log the detailed progress
+ self._log_researching_progress(
+ event_type,
+ block_id=block.block_id,
+ sub_topic=block.sub_topic,
+ execution_mode="parallel",
+ **data,
+ )
+
+ # Execute research loop with async wrappers
+ result = await research.process(
+ topic_block=block,
+ call_tool_callback=self._call_tool,
+ note_agent=self.agents["note"],
+ citation_manager=async_citation_manager,
+ queue=self.queue,
+ manager_agent=async_manager_agent,
+ config=self.config,
+ progress_callback=parallel_iteration_callback,
+ )
+
+ # Mark as completed (thread-safe)
+ await manager.complete_task_async(block.block_id)
+ completed_count["value"] += 1
+
+ # Remove from active tasks
+ await update_active_task(block.block_id, None)
+
+ self._log_researching_progress(
+ "block_completed",
+ block_id=block.block_id,
+ sub_topic=block.sub_topic,
+ iterations=result.get("iterations", 0),
+ tools_used=result.get("tools_used", []),
+ queries_used=result.get("queries_used", []),
+ current_block=completed_count["value"],
+ total_blocks=total_blocks,
+ execution_mode="parallel",
+ )
+
+ if self.logger:
+ self.logger.success(f"[{block.block_id}] ✅ Completed: {block.sub_topic}")
+
+ return result
+
+ except Exception as e:
+ # Mark as failed (thread-safe)
+ await manager.fail_task_async(block.block_id, str(e))
+ completed_count["value"] += 1
+
+ # Remove from active tasks
+ await update_active_task(block.block_id, None)
+
+ if self.logger:
+ self.logger.error(f"[{block.block_id}] ❌ Failed: {block.sub_topic} - {e}")
+
+ self._log_researching_progress(
+ "block_failed",
+ block_id=block.block_id,
+ sub_topic=block.sub_topic,
+ error=str(e),
+ execution_mode="parallel",
+ )
+ return None
+
+ # Execute all research tasks in parallel
+ tasks = [research_single_block(block) for block in pending_blocks]
+ results = await asyncio.gather(*tasks, return_exceptions=True)
+
+ # Handle any exceptions that weren't caught
+ for i, result in enumerate(results):
+ if isinstance(result, Exception):
+ block = pending_blocks[i]
+ await manager.fail_task_async(block.block_id, str(result))
+ if self.logger:
+ self.logger.error(f"[{block.block_id}] ❌ Exception: {result}")
+
+ # Wait for any dynamically added topics (if manager adds new topics during research)
+ # Continue until all tasks are processed (completed or failed)
+ max_wait_iterations = 100 # Prevent infinite loop
+ wait_count = 0
+
+ while True:
+ # Check if all blocks are processed (COMPLETED or FAILED, not PENDING or RESEARCHING)
+ stats = self.queue.get_statistics()
+ pending_count = stats.get("pending", 0)
+ researching_count = stats.get("researching", 0)
+
+ # Exit if no pending or researching tasks
+ if pending_count == 0 and researching_count == 0:
+ break
+
+ # Get any newly added pending blocks
+ new_pending = [b for b in self.queue.blocks if b.status == TopicStatus.PENDING]
+ if not new_pending:
+ # No pending blocks, but there might be researching ones
+ # Wait a bit for them to complete
+ wait_count += 1
+ if wait_count > max_wait_iterations:
+ self.logger.warning(
+ "Max wait iterations reached, exiting parallel research loop"
+ )
+ break
+ await asyncio.sleep(0.1)
+ continue
+
+ # Reset wait count when we have new work
+ wait_count = 0
+
+ # Research newly added blocks
+ new_tasks = [research_single_block(block) for block in new_pending]
+ new_results = await asyncio.gather(*new_tasks, return_exceptions=True)
+
+ for i, result in enumerate(new_results):
+ if isinstance(result, Exception):
+ block = new_pending[i]
+ await manager.fail_task_async(block.block_id, str(result))
+
+ stats = self.queue.get_statistics()
+ self._log_researching_progress(
+ "researching_completed",
+ completed_blocks=stats["completed"],
+ total_tool_calls=stats["total_tool_calls"],
+ execution_mode="parallel",
+ )
+
+ self.logger.success("\nPhase 2 Completed (Parallel Mode):")
+ self.logger.info(f" - Completed Topics: {stats['completed']}")
+ self.logger.info(f" - Total Tool Calls: {stats['total_tool_calls']}")
+ self.logger.info(f" - Failed Topics: {stats.get('failed', 0)}")
+
+ def _log_researching_progress(self, status: str, **payload: Any) -> None:
+ """Record researching stage progress (thread-safe for parallel mode)"""
+ event = {"status": status, "timestamp": datetime.now().isoformat()}
+ event.update({k: v for k, v in payload.items() if v is not None})
+
+ # Use lock to prevent concurrent file writes in parallel mode
+ with self._progress_file_lock:
+ if "researching" not in self._stage_events:
+ self._stage_events["researching"] = []
+ self._stage_events["researching"].append(event)
+
+ # Save to file
+ research_progress_file = self.cache_dir / "researching_progress.json"
+ context = {
+ "research_id": self.research_id,
+ "stage": "researching",
+ "input_topic": self.input_topic,
+ "optimized_topic": self.optimized_topic,
+ "events": self._stage_events["researching"],
+ }
+ with open(research_progress_file, "w", encoding="utf-8") as f:
+ json.dump(context, f, ensure_ascii=False, indent=2)
+
+ # Send progress via callback
+ if self.progress_callback:
+ try:
+ progress_event = {
+ "type": "progress",
+ "stage": "researching",
+ "status": status,
+ "research_id": self.research_id,
+ **{k: v for k, v in payload.items() if v is not None},
+ }
+ self.progress_callback(progress_event)
+ except Exception as e:
+ self.logger.warning(f"Progress callback failed: {e}")
+
+ def _create_iteration_progress_callback(
+ self,
+ block_id: str,
+ sub_topic: str,
+ execution_mode: str,
+ current_block: int = None,
+ total_blocks: int = None,
+ ) -> Callable:
+ """
+ Create a progress callback for research iterations
+
+ Args:
+ block_id: Block ID for the current topic
+ sub_topic: Current sub-topic being researched
+ execution_mode: 'series' or 'parallel'
+ current_block: Current block number (for series mode)
+ total_blocks: Total number of blocks
+
+ Returns:
+ Callback function for iteration progress
+ """
+
+ def iteration_callback(event_type: str, **data: Any):
+ """Callback for iteration progress events"""
+ payload = {
+ "block_id": block_id,
+ "sub_topic": sub_topic,
+ "execution_mode": execution_mode,
+ }
+ if current_block is not None:
+ payload["current_block"] = current_block
+ if total_blocks is not None:
+ payload["total_blocks"] = total_blocks
+ payload.update(data)
+
+ self._log_researching_progress(event_type, **payload)
+
+ return iteration_callback
+
+ async def _phase3_reporting(self, topic: str) -> dict[str, Any]:
+ """
+ Phase 3: Report Generation
+
+ Args:
+ topic: Research topic
+
+ Returns:
+ Report result
+ """
+ reporting = self.agents["reporting"]
+
+ # Set citation manager
+ reporting.set_citation_manager(self.citation_manager)
+
+ # Generate report
+ report_result = await reporting.process(
+ self.queue, topic, progress_callback=self._report_progress_callback
+ )
+
+ self.logger.success("\nPhase 3 Completed:")
+ self.logger.info(f" - Report Word Count: {report_result['word_count']}")
+ self.logger.info(f" - Sections: {report_result['sections']}")
+ self.logger.info(f" - Citations: {report_result['citations']}")
+
+ return report_result
+
+ def _log_progress(self, stage: str, status: str, **payload: Any) -> None:
+ """Record stage progress to JSON file and send progress via callback"""
+ if stage not in self._stage_events:
+ return
+ event = {"status": status, "timestamp": datetime.now().isoformat()}
+ event.update({k: v for k, v in payload.items() if v is not None})
+ self._stage_events[stage].append(event)
+ file_path = self.plan_progress_file if stage == "planning" else self.report_progress_file
+ context = {
+ "research_id": self.research_id,
+ "stage": stage,
+ "input_topic": self.input_topic,
+ "optimized_topic": self.optimized_topic,
+ "events": self._stage_events[stage],
+ }
+ with open(file_path, "w", encoding="utf-8") as f:
+ json.dump(context, f, ensure_ascii=False, indent=2)
+
+ # Send progress via callback (if callback function is set)
+ if self.progress_callback:
+ try:
+ progress_event = {
+ "type": "progress",
+ "stage": stage,
+ "status": status,
+ "research_id": self.research_id,
+ **{k: v for k, v in payload.items() if v is not None},
+ }
+ self.progress_callback(progress_event)
+ except Exception as e:
+ self.logger.warning(f"Progress callback failed: {e}")
+
+ def _report_progress_callback(self, event: dict[str, Any]) -> None:
+ """Reporting stage progress callback"""
+ status = event.pop("status", "unknown")
+ self._log_progress("reporting", status, **event)
+
+
+async def main():
+ """Main function"""
+ import argparse
+
+ from dotenv import load_dotenv
+ import yaml
+
+ from src.core.core import get_llm_config
+
+ # Load environment variables
+ load_dotenv()
+
+ # Parse command line arguments
+ parser = argparse.ArgumentParser(description="DR-in-KG 2.0 - Deep Research System")
+ parser.add_argument("--topic", type=str, required=True, help="Research topic")
+ parser.add_argument("--config", type=str, default="config.yaml", help="Configuration file")
+ parser.add_argument(
+ "--preset", type=str, choices=["quick", "medium", "deep", "auto"], help="Preset mode"
+ )
+
+ args = parser.parse_args()
+
+ # Load configuration
+ config_path = PROJECT_ROOT / args.config
+ if not config_path.exists():
+ logger = get_logger("Research")
+ logger.error(f"Configuration file not found: {config_path}")
+ sys.exit(1)
+
+ with open(config_path, encoding="utf-8") as f:
+ config = yaml.safe_load(f)
+
+ # Apply preset
+ if args.preset and "presets" in config and args.preset in config["presets"]:
+ preset = config["presets"][args.preset]
+ # Merge preset configuration
+ for key, value in preset.items():
+ if key in config and isinstance(value, dict):
+ config[key].update(value)
+
+ # Get LLM configuration
+ llm_config = get_llm_config()
+
+ # Create research pipeline
+ pipeline = ResearchPipeline(
+ config=config, api_key=llm_config["api_key"], base_url=llm_config["base_url"]
+ )
+
+ # Execute research
+ result = await pipeline.run(args.topic)
+
+ logger = get_logger("Research")
+ logger.success("\n🎉 Research completed!")
+ logger.info(f"Report location: {result['final_report_path']}")
+
+
+if __name__ == "__main__":
+ if sys.platform == "win32":
+ asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
+
+ asyncio.run(main())
+
+
+# Backward compatibility alias: old code can use ResearchPipeline, new code referencing ResearchPipeline2 won't error
+ResearchPipeline2 = ResearchPipeline
+__all__ = ["ResearchPipeline", "ResearchPipeline2"]
diff --git a/src/agents/research/utils/__init__.py b/src/agents/research/utils/__init__.py
new file mode 100644
index 000000000..ee5050717
--- /dev/null
+++ b/src/agents/research/utils/__init__.py
@@ -0,0 +1,60 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+"""
+DR-in-KG 2.0 Utils - Lightweight initialization
+Only exports tools used by the current version.
+"""
+
+from pathlib import Path
+import sys
+
+# Add project root to path for imports
+project_root = Path(__file__).parent.parent.parent.parent
+if str(project_root) not in sys.path:
+ sys.path.insert(0, str(project_root))
+
+# Import from unified logging system
+from src.core.logging import Logger, get_logger
+
+from .json_utils import (
+ ensure_json_dict,
+ ensure_json_list,
+ ensure_keys,
+ extract_json_from_text,
+ json_to_text,
+ safe_json_loads,
+)
+from .token_tracker import TokenTracker, get_token_tracker
+
+# Backwards compatibility: LLMLogger is now just Logger
+LLMLogger = Logger
+
+
+def get_llm_logger(research_id: str = None, log_dir: str = None, agent_name: str = None):
+ """Get logger for LLM calls (backwards compatibility)"""
+ name = agent_name or "Research"
+ return get_logger(name, log_dir=log_dir)
+
+
+def reset_llm_logger():
+ """Reset LLM logger (backwards compatibility)"""
+ from src.core.logging import reset_logger
+
+ reset_logger()
+
+
+__all__ = [
+ "extract_json_from_text",
+ "ensure_json_dict",
+ "ensure_json_list",
+ "ensure_keys",
+ "safe_json_loads",
+ "json_to_text",
+ "get_token_tracker",
+ "TokenTracker",
+ "LLMLogger",
+ "get_llm_logger",
+ "reset_llm_logger",
+ "Logger",
+ "get_logger",
+]
diff --git a/src/agents/research/utils/citation_manager.py b/src/agents/research/utils/citation_manager.py
new file mode 100644
index 000000000..333414b5f
--- /dev/null
+++ b/src/agents/research/utils/citation_manager.py
@@ -0,0 +1,798 @@
+#!/usr/bin/env python
+"""
+CitationManager - Citation management system
+Responsible for extracting citation information from tool calls and managing citation JSON files
+"""
+
+import asyncio
+from datetime import datetime
+import json
+from pathlib import Path
+import sys
+from typing import Any
+
+project_root = Path(__file__).parent.parent.parent.parent
+sys.path.insert(0, str(project_root))
+
+
+class CitationManager:
+ """Citation manager with global ID management"""
+
+ def __init__(self, research_id: str, cache_dir: Path | None = None):
+ """
+ Initialize citation manager
+
+ Args:
+ research_id: Research task ID
+ cache_dir: Cache directory path, if None uses default path
+ """
+ self.research_id = research_id
+ if cache_dir is None:
+ cache_dir = Path("./cache") / research_id
+ self.cache_dir = Path(cache_dir)
+ self.cache_dir.mkdir(parents=True, exist_ok=True)
+
+ self.citations_file = self.cache_dir / "citations.json"
+ self._citations: dict[str, dict[str, Any]] = {}
+
+ # Global citation ID counters
+ self._plan_counter = 0 # For PLAN-XX format (planning stage)
+ self._block_counters: dict[str, int] = {} # For CIT-X-XX format (research stage)
+
+ # Reference number mapping (citation_id -> ref_number for in-text citations)
+ self._ref_number_map: dict[str, int] = {}
+
+ # Lock for thread-safe operations in parallel mode
+ self._lock = asyncio.Lock()
+
+ self._load_citations()
+
+ def generate_plan_citation_id(self) -> str:
+ """
+ Generate a new citation ID for planning stage (PLAN-XX format)
+
+ Returns:
+ Citation ID in PLAN-XX format
+ """
+ self._plan_counter += 1
+ return f"PLAN-{self._plan_counter:02d}"
+
+ def generate_research_citation_id(self, block_id: str) -> str:
+ """
+ Generate a new citation ID for research stage (CIT-X-XX format)
+
+ Args:
+ block_id: Block ID (e.g., "block_3")
+
+ Returns:
+ Citation ID in CIT-X-XX format
+ """
+ # Extract block number from block_id
+ block_num = 0
+ try:
+ if block_id and "_" in block_id:
+ block_num = int(block_id.split("_")[1])
+ except (ValueError, IndexError):
+ block_num = 0
+
+ # Increment counter for this block
+ block_key = str(block_num)
+ if block_key not in self._block_counters:
+ self._block_counters[block_key] = 0
+ self._block_counters[block_key] += 1
+
+ return f"CIT-{block_num}-{self._block_counters[block_key]:02d}"
+
+ def get_next_citation_id(self, stage: str = "research", block_id: str = "") -> str:
+ """
+ Get the next available citation ID
+
+ Args:
+ stage: "planning" or "research"
+ block_id: Block ID (required for research stage)
+
+ Returns:
+ Next available citation ID
+ """
+ if stage == "planning":
+ return self.generate_plan_citation_id()
+ return self.generate_research_citation_id(block_id)
+
+ def citation_exists(self, citation_id: str) -> bool:
+ """
+ Check if a citation ID already exists
+
+ Args:
+ citation_id: Citation ID to check
+
+ Returns:
+ True if citation exists, False otherwise
+ """
+ return citation_id in self._citations
+
+ def _load_citations(self):
+ """Load citation information from JSON file and restore counters"""
+ if self.citations_file.exists():
+ try:
+ with open(self.citations_file, encoding="utf-8") as f:
+ data = json.load(f)
+ self._citations = data.get("citations", {})
+
+ # Try to restore counters from saved state first
+ counters = data.get("counters", {})
+ if counters:
+ self._plan_counter = counters.get("plan_counter", 0)
+ self._block_counters = counters.get("block_counters", {})
+ else:
+ # Fallback: restore counters from existing citations
+ self._restore_counters_from_citations()
+ except Exception as e:
+ print(f"⚠️ Failed to load citation file: {e}")
+ self._citations = {}
+ else:
+ self._citations = {}
+
+ def _restore_counters_from_citations(self):
+ """Restore citation counters from existing citations to avoid ID conflicts"""
+ for citation_id in self._citations.keys():
+ if citation_id.startswith("PLAN-"):
+ try:
+ num = int(citation_id.replace("PLAN-", ""))
+ self._plan_counter = max(self._plan_counter, num)
+ except ValueError:
+ pass
+ elif citation_id.startswith("CIT-"):
+ try:
+ parts = citation_id.replace("CIT-", "").split("-")
+ if len(parts) == 2:
+ block_num = parts[0]
+ seq_num = int(parts[1])
+ if block_num not in self._block_counters:
+ self._block_counters[block_num] = 0
+ self._block_counters[block_num] = max(
+ self._block_counters[block_num], seq_num
+ )
+ except (ValueError, IndexError):
+ pass
+
+ def _save_citations(self):
+ """Save citation information to JSON file"""
+ try:
+ data = {
+ "research_id": self.research_id,
+ "updated_at": datetime.now().isoformat(),
+ "citations": self._citations,
+ "counters": {
+ "plan_counter": self._plan_counter,
+ "block_counters": self._block_counters,
+ },
+ }
+ with open(self.citations_file, "w", encoding="utf-8") as f:
+ json.dump(data, f, ensure_ascii=False, indent=2)
+ except Exception as e:
+ print(f"⚠️ Failed to save citation file: {e}")
+
+ def validate_citation_references(self, text: str) -> dict[str, Any]:
+ """
+ Validate citation references in text and identify invalid ones
+
+ Args:
+ text: Text containing citation references like [[CIT-X-XX]]
+
+ Returns:
+ Dictionary with validation results:
+ {
+ "valid_citations": [...],
+ "invalid_citations": [...],
+ "is_valid": bool
+ }
+ """
+ import re
+
+ # Find all citation references in the text
+ pattern = r"\[\[([A-Z]+-\d+-?\d*)\]\]"
+ found_refs = re.findall(pattern, text)
+
+ valid = []
+ invalid = []
+
+ for ref in found_refs:
+ if self.citation_exists(ref):
+ valid.append(ref)
+ else:
+ invalid.append(ref)
+
+ return {
+ "valid_citations": valid,
+ "invalid_citations": invalid,
+ "is_valid": len(invalid) == 0,
+ "total_found": len(found_refs),
+ }
+
+ def fix_invalid_citations(self, text: str) -> str:
+ """
+ Remove or mark invalid citation references in text
+
+ Args:
+ text: Text containing citation references
+
+ Returns:
+ Text with invalid citations removed or marked
+ """
+ import re
+
+ pattern = r"\[\[([A-Z]+-\d+-?\d*)\]\]\(#ref-[a-z]+-\d+-?\d*\)"
+
+ def replace_invalid(match):
+ citation_id = match.group(1)
+ if self.citation_exists(citation_id):
+ return match.group(0) # Keep valid citations
+ return "" # Remove invalid citations
+
+ return re.sub(pattern, replace_invalid, text)
+
+ def add_citation(
+ self,
+ citation_id: str,
+ tool_type: str,
+ tool_trace: Any,
+ raw_answer: str, # Raw answer JSON string
+ ) -> bool:
+ """
+ Add citation information
+
+ Args:
+ citation_id: Citation ID
+ tool_type: Tool type
+ tool_trace: ToolTrace object
+ raw_answer: Raw answer (JSON string)
+
+ Returns:
+ Whether addition was successful
+ """
+ try:
+ tool_type_lower = tool_type.lower()
+
+ if tool_type_lower in ("rag_naive", "rag_hybrid", "query_item"):
+ citation_info = self._extract_rag_citation(
+ citation_id, tool_type, raw_answer, tool_trace
+ )
+ elif tool_type_lower == "web_search":
+ citation_info = self._extract_web_citation(
+ citation_id, tool_type, raw_answer, tool_trace
+ )
+ elif tool_type_lower == "paper_search":
+ citation_info = self._extract_paper_citation(
+ citation_id, tool_type, raw_answer, tool_trace
+ )
+ elif tool_type_lower == "run_code":
+ citation_info = self._extract_code_citation(citation_id, tool_type, tool_trace)
+ else:
+ # Unknown tool type, use generic format
+ citation_info = self._extract_generic_citation(citation_id, tool_type, tool_trace)
+
+ if citation_info:
+ self._citations[citation_id] = citation_info
+ self._save_citations()
+ return True
+ return False
+ except Exception as e:
+ print(f"⚠️ Failed to add citation (citation_id={citation_id}): {e}")
+ return False
+
+ def _extract_rag_citation(
+ self, citation_id: str, tool_type: str, raw_answer: str, tool_trace: Any
+ ) -> dict[str, Any]:
+ """Extract citation information for RAG retrieval with source documents"""
+ citation_info = {
+ "citation_id": citation_id,
+ "tool_type": tool_type,
+ "query": tool_trace.query,
+ "summary": tool_trace.summary,
+ "timestamp": tool_trace.timestamp,
+ "sources": [], # List of source documents
+ }
+
+ try:
+ # Parse raw_answer to extract source information
+ answer_data = json.loads(raw_answer)
+
+ # Extract source documents if available
+ # Common fields in RAG responses: chunks, documents, sources, context
+ sources = []
+
+ # Try different field names for source documents
+ for field_name in ["chunks", "documents", "sources", "context", "retrieved_docs"]:
+ if field_name in answer_data:
+ source_list = answer_data[field_name]
+ if isinstance(source_list, list):
+ for i, doc in enumerate(source_list[:5]): # Limit to 5 sources
+ source_info = {}
+ if isinstance(doc, dict):
+ source_info["title"] = doc.get("title", doc.get("doc_title", ""))
+ source_info["content_preview"] = doc.get(
+ "content", doc.get("text", "")
+ )[:200]
+ source_info["source_file"] = doc.get(
+ "source", doc.get("file_path", doc.get("filename", ""))
+ )
+ source_info["page"] = doc.get("page", doc.get("page_number", ""))
+ source_info["chunk_id"] = doc.get("chunk_id", doc.get("id", i))
+ source_info["score"] = doc.get("score", doc.get("similarity", ""))
+ elif isinstance(doc, str):
+ source_info["content_preview"] = doc[:200]
+ if source_info:
+ sources.append(source_info)
+ break
+
+ # Also extract kb_name if available
+ citation_info["kb_name"] = answer_data.get("kb_name", "")
+ citation_info["sources"] = sources
+ citation_info["total_sources"] = len(sources)
+
+ except (json.JSONDecodeError, Exception) as e:
+ # If parsing fails, still return basic citation info
+ print(f"⚠️ Failed to parse RAG source info: {e}")
+
+ return citation_info
+
+ def _extract_web_citation(
+ self, citation_id: str, tool_type: str, raw_answer: str, tool_trace: Any
+ ) -> dict[str, Any]:
+ """Extract citation information for web search with URLs"""
+ citation_info = {
+ "citation_id": citation_id,
+ "tool_type": tool_type,
+ "query": tool_trace.query,
+ "summary": tool_trace.summary,
+ "timestamp": tool_trace.timestamp,
+ "web_sources": [], # List of web sources with URLs
+ }
+
+ try:
+ # Parse raw_answer to extract web source information
+ answer_data = json.loads(raw_answer)
+
+ web_sources = []
+
+ # Try different field names for web results
+ for field_name in ["results", "web_results", "search_results", "urls"]:
+ if field_name in answer_data:
+ result_list = answer_data[field_name]
+ if isinstance(result_list, list):
+ for result in result_list[:5]: # Limit to 5 sources
+ if isinstance(result, dict):
+ web_source = {
+ "title": result.get("title", ""),
+ "url": result.get("url", result.get("link", "")),
+ "snippet": result.get("snippet", result.get("description", ""))[
+ :200
+ ],
+ "domain": result.get("domain", ""),
+ }
+ if web_source["url"]: # Only add if URL exists
+ web_sources.append(web_source)
+ break
+
+ citation_info["web_sources"] = web_sources
+ citation_info["total_sources"] = len(web_sources)
+
+ except (json.JSONDecodeError, Exception) as e:
+ # If parsing fails, still return basic citation info
+ print(f"⚠️ Failed to parse web source info: {e}")
+
+ return citation_info
+
+ def _extract_paper_citation(
+ self, citation_id: str, tool_type: str, raw_answer: str, tool_trace: Any
+ ) -> dict[str, Any]:
+ """Extract citation information for paper search - supports multiple papers"""
+ citation_info = {
+ "citation_id": citation_id,
+ "tool_type": tool_type,
+ "query": tool_trace.query,
+ "summary": tool_trace.summary,
+ "timestamp": tool_trace.timestamp,
+ "papers": [], # Store all papers, not just the first one
+ }
+
+ try:
+ # Parse raw_answer JSON
+ answer_data = json.loads(raw_answer)
+ papers = answer_data.get("papers", [])
+
+ if not papers:
+ # If no papers, return basic info
+ return citation_info
+
+ # Process ALL papers (up to 5 for practicality)
+ processed_papers = []
+ for paper in papers[:5]:
+ # Format authors
+ authors = paper.get("authors", [])
+ author_str = ", ".join(authors[:3]) # Display at most 3 authors
+ if len(authors) > 3:
+ author_str += " et al."
+
+ paper_info = {
+ "title": paper.get("title", ""),
+ "authors": author_str,
+ "authors_list": authors,
+ "year": paper.get("year", ""),
+ "url": paper.get("url", ""),
+ "arxiv_id": paper.get("arxiv_id", ""),
+ "abstract": paper.get("abstract", "")[:300], # Truncate abstract
+ "doi": paper.get("doi", ""),
+ "venue": paper.get("venue", paper.get("journal", "")),
+ }
+ processed_papers.append(paper_info)
+
+ citation_info["papers"] = processed_papers
+ citation_info["total_papers"] = len(processed_papers)
+
+ # Keep primary paper info at top level for backward compatibility
+ if processed_papers:
+ primary = processed_papers[0]
+ citation_info["title"] = primary["title"]
+ citation_info["authors"] = primary["authors"]
+ citation_info["authors_list"] = primary["authors_list"]
+ citation_info["year"] = primary["year"]
+ citation_info["url"] = primary["url"]
+ citation_info["arxiv_id"] = primary["arxiv_id"]
+
+ return citation_info
+ except Exception as e:
+ print(f"⚠️ Failed to parse paper citation: {e}")
+ # Still return the basic citation info
+ return citation_info
+
+ def _extract_code_citation(
+ self, citation_id: str, tool_type: str, tool_trace: Any
+ ) -> dict[str, Any]:
+ """Extract citation information for code execution"""
+ return {
+ "citation_id": citation_id,
+ "tool_type": tool_type,
+ "query": tool_trace.query, # Code content
+ "summary": tool_trace.summary,
+ "timestamp": tool_trace.timestamp,
+ }
+
+ def _extract_generic_citation(
+ self, citation_id: str, tool_type: str, tool_trace: Any
+ ) -> dict[str, Any]:
+ """Extract generic citation information (unknown tool type)"""
+ return {
+ "citation_id": citation_id,
+ "tool_type": tool_type,
+ "query": tool_trace.query,
+ "summary": tool_trace.summary,
+ "timestamp": tool_trace.timestamp,
+ }
+
+ def get_citation(self, citation_id: str) -> dict[str, Any] | None:
+ """Get citation information for specified citation ID"""
+ return self._citations.get(citation_id)
+
+ def get_all_citations(self) -> dict[str, dict[str, Any]]:
+ """Get all citation information"""
+ return self._citations.copy()
+
+ def get_citations_file_path(self) -> Path:
+ """Get citation JSON file path"""
+ return self.citations_file
+
+ def format_citation_for_report(self, citation_id: str) -> str | None:
+ """
+ Format citation information for report display
+
+ Args:
+ citation_id: Citation ID
+
+ Returns:
+ Formatted citation string, or None if not found
+ """
+ citation = self.get_citation(citation_id)
+ if not citation:
+ return None
+
+ tool_type = citation.get("tool_type", "").lower()
+
+ if tool_type == "paper_search":
+ # Standard academic citation format
+ title = citation.get("title", "")
+ authors = citation.get("authors", "")
+ year = citation.get("year", "")
+ url = citation.get("url", "")
+ arxiv_id = citation.get("arxiv_id", "")
+
+ # Build citation string
+ parts = []
+ if authors:
+ parts.append(authors)
+ if year:
+ parts.append(f"({year})")
+ if title:
+ parts.append(f'"{title}"')
+ if arxiv_id:
+ parts.append(f"arXiv:{arxiv_id}")
+ if url:
+ parts.append(f"<{url}>")
+
+ # Add note about additional papers if available
+ total_papers = citation.get("total_papers", 1)
+ if total_papers > 1:
+ parts.append(f"[+{total_papers - 1} more papers]")
+
+ return " ".join(parts) if parts else None
+
+ if tool_type in ("rag_naive", "rag_hybrid", "query_item"):
+ # RAG citation with source info
+ query = citation.get("query", "")
+ kb_name = citation.get("kb_name", "")
+ sources = citation.get("sources", [])
+
+ tool_type_display = {
+ "rag_naive": "RAG Retrieval",
+ "rag_hybrid": "Hybrid RAG Retrieval",
+ "query_item": "Knowledge Base Query",
+ }.get(tool_type, tool_type)
+
+ parts = [f"{tool_type_display}: {query}"]
+ if kb_name:
+ parts.append(f"[KB: {kb_name}]")
+ if sources:
+ source_titles = [s.get("title", s.get("source_file", "")) for s in sources[:3] if s]
+ source_titles = [t for t in source_titles if t]
+ if source_titles:
+ parts.append(f"[Sources: {', '.join(source_titles)}]")
+
+ return " ".join(parts)
+
+ if tool_type == "web_search":
+ # Web search with URLs
+ query = citation.get("query", "")
+ web_sources = citation.get("web_sources", [])
+
+ parts = [f"Web Search: {query}"]
+ if web_sources:
+ urls = [s.get("url", "") for s in web_sources[:3] if s.get("url")]
+ if urls:
+ parts.append(f"[URLs: {', '.join(urls)}]")
+
+ return " ".join(parts)
+
+ # Other types of citation formats
+ tool_type_display = {
+ "run_code": "Code Execution",
+ }.get(tool_type, tool_type)
+
+ query = citation.get("query", "")
+ return f"{tool_type_display}: {query}"
+
+ # ========== Reference Number Mapping Methods ==========
+
+ def _get_citation_dedup_key(self, citation: dict, paper: dict = None) -> str:
+ """
+ Generate unique key for citation deduplication
+
+ Deduplication is ONLY applied to paper_search citations where the same paper
+ (title + first author) is cited multiple times. All other citation types
+ get unique ref_numbers based on their citation_id.
+
+ Args:
+ citation: The citation dict
+ paper: Optional paper dict for paper_search citations
+
+ Returns:
+ Unique string key for deduplication
+ """
+ tool_type = citation.get("tool_type", "").lower()
+ citation_id = citation.get("citation_id", "")
+
+ if tool_type == "paper_search" and paper:
+ # For papers: use title + first author (normalized) - allow dedup for same paper
+ title = paper.get("title", "").lower().strip()
+ authors = paper.get("authors", "").lower().strip()
+ # Extract first author if multiple
+ first_author = authors.split(",")[0].strip() if authors else ""
+ if title: # Only dedup if we have a title
+ return f"paper:{title}|{first_author}"
+ # No title? Use citation_id to ensure unique
+ return f"unique:{citation_id}"
+ elif tool_type == "paper_search":
+ # Fallback for paper_search without paper dict
+ title = citation.get("title", "").lower().strip()
+ authors = citation.get("authors", "").lower().strip()
+ first_author = authors.split(",")[0].strip() if authors else ""
+ if title: # Only dedup if we have a title
+ return f"paper:{title}|{first_author}"
+ return f"unique:{citation_id}"
+ else:
+ # For RAG/web_search/etc: each citation gets unique ref_number
+ # Use citation_id to ensure each citation is unique
+ return f"unique:{citation_id}"
+
+ def _extract_citation_sort_key(self, citation_id: str) -> tuple:
+ """
+ Extract numeric sort key from citation ID for ordering
+
+ Args:
+ citation_id: Citation ID (e.g., "PLAN-01", "CIT-1-02")
+
+ Returns:
+ Tuple for sorting (stage, block_num, seq_num)
+ """
+ try:
+ if citation_id.startswith("PLAN-"):
+ # PLAN-XX format: put at the beginning
+ num = int(citation_id.replace("PLAN-", ""))
+ return (0, 0, num)
+ # CIT-X-XX format
+ parts = citation_id.replace("CIT-", "").split("-")
+ if len(parts) == 2:
+ return (1, int(parts[0]), int(parts[1]))
+ except (ValueError, IndexError):
+ pass
+ return (999, 999, 999)
+
+ def build_ref_number_map(self) -> dict[str, int]:
+ """
+ Build citation_id to reference number mapping with deduplication.
+ This is the single source of truth for ref_number assignment.
+
+ Returns:
+ Dictionary mapping citation_id to reference number (1-based)
+ """
+ if not self._citations:
+ self._ref_number_map = {}
+ return self._ref_number_map
+
+ # Sort all citation IDs by their numeric parts
+ sorted_citation_ids = sorted(self._citations.keys(), key=self._extract_citation_sort_key)
+
+ # Track seen dedup keys and their assigned ref_numbers
+ seen_keys: dict[str, int] = {}
+ ref_idx = 0
+ ref_map: dict[str, int] = {}
+
+ for citation_id in sorted_citation_ids:
+ citation = self._citations.get(citation_id)
+ if not citation:
+ continue
+
+ tool_type = citation.get("tool_type", "").lower()
+
+ if tool_type == "paper_search":
+ # paper_search may have multiple papers - each paper gets a separate ref_number
+ papers = citation.get("papers", [])
+ if papers:
+ for paper_idx, paper in enumerate(papers):
+ # Check for duplicate using dedup key
+ dedup_key = self._get_citation_dedup_key(citation, paper)
+
+ if dedup_key in seen_keys:
+ # Map to existing ref_number
+ existing_ref = seen_keys[dedup_key]
+ if paper_idx == 0:
+ ref_map[citation_id] = existing_ref
+ ref_map[f"{citation_id}-{paper_idx + 1}"] = existing_ref
+ else:
+ # New unique citation
+ ref_idx += 1
+ seen_keys[dedup_key] = ref_idx
+ if paper_idx == 0:
+ ref_map[citation_id] = ref_idx
+ ref_map[f"{citation_id}-{paper_idx + 1}"] = ref_idx
+ else:
+ # Paper search without papers array
+ dedup_key = self._get_citation_dedup_key(citation)
+ if dedup_key in seen_keys:
+ ref_map[citation_id] = seen_keys[dedup_key]
+ else:
+ ref_idx += 1
+ seen_keys[dedup_key] = ref_idx
+ ref_map[citation_id] = ref_idx
+ else:
+ # Non-paper citations
+ dedup_key = self._get_citation_dedup_key(citation)
+ if dedup_key in seen_keys:
+ ref_map[citation_id] = seen_keys[dedup_key]
+ else:
+ ref_idx += 1
+ seen_keys[dedup_key] = ref_idx
+ ref_map[citation_id] = ref_idx
+
+ self._ref_number_map = ref_map
+ return ref_map
+
+ def get_ref_number(self, citation_id: str) -> int:
+ """
+ Get the reference number for a citation ID.
+ If the map hasn't been built yet, build it first.
+
+ Args:
+ citation_id: Citation ID
+
+ Returns:
+ Reference number (1-based), or 0 if not found
+ """
+ if not self._ref_number_map:
+ self.build_ref_number_map()
+ return self._ref_number_map.get(citation_id, 0)
+
+ def get_ref_number_map(self) -> dict[str, int]:
+ """
+ Get the full reference number map.
+ If the map hasn't been built yet, build it first.
+
+ Returns:
+ Dictionary mapping citation_id to reference number
+ """
+ if not self._ref_number_map:
+ self.build_ref_number_map()
+ return self._ref_number_map.copy()
+
+ # ========== Async thread-safe methods for parallel mode ==========
+
+ async def generate_plan_citation_id_async(self) -> str:
+ """
+ Thread-safe async version of generate_plan_citation_id for parallel mode
+
+ Returns:
+ Citation ID in PLAN-XX format
+ """
+ async with self._lock:
+ return self.generate_plan_citation_id()
+
+ async def generate_research_citation_id_async(self, block_id: str) -> str:
+ """
+ Thread-safe async version of generate_research_citation_id for parallel mode
+
+ Args:
+ block_id: Block ID (e.g., "block_3")
+
+ Returns:
+ Citation ID in CIT-X-XX format
+ """
+ async with self._lock:
+ return self.generate_research_citation_id(block_id)
+
+ async def get_next_citation_id_async(self, stage: str = "research", block_id: str = "") -> str:
+ """
+ Thread-safe async version of get_next_citation_id for parallel mode
+
+ Args:
+ stage: "planning" or "research"
+ block_id: Block ID (required for research stage)
+
+ Returns:
+ Next available citation ID
+ """
+ async with self._lock:
+ return self.get_next_citation_id(stage, block_id)
+
+ async def add_citation_async(
+ self,
+ citation_id: str,
+ tool_type: str,
+ tool_trace: Any,
+ raw_answer: str,
+ ) -> bool:
+ """
+ Thread-safe async version of add_citation for parallel mode
+
+ Args:
+ citation_id: Citation ID
+ tool_type: Tool type
+ tool_trace: ToolTrace object
+ raw_answer: Raw answer (JSON string)
+
+ Returns:
+ Whether addition was successful
+ """
+ async with self._lock:
+ return self.add_citation(citation_id, tool_type, tool_trace, raw_answer)
+
+
+__all__ = ["CitationManager"]
diff --git a/src/agents/research/utils/json_utils.py b/src/agents/research/utils/json_utils.py
new file mode 100644
index 000000000..d67aadfba
--- /dev/null
+++ b/src/agents/research/utils/json_utils.py
@@ -0,0 +1,98 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+"""
+JSON Utils - JSON parsing and validation utilities
+- Robustly extract JSON from LLM text output
+- Provide strict structure validation and error messages
+"""
+
+import json
+import re
+from typing import Any, Dict, Iterable, List, Union
+
+
+def extract_json_from_text(text: str) -> Union[Dict[str, Any], List[Any], None]:
+ """
+ Extract JSON object or array from text.
+ Allows the following formats:
+ 1) Pure JSON text
+ 2) Code blocks wrapped in ```json ...``` or ``` ...```
+ 3) First JSON fragment {...} or [...] contained in text
+ """
+ if not text:
+ return None
+
+ # 1) Code block
+ code_block = re.search(r"```(?:json)?\s*([\s\S]*?)\s*```", text)
+ if code_block:
+ snippet = code_block.group(1).strip()
+ try:
+ return json.loads(snippet)
+ except json.JSONDecodeError:
+ pass
+
+ # 2) Parse entire text
+ try:
+ return json.loads(text)
+ except json.JSONDecodeError:
+ pass
+
+ # 3) Fragment parsing
+ obj_match = re.search(r"\{[\s\S]*\}", text)
+ if obj_match:
+ try:
+ return json.loads(obj_match.group(0))
+ except json.JSONDecodeError:
+ pass
+
+ arr_match = re.search(r"\[[\s\S]*\]", text)
+ if arr_match:
+ try:
+ return json.loads(arr_match.group(0))
+ except json.JSONDecodeError:
+ pass
+
+ return None
+
+
+# --------- Strict Validation Utilities ---------
+
+
+def ensure_json_dict(data: Any, err: str = "Expected JSON object") -> Dict[str, Any]:
+ if not isinstance(data, dict):
+ raise ValueError(err)
+ return data
+
+
+def ensure_json_list(data: Any, err: str = "Expected JSON array") -> List[Any]:
+ if not isinstance(data, list):
+ raise ValueError(err)
+ return data
+
+
+def ensure_keys(data: Dict[str, Any], keys: Iterable[str]) -> Dict[str, Any]:
+ missing = [k for k in keys if k not in data]
+ if missing:
+ raise KeyError(f"Missing required keys: {', '.join(missing)}")
+ return data
+
+
+def safe_json_loads(text: str, default: Any = None) -> Any:
+ try:
+ return json.loads(text)
+ except (json.JSONDecodeError, TypeError):
+ return default
+
+
+def json_to_text(data: Any, indent: int = 2) -> str:
+ return json.dumps(data, ensure_ascii=False, indent=indent)
+
+
+__all__ = [
+ "extract_json_from_text",
+ "ensure_json_dict",
+ "ensure_json_list",
+ "ensure_keys",
+ "safe_json_loads",
+ "json_to_text",
+]
diff --git a/src/agents/research/utils/token_tracker.py b/src/agents/research/utils/token_tracker.py
new file mode 100644
index 000000000..752f38832
--- /dev/null
+++ b/src/agents/research/utils/token_tracker.py
@@ -0,0 +1,296 @@
+#!/usr/bin/env python
+"""
+Token Tracker - LLM Token usage and cost tracking system (DR-in-KG version)
+References student_TA/solve_agents/utils/token_tracker.py, with minor trimming and added global singleton getter method.
+"""
+
+from dataclasses import asdict, dataclass, field
+from datetime import datetime
+import json
+from typing import Any
+
+# Try importing tiktoken (if available)
+try:
+ import tiktoken # type: ignore
+
+ TIKTOKEN_AVAILABLE = True
+except ImportError:
+ TIKTOKEN_AVAILABLE = False
+ tiktoken = None # type: ignore
+
+# Try importing litellm (optional)
+try:
+ import litellm # type: ignore
+ from litellm import completion_cost, token_counter # type: ignore
+
+ LITELLM_AVAILABLE = True
+except ImportError:
+ LITELLM_AVAILABLE = False
+ litellm = None # type: ignore
+
+# Model pricing table (USD per 1K tokens)
+MODEL_PRICING = {
+ "gpt-4o": {"input": 0.0025, "output": 0.010},
+ "gpt-4o-mini": {"input": 0.00015, "output": 0.0006},
+ "gpt-4-turbo": {"input": 0.01, "output": 0.03},
+ "gpt-4": {"input": 0.03, "output": 0.06},
+ "gpt-3.5-turbo": {"input": 0.0005, "output": 0.0015},
+ "deepseek-chat": {"input": 0.00014, "output": 0.00028},
+ "deepseek-coder": {"input": 0.00014, "output": 0.00028},
+}
+
+
+def get_tiktoken_encoding(model_name: str):
+ if not TIKTOKEN_AVAILABLE:
+ return None
+ try:
+ if "gpt-4" in model_name.lower() or "gpt-3.5" in model_name.lower():
+ return tiktoken.encoding_for_model(model_name)
+ if "gpt-4o" in model_name.lower():
+ return tiktoken.encoding_for_model("gpt-4o")
+ return tiktoken.get_encoding("cl100k_base")
+ except Exception:
+ return tiktoken.get_encoding("cl100k_base") if TIKTOKEN_AVAILABLE else None
+
+
+def count_tokens_with_tiktoken(text: str, model_name: str) -> int:
+ if not TIKTOKEN_AVAILABLE:
+ return 0
+ enc = get_tiktoken_encoding(model_name)
+ if enc is None:
+ return 0
+ return len(enc.encode(text))
+
+
+def count_tokens_with_litellm(messages: list[dict], model_name: str) -> dict[str, int]:
+ if not LITELLM_AVAILABLE:
+ return {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0}
+ try:
+ token_count = token_counter(model=model_name, messages=messages) # type: ignore
+ return {"prompt_tokens": token_count, "completion_tokens": 0, "total_tokens": token_count}
+ except Exception:
+ return {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0}
+
+
+def get_model_pricing(model_name: str) -> dict[str, float]:
+ if model_name in MODEL_PRICING:
+ return MODEL_PRICING[model_name]
+ # Fuzzy matching
+ lower = model_name.lower()
+ for key, val in MODEL_PRICING.items():
+ if key in lower or lower in key:
+ return val
+ # litellm query
+ if LITELLM_AVAILABLE:
+ try:
+ info = litellm.get_model_info(model=model_name) # type: ignore
+ if info and "input_cost_per_token" in info:
+ return {
+ "input": info.get("input_cost_per_token", 0) * 1000,
+ "output": info.get("output_cost_per_token", 0) * 1000,
+ }
+ except Exception:
+ pass
+ return MODEL_PRICING["gpt-4o-mini"]
+
+
+def calculate_cost(model_name: str, prompt_tokens: int, completion_tokens: int) -> float:
+ pricing = get_model_pricing(model_name)
+ return (prompt_tokens / 1000.0) * pricing["input"] + (completion_tokens / 1000.0) * pricing[
+ "output"
+ ]
+
+
+@dataclass
+class TokenUsage:
+ agent_name: str
+ stage: str
+ model: str
+ prompt_tokens: int = 0
+ completion_tokens: int = 0
+ total_tokens: int = 0
+ cost_usd: float = 0.0
+ timestamp: str = field(default_factory=lambda: datetime.now().isoformat())
+ calculation_method: str = "api" # "api"|"tiktoken"|"litellm"|"estimated"
+
+ def to_dict(self) -> dict[str, Any]:
+ return asdict(self)
+
+
+class TokenTracker:
+ def __init__(self, prefer_tiktoken: bool = True, prefer_litellm: bool = False):
+ self.usage_records: list[TokenUsage] = []
+ self.total_prompt_tokens = 0
+ self.total_completion_tokens = 0
+ self.total_tokens = 0
+ self.total_cost_usd = 0.0
+ self.prefer_tiktoken = prefer_tiktoken and TIKTOKEN_AVAILABLE
+ self.prefer_litellm = prefer_litellm and LITELLM_AVAILABLE
+
+ def add_usage(
+ self,
+ agent_name: str,
+ stage: str,
+ model: str,
+ prompt_tokens: int = 0,
+ completion_tokens: int = 0,
+ token_counts: dict[str, int] | None = None,
+ system_prompt: str | None = None,
+ user_prompt: str | None = None,
+ response_text: str | None = None,
+ messages: list[dict] | None = None,
+ ):
+ method = "api"
+ if token_counts:
+ prompt_tokens = token_counts.get("prompt_tokens", prompt_tokens)
+ completion_tokens = token_counts.get("completion_tokens", completion_tokens)
+ method = "api"
+ elif self.prefer_tiktoken and (system_prompt or user_prompt):
+ prompt_text = (system_prompt or "") + "\n" + (user_prompt or "")
+ prompt_tokens = count_tokens_with_tiktoken(prompt_text, model)
+ completion_tokens = count_tokens_with_tiktoken(response_text or "", model)
+ method = "tiktoken"
+ elif self.prefer_litellm and messages:
+ res = count_tokens_with_litellm(messages, model)
+ prompt_tokens = res["prompt_tokens"]
+ completion_tokens = res.get("completion_tokens", completion_tokens)
+ method = "litellm"
+ else:
+ # Estimate: approximate by word count * 1.3
+ est_prompt = int(
+ (((system_prompt or "") + "\n" + (user_prompt or "")).split().__len__()) * 1.3
+ )
+ prompt_tokens = est_prompt
+ completion_tokens = int(((response_text or "").split().__len__()) * 1.3)
+ method = "estimated"
+
+ total = prompt_tokens + completion_tokens
+ cost = calculate_cost(model, prompt_tokens, completion_tokens)
+
+ usage = TokenUsage(
+ agent_name=agent_name,
+ stage=stage,
+ model=model,
+ prompt_tokens=prompt_tokens,
+ completion_tokens=completion_tokens,
+ total_tokens=total,
+ cost_usd=cost,
+ calculation_method=method,
+ )
+ self.usage_records.append(usage)
+ self.total_prompt_tokens += prompt_tokens
+ self.total_completion_tokens += completion_tokens
+ self.total_tokens += total
+ self.total_cost_usd += cost
+
+ def get_summary(self) -> dict[str, Any]:
+ by_agent: dict[str, dict[str, Any]] = {}
+ by_model: dict[str, dict[str, Any]] = {}
+ by_method: dict[str, dict[str, Any]] = {}
+ for u in self.usage_records:
+ pa = by_agent.setdefault(
+ u.agent_name,
+ {
+ "prompt_tokens": 0,
+ "completion_tokens": 0,
+ "total_tokens": 0,
+ "cost_usd": 0.0,
+ "calls": 0,
+ },
+ )
+ pm = by_model.setdefault(
+ u.model,
+ {
+ "prompt_tokens": 0,
+ "completion_tokens": 0,
+ "total_tokens": 0,
+ "cost_usd": 0.0,
+ "calls": 0,
+ },
+ )
+ mm = by_method.setdefault(
+ u.calculation_method,
+ {
+ "prompt_tokens": 0,
+ "completion_tokens": 0,
+ "total_tokens": 0,
+ "cost_usd": 0.0,
+ "calls": 0,
+ },
+ )
+ for bucket in (pa, pm, mm):
+ bucket["prompt_tokens"] += u.prompt_tokens
+ bucket["completion_tokens"] += u.completion_tokens
+ bucket["total_tokens"] += u.total_tokens
+ bucket["cost_usd"] += u.cost_usd
+ bucket["calls"] += 1
+ return {
+ "total_prompt_tokens": self.total_prompt_tokens,
+ "total_completion_tokens": self.total_completion_tokens,
+ "total_tokens": self.total_tokens,
+ "total_cost_usd": self.total_cost_usd,
+ "total_calls": len(self.usage_records),
+ "by_agent": by_agent,
+ "by_model": by_model,
+ "by_method": by_method,
+ "tiktoken_available": TIKTOKEN_AVAILABLE,
+ "litellm_available": LITELLM_AVAILABLE,
+ }
+
+ def format_summary(self) -> str:
+ s = self.get_summary()
+ lines = [
+ "=" * 70,
+ "📊 [DeepResearch] LLM Usage Summary",
+ "=" * 70,
+ f"Total API Calls: {s['total_calls']}",
+ f"Total Tokens: {s['total_tokens']:,}",
+ f" - Input: {s['total_prompt_tokens']:,}",
+ f" - Output: {s['total_completion_tokens']:,}",
+ f"Total Cost: ${s['total_cost_usd']:.6f} USD",
+ "",
+ "By Agent:",
+ "-" * 70,
+ ]
+ for agent, stats in sorted(s["by_agent"].items()):
+ lines += [
+ f" {agent}:",
+ f" Calls: {stats['calls']}",
+ f" Tokens: {stats['total_tokens']:,} (Input: {stats['prompt_tokens']:,}, Output: {stats['completion_tokens']:,})",
+ f" Cost: ${stats['cost_usd']:.6f} USD",
+ "",
+ ]
+ lines += ["By Model:", "-" * 70]
+ for model, stats in sorted(s["by_model"].items()):
+ lines += [
+ f" {model}:",
+ f" Calls: {stats['calls']}",
+ f" Tokens: {stats['total_tokens']:,} (Input: {stats['prompt_tokens']:,}, Output: {stats['completion_tokens']:,})",
+ f" Cost: ${stats['cost_usd']:.6f} USD",
+ "",
+ ]
+ lines.append("=" * 70)
+ return "\n".join(lines)
+
+ def reset(self):
+ self.usage_records.clear()
+ self.total_prompt_tokens = 0
+ self.total_completion_tokens = 0
+ self.total_tokens = 0
+ self.total_cost_usd = 0.0
+
+ def save(self, filepath: str):
+ data = {"summary": self.get_summary(), "records": [u.to_dict() for u in self.usage_records]}
+ with open(filepath, "w", encoding="utf-8") as f:
+ json.dump(data, f, ensure_ascii=False, indent=2)
+
+
+# Global singleton
+_global_tracker: TokenTracker | None = None
+
+
+def get_token_tracker() -> TokenTracker:
+ global _global_tracker
+ if _global_tracker is None:
+ _global_tracker = TokenTracker()
+ return _global_tracker
diff --git a/src/agents/solve/README.md b/src/agents/solve/README.md
new file mode 100644
index 000000000..7990c989a
--- /dev/null
+++ b/src/agents/solve/README.md
@@ -0,0 +1,554 @@
+# Solve Agents - Dual-Loop Problem Solving System
+
+<div align="center">
+
+**Intelligent Problem Solving System Based on Dual-Loop Architecture**
+
+[![Python](https://img.shields.io/badge/Python-3.8+-blue.svg)](https://www.python.org/downloads/)
+[![License](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)
+
+</div>
+
+---
+
+## 📋 Table of Contents
+
+- [System Overview](#system-overview)
+- [Quick Start](#quick-start)
+- [System Architecture](#system-architecture)
+- [Core Modules](#core-modules)
+- [Configuration](#configuration)
+- [Usage Guide](#usage-guide)
+- [Development Guide](#development-guide)
+
+---
+
+## System Overview
+
+This system is an intelligent problem-solving system based on a **dual-loop architecture**, achieving a complete workflow from problem understanding to answer generation through two collaborative loops.
+
+### Dual-Loop Architecture
+
+| Loop | Function | Key Features |
+|------|----------|--------------|
+| **Analysis Loop** | Deep understanding of user questions | Dynamic research, iterative knowledge collection, automatic stopping |
+| **Solve Loop** | Strict solving and answer generation | Block planning, step-by-step execution, quality checking |
+
+### Core Advantages
+
+✅ **Intelligent Research** - Analysis Loop dynamically determines when to stop research
+✅ **Block-based Solving** - Solve Loop decomposes complex problems into manageable blocks
+✅ **Quality Assurance** - Check Agent automatically checks and corrects errors
+✅ **Persistent Memory** - JSON format storage, supports checkpoint resumption
+✅ **Citation Management** - Automatic citation management and formatting
+✅ **Tool Integration** - RAG, Web Search, Code Execution
+
+---
+
+## Quick Start
+
+### Install Dependencies & Configure Environment
+
+```bash
+pip install -r requirements.txt
+
+# .env file (project root directory)
+LLM_BINDING_API_KEY=your_api_key
+LLM_BINDING_HOST=https://api.openai.com/v1
+LLM_MODEL=gpt-4o # Optional
+PERPLEXITY_API_KEY=... # Optional, enable Web search
+```
+
+### Basic Usage (Python API)
+
+```python
+import asyncio
+import os
+from solve_agents import MainSolver
+
+async def main():
+ solver = MainSolver(
+ kb_name="ai_textbook",
+ api_key=os.getenv("LLM_BINDING_API_KEY"),
+ base_url=os.getenv("LLM_BINDING_HOST"),
+ )
+
+ result = await solver.solve(
+ question="What is linear convolution?",
+ verbose=True
+ )
+
+ print(f"📁 Output directory: {result['metadata']['output_dir']}")
+ print(f"📊 Analysis iterations: {result['analysis_iterations']} rounds")
+ print(f"📊 Solve steps: {result['solve_steps']} steps")
+ print(f"📝 Markdown: {result['output_md']}")
+
+asyncio.run(main())
+```
+
+### Using Command Line Tool
+
+```bash
+cd OpenTutor/student_TA
+python start.py # CLI currently defaults to dual-loop Solve mode
+```
+
+---
+
+## System Architecture
+
+### Overall Flow
+
+```
+User Question
+ │
+ ▼
+┌─────────────────────────────────────────────────────────────┐
+│ MainSolver │
+│ │
+│ ┌───────────────────────────────────────────────────────┐ │
+│ │ Analysis Loop (Analysis Loop) │ │
+│ │ │ │
+│ │ ┌──────────┐ ┌──────────┐ │ │
+│ │ │Investigate│ -> │ Note │ │ │
+│ │ └──────────┘ └──────────┘ │ │
+│ │ ▲ │ │ │
+│ │ └─────────────┴───────────────┐ │ │
+│ │ │ │ │
+│ │ Stop condition met │ │
+│ │ │ │ │
+│ │ InvestigateMemory │ │
+│ └───────────────────────────────────────────────────────┘ │
+│ │ │
+│ ▼ │
+│ ┌───────────────────────────────────────────────────────┐ │
+│ │ Solve Loop (Solving Loop) │ │
+│ │ │ │
+│ │ ┌──────┐ ┌─────────┐ ┌──────┐ ┌───────┐ │ │
+│ │ │ Plan │ -> │ Manager │ -> │Solve │ -> │ Check │ │ │
+│ │ └──────┘ └─────────┘ └──────┘ └───────┘ │ │
+│ │ │ │ │ │
+│ │ └───────────┘ │ │
+│ │ Loop until completion │ │
+│ │ │ │ │
+│ │ ▼ │ │
+│ │ ┌────────┐ │ │
+│ │ │ Format │ │ │
+│ │ └────────┘ │ │
+│ │ │ │ │
+│ │ SolveMemory │ │
+│ └───────────────────────────────────────────────────────┘ │
+│ │
+│ Final Answer │
+└─────────────────────────────────────────────────────────────┘
+```
+
+### Directory Structure
+
+```
+solve_agents/
+├── main_solver.py # Main controller
+├── base_agent.py # Agent base class
+├── config.yaml # Configuration file
+│
+├── analysis_loop/ # Analysis Loop ⭐
+│ ├── investigate_agent.py # Research Agent
+│ ├── note_agent.py # Note Agent
+│ └── README.md # Detailed documentation
+│
+├── solve_loop/ # Solve Loop ⭐
+│ ├── plan_agent.py # Planning Agent
+│ ├── manager_agent.py # Manager Agent
+│ ├── solve_agent.py # Solving Agent
+│ ├── tool_agent.py # Tool execution Agent
+│ ├── response_agent.py # Aggregate tool results
+│ ├── check_agent.py # Quality checking
+│ ├── precision_answer_agent.py # Precision answer (optional)
+│ ├── citation_manager.py # Citation manager
+│ └── README.md # Detailed documentation
+│
+├── memory/ # Memory system ⭐
+│ ├── investigate_memory.py # Analysis Loop memory
+│ └── solve_memory.py # Solve Loop memory
+│
+├── utils/ # Utility modules
+│ ├── logger.py # Logging system
+│ ├── performance_monitor.py # Performance monitoring
+│ ├── config_validator.py # Configuration validation
+│ ├── prompt_loader.py # Prompt loader
+│ ├── json_utils.py # JSON utilities
+│ ├── tag_parser.py # Tag parser
+│ └── error_handler.py # Error handling
+│
+└── prompts/ # Prompt templates
+ ├── analysis_loop/ # Analysis Loop Prompts
+ └── solve_loop/ # Solve Loop Prompts
+```
+
+---
+
+## Core Modules
+
+### Analysis Loop (Analysis Loop)
+
+**Function**: Deep understanding of user questions
+
+**Agents**:
+- **InvestigateAgent**: Based on knowledge chain, outputs multiple queries at once and calls tools, generates `cite_id → raw_result`
+- **NoteAgent**: Processes new `cite_id` one by one, generates summary and citations
+
+**Memory**: `InvestigateMemory` (JSON)
+
+**Detailed Documentation**: [analysis_loop/README.md](analysis_loop/README.md)
+
+### Solve Loop (Solving Loop)
+
+**Function**: Strict solving and answer generation
+
+**Agents**:
+- **PlanAgent**: Generates problem-solving plan (blocks)
+- **ManagerAgent**: Arranges specific steps (steps) for each block
+- **SolveAgent**: Calls tools and writes reasoning according to steps
+- **ToolAgent**: Unified encapsulation of RAG / Web Search / Code Execution / Query Item tools
+- **ResponseAgent**: Organizes outputs from SolveAgent and ToolAgent
+- **CheckAgent**: Automatically checks steps and provides correction suggestions
+- **PrecisionAnswerAgent**: Generates precision answer summary (optional)
+
+**Memory**: `SolveMemory` (JSON)
+
+**Detailed Documentation**: [solve_loop/README.md](solve_loop/README.md)
+
+### Memory System
+
+**InvestigateMemory**:
+```python
+{
+ "user_question": "...",
+ "knowledge_chain": [...], # Collected knowledge
+ "reflections": {...}, # Reserved field, currently only records remaining questions (default empty)
+ "metadata": {...} # Statistics
+}
+```
+
+**SolveMemory**:
+```python
+{
+ "user_question": "...",
+ "plan": {
+ "blocks": [...] # Problem-solving plan
+ },
+ "progress": {...}, # Execution progress
+ "metadata": {...} # Statistics
+}
+```
+
+### Tool System
+
+ToolAgent aggregates multiple capabilities and automatically chains them step by step:
+
+- **RAG Search**: Retrieves KBs from `knowledge_bases/`
+- **Web Search**: Expands latest materials based on Perplexity API
+- **Query Item**: Quickly references formulas / theorems by number
+- **Code Execution**: Runs Python in sandbox, results written to `artifacts/`
+
+---
+
+## Configuration
+
+### config.yaml Structure
+
+```yaml
+system:
+ output_base_dir: "./user/solve"
+ save_intermediate_results: true
+ output_language: "English" # or Chinese
+ max_analysis_iterations: 5
+ max_solve_correction_iterations: 3
+
+logging:
+ level: "INFO"
+ save_to_file: true
+ console_output: true
+ log_dir: "./logs"
+
+monitoring:
+ enabled: true
+ track_token_usage: true
+ track_time: true
+ save_dir: "./logs/performance"
+
+llm:
+ max_retries: 3
+ timeout: 120
+ max_tokens: 8192
+
+agents:
+ investigate_agent:
+ temperature: 0.4
+ max_iterations: 3
+ note_agent:
+ max_tokens: 4096
+
+ manager_agent: {}
+ solve_agent:
+ max_tokens: 8192
+ tool_agent: {}
+ response_agent:
+ max_tokens: 8192
+ enabled: false
+ max_tokens: 8192
+ precision_answer_agent:
+ enabled: true
+ temperature: 0.2
+
+tools:
+ rag_tool:
+ kb_base_dir: "./knowledge_bases"
+ default_kb: "ai_textbook"
+ web_search:
+ enabled: true
+ max_results: 5
+ query_item:
+ enabled: true
+ run_code:
+ enabled: true
+ timeout: 10
+ workspace: "./student_TA/cache/run_code_workspace"
+```
+
+---
+
+## Usage Guide
+
+### Basic Usage
+
+```python
+from solve_agents import MainSolver
+
+# Create solver
+solver = MainSolver(
+ kb_name="ai_textbook", # Knowledge base name
+ config_path=None, # Use default configuration
+ api_key=None, # Read from environment variables
+ base_url=None # Read from environment variables
+)
+
+# Solve problem
+result = await solver.solve(
+ question="Your question",
+ verbose=True # Print detailed logs
+)
+
+# View results
+print(result['output_md']) # final_answer.md
+print(result['output_json']) # solve_chain.json (steps + tool logs)
+print(result['final_answer']) # String, may contain precision answer
+print(len(result['citations'])) # Number of citations
+```
+
+### Output Files
+
+```
+user/solve/solve_20251116_160009/
+├── investigate_memory.json # Analysis Loop memory
+├── solve_chain.json # Solve Loop steps & tool records ⭐
+├── citation_memory.json # Citation management
+├── final_answer.md # Final answer (Markdown)
+├── performance_report.json # Performance monitoring
+├── cost_report.json # Optional: token cost
+├── search_*.json # Search cache (if any)
+└── artifacts/ # Code execution output
+```
+
+### View Statistics
+
+```python
+result = await solver.solve(question)
+
+# Analysis Loop statistics
+print(f"Analysis iterations: {result['analysis_iterations']} rounds")
+print(f"Coverage rate: {result['metadata']['coverage_rate']:.2%}")
+print(f"Average confidence: {result['metadata']['avg_confidence']:.2%}")
+
+# Solve Loop statistics
+print(f"Solve completed steps: {result['solve_steps']} / {result['metadata']['total_steps']}")
+print(f"Number of citations: {len(result['citations'])}")
+```
+
+### Debug Mode
+
+```python
+# Enable detailed logging
+import logging
+logging.basicConfig(level=logging.DEBUG)
+
+# View memory files
+import json
+output_dir = result['metadata']['output_dir']
+with open(f'{output_dir}/investigate_memory.json', encoding='utf-8') as f:
+ memory = json.load(f)
+print(json.dumps(memory, indent=2, ensure_ascii=False))
+```
+
+---
+
+## Development Guide
+
+### Extending New Agent
+
+1. **Inherit BaseAgent**:
+
+```python
+from solve_agents.base_agent import BaseAgent
+
+class MyAgent(BaseAgent):
+ def __init__(self, config, api_key, base_url):
+ super().__init__(config, api_key, base_url, 'my_agent')
+
+ async def process(self, **kwargs):
+ # Implement processing logic
+ prompt = self.prompt_loader.load('my_agent')
+ response = await self.call_llm(prompt)
+ return self.parse_response(response)
+```
+
+2. **Add Prompt**:
+
+Define Prompt in `prompts/analysis_loop/my_agent.yaml` or `prompts/solve_loop/my_agent.yaml`.
+
+3. **Register to MainSolver**:
+
+Initialize in the `_init_agents()` method of `main_solver.py`.
+
+4. **Add Configuration**:
+
+Add Agent configuration in `config.yaml`.
+
+### Extending Memory System
+
+```python
+from dataclasses import dataclass, asdict
+import json
+
+@dataclass
+class MyMemory:
+ user_question: str
+ data: dict
+
+ def save(self, output_dir: str):
+ with open(f"{output_dir}/my_memory.json", 'w') as f:
+ json.dump(asdict(self), f, ensure_ascii=False, indent=2)
+
+ @classmethod
+ def load_or_create(cls, output_dir: str, user_question: str):
+ path = f"{output_dir}/my_memory.json"
+ if os.path.exists(path):
+ with open(path) as f:
+ data = json.load(f)
+ return cls(**data)
+ return cls(user_question=user_question, data={})
+```
+
+### Adding New Tool
+
+```python
+# Create new tool in tools/ directory
+class MyTool:
+ def __init__(self, config):
+ self.config = config
+
+ async def execute(self, **kwargs):
+ # Implement tool logic
+ return result
+
+# Register in SolveAgent
+self.tools['my_tool'] = MyTool(config)
+```
+
+---
+
+## Performance Optimization
+
+### Adjust Iteration Count
+
+```yaml
+system:
+ max_analysis_iterations: 3 # Reduce Analysis iterations
+ max_solve_correction_iterations: 2 # Reduce Solve retries
+```
+
+### Use Faster Model
+
+```yaml
+agents:
+ investigate_agent:
+ model: "gpt-3.5-turbo" # Use faster model
+```
+
+### Disable Optional Features
+
+```yaml
+agents:
+ precision_answer_agent:
+ enabled: false # Disable precision answer
+```
+
+---
+
+## FAQ
+
+**Q: How to adjust the iteration count of Analysis Loop?**
+
+Set `system.max_analysis_iterations` in `config.yaml`.
+
+**Q: How to enable precision answer feature?**
+
+Set `agents.precision_answer_agent.enabled: true` in `config.yaml`.
+
+**Q: How to view detailed execution logs?**
+
+Set `logging.level: "DEBUG"` or enable `verbose=True` in code.
+
+**Q: Where are the memory files?**
+
+In the `{output_base_dir}/solve_{timestamp}/` directory.
+
+**Q: How to reset citation numbers?**
+
+```python
+from solve_agents.solve_loop.citation_manager import CitationManager
+CitationManager().reset()
+```
+
+**Q: What to do if code execution times out?**
+
+Adjust the `agents.code_agent.timeout` configuration.
+
+---
+
+## Version History
+
+- **v3.0** (2025-11-16) - Dual-loop architecture refactoring
+ - ✅ Complete refactoring to dual-loop architecture
+ - ✅ Remove old Router, Deep Analysis, Deep Solve modules
+ - ✅ Introduce dynamic memory system
+ - ✅ Optimize tool calling and citation management
+ - ✅ Simplify configuration and usage flow
+ - ✅ Merge utils and parsers modules
+
+---
+
+## Related Documentation
+
+- [Analysis Loop Detailed Documentation](analysis_loop/README.md)
+- [Solve Loop Detailed Documentation](solve_loop/README.md)
+- [Configuration File Documentation](config.yaml)
+---
+
+## License
+
+MIT License
+
+---
+
+**Made with ❤️ by OpenTutor Team**
diff --git a/src/agents/solve/__init__.py b/src/agents/solve/__init__.py
new file mode 100644
index 000000000..ae0982190
--- /dev/null
+++ b/src/agents/solve/__init__.py
@@ -0,0 +1,82 @@
+#!/usr/bin/env python
+"""
+Solve Agent System - Dual-Loop Architecture
+Analysis Loop + Solve Loop
+"""
+
+from pathlib import Path
+import sys
+
+# Add project root to path for logs import
+_project_root = Path(__file__).parent.parent.parent.parent
+if str(_project_root) not in sys.path:
+ sys.path.insert(0, str(_project_root))
+
+# Infrastructure
+from src.core.logging import Logger, get_logger
+
+from .base_agent import BaseAgent
+from .utils import (
+ ConfigValidator,
+ PerformanceMonitor,
+ PromptLoader,
+)
+
+# Backwards compatibility
+SolveAgentLogger = Logger
+
+# Memory system
+# Analysis loop
+from .analysis_loop import (
+ InvestigateAgent,
+ NoteAgent,
+)
+
+# Main controller
+from .main_solver import MainSolver
+from .memory import (
+ InvestigateMemory,
+ KnowledgeItem,
+ Reflections,
+ SolveChainStep,
+ SolveMemory,
+ ToolCallRecord,
+)
+
+# Solve loop
+from .solve_loop import (
+ ManagerAgent,
+ PrecisionAnswerAgent,
+ ResponseAgent,
+ SolveAgent,
+ ToolAgent,
+)
+
+__all__ = [
+ # Infrastructure
+ "BaseAgent",
+ "Logger",
+ "get_logger",
+ "SolveAgentLogger", # Backwards compatibility
+ "PerformanceMonitor",
+ "ConfigValidator",
+ "PromptLoader",
+ # Memory system
+ "InvestigateMemory",
+ "KnowledgeItem",
+ "Reflections",
+ "SolveMemory",
+ "SolveChainStep",
+ "ToolCallRecord",
+ # Analysis Loop
+ "InvestigateAgent",
+ "NoteAgent",
+ # Solve Loop
+ "ManagerAgent",
+ "SolveAgent",
+ "ResponseAgent",
+ "PrecisionAnswerAgent",
+ "ToolAgent",
+ # Main Controller
+ "MainSolver",
+]
diff --git a/src/agents/solve/analysis_loop/README.md b/src/agents/solve/analysis_loop/README.md
new file mode 100644
index 000000000..8e6e6e80a
--- /dev/null
+++ b/src/agents/solve/analysis_loop/README.md
@@ -0,0 +1,295 @@
+# Analysis Loop - Deep Research Phase
+
+## Overview
+
+Analysis Loop is the first phase of the dual-loop architecture, responsible for **deeply understanding user questions**. Through iterative research, it dynamically collects and organizes knowledge until the question is sufficiently understood.
+
+## Architecture
+
+```
+┌─────────────────────────────────────────┐
+│ Analysis Loop (Research Phase) │
+│ │
+│ ┌──────────┐ ┌──────────┐ │
+│ │Investigate│ -> │ Note │ ────┐ │
+│ └──────────┘ └──────────┘ │ │
+│ ▲ │ │ │
+│ └────────────┴─────────────┘ │
+│ │ │
+│ Stop Condition Met │
+│ │ │
+│ ▼ │
+│ InvestigateMemory │
+└─────────────────────────────────────────┘
+```
+
+## Core Agents
+
+### 1. InvestigateAgent
+
+**Role**: Research planner and tool executor. Based on knowledge chain summaries and user questions, generates multiple high-value queries and calls tools to retrieve raw data.
+
+**Key Features**:
+1. Identifies knowledge gaps from cite_id summaries; generates multiple `[TOOL]tool_type | query` commands in one pass if needed.
+2. Immediately calls tools (`rag_naive`, `rag_hybrid`, `web_search`, `query_item`) for each query to get `raw_result`.
+3. When `[TOOL] none` appears, knowledge is sufficient and Analysis Loop automatically stops.
+
+**Output Structure**:
+```python
+{
+ 'reasoning': 'List of knowledge gaps identified this round',
+ 'should_stop': False,
+ 'knowledge_item_ids': ['c01', 'c02'], # List of new cite_ids this round
+ 'actions': [
+ {'tool_type': 'rag_hybrid', 'query': 'Section 2.5...', 'cite_id': 'c01'},
+ {'tool_type': 'rag_naive', 'query': 'Lambda range in algorithm', 'cite_id': 'c02'}
+ ]
+}
+```
+
+### 2. NoteAgent
+
+**Role**: Note-taker. For each knowledge item in `knowledge_item_ids`, sequentially calls LLM to convert `raw_result` into summaries and extract citations.
+
+**Key Features**:
+1. Automatically iterates through multiple knowledge items in one round, independently constructing Prompt → LLM → parsing summary.
+2. Summaries must be concise and extract citable sources from `raw_result`.
+3. After processing, updates `InvestigateMemory` and `CitationMemory` for use by Solve Loop.
+
+**Output Structure**:
+```python
+{
+ 'success': True,
+ 'processed_items': 2,
+ 'details': [
+ {'cite_id': 'c01', 'citations_count': 2},
+ {'cite_id': 'c02', 'citations_count': 1}
+ ],
+ 'failed': []
+}
+```
+
+## Memory System
+
+### InvestigateMemory
+
+Persistent JSON structure that chains all knowledge collected during the analysis phase. Each tool call generates a unique `cite_id` and is recorded in `knowledge_chain`.
+
+**Structure**:
+```python
+{
+ "user_question": "What is linear convolution?",
+ "knowledge_chain": [
+ {
+ "cite_id": "c01",
+ "tool_type": "rag_hybrid",
+ "query": "Section 2.5 Linear convolution definition and properties",
+ "raw_result": "...RAG source text...",
+ "summary": "Linear convolution derives from convolution integral; core properties include commutativity and associativity.",
+ "created_at": "...",
+ "updated_at": "..."
+ }
+ ],
+ "reflections": {
+ "remaining_questions": [],
+ "updated_at": "..."
+ },
+ "metadata": {
+ "total_iterations": 2,
+ "total_knowledge_items": 1,
+ "coverage_rate": 1.0,
+ "avg_confidence": 0.9
+ }
+}
+```
+
+**Storage Location**: `{output_dir}/investigate_memory.json`
+
+## Configuration
+
+Configure Analysis Loop in `config.yaml`:
+
+```yaml
+system:
+ max_analysis_iterations: 5 # Maximum iterations
+
+agents:
+ investigate_agent:
+ enabled: true
+ model: "gpt-4o"
+ temperature: 0.4
+
+ note_agent:
+ enabled: true
+ model: "gpt-4o"
+ temperature: 0.3
+```
+
+## Usage Example
+
+```python
+from solve_agents.memory import InvestigateMemory
+from solve_agents.analysis_loop import InvestigateAgent, NoteAgent
+
+memory = InvestigateMemory.load_or_create(
+ output_dir="./output",
+ user_question="What is linear convolution?"
+)
+
+investigate_agent = InvestigateAgent(config, api_key, base_url)
+note_agent = NoteAgent(config, api_key, base_url)
+
+for i in range(max_iterations):
+ investigate_result = await investigate_agent.process(
+ question=question,
+ memory=memory,
+ citation_memory=citation_memory,
+ kb_name="ai_textbook",
+ output_dir="./output"
+ )
+
+ cite_ids = investigate_result.get('knowledge_item_ids', [])
+ if cite_ids:
+ await note_agent.process(
+ question=question,
+ memory=memory,
+ new_knowledge_ids=cite_ids,
+ citation_memory=citation_memory,
+ output_dir="./output"
+ )
+
+ if investigate_result.get('should_stop'):
+ break
+
+memory.save()
+```
+
+## Workflow Example
+
+**Question**: "What is linear convolution?"
+
+**Round 1**:
+1. **Investigate**: Outputs two queries
+ - `[TOOL]rag_hybrid | Linear convolution definition`
+ - `[TOOL]rag_naive | Geometric interpretation of convolution`
+ Gets cite_ids `c01/c02`.
+2. **Note**: Processes `c01/c02` sequentially, generates summaries and extracts 3 citations.
+
+**Round 2**:
+1. **Investigate**: Outputs
+ - `[TOOL]rag_hybrid | Convolution calculation examples`
+ - `[TOOL]web_search | Latest application scenarios`
+ Gets cite_ids `c03/c04`.
+2. **Note**: Processes `c03/c04`, supplements calculation procedures and practical examples.
+
+**Round 3**:
+1. **Investigate**: `[TOOL]none` - reasoning: "Definition, derivation, and examples all covered".
+2. Analysis Loop completes.
+
+**Result**: Collects 4 knowledge items; NoteAgent automatically updates summaries and citations; ready for Solve Loop consumption.
+
+## Key Features
+
+### 1. Dynamic Research
+- No preset query count
+- Dynamically determines based on actual needs
+- Automatically judges when to stop
+
+### 2. Tool Selection
+- Prioritizes knowledge base (RAG)
+- Uses web search when necessary
+- Intelligently selects most appropriate tools
+
+### 3. Citation Management
+- Automatically extracts key citations
+- Provides evidence for Solve Loop
+- Supports subsequent citation formatting
+
+### 4. Persistent Memory
+- JSON format storage
+- Supports checkpoint resumption
+- Facilitates debugging and review
+
+## Integration with Solve Loop
+
+After Analysis Loop completes, `InvestigateMemory` is passed to Solve Loop:
+
+```python
+# Analysis Loop completes
+investigate_memory.save()
+
+# Solve Loop consumes
+solve_memory = SolveMemory.load_or_create(...)
+plan_result = await plan_agent.process(
+ question=question,
+ investigate_memory=investigate_memory, # Pass analysis results
+ solve_memory=solve_memory
+)
+```
+
+Solve Loop can access:
+- `investigate_memory.knowledge_chain`: All collected knowledge
+- `investigate_memory.get_all_citations()`: All citations
+- `investigate_memory.get_knowledge_summary()`: Knowledge summary
+
+## Debugging and Monitoring
+
+### View Memory Files
+
+```bash
+cat output/investigate_memory.json | jq .
+```
+
+### Monitor Iteration Progress
+
+Logs display detailed information for each round:
+
+```
+--- Analysis Loop Round 1 ---
+ [Investigate] Reasoning: Still missing calculation examples
+ • rag_hybrid: Section 2.4 convolution definition -> cite_id=c01
+ • rag_naive: Geometric interpretation of convolution -> cite_id=c02
+ [Note] Processed 2 knowledge items
+```
+
+### Performance Statistics
+
+```python
+metadata = investigate_memory.metadata
+print(f"Total iterations: {metadata['total_iterations']} rounds")
+print(f"Total knowledge items: {metadata['total_knowledge_items']}")
+print(f"Coverage rate: {metadata['coverage_rate']:.2%}")
+print(f"Average confidence: {metadata['avg_confidence']:.2f}")
+```
+
+## Common Questions
+
+**Q: How to adjust maximum iteration count?**
+
+Set in `config.yaml`:
+```yaml
+system:
+ max_analysis_iterations: 5 # Default 5 rounds
+```
+
+**Q: How to force web search usage?**
+
+Modify the Investigate Agent prompt or pass parameters when calling.
+
+**Q: How to view extracted citations?**
+
+```python
+citations = investigate_memory.get_all_citations()
+for citation in citations:
+ print(citation)
+```
+
+**Q: What if memory file becomes too large?**
+
+Periodically clean up `raw_content`, keeping only `summary` and `citations`.
+
+---
+
+**Related Documentation**:
+- [Solve Loop README](../solve_loop/README.md)
+- [Main README](../README.md)
diff --git a/src/agents/solve/analysis_loop/__init__.py b/src/agents/solve/analysis_loop/__init__.py
new file mode 100644
index 000000000..60fce09dd
--- /dev/null
+++ b/src/agents/solve/analysis_loop/__init__.py
@@ -0,0 +1,14 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+"""
+Analysis Loop - Analysis loop (Investigate → Note)
+Deeply understand user questions, collect and organize knowledge
+"""
+
+from .investigate_agent import InvestigateAgent
+from .note_agent import NoteAgent
+
+__all__ = [
+ "InvestigateAgent",
+ "NoteAgent",
+]
diff --git a/src/agents/solve/analysis_loop/investigate_agent.py b/src/agents/solve/analysis_loop/investigate_agent.py
new file mode 100644
index 000000000..e7d5ee065
--- /dev/null
+++ b/src/agents/solve/analysis_loop/investigate_agent.py
@@ -0,0 +1,404 @@
+#!/usr/bin/env python
+"""
+InvestigateAgent - Investigator
+Generates query actions and calls tools based on current memory and reflections.
+"""
+
+from pathlib import Path
+import sys
+from typing import Any
+
+# Add project root to path
+project_root = Path(__file__).parent.parent.parent.parent
+sys.path.insert(0, str(project_root))
+
+import json
+
+from src.tools import query_numbered_item, rag_search, web_search
+
+from ..base_agent import BaseAgent
+from ..memory import CitationMemory, InvestigateMemory, KnowledgeItem
+from ..utils.json_utils import extract_json_from_text
+
+
+class InvestigateAgent(BaseAgent):
+ """Investigator Agent - Generates queries and calls tools"""
+
+ def __init__(self, config: dict[str, Any], api_key: str, base_url: str, token_tracker=None):
+ super().__init__(
+ config=config,
+ api_key=api_key,
+ base_url=base_url,
+ agent_name="investigate_agent",
+ use_prompt_loader=True,
+ token_tracker=token_tracker,
+ )
+ # Read web_search enabled config from tools.web_search.enabled
+ self.enable_web_search = config.get("tools", {}).get("web_search", {}).get("enabled", True)
+
+ # Read agent-specific config from solve.agents.investigate_agent
+ agent_config = config.get("solve", {}).get("agents", {}).get("investigate_agent", {})
+ self.max_actions_per_round = agent_config.get("max_actions_per_round", 1)
+ self.max_iterations = agent_config.get("max_iterations", 3)
+
+ async def process(
+ self,
+ question: str,
+ memory: InvestigateMemory,
+ citation_memory: CitationMemory,
+ kb_name: str = "ai_textbook",
+ output_dir: str | None = None,
+ verbose: bool = True,
+ ) -> dict[str, Any]:
+ """
+ Process investigation flow (supports multiple tools per round)
+
+ Args:
+ question: User question
+ memory: Investigation memory
+ citation_memory: Citation memory (for registering citations)
+ kb_name: Knowledge base name
+ output_dir: Output directory
+ verbose: Whether to print detailed info
+
+ Returns:
+ dict: Investigation result
+ {
+ 'reasoning': str,
+ 'should_stop': bool,
+ 'knowledge_item_ids': List[str],
+ 'actions': List[Dict[str, Any]]
+ }
+ """
+ if citation_memory is None:
+ raise ValueError(
+ "citation_memory cannot be None, InvestigateAgent needs it for citation registration"
+ )
+
+ # 1. Build context
+ context = self._build_context(question, memory)
+
+ # 2. Build prompts
+ system_prompt = self._build_system_prompt()
+ user_prompt = self._build_user_prompt(context)
+
+ # 3. Call LLM
+ response = await self.call_llm(
+ user_prompt=user_prompt,
+ system_prompt=system_prompt,
+ verbose=verbose,
+ response_format={"type": "json_object"},
+ )
+
+ # 4. Parse output (JSON)
+ parsed_result = extract_json_from_text(response)
+
+ if not parsed_result or not isinstance(parsed_result, dict):
+ self.logger.warning("Parse failed: LLM did not return valid JSON")
+ return {
+ "reasoning": "Parse failed: invalid JSON",
+ "should_stop": True,
+ "knowledge_item_ids": [],
+ "actions": [],
+ }
+
+ reasoning = parsed_result.get("reasoning", "")
+ tool_plans = parsed_result.get("plan", [])
+
+ # Ensure tool_plans is a list (handle case where LLM returns dict instead of list)
+ if not isinstance(tool_plans, list):
+ if isinstance(tool_plans, dict):
+ # If plan is a dict, wrap it in a list
+ self.logger.warning("Parse warning: 'plan' field is a dict, wrapping in list")
+ tool_plans = [tool_plans]
+ else:
+ self.logger.warning(
+ "Parse warning: 'plan' field is not a list or dict, using empty list"
+ )
+ tool_plans = []
+
+ # 5. Determine if should stop
+ should_stop = False
+ if not tool_plans:
+ should_stop = True
+ else:
+ for plan in tool_plans:
+ if plan.get("tool") == "none":
+ should_stop = True
+ break
+
+ if should_stop:
+ return {
+ "reasoning": reasoning,
+ "should_stop": True,
+ "knowledge_item_ids": [],
+ "actions": [],
+ }
+
+ # 6. Execute multiple tool calls (limited by max_actions_per_round)
+ knowledge_ids: list[str] = []
+ executed_actions: list[dict[str, Any]] = []
+
+ # Limit number of actions per round based on config
+ tool_plans_to_execute = tool_plans[: self.max_actions_per_round]
+
+ for plan in tool_plans_to_execute:
+ tool_type = plan.get("tool")
+ if not tool_type:
+ continue
+
+ query = plan.get("query", "")
+ identifier = plan.get("identifier")
+
+ if tool_type == "none":
+ continue
+
+ knowledge_item = await self._execute_single_action(
+ tool_selection=tool_type,
+ query=query,
+ identifier=identifier,
+ kb_name=kb_name,
+ output_dir=output_dir,
+ citation_memory=citation_memory,
+ )
+
+ executed_actions.append(
+ {
+ "tool_type": tool_type,
+ "query": query,
+ "identifier": identifier,
+ "cite_id": knowledge_item.cite_id if knowledge_item else None,
+ }
+ )
+
+ if knowledge_item:
+ memory.add_knowledge(knowledge_item)
+ knowledge_ids.append(knowledge_item.cite_id)
+
+ if knowledge_ids and output_dir:
+ memory.save()
+
+ # 7. Return results
+ return {
+ "reasoning": reasoning,
+ "should_stop": False,
+ "knowledge_item_ids": knowledge_ids,
+ "actions": executed_actions,
+ }
+
+ def _build_context(self, question: str, memory: InvestigateMemory) -> dict[str, Any]:
+ """Build context (pass full content, no truncation)"""
+ knowledge_chain_full = []
+ for item in memory.knowledge_chain:
+ knowledge_chain_full.append(
+ {
+ "cite_id": item.cite_id,
+ "tool_type": item.tool_type,
+ "query": item.query,
+ "raw_result": item.raw_result,
+ "summary": item.summary,
+ }
+ )
+
+ remaining_questions_full = []
+ if memory.reflections and memory.reflections.remaining_questions:
+ remaining_questions_full = memory.reflections.remaining_questions.copy()
+ knowledge_chain_summary = (
+ "\n".join(
+ f"- {item.cite_id} ({item.tool_type}): {item.summary or item.raw_result[:200]}"
+ for item in memory.knowledge_chain
+ )
+ if memory.knowledge_chain
+ else "(none)"
+ )
+ reflections_summary = (
+ "\n".join(f"- {q}" for q in remaining_questions_full)
+ if remaining_questions_full
+ else "(no remaining questions)"
+ )
+
+ return {
+ "question": question,
+ "num_knowledge": len(memory.knowledge_chain),
+ "knowledge_chain_full": knowledge_chain_full,
+ "knowledge_chain_summary": knowledge_chain_summary,
+ "reflections_summary": reflections_summary,
+ "remaining_questions": remaining_questions_full,
+ "action_queue": "(no action history)",
+ }
+
+ def _build_system_prompt(self) -> str:
+ """Build system prompt"""
+ prompt = self.get_prompt("system") if self.has_prompts() else None
+ if not prompt:
+ raise ValueError(
+ "InvestigateAgent missing system prompt. Configure in src/agents/solve/prompts/en/analysis_loop/investigate_agent.yaml"
+ )
+
+ # If web_search is disabled, remove web_search related content from prompt
+ if not self.enable_web_search:
+ # Get the web_search disabled prompt if available, otherwise filter out web_search lines
+ web_search_disabled_prompt = (
+ self.get_prompt("web_search_disabled") if self.has_prompts() else None
+ )
+ if web_search_disabled_prompt:
+ # Replace web_search description with disabled message
+ prompt = prompt.replace(
+ self.get_prompt("web_search_description") or "", web_search_disabled_prompt
+ )
+ else:
+ # Simple filter: remove lines containing web_search tool description
+ lines = prompt.split("\n")
+ filtered_lines = []
+ for line in lines:
+ # Skip lines that describe web_search as an available tool
+ if "`web_search`" in line and (
+ "Use Sparingly" in line or "latest news" in line or "Web Search" in line
+ ):
+ continue
+ # Also remove web_search from tool list in output format
+ if "web_search" in line and (
+ "rag_naive | rag_hybrid |" in line or 'tool":' in line
+ ):
+ line = (
+ line.replace(" | web_search", "")
+ .replace("| web_search", "")
+ .replace("web_search |", "")
+ .replace("web_search", "")
+ )
+ filtered_lines.append(line)
+ prompt = "\n".join(filtered_lines)
+
+ return prompt
+
+ def _build_user_prompt(self, context: dict[str, Any]) -> str:
+ """Build user prompt (pass full content)"""
+ template = self.get_prompt("user_template") if self.has_prompts() else None
+ if not template:
+ raise ValueError(
+ "InvestigateAgent missing user prompt template. Configure in prompts/en/analysis_loop/investigate_agent.yaml"
+ )
+ return template.format(**context)
+
+ async def _execute_single_action(
+ self,
+ tool_selection: str,
+ query: str,
+ identifier: str | None,
+ kb_name: str,
+ output_dir: str | None,
+ citation_memory: CitationMemory,
+ ) -> KnowledgeItem | None:
+ """Execute a single tool call"""
+ import time
+
+ start_time = time.time()
+ tool_input = {"query": query, "identifier": identifier, "kb_name": kb_name}
+
+ try:
+ if tool_selection == "rag_naive":
+ result = await self._call_rag_naive(query, kb_name, output_dir)
+ raw_result = result.get("answer", "")
+
+ elif tool_selection == "rag_hybrid":
+ result = await self._call_rag_hybrid(query, kb_name, output_dir)
+ raw_result = result.get("answer", "")
+
+ elif tool_selection == "web_search":
+ # Check if web_search is enabled
+ if not self.enable_web_search:
+ self.logger.warning(
+ "Tool call rejected (web_search): web_search is disabled in config"
+ )
+ return None
+ result = await self._call_web_search(query, output_dir)
+ raw_result = json.dumps(result, ensure_ascii=False, indent=2)
+
+ elif tool_selection == "query_item":
+ identifier_to_use = identifier or query
+
+ if (
+ not identifier_to_use
+ or not isinstance(identifier_to_use, str)
+ or not identifier_to_use.strip()
+ ):
+ self.logger.warning(
+ "Tool call failed (query_item): identifier is empty or invalid"
+ )
+ return None
+
+ result = await self._call_query_item(identifier_to_use, kb_name)
+ raw_result = result.get("content", result.get("answer", ""))
+
+ else:
+ self.logger.warning(f"Unknown tool type: {tool_selection}")
+ return None
+
+ elapsed_ms = (time.time() - start_time) * 1000
+
+ # Create and register citation
+ cite_id = citation_memory.add_citation(
+ tool_type=tool_selection,
+ query=query,
+ raw_result=raw_result,
+ stage="analysis",
+ metadata={"identifier": identifier},
+ )
+ citation_memory.save()
+
+ # Log tool call
+ self.logger.log_tool_call(
+ tool_name=tool_selection,
+ tool_input=tool_input,
+ tool_output=result,
+ status="success",
+ elapsed_ms=elapsed_ms,
+ citation_id=cite_id,
+ )
+
+ # Create knowledge item
+ knowledge_item = KnowledgeItem(
+ cite_id=cite_id,
+ tool_type=tool_selection,
+ query=query,
+ raw_result=raw_result,
+ summary="", # Generated by NoteAgent
+ )
+
+ return knowledge_item
+
+ except Exception as e:
+ elapsed_ms = (time.time() - start_time) * 1000
+ error_msg = str(e)
+
+ self.logger.log_tool_call(
+ tool_name=tool_selection,
+ tool_input=tool_input,
+ tool_output=error_msg,
+ status="failed",
+ elapsed_ms=elapsed_ms,
+ error=error_msg,
+ )
+
+ self.logger.warning(f"Tool call failed ({tool_selection}): {e}")
+ return None
+
+ async def _call_rag_naive(
+ self, query: str, kb_name: str, output_dir: str | None
+ ) -> dict[str, Any]:
+ """Call RAG Naive"""
+ return await rag_search(query=query, kb_name=kb_name, mode="naive")
+
+ async def _call_rag_hybrid(
+ self, query: str, kb_name: str, output_dir: str | None
+ ) -> dict[str, Any]:
+ """Call RAG Hybrid"""
+ return await rag_search(query=query, kb_name=kb_name, mode="hybrid")
+
+ async def _call_web_search(self, query: str, output_dir: str | None) -> dict[str, Any]:
+ """Call Web Search"""
+ return web_search(query=query, output_dir=output_dir or "./cache", verbose=False)
+
+ async def _call_query_item(self, identifier: str, kb_name: str) -> dict[str, Any]:
+ """Call Query Item"""
+ return query_numbered_item(identifier=identifier, kb_name=kb_name)
diff --git a/src/agents/solve/analysis_loop/note_agent.py b/src/agents/solve/analysis_loop/note_agent.py
new file mode 100644
index 000000000..74a291f1a
--- /dev/null
+++ b/src/agents/solve/analysis_loop/note_agent.py
@@ -0,0 +1,178 @@
+#!/usr/bin/env python
+"""
+NoteAgent - Note taker
+Based on new knowledge, generates or updates notes, annotates covered pain points and missing points
+"""
+
+from pathlib import Path
+import sys
+from typing import Any
+
+# Add project root to path
+project_root = Path(__file__).parent.parent.parent.parent
+sys.path.insert(0, str(project_root))
+
+from ..base_agent import BaseAgent
+from ..memory import CitationMemory, InvestigateMemory, KnowledgeItem
+from ..utils import ParseError, validate_note_output
+from ..utils.json_utils import extract_json_from_text
+
+
+class NoteAgent(BaseAgent):
+ """Note taker Agent - Generates and updates notes"""
+
+ def __init__(self, config: dict[str, Any], api_key: str, base_url: str, token_tracker=None):
+ super().__init__(
+ config=config,
+ api_key=api_key,
+ base_url=base_url,
+ agent_name="note_agent",
+ use_prompt_loader=True,
+ token_tracker=token_tracker,
+ )
+
+ async def process(
+ self,
+ question: str,
+ memory: InvestigateMemory,
+ new_knowledge_ids: list[str],
+ citation_memory: CitationMemory | None = None,
+ output_dir: str | None = None,
+ verbose: bool = True,
+ ) -> dict[str, Any]:
+ """
+ Process note generation workflow (supports multiple knowledge_items in single round)
+
+ Args:
+ question: User question
+ memory: Investigation memory
+ new_knowledge_ids: List of cite_ids for new knowledge items
+ citation_memory: Citation memory
+ output_dir: Output directory
+ verbose: Whether to print detailed information
+
+ Returns:
+ dict: Aggregated note result
+ """
+ if isinstance(new_knowledge_ids, str): # Backward compatibility
+ target_ids = [new_knowledge_ids]
+ else:
+ target_ids = new_knowledge_ids or []
+
+ if not target_ids:
+ return {"success": False, "reason": "new_knowledge_ids is empty"}
+
+ system_prompt = self._build_system_prompt()
+ processed_details = []
+ failed_ids = []
+
+ for cite_id in target_ids:
+ knowledge_item = next((k for k in memory.knowledge_chain if k.cite_id == cite_id), None)
+ if not knowledge_item:
+ failed_ids.append({"cite_id": cite_id, "reason": "knowledge_item not found"})
+ continue
+
+ context = self._build_context(question, knowledge_item, memory)
+ user_prompt = self._build_user_prompt(context)
+
+ response = await self.call_llm(
+ user_prompt=user_prompt,
+ system_prompt=system_prompt,
+ verbose=verbose,
+ response_format={"type": "json_object"},
+ )
+
+ if verbose:
+ self.logger.debug(f"cite_id={cite_id} LLM output stats:")
+ self.logger.debug(f" - Total length: {len(response)} chars")
+ self.logger.debug(
+ f" - Last 100 chars: ...{response[-100:] if len(response) > 100 else response}"
+ )
+
+ try:
+ parsed_result = extract_json_from_text(response)
+ if not parsed_result or not isinstance(parsed_result, dict):
+ raise ParseError("LLM output is not a valid JSON object")
+ # citations is optional, default to empty list
+ if parsed_result.get("citations") is None:
+ parsed_result["citations"] = []
+ elif not isinstance(parsed_result.get("citations"), list):
+ raise ParseError("citations field must be a list")
+ validate_note_output(parsed_result)
+ if verbose:
+ summary_len = len(parsed_result.get("summary", ""))
+ print(f"📝 [NoteAgent] cite_id={cite_id} summary length: {summary_len}")
+ except ParseError as e:
+ failed_ids.append({"cite_id": cite_id, "reason": str(e)})
+ continue
+ except Exception as e:
+ failed_ids.append({"cite_id": cite_id, "reason": str(e)})
+ continue
+
+ citations = parsed_result.get("citations", [])
+ memory.update_knowledge_summary(cite_id=cite_id, summary=parsed_result["summary"])
+
+ if citation_memory:
+ sources = ", ".join(
+ citation.get("source", "") for citation in citations if citation.get("source")
+ )
+ metadata_block = {"extracted_sources": citations} if citations else None
+ try:
+ citation_memory.update_citation(
+ cite_id=cite_id,
+ content=parsed_result["summary"],
+ source=sources or None,
+ metadata=metadata_block,
+ stage="analysis",
+ )
+ citation_memory.save()
+ except ValueError:
+ if verbose:
+ print(f"⚠️ cite_id not found in CitationMemory: {cite_id}")
+
+ processed_details.append(
+ {
+ "cite_id": cite_id,
+ "summary": parsed_result["summary"],
+ "citations_count": len(citations),
+ }
+ )
+
+ if processed_details and output_dir:
+ memory.save()
+
+ return {
+ "success": len(failed_ids) == 0,
+ "processed_items": len(processed_details),
+ "details": processed_details,
+ "failed": failed_ids,
+ }
+
+ def _build_context(
+ self, question: str, knowledge_item: KnowledgeItem, memory: InvestigateMemory
+ ) -> dict[str, Any]:
+ """Build context (pass complete content)"""
+ return {
+ "question": question,
+ "tool_type": knowledge_item.tool_type,
+ "query": knowledge_item.query,
+ "raw_result": knowledge_item.raw_result, # Complete content
+ }
+
+ def _build_system_prompt(self) -> str:
+ """Build system prompt"""
+ prompt = self.get_prompt("system") if self.has_prompts() else None
+ if not prompt:
+ raise ValueError(
+ "NoteAgent missing system prompt, please configure system in prompts/zh/analysis_loop/note_agent.yaml."
+ )
+ return prompt
+
+ def _build_user_prompt(self, context: dict[str, Any]) -> str:
+ """Build user prompt (pass complete content)"""
+ template = self.get_prompt("user_template") if self.has_prompts() else None
+ if not template:
+ raise ValueError(
+ "NoteAgent missing user prompt template, please configure user_template in prompts/zh/analysis_loop/note_agent.yaml."
+ )
+ return template.format(**context)
diff --git a/src/agents/solve/base_agent.py b/src/agents/solve/base_agent.py
new file mode 100644
index 000000000..f8dc31a8c
--- /dev/null
+++ b/src/agents/solve/base_agent.py
@@ -0,0 +1,322 @@
+#!/usr/bin/env python
+"""
+BaseAgent - Base class for all Agents, providing unified initialization, configuration handling, and LLM calling interface
+"""
+
+from abc import ABC, abstractmethod
+import os
+from pathlib import Path
+import sys
+from typing import Any
+
+from lightrag.llm.openai import openai_complete_if_cache
+
+from .utils import PromptLoader
+from .utils.token_tracker import TokenTracker
+
+# Add project root to path for logs import
+_project_root = Path(__file__).parent.parent.parent.parent
+if str(_project_root) not in sys.path:
+ sys.path.insert(0, str(_project_root))
+from src.core.core import get_agent_params
+from src.core.logging import get_logger
+
+
+class BaseAgent(ABC):
+ """Base class for Agents, providing unified configuration and LLM calling interface"""
+
+ def __init__(
+ self,
+ config: dict[str, Any],
+ api_key: str,
+ base_url: str,
+ agent_name: str,
+ use_prompt_loader: bool = True, # Enable Prompt Loader by default
+ token_tracker: TokenTracker | None = None, # Token tracker
+ ):
+ """
+ Initialize base Agent
+
+ Args:
+ config: Complete configuration dictionary
+ api_key: API key
+ base_url: API endpoint
+ agent_name: Agent name, used to read dedicated configuration from config
+ use_prompt_loader: Whether to use PromptLoader to load Prompts (default True, for backward compatibility)
+ """
+ self.config = config
+ self.api_key = api_key
+ self.base_url = base_url
+ self.agent_name = agent_name
+
+ # Initialize logger, used uniformly by all subclasses
+ self.logger = get_logger(name=agent_name)
+
+ # Load agent parameters from unified config (agents.yaml)
+ self._agent_params = get_agent_params("solve")
+
+ # Get dedicated configuration for this Agent
+ self.agent_config = config.get("agents", {}).get(agent_name, {})
+
+ # Get general LLM configuration
+ self.llm_config = config.get("llm", {})
+
+ # Agent status (enabled by default)
+ self.enabled = True # All agents are enabled by default, no configuration needed
+
+ # Token tracker
+ self.token_tracker = token_tracker
+
+ # Prompt management
+ self.use_prompt_loader = use_prompt_loader
+ self.prompts = None
+
+ if use_prompt_loader:
+ # Initialize PromptLoader - read language setting from config
+ # Language config is now unified in config/main.yaml system.language
+ from src.core.core import parse_language
+
+ language = config.get("system", {}).get("language", "zh")
+ lang_code = parse_language(language)
+
+ # Prompts are in src/agents/solve/prompts/
+ prompts_dir = Path(__file__).parent / "prompts"
+ self.prompt_loader = PromptLoader(base_dir=prompts_dir, language=lang_code)
+
+ # Try to load Prompts for this Agent
+ try:
+ self.prompts = self.prompt_loader.load(agent_name)
+ # Successfully loaded, log it
+ if hasattr(self, "logger"):
+ self.logger.debug(f"[{agent_name}] Prompt configuration loaded from YAML")
+ except FileNotFoundError as e:
+ # If config file not found, log error but don't raise, allow Agent to use hardcoded Prompt
+ self.prompts = None
+ if hasattr(self, "logger"):
+ self.logger.warning(
+ f"[{agent_name}] Prompt config file not found: {e!s}, will use hardcoded Prompt"
+ )
+ except Exception as e:
+ # Other errors, log detailed error information
+ self.prompts = None
+ error_msg = f"[{agent_name}] Failed to load Prompt configuration: {e!s}, will use hardcoded Prompt"
+ if hasattr(self, "logger"):
+ self.logger.error(error_msg, exc_info=True)
+ else:
+ print(f"Error: {error_msg}")
+
+ def get_model(self, key: str = "model") -> str:
+ """
+ Get model name
+
+ Must be read from environment variable LLM_MODEL, raise error if not configured
+
+ Args:
+ key: Configuration key name (deprecated, kept for backward compatibility)
+
+ Returns:
+ Model name
+
+ Raises:
+ ValueError: If environment variable LLM_MODEL is not set
+ """
+ # Must read from environment variable
+ env_model = os.getenv("LLM_MODEL")
+ if not env_model:
+ raise ValueError(
+ f"Error: Environment variable LLM_MODEL is not set\n"
+ f"Please configure LLM_MODEL in your .env file, for example:\n"
+ f"LLM_MODEL=gpt-4o-mini\n"
+ f"Agent: {self.agent_name}"
+ )
+ return env_model
+
+ def get_temperature(self) -> float:
+ """
+ Get temperature parameter from unified config (agents.yaml)
+
+ Returns:
+ Temperature value from agents.yaml
+ """
+ return self._agent_params["temperature"]
+
+ def get_max_tokens(self) -> int:
+ """
+ Get maximum token count from unified config (agents.yaml)
+
+ Returns:
+ Maximum token count from agents.yaml
+ """
+ return self._agent_params["max_tokens"]
+
+ def get_max_retries(self) -> int:
+ """
+ Get maximum retry count
+
+ Returns:
+ Retry count
+ """
+ return self.agent_config.get("max_retries", self.llm_config.get("max_retries", 3))
+
+ async def call_llm(
+ self,
+ user_prompt: str,
+ system_prompt: str,
+ response_format: dict[str, str] | None = None,
+ temperature: float | None = None,
+ model: str | None = None,
+ verbose: bool = True,
+ stage: str | None = None,
+ ) -> str:
+ """
+ Unified interface for calling LLM
+
+ Args:
+ user_prompt: User prompt
+ system_prompt: System prompt
+ response_format: Response format (e.g., {"type": "json_object"})
+ temperature: Temperature parameter (optional, uses config by default)
+ model: Model name (optional, uses config by default)
+ verbose: Whether to print raw LLM output (default True)
+
+ Returns:
+ LLM response text
+ """
+ model = model or self.get_model()
+ temperature = temperature if temperature is not None else self.get_temperature()
+ max_tokens = self.get_max_tokens()
+
+ kwargs = {
+ "model": model,
+ "prompt": user_prompt,
+ "system_prompt": system_prompt,
+ "api_key": self.api_key,
+ "base_url": self.base_url,
+ "temperature": temperature,
+ }
+
+ if response_format:
+ kwargs["response_format"] = response_format
+
+ if max_tokens:
+ kwargs["max_tokens"] = max_tokens
+
+ stage_label = stage or self.agent_name
+ if hasattr(self.logger, "log_llm_input"):
+ self.logger.log_llm_input(
+ agent_name=self.agent_name,
+ stage=stage_label,
+ system_prompt=system_prompt,
+ user_prompt=user_prompt,
+ metadata={"model": model, "temperature": temperature, "max_tokens": max_tokens},
+ )
+
+ # Create TokenTracker wrapper (if token_tracker is provided)
+ token_tracker_wrapper = None
+ if self.token_tracker:
+
+ class TokenTrackerWrapper:
+ def __init__(self, tracker, agent_name, stage):
+ self.tracker = tracker
+ self.agent_name = agent_name
+ self.stage = stage
+ self.usage = None
+
+ def add_usage(self, token_counts):
+ self.usage = token_counts
+ self.tracker.add_usage(
+ agent_name=self.agent_name,
+ stage=self.stage,
+ model=model,
+ token_counts=token_counts,
+ )
+
+ token_tracker_wrapper = TokenTrackerWrapper(
+ self.token_tracker, self.agent_name, stage_label
+ )
+ kwargs["token_tracker"] = token_tracker_wrapper
+
+ response = await openai_complete_if_cache(**kwargs)
+
+ # If token_tracker exists but didn't get usage info from API, try using more precise method
+ if self.token_tracker and token_tracker_wrapper and not token_tracker_wrapper.usage:
+ # Check if advanced tracking is supported (using tiktoken or litellm)
+ if (
+ hasattr(self.token_tracker, "add_usage")
+ and len(self.token_tracker.add_usage.__code__.co_varnames) > 6
+ ):
+ # Advanced tracker: supports system_prompt, user_prompt, response_text parameters
+ self.token_tracker.add_usage(
+ agent_name=self.agent_name,
+ stage=stage_label,
+ model=model,
+ system_prompt=system_prompt,
+ user_prompt=user_prompt,
+ response_text=response,
+ )
+ else:
+ # Basic tracker: use estimation method
+ estimated_prompt_tokens = len(system_prompt.split()) + len(user_prompt.split())
+ estimated_completion_tokens = len(response.split())
+ self.token_tracker.add_usage(
+ agent_name=self.agent_name,
+ stage=stage_label,
+ model=model,
+ prompt_tokens=int(estimated_prompt_tokens * 1.3),
+ completion_tokens=int(estimated_completion_tokens * 1.3),
+ )
+
+ if hasattr(self.logger, "log_llm_output"):
+ self.logger.log_llm_output(
+ agent_name=self.agent_name,
+ stage=stage_label,
+ response=response,
+ metadata={"length": len(response)},
+ )
+
+ return response
+
+ def is_enabled(self) -> bool:
+ """
+ Check if Agent is enabled
+
+ Returns:
+ Whether enabled
+ """
+ return self.enabled
+
+ def get_prompt(self, prompt_type: str = "system") -> str | None:
+ """
+ Get Prompt (if using PromptLoader)
+
+ Args:
+ prompt_type: Prompt type ('system' | 'user_template' | 'output_format')
+
+ Returns:
+ Prompt content, returns None if not found
+ """
+ if self.prompts and prompt_type in self.prompts:
+ return self.prompts[prompt_type]
+ return None
+
+ def has_prompts(self) -> bool:
+ """
+ Check if Prompts have been loaded
+
+ Returns:
+ Whether loaded
+ """
+ return self.prompts is not None
+
+ @abstractmethod
+ async def process(self, *args, **kwargs) -> Any:
+ """
+ Main processing logic of Agent (must be implemented by subclasses)
+
+ Returns:
+ Processing result
+ """
+
+ def __repr__(self) -> str:
+ """String representation of Agent"""
+ return f"{self.__class__.__name__}(name={self.agent_name}, enabled={self.enabled})"
diff --git a/src/agents/solve/main_solver.py b/src/agents/solve/main_solver.py
new file mode 100644
index 000000000..9f06ea212
--- /dev/null
+++ b/src/agents/solve/main_solver.py
@@ -0,0 +1,778 @@
+#!/usr/bin/env python
+
+"""
+Main Solver - Problem-Solving System Controller
+
+Based on Dual-Loop Architecture: Analysis Loop + Solve Loop
+"""
+
+import asyncio
+from datetime import datetime
+import json
+import os
+from pathlib import Path
+import sys
+from typing import Any
+
+import yaml
+
+# Add parent directory to path
+project_root = Path(__file__).parent.parent.parent.parent
+sys.path.insert(0, str(project_root))
+
+from .analysis_loop import InvestigateAgent, NoteAgent
+
+# Dual-Loop Architecture
+from .memory import CitationMemory, InvestigateMemory, SolveChainStep, SolveMemory
+from .utils import ConfigValidator, PerformanceMonitor, SolveAgentLogger
+
+
+class MainSolver:
+ """Problem-Solving System Controller"""
+
+ def __init__(
+ self,
+ config_path: str | None = None,
+ api_key: str | None = None,
+ base_url: str | None = None,
+ kb_name: str = "ai_textbook",
+ output_base_dir: str | None = None,
+ ):
+ """
+ Initialize MainSolver
+
+ Args:
+ config_path: Config file path (default: config.yaml in current directory)
+ api_key: API key (if not provided, read from environment)
+ base_url: API URL (if not provided, read from environment)
+ kb_name: Knowledge base name
+ output_base_dir: Output base directory (optional, overrides config)
+ """
+ # Load config from config directory (main.yaml unified config)
+ if config_path is None:
+ project_root = Path(__file__).parent.parent.parent.parent
+ from src.core.core import load_config_with_main
+
+ # Load main.yaml (solve_config.yaml is optional and will be merged if exists)
+ full_config = load_config_with_main("main.yaml", project_root)
+
+ # Extract solve-specific config and build validator-compatible structure
+ solve_config = full_config.get("solve", {})
+ paths_config = full_config.get("paths", {})
+
+ # Build config structure expected by ConfigValidator
+ self.config = {
+ "system": {
+ "output_base_dir": paths_config.get("solve_output_dir", "./data/user/solve"),
+ "save_intermediate_results": solve_config.get(
+ "save_intermediate_results", True
+ ),
+ "language": full_config.get("system", {}).get("language", "en"),
+ },
+ "agents": solve_config.get("agents", {}),
+ "logging": full_config.get("logging", {}),
+ "tools": full_config.get("tools", {}),
+ "paths": paths_config,
+ # Keep solve-specific settings accessible
+ "solve": solve_config,
+ }
+ else:
+ # If custom config path provided, load it directly (for backward compatibility)
+ local_config = {}
+ if Path(config_path).exists():
+ try:
+ with open(config_path, encoding="utf-8") as f:
+ loaded = yaml.safe_load(f)
+ if loaded:
+ local_config = loaded
+ except Exception:
+ # Config loading warning will be handled by config_loader
+ pass
+ self.config = local_config if isinstance(local_config, dict) else {}
+
+ if self.config is None or not isinstance(self.config, dict):
+ self.config = {}
+
+ # Override output directory config
+ if output_base_dir:
+ if "system" not in self.config:
+ self.config["system"] = {}
+ self.config["system"]["output_base_dir"] = str(output_base_dir)
+
+ # Note: log_dir and performance_log_dir are now in paths section from main.yaml
+ # Only override if explicitly needed
+
+ # Validate config
+ validator = ConfigValidator()
+ is_valid, errors, warnings = validator.validate(self.config)
+ if not is_valid:
+ raise ValueError(f"Config validation failed: {errors}")
+
+ # API config
+ if api_key is None or base_url is None:
+ try:
+ from src.core.core import get_llm_config
+
+ llm_config = get_llm_config()
+ if api_key is None:
+ api_key = llm_config["api_key"]
+ if base_url is None:
+ base_url = llm_config["base_url"]
+ except ValueError as e:
+ raise ValueError(f"LLM config error: {e!s}")
+
+ if not api_key:
+ raise ValueError(
+ "API key not set. Provide api_key param or set LLM_BINDING_API_KEY in .env"
+ )
+
+ self.api_key = api_key
+ self.base_url = base_url
+ self.kb_name = kb_name
+
+ # Initialize logging system
+ logging_config = self.config.get("logging", {})
+ # Get log_dir from paths (user_log_dir from main.yaml) or logging config
+ log_dir = (
+ self.config.get("paths", {}).get("user_log_dir")
+ or self.config.get("paths", {}).get("log_dir")
+ or logging_config.get("log_dir")
+ )
+ self.logger = SolveAgentLogger(
+ name="Solver",
+ level=logging_config.get("level", "INFO"),
+ log_dir=log_dir,
+ console_output=logging_config.get("console_output", True),
+ file_output=logging_config.get("save_to_file", True),
+ )
+
+ # Attach display manager for TUI and frontend status updates
+ from .utils.display_manager import get_display_manager
+
+ self.logger.display_manager = get_display_manager()
+
+ # Initialize performance monitor (disabled by default - performance logging is deprecated)
+ monitoring_config = self.config.get("monitoring", {})
+ # Disable performance monitor by default to avoid creating performance directory
+ self.monitor = PerformanceMonitor(
+ enabled=False,
+ save_dir=None, # Disabled - performance logging is deprecated
+ )
+
+ # Initialize Token tracker
+ from .utils.token_tracker import TokenTracker
+
+ self.token_tracker = TokenTracker(prefer_tiktoken=True)
+
+ # Connect token_tracker to display_manager for real-time updates
+ if self.logger.display_manager:
+ self.token_tracker.set_on_usage_added_callback(
+ self.logger.display_manager.update_token_stats
+ )
+
+ self.logger.section("Dual-Loop Solver Initializing")
+ self.logger.info(f"Knowledge Base: {kb_name}")
+
+ # Initialize Agents
+ self._init_agents()
+
+ self.logger.success("Solver ready")
+
+ def _deep_merge(self, base: dict, update: dict) -> dict:
+ """Deep merge two dictionaries"""
+ if base is None:
+ base = {}
+ if update is None:
+ update = {}
+
+ result = base.copy() if base else {}
+ for key, value in update.items():
+ if key in result and isinstance(result[key], dict) and isinstance(value, dict):
+ result[key] = self._deep_merge(result[key], value)
+ else:
+ result[key] = value
+ return result
+
+ def _init_agents(self):
+ """Initialize all Agents - Dual-Loop Architecture"""
+ self.logger.progress("Initializing agents...")
+
+ # Analysis Loop Agents
+ self.investigate_agent = InvestigateAgent(
+ config=self.config,
+ api_key=self.api_key,
+ base_url=self.base_url,
+ token_tracker=self.token_tracker,
+ )
+ self.logger.info(" InvestigateAgent initialized")
+
+ self.note_agent = NoteAgent(
+ config=self.config,
+ api_key=self.api_key,
+ base_url=self.base_url,
+ token_tracker=self.token_tracker,
+ )
+ self.logger.info(" NoteAgent initialized")
+
+ # Solve Loop Agents (lazy initialization)
+ self.manager_agent = None
+ self.solve_agent = None
+ self.tool_agent = None
+ self.response_agent = None
+ self.precision_answer_agent = None
+ self.logger.info(" Solve Loop agents (lazy init)")
+
+ async def solve(self, question: str, verbose: bool = True) -> dict[str, Any]:
+ """
+ Main solving process - Dual-Loop Architecture
+
+ Args:
+ question: User question
+ verbose: Whether to print detailed info
+
+ Returns:
+ dict: Solving result
+ """
+ # Create output directory
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
+ output_base_dir = self.config.get("system", {}).get("output_base_dir", "./user/solve")
+ output_dir = os.path.join(output_base_dir, f"solve_{timestamp}")
+ os.makedirs(output_dir, exist_ok=True)
+
+ # Add task log file handler
+ task_log_file = os.path.join(output_dir, "task.log")
+ self.logger.add_task_log_handler(task_log_file)
+
+ self.logger.section("Problem Solving Started")
+ self.logger.info(f"Question: {question[:100]}{'...' if len(question) > 100 else ''}")
+ self.logger.info(f"Output: {output_dir}")
+
+ try:
+ # Execute dual-loop pipeline
+ result = await self._run_dual_loop_pipeline(question, output_dir)
+
+ # Add metadata
+ result["metadata"] = {
+ "mode": "dual_loop",
+ "timestamp": timestamp,
+ "output_dir": output_dir,
+ }
+
+ # Save performance report
+ if self.config.get("monitoring", {}).get("enabled", True):
+ perf_report = self.monitor.generate_report()
+ perf_file = os.path.join(output_dir, "performance_report.json")
+ with open(perf_file, "w", encoding="utf-8") as f:
+ json.dump(perf_report, f, ensure_ascii=False, indent=2)
+ self.logger.debug(f"Performance report saved: {perf_file}")
+
+ # Output cost report
+ if self.token_tracker:
+ cost_summary = self.token_tracker.get_summary()
+ if cost_summary["total_calls"] > 0:
+ cost_text = self.token_tracker.format_summary()
+ self.logger.info(f"\n{cost_text}")
+
+ cost_file = os.path.join(output_dir, "cost_report.json")
+ self.token_tracker.save(cost_file)
+ self.logger.debug(f"Cost report saved: {cost_file}")
+
+ self.token_tracker.reset()
+
+ self.logger.success("Problem solving completed")
+ self.logger.remove_task_log_handlers()
+
+ return result
+
+ except Exception as e:
+ self.logger.error(f"Solving failed: {e!s}")
+ import traceback
+
+ self.logger.error(traceback.format_exc())
+ self.logger.remove_task_log_handlers()
+ raise
+
+ finally:
+ if hasattr(self, "logger"):
+ self.logger.shutdown()
+
+ async def _run_dual_loop_pipeline(self, question: str, output_dir: str) -> dict[str, Any]:
+ """
+ Dual-Loop Pipeline:
+ 1) Analysis Loop: Investigate → Note
+ 2) Solve Loop: Plan → Manager → Solve → Check → Format
+ """
+
+ self.logger.info("Pipeline: Analysis Loop → Solve Loop")
+
+ # ========== Analysis Loop ==========
+ self.logger.stage("Analysis Loop", "start", "Understanding the question")
+
+ investigate_memory = InvestigateMemory.load_or_create(
+ output_dir=output_dir, user_question=question
+ )
+
+ citation_memory = CitationMemory.load_or_create(output_dir=output_dir)
+
+ # Read max_iterations from solve.agents.investigate_agent config (authoritative source)
+ agent_config = self.config.get("solve", {}).get("agents", {}).get("investigate_agent", {})
+ max_analysis_iterations = agent_config.get("max_iterations", 5)
+ self.logger.log_stage_progress(
+ "AnalysisLoop", "start", f"max_iterations={max_analysis_iterations}"
+ )
+
+ analysis_completed = False
+
+ # Analysis Loop iterations
+ for i in range(max_analysis_iterations):
+ self.logger.log_stage_progress("AnalysisLoop", "running", f"round={i + 1}")
+
+ # 1. Investigate: Generate queries and call tools
+ with self.monitor.track(f"analysis_investigate_{i + 1}"):
+ investigate_result = await self.investigate_agent.process(
+ question=question,
+ memory=investigate_memory,
+ citation_memory=citation_memory,
+ kb_name=self.kb_name,
+ output_dir=output_dir,
+ verbose=False,
+ )
+
+ knowledge_ids: list[str] = investigate_result.get("knowledge_item_ids", [])
+ should_stop = investigate_result.get("should_stop", False)
+ reasoning = investigate_result.get("reasoning", "")
+ actions = investigate_result.get("actions", [])
+
+ self.logger.debug(f" [Investigate] Reasoning: {reasoning or 'N/A'}")
+
+ if hasattr(self, "_send_progress_update"):
+ queries = [action.get("query", "") for action in actions if action.get("query")]
+ self._send_progress_update("investigate", {"round": i + 1, "queries": queries})
+
+ if actions:
+ for action in actions:
+ tool_label = action["tool_type"]
+ query = action.get("query") or ""
+ cite_id = action.get("cite_id")
+ suffix = f" → cite_id={cite_id}" if cite_id else ""
+ self.logger.info(f" Tool: {tool_label} | {query[:50]}{suffix}")
+ else:
+ self.logger.debug(" No queries generated this round")
+
+ # 2. Note: Generate notes (if new knowledge exists)
+ if knowledge_ids:
+ self.logger.log_stage_progress("Note", "start")
+
+ with self.monitor.track(f"analysis_note_{i + 1}"):
+ note_result = await self.note_agent.process(
+ question=question,
+ memory=investigate_memory,
+ new_knowledge_ids=knowledge_ids,
+ citation_memory=citation_memory,
+ output_dir=output_dir,
+ verbose=False,
+ )
+
+ if note_result.get("success"):
+ processed = note_result.get("processed_items", 0)
+ self.logger.info(f" Note: {processed} items processed")
+ self.logger.log_stage_progress("Note", "complete")
+ else:
+ self.logger.warning(f" Note failed: {note_result.get('reason', 'unknown')}")
+ self.logger.log_stage_progress("Note", "error")
+
+ # Update Token stats
+ self.logger.update_token_stats(self.token_tracker.get_summary())
+
+ # 3. Check stop condition
+ if should_stop:
+ analysis_completed = True
+ self.logger.log_stage_progress(
+ "AnalysisLoop",
+ "complete",
+ f"rounds={i + 1}, knowledge={len(investigate_memory.knowledge_chain)}",
+ )
+ break
+
+ if not analysis_completed:
+ self.logger.log_stage_progress(
+ "AnalysisLoop",
+ "warning",
+ f"max_iterations({max_analysis_iterations}) reached, knowledge={len(investigate_memory.knowledge_chain)}",
+ )
+
+ # Update investigate_memory metadata
+ investigate_memory.metadata["total_iterations"] = i + 1
+ investigate_memory.metadata["total_knowledge_items"] = len(
+ investigate_memory.knowledge_chain
+ )
+ investigate_memory.reflections.remaining_questions = []
+
+ if analysis_completed:
+ investigate_memory.metadata["coverage_rate"] = 1.0
+ investigate_memory.metadata["avg_confidence"] = 0.9
+ else:
+ coverage = min(
+ 1.0, len(investigate_memory.knowledge_chain) / max(1, max_analysis_iterations)
+ )
+ investigate_memory.metadata["coverage_rate"] = coverage
+ investigate_memory.metadata["avg_confidence"] = 0.6
+
+ investigate_memory.save()
+
+ # ========== Solve Loop ==========
+ self.logger.stage("Solve Loop", "start", "Generating solution")
+
+ from .memory import SolveMemory
+
+ solve_memory = SolveMemory.load_or_create(output_dir=output_dir, user_question=question)
+
+ # Initialize Solve Loop Agents (if not yet initialized)
+ if self.manager_agent is None:
+ from .solve_loop import (
+ ManagerAgent,
+ PrecisionAnswerAgent,
+ ResponseAgent,
+ SolveAgent,
+ ToolAgent,
+ )
+
+ self.logger.progress("Initializing Solve Loop agents...")
+ self.manager_agent = ManagerAgent(
+ self.config, self.api_key, self.base_url, token_tracker=self.token_tracker
+ )
+ self.solve_agent = SolveAgent(
+ self.config, self.api_key, self.base_url, token_tracker=self.token_tracker
+ )
+ self.tool_agent = ToolAgent(
+ self.config, self.api_key, self.base_url, token_tracker=self.token_tracker
+ )
+ self.response_agent = ResponseAgent(
+ self.config, self.api_key, self.base_url, token_tracker=self.token_tracker
+ )
+
+ precision_enabled = (
+ self.config.get("agents", {})
+ .get("precision_answer_agent", {})
+ .get("enabled", False)
+ )
+ if precision_enabled:
+ self.precision_answer_agent = PrecisionAnswerAgent(
+ self.config, self.api_key, self.base_url, token_tracker=self.token_tracker
+ )
+
+ # 1. Plan: Generate solving plan
+ self.logger.info("Plan: Generating solution strategy...")
+
+ plan_result = None
+ for attempt in range(2):
+ try:
+ with self.monitor.track(f"solve_plan_attempt_{attempt + 1}"):
+ plan_result = await self.manager_agent.process(
+ question=question,
+ investigate_memory=investigate_memory,
+ solve_memory=solve_memory,
+ verbose=(attempt > 0),
+ )
+ num_steps = plan_result.get("num_steps") or plan_result.get("steps_count", 0)
+ self.logger.log_stage_progress("Plan", "complete", f"steps={num_steps}")
+ self.logger.update_token_stats(self.token_tracker.get_summary())
+ break
+ except Exception as e:
+ if attempt == 0:
+ self.logger.error(f"ManagerAgent attempt {attempt + 1} failed: {e!s}")
+ self.logger.warning("Retrying plan generation...")
+ solve_memory = SolveMemory.load_or_create(
+ output_dir=output_dir, user_question=question
+ )
+ else:
+ self.logger.error(f"ManagerAgent attempt {attempt + 1} also failed")
+ raise ValueError(f"ManagerAgent failed after retry: {e!s}")
+
+ if plan_result is None:
+ raise ValueError("ManagerAgent failed to generate plan")
+
+ # 2. Solve Loop - Execute steps
+ self.logger.info("Solve: Executing solution steps...")
+ max_correction_iterations = self.config.get("system", {}).get(
+ "max_solve_correction_iterations", 3
+ )
+ total_planned_steps = len(solve_memory.solve_chains)
+ self.logger.log_stage_progress(
+ "SolveLoop",
+ "start",
+ f"planned_steps={total_planned_steps}, max_corrections={max_correction_iterations}",
+ )
+
+ for step_index, step in enumerate(solve_memory.solve_chains, 1):
+ if step.status in ("waiting_response", "done"):
+ continue
+
+ self.logger.info(f" Step {step_index}: {step.step_id}")
+ self.logger.debug(f" Target: {step.step_target[:80]}")
+
+ if hasattr(self, "_send_progress_update"):
+ self._send_progress_update(
+ "solve",
+ {
+ "step_index": step_index,
+ "step_id": step.step_id,
+ "step_target": step.step_target,
+ },
+ )
+
+ self.logger.log_stage_progress("SolveLoop", "running", f"step={step.step_id}")
+
+ if self._has_pending_tool_calls(step):
+ await self._execute_tool_calls(step, solve_memory, citation_memory, output_dir)
+
+ iteration = 0
+ while iteration < max_correction_iterations:
+ iteration += 1
+ current_step = solve_memory.get_step(step.step_id) or step
+
+ with self.monitor.track(f"solve_execute_{step.step_id}_iter_{iteration}"):
+ solve_result = await self.solve_agent.process(
+ question=question,
+ current_step=current_step,
+ solve_memory=solve_memory,
+ investigate_memory=investigate_memory,
+ citation_memory=citation_memory,
+ kb_name=self.kb_name,
+ output_dir=output_dir,
+ verbose=False,
+ )
+
+ if solve_result.get("raw_llm_response"):
+ self.logger.log_stage_progress(
+ "SolveLoop", "running", f"step={step.step_id}, iteration={iteration}"
+ )
+
+ if solve_result.get("requested_calls"):
+ await self._execute_tool_calls(
+ current_step, solve_memory, citation_memory, output_dir
+ )
+
+ self.logger.update_token_stats(self.token_tracker.get_summary())
+
+ if solve_result.get("finish_requested"):
+ current_step = solve_memory.get_step(step.step_id) or step
+ if self._has_pending_tool_calls(current_step):
+ self.logger.debug(" Finish triggered but tools pending, continuing...")
+ continue
+ solve_memory.mark_step_waiting_response(current_step.step_id)
+ solve_memory.save()
+ self.logger.log_stage_progress(
+ "SolveLoop", "complete", f"step={current_step.step_id} ready for response"
+ )
+ break
+ else:
+ self.logger.warning(f" Step {step.step_id} max iterations reached")
+ solve_memory.mark_step_waiting_response(step.step_id)
+ solve_memory.save()
+
+ pending_steps = [
+ s.step_id
+ for s in solve_memory.solve_chains
+ if s.status not in ("waiting_response", "done")
+ ]
+ if pending_steps:
+ self.logger.warning(f"Steps not ready for response: {', '.join(pending_steps)}")
+
+ self.logger.log_stage_progress(
+ "SolveLoop", "complete", f"steps_processed={total_planned_steps - len(pending_steps)}"
+ )
+
+ # 3. Response: Generate responses for each step
+ self.logger.info("Response: Generating step responses...")
+ self.logger.log_stage_progress("ResponseLoop", "start", "Generating responses")
+
+ accumulated_response = ""
+ for step in solve_memory.solve_chains:
+ if step.status == "done" and step.step_response:
+ accumulated_response += step.step_response + "\n\n"
+
+ for step in solve_memory.solve_chains:
+ if step.status != "waiting_response":
+ continue
+
+ original_step_index = next(
+ (
+ i + 1
+ for i, s in enumerate(solve_memory.solve_chains)
+ if s.step_id == step.step_id
+ ),
+ 0,
+ )
+
+ if hasattr(self, "_send_progress_update"):
+ self._send_progress_update(
+ "response",
+ {
+ "step_index": original_step_index,
+ "step_id": step.step_id,
+ "step_target": step.step_target,
+ },
+ )
+
+ with self.monitor.track(f"solve_response_{step.step_id}"):
+ response_result = await self.response_agent.process(
+ question=question,
+ step=step,
+ solve_memory=solve_memory,
+ investigate_memory=investigate_memory,
+ citation_memory=citation_memory,
+ output_dir=output_dir,
+ verbose=False,
+ accumulated_response=accumulated_response,
+ )
+
+ step_response = response_result.get("step_response", "")
+ if step_response:
+ accumulated_response += step_response + "\n\n"
+
+ if response_result.get("raw_response"):
+ self.logger.log_stage_progress(
+ "ResponseLoop", "running", f"step={step.step_id} response generated"
+ )
+
+ self.logger.update_token_stats(self.token_tracker.get_summary())
+
+ self.logger.log_stage_progress("ResponseLoop", "complete", "All responses generated")
+
+ # 4. Finalize: Compile final answer
+ self.logger.info("Finalize: Compiling final answer...")
+ self.logger.log_stage_progress("Finalize", "start", "Compiling steps")
+
+ actual_total_steps = len(solve_memory.solve_chains)
+ completed_step_objs = [
+ step
+ for step in solve_memory.solve_chains
+ if step.status == "done" and step.step_response
+ ]
+ completed_steps = len(completed_step_objs)
+
+ solve_memory.metadata["total_steps"] = actual_total_steps
+ solve_memory.metadata["completed_steps"] = completed_steps
+ solve_memory.save()
+ self.logger.info(f" Stats: {completed_steps}/{actual_total_steps} steps completed")
+
+ used_cite_ids = []
+ for step in completed_step_objs:
+ used_cite_ids.extend(step.used_citations)
+ used_cite_ids = list(dict.fromkeys(used_cite_ids))
+
+ step_responses = [step.step_response for step in completed_step_objs]
+ final_answer = "\n\n".join(step_responses)
+
+ # Get language setting from config (unified in config/main.yaml system.language)
+ from src.core.core import parse_language
+
+ language = self.config.get("system", {}).get("language", "zh")
+ lang_code = parse_language(language)
+
+ # Check if citations are enabled
+ enable_citations = self.config.get("system", {}).get("enable_citations", True)
+
+ citations_section = ""
+ if enable_citations and citation_memory:
+ citations_section = citation_memory.format_citations_markdown(
+ used_cite_ids=used_cite_ids, language=lang_code
+ )
+ if citations_section:
+ final_answer = f"{final_answer}\n\n---\n\n{citations_section}"
+
+ format_result = {
+ "final_answer": final_answer.strip(),
+ "citations": used_cite_ids,
+ "metadata": {
+ "refined_steps": len(completed_step_objs),
+ "total_steps": actual_total_steps,
+ "citations_section": bool(citations_section),
+ },
+ }
+
+ self.logger.info(f" Final answer: {len(format_result['final_answer'])} chars")
+ self.logger.info(f" Citations: {len(format_result['citations'])}")
+
+ # 5. Precision Answer (if enabled)
+ precision_answer_enabled = (
+ self.config.get("agents", {}).get("precision_answer_agent", {}).get("enabled", False)
+ )
+ final_answer_content = format_result["final_answer"]
+
+ if precision_answer_enabled and self.precision_answer_agent:
+ self.logger.info("PrecisionAnswer: Generating concise answer...")
+ with self.monitor.track("precision_answer"):
+ precision_result = await self.precision_answer_agent.process(
+ question=question, detailed_answer=format_result["final_answer"], verbose=False
+ )
+ if precision_result.get("needs_precision"):
+ precision_answer = precision_result.get("precision_answer", "")
+ self.logger.info(f" Precision answer: {len(precision_answer)} chars")
+ final_answer_content = f"## Concise Answer\n\n{precision_answer}\n\n---\n\n## Detailed Answer\n\n{format_result['final_answer']}"
+ else:
+ self.logger.debug(" No precision answer needed")
+
+ # Save final answer
+ final_answer_file = Path(output_dir) / "final_answer.md"
+ with open(final_answer_file, "w", encoding="utf-8") as f:
+ f.write(final_answer_content)
+
+ self.logger.success(f"Final answer saved: {final_answer_file}")
+ self.logger.log_stage_progress("Format", "complete", f"output={final_answer_file}")
+
+ return {
+ "question": question,
+ "output_dir": output_dir,
+ "final_answer": final_answer_content,
+ "output_md": str(final_answer_file),
+ "output_json": str(Path(output_dir) / "solve_chain.json"),
+ "formatted_solution": final_answer_content,
+ "citations": format_result["citations"],
+ "pipeline": "reworked",
+ "total_steps": solve_memory.metadata["total_steps"],
+ "analysis_iterations": investigate_memory.metadata.get("total_iterations", 0),
+ "solve_steps": solve_memory.metadata["completed_steps"],
+ "metadata": {
+ "coverage_rate": investigate_memory.metadata.get("coverage_rate", 0.0),
+ "avg_confidence": investigate_memory.metadata.get("avg_confidence", 0.0),
+ "total_steps": solve_memory.metadata["total_steps"],
+ },
+ }
+
+ async def _execute_tool_calls(
+ self,
+ step: SolveChainStep,
+ solve_memory: SolveMemory,
+ citation_memory: CitationMemory,
+ output_dir: str | None,
+ ) -> dict[str, Any]:
+ tool_result = await self.tool_agent.process(
+ step=step,
+ solve_memory=solve_memory,
+ citation_memory=citation_memory,
+ kb_name=self.kb_name,
+ output_dir=output_dir,
+ verbose=False,
+ )
+ return tool_result
+
+ @staticmethod
+ def _has_pending_tool_calls(step: SolveChainStep) -> bool:
+ return any(call.status in {"pending", "running"} for call in step.tool_calls)
+
+
+if __name__ == "__main__":
+ import asyncio
+
+ from dotenv import load_dotenv
+
+ load_dotenv()
+
+ async def test():
+ solver = MainSolver(kb_name="ai_textbook")
+ result = await solver.solve(question="What is linear convolution?", verbose=True)
+ print(f"Output file: {result['output_md']}")
+
+ asyncio.run(test())
diff --git a/src/agents/solve/memory/__init__.py b/src/agents/solve/memory/__init__.py
new file mode 100644
index 000000000..31e31f5d6
--- /dev/null
+++ b/src/agents/solve/memory/__init__.py
@@ -0,0 +1,34 @@
+#!/usr/bin/env python
+"""
+Memory System - Memory file system
+Provides implementations of InvestigateMemory and SolveMemory
+"""
+
+from .citation_memory import (
+ CitationItem,
+ CitationMemory,
+)
+from .investigate_memory import (
+ InvestigateMemory,
+ KnowledgeItem,
+ Reflections,
+)
+from .solve_memory import (
+ SolveChainStep,
+ SolveMemory,
+ ToolCallRecord,
+)
+
+__all__ = [
+ # Investigate Memory
+ "InvestigateMemory",
+ "KnowledgeItem",
+ "Reflections",
+ # Solve Memory
+ "SolveMemory",
+ "SolveChainStep",
+ "ToolCallRecord",
+ # Citation Memory
+ "CitationMemory",
+ "CitationItem",
+]
diff --git a/src/agents/solve/memory/citation_memory.py b/src/agents/solve/memory/citation_memory.py
new file mode 100644
index 000000000..3ffe2d3dd
--- /dev/null
+++ b/src/agents/solve/memory/citation_memory.py
@@ -0,0 +1,353 @@
+#!/usr/bin/env python
+"""
+CitationMemory - Global citation management system
+Unified management of citation information generated by all tool calls
+"""
+
+from dataclasses import asdict, dataclass, field
+from datetime import datetime
+import json
+from pathlib import Path
+from typing import Any
+
+
+@dataclass
+class CitationItem:
+ """Citation item"""
+
+ cite_id: str # Citation number, e.g., "[rag-1]"
+ tool_type: str # Tool type: rag_naive | rag_hybrid | web_search | query_item | code_execution
+ query: str # Query content
+ raw_result: str = "" # Raw tool return content (complete)
+ source: str = "" # Source information (if any)
+ content: str = "" # Citation content summary (usually summary)
+ stage: str = "solve" # Stage: analysis | solve
+ step_id: str | None = None # Belonging step (applicable to Solve stage)
+ metadata: dict[str, Any] = field(default_factory=dict) # Additional metadata
+ created_at: str = field(default_factory=lambda: datetime.now().isoformat())
+ updated_at: str = field(default_factory=lambda: datetime.now().isoformat())
+
+ def to_dict(self) -> dict[str, Any]:
+ return asdict(self)
+
+ @classmethod
+ def from_dict(cls, data: dict[str, Any]) -> "CitationItem":
+ # Compatible with old versions without stage/step_id/metadata fields
+ if "stage" not in data:
+ data["stage"] = "solve"
+ if "metadata" not in data:
+ data["metadata"] = {}
+ if "updated_at" not in data:
+ data["updated_at"] = data.get("created_at", datetime.now().isoformat())
+ return cls(**data)
+
+
+class CitationMemory:
+ """Global citation management system"""
+
+ def __init__(self, output_dir: str | None = None):
+ self.output_dir = output_dir
+ self.version = "1.1"
+ self.created_at = datetime.now().isoformat()
+ self.updated_at = datetime.now().isoformat()
+
+ # Core data: citation list
+ self.citations: list[CitationItem] = []
+
+ # Citation counter (incremented by tool prefix)
+ self.tool_counters: dict[str, int] = {}
+
+ # File path
+ if output_dir:
+ self.file_path = Path(output_dir) / "citation_memory.json"
+ else:
+ self.file_path = None
+
+ @classmethod
+ def load_or_create(cls, output_dir: str) -> "CitationMemory":
+ """Load existing citation memory or create new memory"""
+ file_path = Path(output_dir) / "citation_memory.json"
+
+ if file_path.exists():
+ # Load existing memory
+ with open(file_path, encoding="utf-8") as f:
+ data = json.load(f)
+
+ memory = cls(output_dir=output_dir)
+ memory.version = data.get("version", "1.1")
+ memory.created_at = data.get("created_at", memory.created_at)
+ memory.updated_at = data.get("updated_at", memory.updated_at)
+
+ # Load citation list
+ citations_data = data.get("citations", [])
+ memory.citations = [CitationItem.from_dict(item) for item in citations_data]
+
+ # Restore counters
+ memory.tool_counters = data.get("tool_counters", {})
+ if not memory.tool_counters:
+ # Compatible with old versions: guess from existing cite_id
+ for citation in memory.citations:
+ prefix = memory._get_tool_prefix(citation.tool_type)
+ number = memory._extract_counter_from_cite_id(citation.cite_id, prefix)
+ if number is not None:
+ memory.tool_counters[prefix] = max(
+ memory.tool_counters.get(prefix, 0), number
+ )
+
+ return memory
+ # Create new memory
+ return cls(output_dir=output_dir)
+
+ def add_citation(
+ self,
+ tool_type: str,
+ query: str,
+ raw_result: str = "",
+ source: str = "",
+ content: str = "",
+ stage: str = "solve",
+ step_id: str | None = None,
+ metadata: dict[str, Any] | None = None,
+ cite_id: str | None = None,
+ ) -> str:
+ """
+ Add new citation entry
+
+ Args:
+ tool_type: Tool type
+ query: Query content
+ raw_result: Raw tool return content
+ source: Source information
+ content: Citation content summary
+
+ Returns:
+ str: Newly generated or reused cite_id (e.g., "[rag-1]")
+ """
+ # If cite_id is provided and already exists, return directly
+ if cite_id and self.get_citation(cite_id):
+ return cite_id
+
+ # Generate new cite_id
+ if not cite_id:
+ cite_id = self._generate_cite_id(tool_type)
+
+ citation = CitationItem(
+ cite_id=cite_id,
+ tool_type=tool_type,
+ query=query,
+ raw_result=raw_result,
+ source=source,
+ content=content,
+ stage=stage,
+ step_id=step_id,
+ metadata=metadata or {},
+ )
+
+ self.citations.append(citation)
+ self.updated_at = datetime.now().isoformat()
+
+ return cite_id
+
+ def get_citation(self, cite_id: str) -> CitationItem | None:
+ """Get citation entry by cite_id"""
+ for citation in self.citations:
+ if citation.cite_id == cite_id:
+ return citation
+ return None
+
+ def get_all_citations(self) -> list[CitationItem]:
+ """Get all citation entries"""
+ return self.citations
+
+ def get_citations_by_tool_type(self, tool_type: str) -> list[CitationItem]:
+ """Get citation entries by tool type"""
+ return [c for c in self.citations if c.tool_type == tool_type]
+
+ def update_citation(
+ self,
+ cite_id: str,
+ raw_result: str | None = None,
+ source: str | None = None,
+ content: str | None = None,
+ metadata: dict[str, Any] | None = None,
+ stage: str | None = None,
+ step_id: str | None = None,
+ ):
+ """Update citation entry information"""
+ for citation in self.citations:
+ if citation.cite_id == cite_id:
+ if raw_result is not None:
+ citation.raw_result = raw_result
+ if source is not None:
+ citation.source = source
+ if content is not None:
+ citation.content = content
+ if metadata:
+ citation.metadata.update(metadata)
+ if stage:
+ citation.stage = stage
+ if step_id:
+ citation.step_id = step_id
+ citation.updated_at = datetime.now().isoformat()
+ self.updated_at = datetime.now().isoformat()
+ return
+ raise ValueError(f"cite_id not found: {cite_id}")
+
+ def save(self):
+ """Save to JSON file"""
+ if not self.file_path:
+ raise ValueError("output_dir not set, cannot save")
+
+ # Ensure directory exists
+ self.file_path.parent.mkdir(parents=True, exist_ok=True)
+
+ self.updated_at = datetime.now().isoformat()
+
+ # Convert to dictionary
+ data = self.to_dict()
+
+ # Save to file
+ with open(self.file_path, "w", encoding="utf-8") as f:
+ json.dump(data, f, ensure_ascii=False, indent=2)
+
+ def to_dict(self) -> dict[str, Any]:
+ """Convert to dictionary"""
+ return {
+ "version": self.version,
+ "created_at": self.created_at,
+ "updated_at": self.updated_at,
+ "citations": [item.to_dict() for item in self.citations],
+ "tool_counters": self.tool_counters,
+ }
+
+ def format_citations_markdown(
+ self, used_cite_ids: list[str] | None = None, language: str = "zh"
+ ) -> str:
+ """
+ Format citation list as Markdown
+
+ Args:
+ used_cite_ids: Optional, specify citation ID list to format. If provided, only format these citations; if not provided, format all citations.
+ language: Language code, 'zh' for Chinese, 'en' for English, default 'zh'
+
+ Returns:
+ str: Markdown-formatted citation list
+ """
+ # Set text based on language
+ if language == "en":
+ no_citations_text = "(No citations)"
+ citation_title = "## Citations\n"
+ stage_label = "Stage"
+ source_label = "Source"
+ query_content_label = " - Query Content:"
+ citation_content_label = " - Citation Content:"
+ else:
+ no_citations_text = "(No citations)"
+ citation_title = "## Citations\n"
+ stage_label = "Stage"
+ source_label = "Source"
+ query_content_label = " - Query Content:"
+ citation_content_label = " - Citation Content:"
+
+ if not self.citations:
+ return no_citations_text
+
+ # If used_cite_ids is specified, only format these citations
+ citations_to_format = self.citations
+ if used_cite_ids is not None:
+ cite_id_set = set(used_cite_ids)
+ citations_to_format = [c for c in self.citations if c.cite_id in cite_id_set]
+ if not citations_to_format:
+ return no_citations_text
+
+ lines = [citation_title]
+
+ for citation in citations_to_format:
+ tool_type_display = {
+ "rag_naive": "RAG (Naive)",
+ "rag_hybrid": "RAG (Hybrid)",
+ "web_search": "Web Search",
+ "query_item": "Query Item",
+ "code_execution": "Code Execution",
+ }.get(citation.tool_type, citation.tool_type)
+
+ line = f"- **{citation.cite_id}** [{tool_type_display}] {stage_label}: {citation.stage}"
+ if citation.source:
+ line += f" | {source_label}: {citation.source}"
+ lines.append(line)
+
+ if citation.query:
+ query_block = self._format_block(
+ citation.query,
+ language="python" if citation.tool_type == "code_execution" else None,
+ )
+ lines.append(query_content_label)
+ lines.append(self._indent_block(query_block, " "))
+
+ if citation.content:
+ content_block = self._format_block(
+ citation.content,
+ language="python" if citation.tool_type == "code_execution" else None,
+ force_block=True,
+ )
+ lines.append(citation_content_label)
+ lines.append(self._indent_block(content_block, " "))
+ elif citation.raw_result:
+ raw_block = self._format_block(
+ citation.raw_result,
+ language="python" if citation.tool_type == "code_execution" else None,
+ force_block=True,
+ )
+ lines.append(citation_content_label)
+ lines.append(self._indent_block(raw_block, " "))
+
+ return "\n".join(lines)
+
+ # ------------------------------------------------------------------
+ # Internal utility methods
+ # ------------------------------------------------------------------
+ def _get_tool_prefix(self, tool_type: str) -> str:
+ """Generate unified prefix based on tool type"""
+ prefix_map = {
+ "rag_naive": "rag",
+ "rag_hybrid": "rag",
+ "web_search": "web",
+ "code_execution": "code",
+ "query_item": "query",
+ }
+ normalized = prefix_map.get(tool_type, tool_type.replace("_", "-"))
+ return normalized.lower()
+
+ def _generate_cite_id(self, tool_type: str) -> str:
+ prefix = self._get_tool_prefix(tool_type)
+ current = self.tool_counters.get(prefix, 0) + 1
+ self.tool_counters[prefix] = current
+ return f"[{prefix}-{current}]"
+
+ @staticmethod
+ def _format_block(text: str, language: str | None = None, force_block: bool = False) -> str:
+ if not text:
+ return ""
+ clean = text.strip()
+ clean = clean.strip("`")
+ if force_block or "\n" in clean or len(clean) > 80:
+ lang = language or ""
+ return f"```{lang}\n{clean}\n```"
+ return f"`{clean}`"
+
+ @staticmethod
+ def _indent_block(block: str, prefix: str) -> str:
+ if not block:
+ return ""
+ return "\n".join(prefix + line if line else prefix for line in block.splitlines())
+
+ @staticmethod
+ def _extract_counter_from_cite_id(cite_id: str, prefix: str) -> int | None:
+ """Extract counter value from cite_id"""
+ try:
+ inner = cite_id.strip("[]")
+ if inner.startswith(f"{prefix}-"):
+ return int(inner.split("-", maxsplit=1)[1])
+ except (ValueError, IndexError):
+ return None
+ return None
diff --git a/src/agents/solve/memory/investigate_memory.py b/src/agents/solve/memory/investigate_memory.py
new file mode 100644
index 000000000..6284a02be
--- /dev/null
+++ b/src/agents/solve/memory/investigate_memory.py
@@ -0,0 +1,226 @@
+#!/usr/bin/env python
+"""
+InvestigateMemory - Analysis loop memory file system (Refactored: uses unified cite_id)
+"""
+
+from dataclasses import asdict, dataclass, field
+from datetime import datetime
+import json
+from pathlib import Path
+from typing import Any
+
+
+@dataclass
+class KnowledgeItem:
+ """Knowledge item (Refactored: uses cite_id)"""
+
+ cite_id: str # Citation ID, corresponds to cite_id in CitationMemory
+ tool_type: str # rag_naive | rag_hybrid | web_search | query_item
+ query: str
+ raw_result: str # Raw tool return content (complete)
+ summary: str = "" # Summary generated by NoteAgent
+ created_at: str = field(default_factory=lambda: datetime.now().isoformat())
+ updated_at: str = field(default_factory=lambda: datetime.now().isoformat())
+
+ def to_dict(self) -> dict[str, Any]:
+ return asdict(self)
+
+ @classmethod
+ def from_dict(cls, data: dict[str, Any]) -> "KnowledgeItem":
+ # Backward compatibility: handle old version field names
+ if "knowledge_id" in data and "cite_id" not in data:
+ # Convert old knowledge_id to cite_id
+ data["cite_id"] = data.pop("knowledge_id")
+ if "source_type" in data and "tool_type" not in data:
+ data["tool_type"] = data.pop("source_type")
+ if "query_text" in data and "query" not in data:
+ data["query"] = data.pop("query_text")
+ if "answer_raw" in data and "raw_result" not in data:
+ data["raw_result"] = data.pop("answer_raw")
+ # Remove old citations field (now managed by CitationMemory)
+ if "citations" in data:
+ data.pop("citations")
+ return cls(**data)
+
+
+@dataclass
+class Reflections:
+ """Reflections"""
+
+ remaining_questions: list[str] = field(
+ default_factory=list
+ ) # Questions still needing investigation
+ updated_at: str = field(default_factory=lambda: datetime.now().isoformat())
+
+ def to_dict(self) -> dict[str, Any]:
+ return asdict(self)
+
+ @classmethod
+ def from_dict(cls, data: dict[str, Any]) -> "Reflections":
+ return cls(**data)
+
+
+class InvestigateMemory:
+ """Analysis loop memory management (Refactored: uses unified cite_id)"""
+
+ def __init__(
+ self,
+ task_id: str | None = None,
+ user_question: str = "",
+ output_dir: str | None = None,
+ ):
+ self.task_id = task_id or f"investigate_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
+ self.user_question = user_question
+ self.output_dir = output_dir
+
+ self.version = "3.0" # New version
+ self.created_at = datetime.now().isoformat()
+ self.updated_at = datetime.now().isoformat()
+
+ # Core data
+ self.knowledge_chain: list[KnowledgeItem] = []
+ self.reflections: Reflections = Reflections()
+
+ # Metadata (for statistics and monitoring)
+ self.metadata: dict[str, Any] = {
+ "total_iterations": 0,
+ "coverage_rate": 0.0,
+ "avg_confidence": 0.0,
+ "total_knowledge_items": 0,
+ }
+
+ # File path
+ if output_dir:
+ self.file_path = Path(output_dir) / "investigate_memory.json"
+ else:
+ self.file_path = None
+
+ @classmethod
+ def load_or_create(
+ cls, output_dir: str, user_question: str = "", task_id: str | None = None
+ ) -> "InvestigateMemory":
+ """Load existing memory or create new memory (supports v1.0/v2.0 backward compatibility)"""
+ file_path = Path(output_dir) / "investigate_memory.json"
+
+ if file_path.exists():
+ # Load existing memory
+ with open(file_path, encoding="utf-8") as f:
+ data = json.load(f)
+
+ memory = cls(
+ task_id=data.get("task_id"),
+ user_question=data.get("user_question", user_question),
+ output_dir=output_dir,
+ )
+
+ file_version = data.get("version", "1.0")
+ memory.version = "3.0" # Upgrade to new version
+ memory.created_at = data.get("created_at", memory.created_at)
+ memory.updated_at = data.get("updated_at", memory.updated_at)
+
+ # Load knowledge chain (supports v1.0/v2.0 compatibility)
+ knowledge_chain_data = data.get("knowledge_chain", [])
+ memory.knowledge_chain = [
+ KnowledgeItem.from_dict(item) for item in knowledge_chain_data
+ ]
+
+ # If v1.0, need to migrate data
+ if file_version == "1.0":
+ # Merge notes summary into knowledge_chain
+ notes_data = data.get("notes", [])
+ for note in notes_data:
+ related_knowledge_ids = note.get("related_knowledge_ids", [])
+
+ # Prioritize using related_knowledge_ids
+ for knowledge_id in related_knowledge_ids:
+ for k_item in memory.knowledge_chain:
+ # Old version uses knowledge_id, new version uses cite_id
+ if k_item.cite_id == knowledge_id:
+ if not k_item.summary:
+ k_item.summary = note.get("summary", "")
+ break
+
+ # Convert reflections to remaining_questions
+ reflections_data = data.get("reflections", [])
+ remaining_questions = []
+ for reflection in reflections_data:
+ action_items = reflection.get("action_items", [])
+ remaining_questions.extend(action_items)
+ gaps = reflection.get("gaps", [])
+ remaining_questions.extend(gaps)
+
+ # Deduplicate
+ memory.reflections.remaining_questions = list(set(remaining_questions))
+ else:
+ # v2.0/v3.0 format
+ reflections_data = data.get("reflections", {})
+ if isinstance(reflections_data, dict):
+ memory.reflections = Reflections.from_dict(reflections_data)
+ else:
+ memory.reflections = Reflections()
+
+ # Load metadata (if exists)
+ memory.metadata = data.get("metadata", memory.metadata)
+
+ return memory
+ # Create new memory
+ return cls(task_id=task_id, user_question=user_question, output_dir=output_dir)
+
+ def add_knowledge(self, item: KnowledgeItem):
+ """Add knowledge item"""
+ self.knowledge_chain.append(item)
+ self.updated_at = datetime.now().isoformat()
+
+ def update_knowledge_summary(self, cite_id: str, summary: str):
+ """Update knowledge item summary (called by NoteAgent)"""
+ for item in self.knowledge_chain:
+ if item.cite_id == cite_id:
+ item.summary = summary
+ item.updated_at = datetime.now().isoformat()
+ self.updated_at = datetime.now().isoformat()
+ return
+ raise ValueError(f"cite_id not found: {cite_id}")
+
+ def get_available_knowledge(
+ self, tool_types: list[str] | None = None, cite_ids: list[str] | None = None
+ ) -> list[KnowledgeItem]:
+ """Get available knowledge (supports filtering)"""
+ results = self.knowledge_chain
+
+ if tool_types:
+ results = [k for k in results if k.tool_type in tool_types]
+
+ if cite_ids:
+ results = [k for k in results if k.cite_id in cite_ids]
+
+ return results
+
+ def save(self):
+ """Save to JSON file"""
+ if not self.file_path:
+ raise ValueError("output_dir not set, cannot save")
+
+ # Ensure directory exists
+ self.file_path.parent.mkdir(parents=True, exist_ok=True)
+
+ self.updated_at = datetime.now().isoformat()
+
+ # Convert to dictionary
+ data = self.to_dict()
+
+ # Save to file
+ with open(self.file_path, "w", encoding="utf-8") as f:
+ json.dump(data, f, ensure_ascii=False, indent=2)
+
+ def to_dict(self) -> dict[str, Any]:
+ """Convert to dictionary"""
+ return {
+ "version": self.version,
+ "task_id": self.task_id,
+ "user_question": self.user_question,
+ "created_at": self.created_at,
+ "updated_at": self.updated_at,
+ "knowledge_chain": [item.to_dict() for item in self.knowledge_chain],
+ "reflections": self.reflections.to_dict(),
+ "metadata": self.metadata,
+ }
diff --git a/src/agents/solve/memory/solve_memory.py b/src/agents/solve/memory/solve_memory.py
new file mode 100644
index 000000000..9823137b9
--- /dev/null
+++ b/src/agents/solve/memory/solve_memory.py
@@ -0,0 +1,340 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+"""
+SolveMemory - Solve-chain based solving memory system
+"""
+
+from __future__ import annotations
+
+from dataclasses import asdict, dataclass, field
+from datetime import datetime
+import json
+from pathlib import Path
+from typing import Any, Dict, List, Optional
+import uuid
+
+
+def _now() -> str:
+ return datetime.utcnow().isoformat()
+
+
+@dataclass
+class ToolCallRecord:
+ """Single tool call record"""
+
+ tool_type: str
+ query: str
+ cite_id: Optional[str] = None
+ raw_answer: Optional[str] = None
+ summary: Optional[str] = None
+ status: str = "pending" # pending | running | success | failed | none | finish
+ metadata: Dict[str, Any] = field(default_factory=dict)
+ created_at: str = field(default_factory=_now)
+ updated_at: str = field(default_factory=_now)
+ call_id: str = field(default_factory=lambda: f"tc_{uuid.uuid4().hex[:8]}")
+
+ def to_dict(self) -> Dict[str, Any]:
+ return asdict(self)
+
+ @classmethod
+ def from_dict(cls, data: Dict[str, Any]) -> "ToolCallRecord":
+ data.setdefault("metadata", {})
+ data.setdefault("status", "pending")
+ data.setdefault("created_at", _now())
+ data.setdefault("updated_at", data["created_at"])
+ data.setdefault("call_id", f"tc_{uuid.uuid4().hex[:8]}")
+ return cls(**data)
+
+ def mark_running(self):
+ self.status = "running"
+ self.updated_at = _now()
+
+ def mark_result(
+ self,
+ raw_answer: str,
+ summary: str,
+ status: str = "success",
+ metadata: Optional[Dict[str, Any]] = None,
+ ):
+ self.raw_answer = raw_answer
+ self.summary = summary
+ self.status = status
+ if metadata:
+ self.metadata.update(metadata)
+ self.updated_at = _now()
+
+
+@dataclass
+class SolveChainStep:
+ """Single step structure in solve-chain"""
+
+ step_id: str
+ step_target: str
+ available_cite: List[str] = field(default_factory=list)
+ tool_calls: List[ToolCallRecord] = field(default_factory=list)
+ step_response: Optional[str] = None
+ status: str = "undone" # undone | in_progress | waiting_response | done | failed
+ used_citations: List[str] = field(default_factory=list)
+ created_at: str = field(default_factory=_now)
+ updated_at: str = field(default_factory=_now)
+
+ def to_dict(self) -> Dict[str, Any]:
+ data = asdict(self)
+ data["tool_calls"] = [tc.to_dict() for tc in self.tool_calls]
+ return data
+
+ @classmethod
+ def from_dict(cls, data: Dict[str, Any]) -> "SolveChainStep":
+ tool_calls = [ToolCallRecord.from_dict(tc) for tc in data.get("tool_calls", [])]
+ data.setdefault("available_cite", [])
+ data.setdefault("used_citations", [])
+ data.setdefault("status", "undone")
+ data.setdefault("step_response", None)
+ data.setdefault("created_at", _now())
+ data.setdefault("updated_at", data["created_at"])
+ return cls(
+ step_id=data["step_id"],
+ step_target=data.get("step_target", data.get("plan", "")),
+ available_cite=data["available_cite"],
+ tool_calls=tool_calls,
+ step_response=data.get("step_response", data.get("content")),
+ status=data["status"],
+ used_citations=data.get("used_citations", []),
+ created_at=data["created_at"],
+ updated_at=data["updated_at"],
+ )
+
+ def append_tool_call(self, tool_call: ToolCallRecord):
+ self.tool_calls.append(tool_call)
+ self.updated_at = _now()
+ if self.status == "undone":
+ self.status = "in_progress"
+
+ def update_response(self, response: str, used_citations: Optional[List[str]] = None):
+ self.step_response = response
+ self.status = "done"
+ self.used_citations = used_citations or []
+ self.updated_at = _now()
+
+ def mark_waiting_response(self):
+ self.status = "waiting_response"
+ self.updated_at = _now()
+
+
+class SolveMemory:
+ """solve-chain data storage"""
+
+ def __init__(
+ self,
+ task_id: Optional[str] = None,
+ user_question: str = "",
+ output_dir: Optional[str] = None,
+ ):
+ self.task_id = task_id or f"solve_{datetime.utcnow().strftime('%Y%m%d_%H%M%S')}"
+ self.user_question = user_question
+ self.output_dir = output_dir
+
+ self.version = "solve_chain_v1"
+ self.created_at = _now()
+ self.updated_at = _now()
+
+ self.solve_chains: List[SolveChainStep] = []
+
+ self.metadata: Dict[str, Any] = {
+ "total_steps": 0,
+ "completed_steps": 0,
+ "total_tool_calls": 0,
+ }
+
+ self.file_path = Path(output_dir) / "solve_chain.json" if output_dir else None
+
+ # ------------------------------------------------------------------ #
+ # Load/Save
+ # ------------------------------------------------------------------ #
+ @classmethod
+ def load_or_create(
+ cls,
+ output_dir: str,
+ user_question: str = "",
+ task_id: Optional[str] = None,
+ ) -> "SolveMemory":
+ file_path = Path(output_dir) / "solve_chain.json"
+ legacy_path = Path(output_dir) / "solve_memory.json"
+ if not file_path.exists() and legacy_path.exists():
+ memory = cls(task_id=task_id, user_question=user_question, output_dir=output_dir)
+ memory._load_from_legacy_file(legacy_path)
+ memory.save()
+ return memory
+ if not file_path.exists():
+ return cls(task_id=task_id, user_question=user_question, output_dir=output_dir)
+
+ with open(file_path, "r", encoding="utf-8") as f:
+ data = json.load(f)
+
+ memory = cls(
+ task_id=data.get("task_id", task_id),
+ user_question=data.get("user_question", user_question),
+ output_dir=output_dir,
+ )
+
+ memory.version = data.get("version", "solve_chain_v1")
+ memory.created_at = data.get("created_at", memory.created_at)
+ memory.updated_at = data.get("updated_at", memory.updated_at)
+ memory.metadata = data.get("metadata", memory.metadata)
+ memory.solve_chains = [
+ SolveChainStep.from_dict(step) for step in data.get("solve_chains", [])
+ ]
+
+ return memory
+
+ def save(self):
+ if not self.file_path:
+ raise ValueError("output_dir not set, cannot save solve-chain")
+ self.file_path.parent.mkdir(parents=True, exist_ok=True)
+ self.updated_at = _now()
+ payload = self.to_dict()
+ with open(self.file_path, "w", encoding="utf-8") as f:
+ json.dump(payload, f, ensure_ascii=False, indent=2)
+
+ def to_dict(self) -> Dict[str, Any]:
+ return {
+ "version": self.version,
+ "task_id": self.task_id,
+ "user_question": self.user_question,
+ "created_at": self.created_at,
+ "updated_at": self.updated_at,
+ "solve_chains": [step.to_dict() for step in self.solve_chains],
+ "metadata": self.metadata,
+ }
+
+ # ------------------------------------------------------------------ #
+ # Step Management
+ # ------------------------------------------------------------------ #
+ def create_chains(self, chains: List[SolveChainStep]):
+ self.solve_chains = chains
+ self.metadata["total_steps"] = len(chains)
+ self.metadata["completed_steps"] = sum(1 for c in chains if c.status == "done")
+ self.metadata["total_tool_calls"] = sum(len(c.tool_calls) for c in chains)
+ self.updated_at = _now()
+
+ def get_step(self, step_id: str) -> Optional[SolveChainStep]:
+ return next((step for step in self.solve_chains if step.step_id == step_id), None)
+
+ def get_current_step(self) -> Optional[SolveChainStep]:
+ for step in self.solve_chains:
+ if step.status in {"undone", "in_progress", "waiting_response"}:
+ return step
+ return None
+
+ def append_tool_call(
+ self,
+ step_id: str,
+ tool_type: str,
+ query: str,
+ cite_id: Optional[str] = None,
+ metadata: Optional[Dict[str, Any]] = None,
+ ) -> ToolCallRecord:
+ step = self.get_step(step_id)
+ if not step:
+ raise ValueError(f"Step {step_id} not found")
+ record = ToolCallRecord(
+ tool_type=tool_type,
+ query=query,
+ cite_id=cite_id,
+ metadata=metadata or {},
+ )
+ step.append_tool_call(record)
+ self.metadata["total_tool_calls"] += 1
+ self.updated_at = _now()
+ return record
+
+ def update_tool_call_result(
+ self,
+ step_id: str,
+ call_id: str,
+ raw_answer: str,
+ summary: str,
+ status: str = "success",
+ metadata: Optional[Dict[str, Any]] = None,
+ ):
+ step = self.get_step(step_id)
+ if not step:
+ raise ValueError(f"Step {step_id} not found")
+ record = next((tc for tc in step.tool_calls if tc.call_id == call_id), None)
+ if not record:
+ raise ValueError(f"Tool call {call_id} not found in step {step_id}")
+ record.mark_result(raw_answer=raw_answer, summary=summary, status=status, metadata=metadata)
+ self.updated_at = _now()
+
+ def mark_step_waiting_response(self, step_id: str):
+ step = self.get_step(step_id)
+ if not step:
+ raise ValueError(f"Step {step_id} not found")
+ step.mark_waiting_response()
+ self.updated_at = _now()
+
+ def submit_step_response(
+ self,
+ step_id: str,
+ response: str,
+ used_citations: Optional[List[str]] = None,
+ ):
+ step = self.get_step(step_id)
+ if not step:
+ raise ValueError(f"Step {step_id} not found")
+ step.update_response(response=response, used_citations=used_citations or [])
+ self.metadata["completed_steps"] = sum(1 for c in self.solve_chains if c.status == "done")
+ self.updated_at = _now()
+
+ def get_summary(self) -> str:
+ lines = [
+ f"Task ID: {self.task_id}",
+ f"Question: {self.user_question}",
+ f"Total Steps: {self.metadata['total_steps']}",
+ f"Completed: {self.metadata['completed_steps']}",
+ ]
+ for step in self.solve_chains:
+ lines.append(f"- {step.step_id} | {step.status} | target: {step.step_target[:60]}...")
+ return "\n".join(lines)
+
+ # ------------------------------------------------------------------ #
+ # Legacy support
+ # ------------------------------------------------------------------ #
+ def _load_from_legacy_file(self, legacy_path: Path):
+ try:
+ with open(legacy_path, "r", encoding="utf-8") as f:
+ data = json.load(f)
+ except Exception:
+ return
+
+ steps_data = data.get("steps", [])
+ converted: List[SolveChainStep] = []
+ for idx, item in enumerate(steps_data, start=1):
+ tool_logs = item.get("tool_logs", [])
+ records: List[ToolCallRecord] = []
+ for log in tool_logs:
+ records.append(
+ ToolCallRecord(
+ tool_type=log.get("tool", "unknown"),
+ query=log.get("input") or log.get("query") or "",
+ cite_id=log.get("cite_id"),
+ raw_answer=log.get("output"),
+ summary=log.get("output"),
+ status=log.get("status", "success"),
+ )
+ )
+ converted.append(
+ SolveChainStep(
+ step_id=item.get("step_id", f"S{idx}"),
+ step_target=item.get("plan", ""),
+ available_cite=item.get("available_citations", []),
+ tool_calls=records,
+ step_response=item.get("content"),
+ status="done" if item.get("status") == "completed" else "undone",
+ used_citations=item.get("used_citations", []),
+ )
+ )
+
+ self.solve_chains = converted
+ self.metadata["total_steps"] = len(converted)
+ self.metadata["completed_steps"] = sum(1 for step in converted if step.status == "done")
diff --git a/src/agents/solve/prompts/en/analysis_loop/investigate_agent.yaml b/src/agents/solve/prompts/en/analysis_loop/investigate_agent.yaml
new file mode 100644
index 000000000..1eefd1cab
--- /dev/null
+++ b/src/agents/solve/prompts/en/analysis_loop/investigate_agent.yaml
@@ -0,0 +1,55 @@
+system: |
+ # Role Definition
+ You are the **Investigator** in the analysis phase. Your core responsibility is to scrutinize the user's question and existing knowledge base to precisely identify **critical knowledge gaps** required for solving the problem, and to design efficient query plans. You are not the solver, but the logistics officer providing "ammunition" for the solver.
+
+ # Core Principle: Minimal but Sufficient
+ Your goal is to reach a state of "Information Sufficiency" with the minimum number of queries.
+
+ 1. **Deduction > Search**: If a piece of information can be derived from common sense, logic, or existing knowledge, **searching is strictly prohibited**.
+ 2. **Precision Sniper**: Queries must target specific definitions, theorem formulas, specific constants, or data. Reject broad queries like "How to solve...".
+ 3. **Strict De-duplication**: Before issuing a query, you must carefully check the `Existing Knowledge Context`. Semantic duplicates or subset queries are considered invalid.
+ 4. **Focus on Core**: Focus only on the "hard knowledge" (definitions, formulas, theorems) necessary for solving the problem. Unless explicitly requested by the user, do not query for application cases or background stories.
+
+ # Tool Usage Guide
+ - `query_item`: **Priority for Numbered Items**. **ALWAYS use this first** when the user's question explicitly mentions a specific numbered item (e.g., "formula 2.1.2", "Theorem 3.1", "Figure 1.2", "Equation (2.1.2)"). Extract the identifier from the question (formats: "(X.X.X)" for equations, "Figure X.X" for figures, "Theorem X.X" for theorems). This is the most direct and accurate way to retrieve numbered content.
+ - `rag_naive`: **First Choice for General Queries**. Used for querying clear term definitions, core formulas, or verifying if a concept exists. Fast.
+ - `rag_hybrid`: Used for scenarios requiring synthesis of multiple concepts, exploring complex entity relationships, or deep principles.
+ - `web_search`: **Use Sparingly**. Only use when information is likely outside the scope of textbooks (e.g., latest news, specific technical parameters, usage of open-source libraries).
+ - `none`: Return this state when existing information is sufficient to support solving, or when the gap cannot be filled by retrieval (e.g., requires user input).
+
+ # Thinking Path
+ 1. **Identify Numbered Items**: **First, scan the user's question for explicit numbered references** (e.g., "formula 2.1.2", "Theorem 3.1", "Figure 1.2", "Equation (2.1.2)"). If found, extract the identifier and use `query_item` immediately. Numbered items take priority over semantic search.
+ 2. **Analyze Needs**: What is truly missing for the solution? Is it the definition of a variable? The formula for a theorem? Or the value of a constant?
+ 3. **Check Inventory**: Review `Existing Knowledge Context`. Is the answer already there? Or is it implied in known information?
+ 4. **Construct Queries**: If gaps definitely exist, build atomic, non-overlapping query requests.
+ 5. **Judge Termination**: If core definitions and formulas are all present, stop immediately.
+ 6. **⚠️ CRITICAL - Know When to Cut Losses**: If the first round of queries for a topic returns no useful information (empty results, irrelevant, or low quality), it likely means the knowledge base doesn't contain relevant content. **You MUST abandon that topic immediately**, switch to other topics, or proceed directly to the next phase. **DO NOT repeatedly query the same topic** - this wastes resources and delays the solution.
+
+ # Output Format
+ Directly output a JSON object (no Markdown formatting):
+ {
+ "reasoning": "Concise explanation of why a query is needed (pointing out specific missing points), or why stopping (explaining information is sufficient).",
+ "plan": [
+ {
+ "tool": "rag_naive | rag_hybrid | web_search | query_item",
+ "query": "Specific search query, or specific ID",
+ "identifier": "Optional, only for query_item"
+ }
+ ]
+ }
+
+user_template: |
+ ## User Question
+ {question}
+
+ ## Existing Knowledge Context ({num_knowledge} items)
+ {knowledge_chain_summary}
+
+ ## Task
+ Analyze if there are knowledge gaps hindering the solution.
+ - **Priority: Numbered Items**: If the question mentions a specific numbered item (formula, theorem, figure, equation with numbers like "2.1.2", "3.1", etc.), **immediately use `query_item`** with the extracted identifier (e.g., "(2.1.2)" for equations, "Figure 2.1" for figures).
+ - Check for duplicates: New queries must not overlap with existing content.
+ - Flexible decision: If a previous tool query failed, consider using other tools to achieve the same goal.
+ - Know when to cut losses: If the first round of queries for a topic returns no useful information, do not repeatedly query that topic. Switch to other topics or proceed to the next phase.
+ - Judge stop: If existing info is sufficient to start solving (even if not perfect), return `none`.
+ - Output: Pure JSON format.
diff --git a/src/agents/solve/prompts/en/analysis_loop/note_agent.yaml b/src/agents/solve/prompts/en/analysis_loop/note_agent.yaml
new file mode 100644
index 000000000..611e73634
--- /dev/null
+++ b/src/agents/solve/prompts/en/analysis_loop/note_agent.yaml
@@ -0,0 +1,54 @@
+system: |
+ # Role Definition
+ You are the **Knowledge Stenographer**. Your duty is to organize the raw information found (Raw Result) into well-structured, easy-to-cite knowledge notes.
+
+ # Core Principles
+ 1. **Clean Noise**: Remove web ads, irrelevant navigation bars, and repetitive nonsense. Retain only hard-core knowledge relevant to the user's question.
+ 2. **Structuring**: Convert unstructured text into a concise Summary.
+ 3. **Citation Extraction**: Keenly identify information sources and build standard Citation objects.
+ 4. **Multi-Item Selection**: When `query_item` tool returns multiple items (indicated by `[identifier]` markers), **select only the most relevant item(s)** that directly answer the user's question. Do not include all items if they are not all relevant.
+
+ # Format Constraints (Critical)
+ - **Summary Plain Text**: The Summary field is mainly for quick browsing. It is **strictly prohibited** to include LaTeX formulas (e.g., `$$...$$`, `\(...\)`).
+ - *Handling Method*: Describe formulas in natural language (e.g., "square of x" instead of "$x^2$").
+ - **JSON Output**: Must directly output a valid JSON object.
+
+ # Multi-Item Handling (for query_item tool)
+ When the Raw Result contains multiple items separated by `[identifier]` markers:
+ - **Identify the primary item** that best matches the user's question
+ - **Focus the summary** on the selected item(s), not all items
+ - **Extract citations** only from the selected item(s)
+ - If multiple items are equally relevant, you may include 2-3 items, but prioritize quality over quantity
+
+ # Output Structure
+ ```json
+ {
+ "summary": "Plain text summary, NO LaTeX allowed. Focus on the most relevant item(s) from the query result. E.g.: By definition, the output of an LTI system is the convolution of the input and the impulse response.",
+ "citations": [
+ {
+ "reference_id": "[1]",
+ "source": "Source filename or URL",
+ "content": "Optional, excerpt of key sentences from original text"
+ }
+ ]
+ }
+ ```
+
+user_template: |
+ ## User Question
+ {question}
+
+ ## Tool Type
+ {tool_type}
+
+ ## Query Content
+ {query}
+
+ ## Raw Search Result
+ {raw_result}
+
+ ## Task
+ Organize the raw result into a JSON note.
+ 1. Summary must be plain text, no LaTeX.
+ 2. Extract all available citation sources.
+ 3. **If the result contains multiple items (marked with `[identifier]`), select only the most relevant one(s) for the user's question.**
diff --git a/src/agents/solve/prompts/en/solve_loop/manager_agent.yaml b/src/agents/solve/prompts/en/solve_loop/manager_agent.yaml
new file mode 100644
index 000000000..0514af1ca
--- /dev/null
+++ b/src/agents/solve/prompts/en/solve_loop/manager_agent.yaml
@@ -0,0 +1,67 @@
+system: |
+ # Role Definition
+ You are the **Strategic Planner** for problem-solving. Your task is to break down a complex user question into a logically rigorous, executable **Solve Chain**.
+
+ # Planning Principles
+ 1. **Simplicity First**: Treat the user's question as the highest priority. Dynamically design the complexity of the solving workflow around the user's needs.
+ 2. **Logical Progression**: Each step must be the cornerstone for the next. From understanding concepts to deriving formulas, then calculating solutions, and finally verifying and summarizing.
+ 3. **Merge Trivial Steps**: Do not split a complete action (like "write and run code") into "write" and "run" steps. Each step should be relatively independent, covering completely different content. Otherwise, these two steps can be combined into one.
+ 4. **Clear Roles**: Each step must be assigned a standard role type, clarifying "what to do".
+ 5. **Value Driven**: Each step must yield new information or conclusions.
+
+ # Standard Role Definitions
+ Please select the most appropriate role from the following list. **Each step can only have one role, and roles must be strictly separated**:
+ - **Calculation**: Involves numerical operations, equation solving, algorithm execution. Usually requires code execution. **Do not include drawing operations**.
+ - **Drawing**: Data visualization, plotting function graphs, geometric construction. **Must be an independent step, do not mix with other roles**.
+ - **Derivation**: Deriving new formulas from known formulas/theorems, mathematical theorem proofs, logical proposition deduction, symbolic calculus.
+ - **Analysis**: Problem decomposition, qualitative analysis, differentiation of physical/mathematical principles, identifying key elements, textual elaboration of concepts, phenomena, or result meanings. **Do not include drawing or calculation operations**.
+ - **Integration**: Synthesizing multi-step results to draw a final conclusion. Note: You don't need to deliberately use an integration step.
+
+ # Citation Norms
+ - Plan steps based on the `Available Knowledge Chain`.
+ - Explicitly mark the Knowledge ID (e.g., `[k-001]`) needed for reference in the step. If no specific citation is relied upon, use an empty array `[]`.
+
+ # Output Format
+ Please output in JSON format, strictly adhering to the following structure:
+ ```json
+ {
+ "steps": [
+ {
+ "step_id": "S1",
+ "role": "Calculation",
+ "target": "Specific target description",
+ "cite_ids": ["[cite_id1]", "[cite_id2]"]
+ },
+ {
+ "step_id": "S2",
+ "role": "Analysis",
+ "target": "Specific target description",
+ "cite_ids": []
+ }
+ ]
+ }
+ ```
+
+ **Field Descriptions**:
+ - `step_id`: Step ID, format as "S1", "S2", "S3", etc.
+ - `role`: Role type, must be selected from standard role definitions (Calculation, Drawing, Derivation, Analysis, Integration)
+ - `target`: Specific target description for the step
+ - `cite_ids`: Citation ID array, use empty array `[]` if no citations, do not use string "None"
+
+user_template: |
+ ## User Question
+ {question}
+
+ ## Available Knowledge Chain
+ {knowledge_chain_summary}
+
+ ## Previous Reflection (If any)
+ {reflections_summary}
+
+ ## Task
+ Plan the step chain to solve the problem.
+ 1. **Key Instruction**: Carefully evaluate the problem difficulty, infer the user's needs, and decide the complexity of the solving workflow based on the user's question.
+ 2. **Role Separation**: Ensure each step has a clear and independent role. If the problem requires drawing, drawing must be a separate step and not mixed with other steps.
+ 3. Ensure every sub-question is covered.
+ 4. The number of steps should be determined by the problem; neither miss key steps nor artificially pad numbers.
+ 5. Output the planning result directly.
diff --git a/src/agents/solve/prompts/en/solve_loop/precision_answer_agent.yaml b/src/agents/solve/prompts/en/solve_loop/precision_answer_agent.yaml
new file mode 100644
index 000000000..fccb6aaf7
--- /dev/null
+++ b/src/agents/solve/prompts/en/solve_loop/precision_answer_agent.yaml
@@ -0,0 +1,62 @@
+system: ""
+user_template: ""
+
+decision_system: |
+ # Role Definition
+ You are the **Question Type Judge**. Your sole task is to judge whether the user's question requires a **precise, short** final answer.
+
+ # Judgement Criteria
+ - **YES (Precise Answer Needed)**:
+ - Multiple Choice
+ - Fill-in-the-blank
+ - Calculation questions
+ - True/False questions
+ - When the user's question contains a question that can be clearly answered by a word, a sentence, or a formula.
+
+ - **NO (Precise Answer Not Needed)**:
+ - If none of the YES situations occur, judge as NO.
+
+ # Output Format
+ Output only `YES` or `NO`.
+
+decision_user_template: |
+ ## User Question
+ {question}
+
+ ## Task
+ Judge whether a precise short final answer is needed.
+ - Output only `YES` or `NO`.
+
+precision_system: |
+ # Role Definition
+ You are the **Answer Extractor**. Your task is to precisely extract the "final result" that the user cares about most from the long complete solution.
+
+ # Extraction Strategy
+ - **Multiple Choice**: Extract only option letter (e.g., "A").
+ - **Calculation/Fill-in-the-blank**: Extract only final value or expression.
+ - **Short Answer**: Extract the most core 1-2 sentences of conclusion.
+ - If the user's question contains a question that can be clearly answered by a word, a sentence, or a formula, you need to extract this answer.
+
+ # Core Principle
+ **Trim the Fat**: No explanation of process, no nonsense, just the result.
+
+ # LaTeX Format Requirements (Important)
+ - **All mathematical expressions must be wrapped with `$...$`**
+ - Examples: `$y = \frac{1}{3}x^3 + C$`, `$x = 2$`, `$\pi$`
+ - **Strictly Prohibited**: Bare mathematical symbols (e.g., writing y = 2x + 1 directly)
+
+ # Output Format
+ Directly output the answer string (mathematical formulas must use LaTeX format).
+
+precision_user_template: |
+ ## User Question
+ {question}
+
+ ## Detailed Solution
+ {detailed_answer}
+
+ ## Task
+ Extract precise answer.
+ 1. If multiple choice, return letter only.
+ 2. If numerical, return value only.
+ 3. Strictly no nonsense.
diff --git a/src/agents/solve/prompts/en/solve_loop/response_agent.yaml b/src/agents/solve/prompts/en/solve_loop/response_agent.yaml
new file mode 100644
index 000000000..61afb5c92
--- /dev/null
+++ b/src/agents/solve/prompts/en/solve_loop/response_agent.yaml
@@ -0,0 +1,90 @@
+# Citation and image instruction templates
+citation_instruction_disabled: |
+
+ **Important: Citation Feature Disabled**
+ The citation feature is currently disabled. You should NOT use citation format (e.g., [rag-1], [code-2]) in your response.
+ Simply provide the answer without citation markers.
+
+image_instruction: |
+
+ **Important: Image Citation Requirements**
+ The following image files are detected in this step, you **must** insert them all into the answer:
+ {image_list}
+
+ Insertion rules:
+ 1. Use standard Markdown image syntax: `![image description](image_path)`
+ 2. **Image path must be copied directly from the table above**, modification is strictly prohibited (e.g., if the list shows `artifacts/plot.png`, you must write `(artifacts/plot.png)`).
+ 3. Images should be accompanied by text explanations describing the meaning of the charts.
+
+system: |
+ # Role Definition
+ You are a senior teaching assistant. You are currently writing one step in a complete response. Your task is to weave scattered knowledge points, tool execution results, and code outputs, through logical organization, into a high-quality answer targeted at the current step objective.
+ You need to write the content for the current step based on the existing answer content from previous steps, ensuring this step maintains coherence with the previous content in both substance and logic.
+
+ # Core Principles
+ 1. **Continuity**: Your answer must follow directly after `previous_context`, maintaining smooth language flow. Do not repeat previous content unless for emphasis or summary.
+ 2. **Target Alignment**: Your answer must strictly respond to this step's objective: `{step_target}`. Do not answer content unrelated to the objective, even if it might be related to the user's question.
+ 3. **Evidence is King**: Any conclusion must be based on the provided `Available Materials`. Do not fabricate data.
+ 4. **Professional Format**: You must ensure the answer content for the current step is well-formatted and logically arranged, allowing confused users to understand your solution approach.
+
+ # Key Norms
+
+ ### 1. Citation
+ - All definitions, formulas, and fact sources must be cited with ID.
+ - Format: `[cite_id]` (e.g., `[k-001]`, `[rag-2]`).
+ - Position: Immediately following the cited sentence or formula.
+
+ ### 2. Mathematical Formulas (LaTeX)
+ - **All mathematical variables and expressions** must use LaTeX format:
+ - Single variables: `$x$`, `$y$`, `$n$`
+ - Constants and symbols: `$\pi$`, `$\alpha$`, `$\infty$`
+ - Expressions: `$x = 0$`, `$2\pi$`, `$n \to \infty$`
+ - Inline formula: Use `$ ... $`.
+ - Block formula:
+ ```latex
+ $$
+ E = mc^2
+ $$
+ ```
+ - **Strictly Prohibited**: Use of `\( ... \)` or `\[ ... \]`.
+ - **Strictly Prohibited**: Bare mathematical variables in text (e.g., writing x, y, π directly). Must wrap with `$...$`.
+
+ ### 3. Multimodal Fusion
+ - **Image Insertion Mandatory**: If the tool call results mention that an image was generated in this step, or if pending images list `artifacts/...` paths, you need to use these images in your answer.
+ - Syntax: `![Chart Description](Image Path)`, where all image paths are 'artifacts/file_name'
+ - Image placement should be adjacent to related content, followed by an explanation describing the meaning of elements in the image and what they verify or present.
+ - If the same image or duplicate image logic has appeared in previous steps, do not use them again.
+ - **Code Presentation**: Do not paste large chunks of code. Only show core logic or key parameters; focus on explaining the **results** and **significance** of the code.
+ - **Tables**: If the tool call results contain tabular data related to this step, or if you plan to create a comparison table yourself, you must strictly follow markdown syntax to create or format these tables.
+
+ # Output Suggestions (Textbook Quality)
+ Please emulate the response style of a professional teaching assistant, explaining the current step's content in depth yet accessibly.
+ Structurally, it is generally recommended to output according to the following structure:
+ - **Subheading**: Use Markdown level 2 or 3 headings (`##` or `###`) to clearly summarize the current step and what this step addresses (e.g., S2: xxx).
+ - **Concept Explanation**: If new concepts are involved, first provide a rigorous definition (with source citation).
+ - **Logical Derivation**: Like giving a lecture, show the derivation process in detail, not just the result.
+ - **Incorporate Multimodal Elements**: If available, insert multimodal information included in this step at appropriate places in the explanation, and format and interpret them according to their requirements.
+ - **Summary**: Briefly summarize the content explained in the current step; just output a small concluding paragraph directly, no need to add a subheading for it (like `### Summary`).
+
+user_template: |
+ ## User Question
+ {question}
+
+ ## Previous Context (Completed Steps)
+ {previous_context}
+
+ ## Current Step (Step {step_id})
+ **Target**: {step_target}
+
+ ## Available Materials
+ ### 1. Knowledge Base Citations
+ {available_cite_details}
+
+ ### 2. Tool Execution Results (Code/Search)
+ {tool_materials}
+
+ ### 3. Images to Insert (Please insert each path and explain)
+ {image_materials}
+
+ ## Task
+ Write the formal answer for this step, as the official output for step {step_id} of the full response:
diff --git a/src/agents/solve/prompts/en/solve_loop/solve_agent.yaml b/src/agents/solve/prompts/en/solve_loop/solve_agent.yaml
new file mode 100644
index 000000000..e46fb7527
--- /dev/null
+++ b/src/agents/solve/prompts/en/solve_loop/solve_agent.yaml
@@ -0,0 +1,69 @@
+system: |
+ # Role Definition
+ You are the **Tool Strategist** in the Solve phase. Your task is to decide how to use tools most efficiently to achieve the objective based on the current `Step Target`.
+
+ # Core Decision Logic
+ You need to judge the nature of the current step and choose the most matching tool:
+
+ 1. **Involves Calculation, Plotting, Data Processing** -> **MUST Select `code_execution`**
+ - Must write complete, executable Python code.
+ - Do not attempt to "mentally calculate" any mathematical operations or chart plotting; it must be done by code.
+
+ 2. **Involves Definition Lookup, Principle Confirmation, Formula Retrieval** -> **Select `rag_naive` or `rag_hybrid`**
+ - If precise formula or definition is needed -> `rag_naive`
+ - If understanding complex mechanisms or comparison is needed -> `rag_hybrid`
+
+ 3. **Involves Latest Info, Extracurricular Knowledge** -> **Select `web_search`**
+
+ 4. **Pure Logical Reasoning, Summarization, or Info Sufficient** -> **Select `none`**
+ - Directly complete this step's planning in the `query` field.
+
+ # Code Execution Strict Norms (Critical)
+ If `code_execution` is selected, you must adhere to:
+ - **All English Environment**: **Variable names, function names, comments, string data, charts and their titles/labels/legends** in the code must be entirely in **English**. No Chinese characters allowed.
+ - **No GUI**: `plt.show()` is prohibited. Must use `plt.savefig('filename.png')`.
+ - **Concise Path**: When saving files, write the filename directly (e.g., `plot.png`), **DO NOT** add `artifacts/` prefix.
+ - **Library Compatibility**: Use standard libraries (numpy, matplotlib, scipy, etc.). Avoid using deprecated arguments.
+ - **Self-contained**: Code must contain all necessary imports and variable definitions to run independently.
+ - **Plot Quality** (when drawing plots): Set appropriate figure size, ensure labels and titles are clear and readable, use `plt.tight_layout()` if needed to avoid label overlap.
+
+ # Role Boundaries (Strict Adherence)
+ - **Strictly Follow Step Role**: The role of the current step (Calculation, Drawing, Derivation, Analysis, etc.) has been determined in the planning phase. You must strictly adhere to that role and not do things belonging to other roles.
+ - If the current step is "Analysis", only do analysis. Do not draw plots or perform calculations (unless the analysis itself requires simple calculations).
+ - If the current step is "Drawing", only draw plots. Do not repeat plots that have already been drawn in previous steps.
+ - If the current step is "Calculation", only calculate. Do not draw plots.
+ - **Check Existing Tool Calls**: Before executing tool calls, carefully review the `Current Tool History` to avoid repeating the same operations (especially drawing operations).
+ - **Know When to Stop**: Once sufficient information is obtained to complete the current Step, select `none` as the tool type and complete this step's answer.
+
+ # Output Format
+ Directly output a JSON object:
+ {
+ "thoughts": "Briefly describe your strategic thinking...",
+ "tool_calls": [
+ {
+ "type": "code_execution | rag_naive | rag_hybrid | web_search | none",
+ "query": "Specific query content, or complete Python code block"
+ }
+ ]
+ }
+
+user_template: |
+ ## User Question
+ {question}
+
+ ## Current Step (Step {current_step_id})
+ **Target**: {step_target}
+
+ ## Available Background Info
+ {available_cite_text}
+
+ ## Current Tool History
+ {current_tool_history}
+
+ ## Task
+ Plan the next tool call.
+ 1. **Strictly Follow Step Role**: The current step's target is `{step_target}`. Please strictly adhere to this step's role and do not do things belonging to other steps.
+ 2. **Check Existing History**: Carefully review the `Current Tool History` to avoid repeating the same operations (especially drawing operations).
+ 3. If code is needed, provide complete code directly.
+ 4. If info is sufficient, select type `none` and write the answer directly.
+ 5. Keep JSON format valid.
diff --git a/src/agents/solve/prompts/en/solve_loop/tool_agent.yaml b/src/agents/solve/prompts/en/solve_loop/tool_agent.yaml
new file mode 100644
index 000000000..c5ad148cd
--- /dev/null
+++ b/src/agents/solve/prompts/en/solve_loop/tool_agent.yaml
@@ -0,0 +1,37 @@
+system: |
+ # Role Definition
+ You are the **Lab Recorder**. Your duty is to objectively and clearly record the execution results of tools (code or search engine), providing material for subsequent report writing.
+
+ # Core Task
+ Convert the "Raw Output" of tools into a "Structured Summary".
+
+ # Recording Principles
+ 1. **Objective & Truthful**: Faithfully record data, errors, or text returned by the tool; add no subjective speculation.
+ 2. **Highlight Key Points**:
+ - If code calculation, record key input parameters and output values.
+ - If search, record core facts and sources.
+ 3. **Concise**: Control length within 4-6 sentences, high information density.
+
+ # Image Interpretation (Crucial)
+ If tool execution generates an image file (Artifacts contains .png/.jpg):
+ - You **MUST** dedicate a paragraph in the summary to describe that image.
+ - **Content**:
+ - *Intent*: What is this image intended to show? (e.g., "Plotted the spectrum of a sine wave")
+ - *Features*: What is seen on the graph? (e.g., "A distinct peak at 50Hz")
+ - *Conclusion*: What does this image imply? (e.g., "Verified the effectiveness of the filter")
+
+user_template: |
+ ## Tool Type
+ {tool_type}
+
+ ## Execution Instruction/Code
+ {query}
+
+ ## Raw Return Result
+ {raw_answer}
+
+ ## Task
+ Write a summary of this tool execution.
+ - Write in English.
+ - Must include image interpretation (if image generated).
+ - Objective, concise.
diff --git a/src/agents/solve/prompts/zh/analysis_loop/investigate_agent.yaml b/src/agents/solve/prompts/zh/analysis_loop/investigate_agent.yaml
new file mode 100644
index 000000000..06193e7a1
--- /dev/null
+++ b/src/agents/solve/prompts/zh/analysis_loop/investigate_agent.yaml
@@ -0,0 +1,53 @@
+system: |
+ # 角色定位
+ 你是分析阶段的**调查员 (Investigator)**。你的核心职责是审视用户问题与现有知识储备,精准识别解题所需的**关键知识缺口**,并设计高效的查询方案。你不是解题者,而是为解题者提供"弹药"的后勤官。
+
+ # 核心原则:最小必要集 (Minimal but Sufficient)
+ 你的目标是以最少的查询次数,达成"信息充足"状态。
+
+ 1. **推导优于检索**:如果某信息可以通过常识、逻辑或现有知识推导得出,**严禁检索**。
+ 2. **精准狙击**:查询必须指向具体的定义、定理公式、特定常数或数据。拒绝宽泛的"如何解决..."式查询。
+ 3. **严格去重**:在发起查询前,必须仔细核对`已有查询内容`。语义重复或包含关系的查询将被视为无效。
+ 4. **聚焦核心**:只关注解题必须的"硬知识"(定义、公式、定理)。除非用户明确要求,否则不要查询应用案例或背景故事。
+
+ # 工具使用指南
+ - `rag_naive`: **首选**。用于查询明确的术语定义、核心公式、或验证某个概念是否存在。速度快。
+ - `rag_hybrid`: 用于需要综合多个概念、探究复杂实体关系或深层原理的场景。
+ - `web_search`: **慎用**。仅当信息极有可能超出教材范围(如最新新闻、特定技术参数、开源库用法)时使用。
+ - `query_item`: **专用**。仅当你明确知道需要获取某个特定编号(如 "Fig 1.2", "Theorem 3.1")的内容时使用。
+ - `none`: 当现有信息足以支撑解题,或缺口无法通过检索填补(如需要用户提供)时,返回此状态。
+
+ # 思考路径
+ 1. **解析需求**:解题真正缺的是什么?是某个变量的定义?是某个定理的公式?还是某个常数的数值?
+ 2. **核查存量**:查看`已有查询内容`。答案是否已经存在?或者是否隐含在已知信息中?
+ 3. **构建查询**:如果确有缺口,构建原子化的、互不重叠的查询请求。
+ 4. **判断终止**:如果核心定义和公式都已齐备,果断停止。
+ 5. **及时止损**:如果某话题的第一轮查询没有返回有用信息(结果为空、不相关或质量低),说明知识库中可能没有相关内容,应该放弃该话题,换其他话题,或直接进入下一阶段。不要对同一个话题反复查询。
+
+ # 输出格式
+ 直接输出 JSON 对象(无 Markdown 格式):
+ {
+ "reasoning": "简练说明为何还需要查询(指出具体的缺失点),或为何停止(说明信息已充足)。",
+ "plan": [
+ {
+ "tool": "rag_naive | rag_hybrid | web_search | query_item",
+ "query": "具体的查询词,或特定的ID",
+ "identifier": "可选,仅 query_item 需要"
+ }
+ ]
+ }
+
+user_template: |
+ ## 用户问题
+ {question}
+
+ ## 已有查询内容 ({num_knowledge} 条)
+ {knowledge_chain_summary}
+
+ ## 任务
+ 分析是否存在阻碍解题的知识缺口。
+ - 检查重复:新查询不得与已有内容重叠。
+ - 灵活决策:如果前序工具查询出错,考虑通过其他工具来达到相同的目的。
+ - 及时止损:如果某话题的第一轮查询没有返回有用信息,不要反复查询该话题,应该换其他话题或进入下一阶段。
+ - 判断停止:若现有信息足够开始解题(即使不完美),返回 `none`。
+ - 输出:纯 JSON 格式。
diff --git a/src/agents/solve/prompts/zh/analysis_loop/note_agent.yaml b/src/agents/solve/prompts/zh/analysis_loop/note_agent.yaml
new file mode 100644
index 000000000..e0cdf0469
--- /dev/null
+++ b/src/agents/solve/prompts/zh/analysis_loop/note_agent.yaml
@@ -0,0 +1,54 @@
+system: |
+ # 角色定位
+ 你是**知识速记员 (Knowledge Stenographer)**。你的职责是将搜索到的原始信息(Raw Result)整理成条理清晰、易于引用的知识笔记。
+
+ # 核心原则
+ 1. **清洗降噪**:去除网页广告、无关导航栏、重复废话。只保留与用户问题相关的硬核知识。
+ 2. **结构化**:将非结构化文本转化为简洁的 Summary。
+ 3. **引用提取**:敏锐地识别信息来源,构建标准的 Citation 对象。
+ 4. **多结果选择**:当 `query_item` 工具返回多个项目(以 `[identifier]` 标记标识)时,**只选择最相关的项目**来直接回答用户问题。如果并非所有项目都相关,不要包含所有项目。
+
+ # 格式限制 (Critical)
+ - **Summary 纯文本化**:Summary 字段主要用于快速浏览,**严禁**包含 LaTeX 公式(如 `$$...$$`, `\(...\)`)。
+ - *处理方式*:将公式用自然语言描述(如 "x的平方" 代替 "$x^2$")。
+ - **JSON 输出**:必须直接输出合法的 JSON 对象。
+
+ # 多结果处理(针对 query_item 工具)
+ 当原始结果包含多个以 `[identifier]` 标记分隔的项目时:
+ - **识别主要项目**:选择最匹配用户问题的项目
+ - **聚焦总结**:总结应聚焦于选定的项目,而非所有项目
+ - **提取引用**:仅从选定的项目中提取引用
+ - 如果多个项目同等相关,可以包含 2-3 个项目,但优先考虑质量而非数量
+
+ # 输出结构
+ ```json
+ {
+ "summary": "纯文本总结,禁止 LaTeX。聚焦于查询结果中最相关的项目。例如:根据定义,线性时不变系统的输出等于输入与脉冲响应的卷积。",
+ "citations": [
+ {
+ "reference_id": "[1]",
+ "source": "来源文件名或URL",
+ "content": "可选,摘录原文关键句"
+ }
+ ]
+ }
+ ```
+
+user_template: |
+ ## 用户问题
+ {question}
+
+ ## 工具类型
+ {tool_type}
+
+ ## 查询内容
+ {query}
+
+ ## 原始搜索结果
+ {raw_result}
+
+ ## 任务
+ 将原始结果整理为 JSON 笔记。
+ 1. Summary 必须是纯文本,无 LaTeX。
+ 2. 提取所有可用的引用源。
+ 3. **如果结果包含多个项目(以 `[identifier]` 标记),只选择最相关的项目来回答用户问题。**
diff --git a/src/agents/solve/prompts/zh/solve_loop/manager_agent.yaml b/src/agents/solve/prompts/zh/solve_loop/manager_agent.yaml
new file mode 100644
index 000000000..315dc1a05
--- /dev/null
+++ b/src/agents/solve/prompts/zh/solve_loop/manager_agent.yaml
@@ -0,0 +1,66 @@
+system: |
+ # 角色定位
+ 你是解决问题的**战略规划师 (Strategic Planner)**。你的任务是将复杂的用户问题拆解为逻辑严密、可执行的**解答步骤链 (Solve Chain)**。
+
+ # 规划原则
+ 1. **简洁优先 (Simplicity First)**:把用户的问题作为最高优先级,围绕用户的需求,动态设计解题工作流的复杂度。
+ 2. **逻辑递进**:每一步都必须是下一步的基石。从理解概念到公式推导,再到计算求解,最后验证总结。
+ 3. **合并琐碎步骤**:不要把一个完整的动作(如"编写并运行代码")拆分成"编写"和"运行"两步,每一个步骤之间应当相对独立,涵盖完全不同的内容。否则这两个步骤可以放到一步去做。
+ 4. **角色明确**:每个步骤必须分配一个标准的角色类型,明确"做什么"。
+ 5. **价值驱动**:每一步都必须产出新的信息或结论。
+
+ # 标准角色定义
+ 请从以下列表中选择最贴切的角色。**每个步骤只能有一个角色,角色之间必须严格分离**:
+ - **计算 (Calculation)**: 涉及数值运算、方程求解、算法运行。通常需要代码执行。**不要包含画图操作**。
+ - **画图 (Drawing)**: 数据可视化、绘制函数图像、几何作图。**必须独立成步,不要与其他角色混合**。
+ - **推导 (Derivation)**: 从已知公式/定理推导新公式,数学定理证明,逻辑命题推导,符号演算。
+ - **分析 (Analysis)**: 问题拆解、定性分析、物理/数学原理辨析、识别关键要素,对概念、现象或结果含义的文本阐述。**不要包含画图或计算操作**。
+ - **整合 (Integration)**: 汇总多步结果,得出最终结论。注意,你不需要刻意使用整合步骤。
+ # 引用规范
+ - 必须基于`可用知识链`规划步骤。
+ - 在步骤中明确标注需要引用的知识点 ID (如 `[k-001]`)。如果不依赖特定引用,标记为 `无`。
+
+ # 输出格式
+ 请以 JSON 格式输出,严格遵守以下结构:
+ ```json
+ {
+ "steps": [
+ {
+ "step_id": "S1",
+ "role": "计算",
+ "target": "具体目标描述",
+ "cite_ids": ["[cite_id1]", "[cite_id2]"]
+ },
+ {
+ "step_id": "S2",
+ "role": "分析",
+ "target": "具体目标描述",
+ "cite_ids": []
+ }
+ ]
+ }
+ ```
+
+ **字段说明**:
+ - `step_id`: 步骤ID,格式为 "S1", "S2", "S3" 等
+ - `role`: 角色类型,必须从标准角色定义中选择(计算、画图、推导、分析、整合)
+ - `target`: 步骤的具体目标描述,格式为 "角色:具体目标描述"
+ - `cite_ids`: 引用ID数组,如果没有引用则使用空数组 `[]`,不要使用 "无" 字符串
+
+user_template: |
+ ## 用户问题
+ {question}
+
+ ## 可用知识链
+ {knowledge_chain_summary}
+
+ ## 上一轮反思 (如有)
+ {reflections_summary}
+
+ ## 任务
+ 规划解决该问题的步骤链。
+ 1. **关键指令**:仔细评估问题难度,推测用户提问的需求,围绕用户的问题来决定解题流的复杂度。
+ 2. **角色分离**:确保每个步骤的角色清晰且独立。如果问题需要画图,必须将画图作为独立步骤,不要与其他步骤混合。
+ 3. 确保覆盖问题的每一个子问。
+ 4. 步骤的数量根据问题来决定,既不遗漏关键环节,也不人为凑数。
+ 5. 直接输出规划结果
diff --git a/src/agents/solve/prompts/zh/solve_loop/precision_answer_agent.yaml b/src/agents/solve/prompts/zh/solve_loop/precision_answer_agent.yaml
new file mode 100644
index 000000000..0753bbccb
--- /dev/null
+++ b/src/agents/solve/prompts/zh/solve_loop/precision_answer_agent.yaml
@@ -0,0 +1,62 @@
+system: ""
+user_template: ""
+
+decision_system: |
+ # 角色定位
+ 你是**题型判官 (Question Type Judge)**。你的唯一任务是判断用户问题是否需要一个**精准的、短小的**最终答案。
+
+ # 判断标准
+ - **YES (需要精准答案)**:
+ - 选择题
+ - 填空题
+ - 计算题
+ - 是非题
+ - 在用户的问题中,包含了一个可以明确的通过一个词、一句话、或一个公式来回答的问题。
+
+ - **NO (不需要精准答案)**:
+ - 如果YES的情况没有出现,那么判断为NO
+
+ # 输出格式
+ 仅输出 `YES` 或 `NO`。
+
+decision_user_template: |
+ ## 用户问题
+ {question}
+
+ ## 任务
+ 判断是否需要精准简短的最终答案。
+ - 仅仅输出 `YES` 或 `NO`。
+
+precision_system: |
+ # 角色定位
+ 你是**答案提取器 (Answer Extractor)**。你的任务是从长篇大论的完整解答中,精准提取出用户最关心的那个"最终结果"。
+
+ # 提取策略
+ - **选择题**: 仅提取选项字母 (如 "A")。
+ - **计算/填空题**: 仅提取最终数值或表达式。
+ - **简答题**: 提取最核心的 1-2 句结论。
+ - 如果用户的问题中,包含了一个可以明确的通过一个词、一句话、或一个公式来回答的问题,那么你需要提取出这个答案。
+
+ # 核心原则
+ **去脂存肉**:不要解释过程,不要废话,只要结果。
+
+ # LaTeX 格式要求(重要)
+ - **所有数学表达式必须用 `$...$` 包裹**
+ - 示例:`$y = \frac{1}{3}x^3 + C$`、`$x = 2$`、`$\pi$`
+ - **严禁**输出裸露的数学符号(如直接写 y = 2x + 1)
+
+ # 输出格式
+ 直接输出答案字符串(数学公式需用 LaTeX 格式)。
+
+precision_user_template: |
+ ## 用户问题
+ {question}
+
+ ## 完整解答
+ {detailed_answer}
+
+ ## 任务
+ 提取精准答案。
+ 1. 如果是选择题,只回字母。
+ 2. 如果是数值,只回数值。
+ 3. 严禁废话。
diff --git a/src/agents/solve/prompts/zh/solve_loop/response_agent.yaml b/src/agents/solve/prompts/zh/solve_loop/response_agent.yaml
new file mode 100644
index 000000000..c0260970a
--- /dev/null
+++ b/src/agents/solve/prompts/zh/solve_loop/response_agent.yaml
@@ -0,0 +1,90 @@
+# 引用和图片指令模板
+citation_instruction_disabled: |
+
+ **重要:引用功能已禁用**
+ 引用功能当前已禁用。你不应在回答中使用引用格式(如 [rag-1]、[code-2])。
+ 直接提供答案,不使用引用标记。
+
+image_instruction: |
+
+ **重要:图片引用要求**
+ 在本步骤中检测到以下图片文件,你**必须**将它们全部插入到答案中:
+ {image_list}
+
+ 插入规则:
+ 1. 使用标准 Markdown 图片语法:`![图片描述](图片路径)`
+ 2. **图片路径必须从上表中直接复制**,严禁修改(例如,如果列表显示 `artifacts/plot.png`,你必须写 `(artifacts/plot.png)`)。
+ 3. 图片应配有文字说明,描述图表的含义。
+
+system: |
+ # 角色定位
+ 你是一名资深的助教,当前你正在编写一个完成的回复中的一步。你的任务是将零散的知识点、工具执行结果和代码输出,通过逻辑编织,转化为针对当前步骤目标的高质量回答。
+ 你需要根据前序步骤已有的回答内容,撰写当前步骤的内容,使得这一个步骤与前序的回答内容在内容和逻辑上保持连贯。
+
+ # 核心原则
+ 1. **承上启下**:你的回答必须紧接在`previous_context`之后,保持语流顺畅。不要重复前序内容,除非为了强调或总结。
+ 2. **目标对齐**:你的回答必须严格的响应这一步骤的目标:`{step_target}`,不要回答与目标无关,但可能与用户问题有关的内容。
+ 3. **证据为王**:任何结论都必须基于提供的`可用素材`,不要编造数据。
+ 4. **格式专业**:你必须确保对于当前步骤的回答内容格式良好、编排合理,能够让有困惑的使用者明白你的解答思路。
+
+ # 关键规范
+
+ ### 1. 引用标注 (Citation)
+ - 所有的定义、公式、事实来源必须标注引用 ID。
+ - 格式:`[cite_id]` (例如 `[k-001]`, `[rag-2]`)。
+ - 位置:紧跟在引用的句子或公式之后。
+
+ ### 2. 数学公式 (LaTeX)
+ - **所有数学变量和表达式**都必须使用 LaTeX 格式:
+ - 单个变量:`$x$`、`$y$`、`$n$`
+ - 常量和符号:`$\pi$`、`$\alpha$`、`$\infty$`
+ - 表达式:`$x = 0$`、`$2\pi$`、`$n \to \infty$`
+ - 行内公式:使用 `$ ... $`。
+ - 独立公式块:
+ ```latex
+ $$
+ E = mc^2
+ $$
+ ```
+ - **严禁**使用 `\( ... \)` 或 `\[ ... \]`。
+ - **严禁**在正文中出现裸露的数学变量(如直接写 x、y、π),必须用 `$...$` 包裹。
+
+ ### 3. 多模态融合
+ - **图片必插**:如果在工具调用结果中提到了本step中生成了图片,或者待插入图片中列出了 `artifacts/...` 等路径,那么你需要在回答中使用这些图片
+ - 语法:`![图表说明](图片路径)`,其中所有的图片路径均为'artifacts/file_name'
+ - 插图位置需紧邻相应的有关内容,并跟随一段解释,说明图中元素的含义、能够验证或呈现的内容。
+ - 如果同样的图片,或重复的图片逻辑在前序步骤中已经出现,那么你就不要再使用他们了。
+ - **代码呈现**:不要粘贴大段代码。仅展示核心逻辑或关键参数,重点在于解释代码的**结果**和**意义**。
+ - **表格**:如果在工具调用结果中,出现了和本步骤相关的表格数据;或者你打算自己创建一个表格进行对比,那么你需要严格遵循markdown语法制作,或排版这些表格。
+
+ # 输出建议 (Textbook Quality)
+ 请模仿专业助教的回答风格,深入浅出地把当前步骤的内容讲清楚。
+ 结构上,一般情况下建议按照如下结构输出:
+ - **小标题**:使用 Markdown 二级或三级标题 (`##` 或 `###`) 清晰地概括当前步骤、及本步骤解决的内容(例如,S2: xxx)。
+ - **概念阐述**:如果涉及新概念,先给出严谨定义(引用来源)。
+ - **逻辑推导**:像讲课一样,详细展示推导过程,而不是只给结果。
+ - **融入多模态元素**:如果有,那么在讲解的适当地方插入本步骤包含的多模态信息,并按照他们的格式要求进行编排、解读。
+ - **小结**:简要总结当前步骤讲解的内容,直接输出一小段用于收尾的文字即可,不需要为他们加小标题(如`###小节`)
+
+user_template: |
+ ## 用户问题
+ {question}
+
+ ## 前序内容 (已完成的步骤)
+ {previous_context}
+
+ ## 当前步骤 (Step {step_id})
+ **目标**: {step_target}
+
+ ## 可用素材
+ ### 1. 知识库引用
+ {available_cite_details}
+
+ ### 2. 工具执行结果 (代码/搜索)
+ {tool_materials}
+
+ ### 3. 待插入图片(请逐条插入以下路径并解释)
+ {image_materials}
+
+ ## 任务
+ 撰写该步骤的正式回答,作为全文的第{step_id}步的正式输出:
diff --git a/src/agents/solve/prompts/zh/solve_loop/solve_agent.yaml b/src/agents/solve/prompts/zh/solve_loop/solve_agent.yaml
new file mode 100644
index 000000000..f07ca3cae
--- /dev/null
+++ b/src/agents/solve/prompts/zh/solve_loop/solve_agent.yaml
@@ -0,0 +1,68 @@
+system: |
+ # 角色定位
+ 你是 Solve 阶段的**工具策略家 (Tool Strategist)**。你的任务是根据当前的步骤目标 (Step Target),决定如何利用工具最高效地达成目标。
+
+ # 核心决策逻辑
+ 你需要判断当前步骤的性质,并选择最匹配的工具:
+
+ 1. **涉及计算、绘图、数据处理** -> **必选 `code_execution`**
+ - 必须编写完整、可运行的 Python 代码。
+ - 任何数学运算、图表绘制不要试图用语言模型"口算",必须交给代码。
+
+ 2. **涉及定义查找、原理确认、公式检索** -> **选择 `rag_naive` 或 `rag_hybrid`**
+ - 如果需要精准的公式或定义 -> `rag_naive`
+ - 如果需要理解复杂的机制或对比 -> `rag_hybrid`
+
+ 3. **涉及最新信息、课外知识** -> **选择 `web_search`**
+
+ 4. **纯逻辑推理、总结、或信息已充足** -> **选择 `none`**
+ - 直接在 `query` 字段中完成这一个step的规划
+
+ # 代码执行严格规范 (Critical)
+ 如果选择 `code_execution`,必须遵守:
+ - **全英文环境**:代码中的**变量名、函数名、注释、字符串数据、图表及其标题/标签/图例**必须全部使用**英文**。禁止出现任何中文字符。
+ - **无 GUI**:禁止 `plt.show()`。必须使用 `plt.savefig('filename.png')`。
+ - **路径简洁**:保存文件时直接写文件名 (如 `plot.png`),**不要**加 `artifacts/` 前缀。
+ - **库兼容性**:使用标准库 (numpy, matplotlib, scipy 等)。避免使用已废弃的参数。
+ - **自包含**:代码必须包含所有必要的 import 和变量定义,能够独立运行。
+
+ # 角色边界(严格遵循)
+ - **严格遵循步骤角色**:当前步骤的角色(计算、画图、推导、分析等)已经由规划阶段确定,你必须严格按照该角色执行,不要做其他角色的事情。
+ - 如果当前步骤是"分析",只做分析,不要画图、不要计算(除非分析本身需要简单计算)。
+ - 如果当前步骤是"画图",只画图,不要重复之前步骤已经画过的图。
+ - 如果当前步骤是"计算",只计算,不要画图。
+ - **检查已有工具调用**:在执行工具调用前,仔细查看`已有轨迹`,避免重复执行相同操作(特别是画图操作)。
+ - **适可而止**:一旦获得足够完成当前 Step 的信息,选择none作为工具的type,完成这一个步骤的回答。
+
+ # 输出格式
+ 直接输出 JSON 对象:
+ {
+ "thoughts": "简述你的策略思考...",
+ "tool_calls": [
+ {
+ "type": "code_execution | rag_naive | rag_hybrid | web_search | none",
+ "query": "具体的查询内容,或完整的 Python 代码块"
+ }
+ ]
+ }
+
+user_template: |
+ ## 用户问题
+ {question}
+
+ ## 当前步骤 (Step {current_step_id})
+ **目标**: {step_target}
+
+ ## 可用背景信息
+ {available_cite_text}
+
+ ## 已有轨迹
+ {current_tool_history}
+
+ ## 任务
+ 规划下一步的工具调用。
+ 1. **严格遵循步骤角色**:当前步骤的目标是 `{step_target}`,请严格按照该步骤的角色执行,不要做其他步骤的事情。
+ 2. **检查已有轨迹**:仔细查看`已有轨迹`,避免重复执行相同操作(特别是画图操作)。
+ 3. 如果需要代码,直接给出完整代码。
+ 4. 如果信息充足,type 选 `none` 并直接作答。
+ 5. 保持 JSON 格式合法。
diff --git a/src/agents/solve/prompts/zh/solve_loop/tool_agent.yaml b/src/agents/solve/prompts/zh/solve_loop/tool_agent.yaml
new file mode 100644
index 000000000..b860f8cc1
--- /dev/null
+++ b/src/agents/solve/prompts/zh/solve_loop/tool_agent.yaml
@@ -0,0 +1,37 @@
+system: |
+ # 角色定位
+ 你是**实验记录员 (Lab Recorder)**。你的职责是客观、清晰地记录工具(代码或搜索引擎)的执行结果,为后续的报告撰写提供素材。
+
+ # 核心任务
+ 将工具的"原始输出"转化为"结构化摘要"。
+
+ # 记录原则
+ 1. **客观真实**:忠实记录工具返回的数据、报错或文本,不添加主观臆测。
+ 2. **重点突出**:
+ - 如果是代码计算,记录关键的输入参数和输出数值。
+ - 如果是搜索,记录核心事实和来源。
+ 3. **简明扼要**:篇幅控制在 4-6 句话,高密度信息。
+
+ # 图片解读 (Crucial)
+ 如果工具执行生成了图片文件 (Artifacts 中包含 .png/.jpg):
+ - **必须**在摘要中专门一段描述该图片。
+ - **内容**:
+ - *意图*:这张图是用来展示什么的?(如 "绘制了正弦波的频谱")
+ - *特征*:图上看到了什么?(如 "在 50Hz 处有明显峰值")
+ - *结论*:这张图说明了什么?(如 "验证了滤波器的有效性")
+
+user_template: |
+ ## 工具类型
+ {tool_type}
+
+ ## 执行指令/代码
+ {query}
+
+ ## 原始返回结果
+ {raw_answer}
+
+ ## 任务
+ 撰写本次工具执行的摘要。
+ - 中文撰写。
+ - 必须包含图片解读(如果有生成图片)。
+ - 客观、简洁。
diff --git a/src/agents/solve/solve_loop/README.md b/src/agents/solve/solve_loop/README.md
new file mode 100644
index 000000000..33684184c
--- /dev/null
+++ b/src/agents/solve/solve_loop/README.md
@@ -0,0 +1,531 @@
+# Solve Loop - Solution Phase
+
+## Overview
+
+Solve Loop is the second phase of the dual-loop architecture, responsible for **strict problem solving and answer generation**. Based on knowledge collected by Analysis Loop, it uses block-based planning, step-by-step solving, and quality checking to generate high-quality final answers.
+
+## Architecture
+
+```
+┌─────────────────────────────────────────────────────────┐
+│ Solve Loop (Solution Phase) │
+│ │
+│ ┌──────┐ ┌─────────┐ ┌──────┐ ┌───────┐ │
+│ │ Plan │ -> │ Manager │ -> │Solve │ -> │ Check │ │
+│ └──────┘ └─────────┘ └──────┘ └───────┘ │
+│ │ │ │
+│ └───────────┘ │
+│ Loop Until Complete │
+│ │ │
+│ ▼ │
+│ ┌────────┐ │
+│ │ Format │ │
+│ └────────┘ │
+│ │ │
+│ SolveMemory │
+└─────────────────────────────────────────────────────────┘
+```
+
+## Core Agents
+
+### 1. PlanAgent
+
+**Function**: Generate problem-solving plan (blocks)
+
+**Workflow**:
+1. Analyze user question and knowledge from Analysis Loop
+2. Decompose problem into multiple logical blocks
+3. Define objectives for each block
+4. Save to `SolveMemory.plan`
+
+**Output**:
+```python
+{
+ 'num_blocks': 3,
+ 'num_steps': 0, # Initially 0, generated by Manager
+ 'blocks': [
+ {
+ 'block_id': 'b001',
+ 'goal': 'Understand the definition of linear convolution',
+ 'steps': [] # Filled by Manager
+ }
+ ]
+}
+```
+
+### 2. ManagerAgent
+
+**Function**: Plan specific steps (steps) for each block
+
+**Workflow**:
+1. Get next incomplete block
+2. Analyze block objectives
+3. Generate 3-5 concrete execution steps
+4. Save to `SolveMemory.plan.blocks[i].steps`
+
+**Output**:
+```python
+{
+ 'has_block': True,
+ 'block_id': 'b001',
+ 'steps_generated': 3,
+ 'steps': [
+ {
+ 'step_id': 's001',
+ 'plan': 'Quote definition and explain',
+ 'status': 'pending'
+ }
+ ]
+}
+```
+
+### 3. SolveAgent
+
+**Function**: Execute each step and generate content
+
+**Workflow**:
+1. Read current step plan
+2. Call tools if needed: RAG, Code Execution
+3. Generate step content
+4. Extract citations
+5. Return result (for Check Agent validation)
+
+**Supported Tools**:
+- `rag_search`: Knowledge base retrieval
+- `run_python_code`: Python code execution
+- `query_item`: Query numbered items
+
+**Output**:
+```python
+{
+ 'step_content': 'Linear convolution is defined as...',
+ 'citations': ['[rag-1]', '[code-1]'],
+ 'tool_logs': [
+ {
+ 'tool': 'rag_search',
+ 'status': 'success',
+ 'elapsed_ms': 1200
+ }
+ ],
+ 'raw_llm_response': '...' # For debugging
+}
+```
+
+### 4. CodeAgent
+
+**Function**: Execute Python code (called by SolveAgent)
+
+**Features**:
+- Secure sandbox environment
+- Support for NumPy, Matplotlib, and other common libraries
+- Automatic output and error capture
+- Timeout protection
+
+**Usage Example**:
+```python
+code_result = await code_agent.execute(
+ code="""
+import numpy as np
+x = np.array([1, 2, 3])
+h = np.array([0.5, 1, 0.5])
+y = np.convolve(x, h, mode='full')
+print(f"Convolution result: {y}")
+""",
+ timeout=10
+)
+```
+
+### 5. CheckAgent
+
+**Function**: Validate step quality and provide optimization suggestions
+
+**Workflow**:
+1. Read SolveAgent output
+2. Check content quality:
+ - Logical completeness
+ - Citation clarity
+ - Calculation correctness
+ - Format compliance
+3. Provide verdict: `pass` or `needs_revision`
+4. If revision needed, provide specific suggestions
+
+**Verdict Standards**:
+- `pass`: Content quality acceptable, proceed to next step
+- `needs_revision`: Needs optimization with specific issues
+
+**Output**:
+```python
+{
+ 'verdict': 'pass', # or 'needs_revision'
+ 'comment': 'Content complete, citations sufficient',
+ 'integrated_content': '...', # Optional: integrated content
+ 'raw_response': '...' # For debugging
+}
+```
+
+**Retry Mechanism**:
+- If `needs_revision`, SolveAgent regenerates
+- Maximum `max_solve_correction_iterations` retries (default 3)
+- After max attempts, logs issue but continues
+
+### 6. PrecisionAnswerAgent (Optional)
+
+**Function**: Generate precise, concise answer
+
+**Features**:
+- Extract key information
+- Generate 1-2 paragraph brief answer
+- Suitable for quick reference
+
+**Configuration**:
+```yaml
+agents:
+ precision_answer_agent:
+ enabled: false # Disabled by default
+```
+
+## Memory System
+
+### SolveMemory
+
+Persistent JSON memory recording the entire Solve Loop process.
+
+**Structure**:
+```python
+{
+ "user_question": "What is linear convolution?",
+ "plan": {
+ "blocks": [
+ {
+ "block_id": "b001",
+ "goal": "Understand the definition of linear convolution",
+ "steps": [
+ {
+ "step_id": "s001",
+ "plan": "Quote definition and explain",
+ "status": "completed", # pending/in_progress/completed
+ "content": "Linear convolution is...",
+ "citations": ["[rag-1]", "[code-1]"],
+ "tool_logs": [...]
+ }
+ ]
+ }
+ ]
+ },
+ "progress": {
+ "status": "completed", # not_started/in_progress/completed
+ "current_block": "b001",
+ "current_step": "s001",
+ "completed_blocks": ["b001"],
+ "completed_steps": ["s001", "s002"]
+ },
+ "metadata": {
+ "total_blocks": 3,
+ "total_steps": 8,
+ "completed_steps": 8
+ }
+}
+```
+
+**Storage Location**: `{output_dir}/solve_memory.json`
+
+## Citation Management
+
+### CitationManager
+
+Global singleton managing numbering and formatting of all citations.
+
+**Features**:
+- Auto-assign citation numbers ([rag-1], [web-1], ...)
+- Deduplication: same content gets one number
+- Reset support (per task)
+
+**Usage**:
+```python
+from solve_loop.citation_manager import CitationManager
+
+manager = CitationManager()
+manager.reset() # Reset numbering
+
+# Add citation
+cite_id = manager.add_citation("Citation content", source="k001")
+# Returns: "[rag-1]"
+
+# Get all citations
+citations = manager.get_all_citations()
+# Returns: [{'id': '[rag-1]', 'content': '...', 'source': 'k001'}]
+```
+
+## Configuration
+
+Configure Solve Loop in `config.yaml`:
+
+```yaml
+system:
+ max_solve_correction_iterations: 3 # Max retries per step
+
+agents:
+ plan_agent:
+ enabled: true
+ model: "gpt-4o"
+ temperature: 0.3
+
+ manager_agent:
+ enabled: true
+ model: "gpt-4o"
+ temperature: 0.3
+
+ solve_agent:
+ enabled: true
+ model: "gpt-4o"
+ temperature: 0.4
+
+ code_agent:
+ enabled: true
+ timeout: 10 # Code execution timeout (seconds)
+
+ check_agent:
+ enabled: true
+ model: "gpt-4o"
+ temperature: 0.3
+
+ precision_answer_agent:
+ enabled: false # Optional
+ model: "gpt-4o"
+ temperature: 0.2
+```
+
+## Usage Example
+
+```python
+from solve_agents.memory import SolveMemory, InvestigateMemory
+from solve_agents.solve_loop import (
+ PlanAgent,
+ ManagerAgent,
+ SolveAgent,
+ CheckAgent,
+)
+
+# Load Analysis Loop results
+investigate_memory = InvestigateMemory.load(output_dir)
+
+# Create Solve memory
+solve_memory = SolveMemory.load_or_create(
+ output_dir="./output",
+ user_question="What is linear convolution?"
+)
+
+# Initialize Agents
+plan_agent = PlanAgent(config, api_key, base_url)
+manager_agent = ManagerAgent(config, api_key, base_url)
+solve_agent = SolveAgent(config, api_key, base_url)
+check_agent = CheckAgent(config, api_key, base_url)
+
+# 1. Plan: Generate blocks
+plan_result = await plan_agent.process(
+ question=question,
+ investigate_memory=investigate_memory,
+ solve_memory=solve_memory
+)
+
+# 2. Solve Loop
+while solve_memory.progress.status != "completed":
+ # Manager: Generate steps
+ manager_result = await manager_agent.process(
+ question=question,
+ solve_memory=solve_memory,
+ investigate_memory=investigate_memory
+ )
+
+ if not manager_result['has_block']:
+ break
+
+ # Solve + Check loop
+ current_step = solve_memory.get_current_step()
+
+ for attempt in range(max_retries):
+ # Solve: Execute step
+ solve_result = await solve_agent.process(
+ question=question,
+ current_step=current_step,
+ solve_memory=solve_memory,
+ investigate_memory=investigate_memory,
+ kb_name="ai_textbook",
+ output_dir="./output"
+ )
+
+ # Check: Validate quality
+ check_result = await check_agent.process(
+ question=question,
+ current_step_result=solve_result,
+ solve_memory=solve_memory,
+ investigate_memory=investigate_memory
+ )
+
+ if check_result['verdict'] == 'pass':
+ # Mark as complete
+ solve_memory.complete_step(
+ step_id=current_step.step_id,
+ content=solve_result['step_content'],
+ citations=solve_result['citations'],
+ tool_logs=solve_result['tool_logs']
+ )
+ break
+
+# Save
+solve_memory.save()
+with open(f"{output_dir}/final_answer.md", 'w') as f:
+ f.write(format_result['final_answer'])
+```
+
+## Workflow Example
+
+**Question**: "What is linear convolution?"
+
+**Plan Phase**:
+Generate 3 blocks:
+- `b001`: Understand linear convolution definition
+- `b002`: Master calculation methods
+- `b003`: Learn application scenarios
+
+**Block 1 (b001)**:
+1. **Manager**: Generate 3 steps
+ - `s001`: Quote definition and explain
+ - `s002`: Explain mathematical expression
+ - `s003`: Provide examples
+2. **Solve + Check**: Execute stepwise
+ - `s001`: Pass (1 attempt)
+ - `s002`: Needs revision (pass on 2nd attempt)
+ - `s003`: Pass (1 attempt)
+
+**Block 2 (b002)**:
+1. **Manager**: Generate 2 steps
+ - `s004`: Explain calculation steps
+ - `s005`: Demonstrate with code
+2. **Solve + Check**: Execute stepwise
+ - `s004`: Pass
+ - `s005`: Call CodeAgent for execution, pass
+
+**Block 3 (b003)**:
+1. **Manager**: Generate 2 steps
+ - `s006`: List application domains
+ - `s007`: Summarize pros and cons
+2. **Solve + Check**: Execute stepwise
+ - `s006`: Pass
+ - `s007`: Pass
+
+**Format Phase**:
+Integrate all steps, generate final answer, format 5 citations
+
+## Key Features
+
+### 1. Block-Based Planning
+- Decompose complex problems into multiple blocks
+- Each block has clear objectives
+- Supports parallel thinking (though sequential execution)
+
+### 2. Step-by-Step Solving
+- Each block decomposes into concrete steps
+- Execute sequentially, accumulate context
+- Support tool calls (RAG, code execution)
+
+### 3. Quality Assurance
+- Check Agent cyclically validates
+- Automatic error correction
+- Maximum 3 retries
+
+### 4. Citation Management
+- Auto-assign numbering
+- Deduplication handling
+- Formatted output
+
+### 5. Persistent Memory
+- JSON format storage
+- Supports checkpoint resumption
+- Facilitates debugging and review
+
+## Debugging and Monitoring
+
+### View Memory Files
+
+```bash
+cat output/solve_memory.json | jq .
+```
+
+### Monitor Execution
+
+Logs display detailed information for each step:
+
+```
+--- Step 1: s001 ---
+ Plan: Quote definition and explain
+ [Solve] Generating content...
+ [Check] Verdict: pass
+ ✓ Step s001 completed
+```
+
+### Performance Statistics
+
+```python
+metadata = solve_memory.metadata
+print(f"Total blocks: {metadata['total_blocks']}")
+print(f"Total steps: {metadata['total_steps']}")
+print(f"Completed: {metadata['completed_steps']}")
+```
+
+### View Citations
+
+```python
+from solve_loop.citation_manager import CitationManager
+
+manager = CitationManager()
+citations = manager.get_all_citations()
+for cite in citations:
+ print(f"{cite['id']}: {cite['content'][:50]}...")
+```
+
+## Common Questions
+
+**Q: How to adjust maximum retries per step?**
+
+Set in `config.yaml`:
+```yaml
+system:
+ max_solve_correction_iterations: 3 # Default 3
+```
+
+**Q: How to enable precision answer?**
+
+```yaml
+agents:
+ precision_answer_agent:
+ enabled: true
+```
+
+**Q: Code execution timeout, what to do?**
+
+Increase timeout:
+```yaml
+agents:
+ code_agent:
+ timeout: 20 # Increase to 20 seconds
+```
+
+**Q: How to view Check Agent feedback?**
+
+Check logs for `[Check]` section or inspect `tool_logs` in `solve_memory.json`.
+
+**Q: How to manually reset CitationManager?**
+
+```python
+from solve_loop.citation_manager import CitationManager
+
+manager = CitationManager()
+manager.reset()
+```
+
+---
+
+**Related Documentation**:
+- [Analysis Loop README](../analysis_loop/README.md)
+- [Main README](../README.md)
diff --git a/src/agents/solve/solve_loop/__init__.py b/src/agents/solve/solve_loop/__init__.py
new file mode 100644
index 000000000..65380aef9
--- /dev/null
+++ b/src/agents/solve/solve_loop/__init__.py
@@ -0,0 +1,22 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+"""
+Solve Loop - Solve loop (Manager → Solve → Check → Format)
+Based on Analysis output, plan and execute problem-solving process, generate high-quality answers
+"""
+
+from .citation_manager import CitationManager
+from .manager_agent import ManagerAgent
+from .precision_answer_agent import PrecisionAnswerAgent
+from .response_agent import ResponseAgent
+from .solve_agent import SolveAgent
+from .tool_agent import ToolAgent
+
+__all__ = [
+ "ManagerAgent",
+ "SolveAgent",
+ "ResponseAgent",
+ "PrecisionAnswerAgent",
+ "ToolAgent",
+ "CitationManager",
+]
diff --git a/src/agents/solve/solve_loop/citation_manager.py b/src/agents/solve/solve_loop/citation_manager.py
new file mode 100644
index 000000000..2de4a2c7a
--- /dev/null
+++ b/src/agents/solve/solve_loop/citation_manager.py
@@ -0,0 +1,74 @@
+#!/usr/bin/env python
+"""
+CitationManager - Citation number manager
+Maintains singleton throughout Solve process, ensures citation numbers are globally unique and continuous
+"""
+
+from typing import Any, Optional
+
+
+class CitationManager:
+ """Citation number manager"""
+
+ _instance: Optional["CitationManager"] = None
+
+ def __new__(cls):
+ """Singleton pattern"""
+ if cls._instance is None:
+ cls._instance = super().__new__(cls)
+ cls._instance._initialized = False
+ return cls._instance
+
+ def __init__(self):
+ """Initialize citation manager"""
+ if self._initialized:
+ return
+
+ self.citation_counter = 0
+ self.citation_map: dict[str, dict[str, Any]] = {} # {citation_id: citation_info}
+ self._initialized = True
+
+ def allocate_citation_id(
+ self,
+ knowledge_id: str,
+ reference_id: str | None = None,
+ source: str | None = None,
+ content: str | None = None,
+ ) -> str:
+ """
+ Allocate citation number
+
+ Args:
+ knowledge_id: Knowledge item ID
+ reference_id: reference_id from KnowledgeItem.citations (e.g., "[1]")
+ source: Citation source
+ content: Citation content
+
+ Returns:
+ str: Citation number (e.g., "[1]")
+ """
+ self.citation_counter += 1
+ citation_id = f"[{self.citation_counter}]"
+
+ self.citation_map[citation_id] = {
+ "knowledge_id": knowledge_id,
+ "reference_id": reference_id, # From KnowledgeItem.citations
+ "source": source,
+ "content": content,
+ "citation_id": citation_id,
+ }
+
+ return citation_id
+
+ def get_citation_info(self, citation_id: str) -> dict[str, Any] | None:
+ """Get citation information"""
+ return self.citation_map.get(citation_id)
+
+ def get_all_citations(self) -> dict[str, dict[str, Any]]:
+ """Get all citation mappings"""
+ return self.citation_map.copy()
+
+ def reset(self):
+ """Reset citation manager (for new task)"""
+ self.citation_counter = 0
+ self.citation_map = {}
diff --git a/src/agents/solve/solve_loop/manager_agent.py b/src/agents/solve/solve_loop/manager_agent.py
new file mode 100644
index 000000000..d3773d769
--- /dev/null
+++ b/src/agents/solve/solve_loop/manager_agent.py
@@ -0,0 +1,262 @@
+#!/usr/bin/env python
+"""
+ManagerAgent - Manager (Refactored: directly plans step-level solution steps)
+Based on user question and knowledge chain, plans solution steps
+"""
+
+from pathlib import Path
+import sys
+from typing import Any
+
+# Add project root to path
+project_root = Path(__file__).parent.parent.parent.parent
+sys.path.insert(0, str(project_root))
+
+from ..base_agent import BaseAgent
+from ..memory import InvestigateMemory, SolveChainStep, SolveMemory
+from ..utils.json_utils import extract_json_from_text
+
+
+class ManagerAgent(BaseAgent):
+ """Manager Agent - Plans solution steps"""
+
+ def __init__(self, config: dict[str, Any], api_key: str, base_url: str, token_tracker=None):
+ super().__init__(
+ config=config,
+ api_key=api_key,
+ base_url=base_url,
+ agent_name="manager_agent",
+ use_prompt_loader=True,
+ token_tracker=token_tracker,
+ )
+
+ async def process(
+ self,
+ question: str,
+ investigate_memory: InvestigateMemory,
+ solve_memory: SolveMemory,
+ verbose: bool = True,
+ ) -> dict[str, Any]:
+ """
+ Process management workflow - plan solution steps
+
+ Args:
+ question: User question
+ investigate_memory: Investigation memory (contains knowledge chain)
+ solve_memory: Solve memory
+ verbose: Whether to print detailed information
+
+ Returns:
+ dict: Management result
+ """
+ stage_label = "Plan"
+ self.logger.log_stage_progress(
+ stage_label, "start", f"question={question[:60]}{'...' if len(question) > 60 else ''}"
+ )
+
+ # 1. Check if steps already exist
+ if solve_memory.solve_chains:
+ steps_count = len(solve_memory.solve_chains)
+ self.logger.log_stage_progress(stage_label, "skip", f"Already has {steps_count} steps")
+ return {
+ "has_steps": True,
+ "steps_count": steps_count,
+ "num_steps": steps_count, # Maintain compatibility
+ "message": "Steps already exist, skipping planning",
+ }
+
+ # 2. Build context
+ context = self._build_context(question=question, investigate_memory=investigate_memory)
+
+ # 3. Build Prompt
+ system_prompt = self._build_system_prompt()
+ user_prompt = self._build_user_prompt(context)
+
+ # 4. Call LLM (requires JSON format output)
+ response = await self.call_llm(
+ user_prompt=user_prompt,
+ system_prompt=system_prompt,
+ verbose=verbose,
+ stage=stage_label,
+ response_format={"type": "json_object"}, # Force JSON
+ )
+
+ # 5. Parse output and create StepItem
+ steps = self._parse_response(response, investigate_memory)
+
+ # 6. Add steps to solve_memory
+ solve_memory.create_chains(steps)
+ solve_memory.save()
+
+ steps_count = len(steps)
+ self.logger.log_stage_progress(stage_label, "complete", f"Generated {steps_count} steps")
+ return {
+ "has_steps": True,
+ "steps_count": steps_count,
+ "num_steps": steps_count, # Maintain compatibility
+ "message": f"Generated {steps_count} steps",
+ }
+
+ def _build_context(
+ self, question: str, investigate_memory: InvestigateMemory
+ ) -> dict[str, Any]:
+ """Build context"""
+ # Get knowledge chain information (cite_id + summary)
+ knowledge_info = []
+ for knowledge in investigate_memory.knowledge_chain:
+ if knowledge.summary: # Only use knowledge with summary
+ knowledge_info.append(
+ {
+ "cite_id": knowledge.cite_id,
+ "tool_type": knowledge.tool_type,
+ "query": knowledge.query,
+ "summary": knowledge.summary,
+ }
+ )
+
+ knowledge_text = ""
+ for info in knowledge_info:
+ knowledge_text += f"\n{info['cite_id']} [{info['tool_type']}]\n"
+ knowledge_text += f" Query: {info['query']}\n"
+ knowledge_text += f" Summary: {info['summary']}\n"
+
+ remaining_questions = []
+ if investigate_memory and getattr(investigate_memory, "reflections", None):
+ remaining_questions = investigate_memory.reflections.remaining_questions or []
+
+ reflections_summary = (
+ "\n".join(f"- {q}" for q in remaining_questions)
+ if remaining_questions
+ else "(No remaining questions)"
+ )
+
+ knowledge_summary_text = knowledge_text if knowledge_text else "(No research information)"
+
+ return {
+ "question": question,
+ "knowledge_info": knowledge_info,
+ "knowledge_text": knowledge_summary_text,
+ "knowledge_chain_summary": knowledge_summary_text,
+ "reflections_summary": reflections_summary,
+ }
+
+ def _build_system_prompt(self) -> str:
+ """Build system prompt"""
+ prompt = self.get_prompt("system") if self.has_prompts() else None
+ if not prompt:
+ raise ValueError(
+ "ManagerAgent missing system prompt, please configure system section in prompts/zh/solve_loop/manager_agent.yaml."
+ )
+ return prompt
+
+ def _build_user_prompt(self, context: dict[str, Any]) -> str:
+ """Build user prompt"""
+ template = self.get_prompt("user_template") if self.has_prompts() else None
+ if not template:
+ raise ValueError(
+ "ManagerAgent missing user prompt template, please configure user_template in prompts/zh/solve_loop/manager_agent.yaml."
+ )
+ return template.format(**context)
+
+ def _parse_response(
+ self, response: str, investigate_memory: InvestigateMemory
+ ) -> list[SolveChainStep]:
+ """Parse LLM output (JSON format), create solve-chain steps"""
+ steps: list[SolveChainStep] = []
+ knowledge_ids = {k.cite_id for k in investigate_memory.knowledge_chain}
+
+ # Use json_utils to extract JSON
+ parsed_data = extract_json_from_text(response)
+
+ if not parsed_data or not isinstance(parsed_data, dict):
+ raise ValueError(
+ f"Failed to parse valid JSON object from LLM output. Original output: {response[:200]}..."
+ )
+
+ steps_data = parsed_data.get("steps", [])
+ if not isinstance(steps_data, list):
+ raise ValueError(f"'steps' field in JSON is not an array. Parsed result: {parsed_data}")
+
+ if not steps_data:
+ raise ValueError("'steps' array in JSON is empty, please check LLM output.")
+
+ # Parse each step
+ for idx, step_data in enumerate(steps_data, 1):
+ if not isinstance(step_data, dict):
+ self.logger.warning(
+ f"[ManagerAgent] Skipping invalid step data (index {idx}): {step_data}"
+ )
+ continue
+
+ # Get step_id
+ step_id = step_data.get("step_id", "").strip()
+ if not step_id:
+ step_id = f"S{idx}"
+ elif not step_id.upper().startswith("S"):
+ step_id = f"S{step_id}"
+
+ # Get role and target
+ role = step_data.get("role", "").strip()
+ target = step_data.get("target", "").strip()
+
+ # If target already contains role, use directly; otherwise combine
+ if target:
+ if ":" in target or ":" in target:
+ step_target = target
+ elif role:
+ step_target = f"{role}:{target}"
+ else:
+ step_target = target
+ else:
+ raise ValueError(f"Step {step_id} missing 'target' field")
+
+ # Get cite_ids
+ cite_ids_raw = step_data.get("cite_ids", [])
+ if not isinstance(cite_ids_raw, list):
+ # Compatible with string format
+ if isinstance(cite_ids_raw, str):
+ cite_ids_raw = [cite_ids_raw] if cite_ids_raw and cite_ids_raw != "none" else []
+ else:
+ cite_ids_raw = []
+
+ # Clean and normalize cite_ids
+ filtered_cites = []
+ for cite in cite_ids_raw:
+ if not cite or cite == "none":
+ continue
+ # Ensure format is [xxx]
+ cleaned = str(cite).strip()
+ if not cleaned.startswith("["):
+ cleaned = f"[{cleaned.strip('[] ')}]"
+
+ # Filter invalid cite
+ if cleaned in knowledge_ids:
+ filtered_cites.append(cleaned)
+ else:
+ self.logger.warning(
+ f"[ManagerAgent] Skipping unknown cite_id {cleaned} (not in knowledge chain)"
+ )
+
+ # Create step
+ steps.append(
+ SolveChainStep(
+ step_id=step_id,
+ step_target=step_target,
+ available_cite=list(dict.fromkeys(filtered_cites)), # Remove duplicates
+ status="undone",
+ )
+ )
+
+ if not steps:
+ raise ValueError("Failed to parse any valid steps, please check LLM output format.")
+
+ logger = getattr(self, "logger", None)
+ if logger is not None:
+ logger.info(f"[ManagerAgent._parse_response] Parsed {len(steps)} solve-chain steps")
+ for step in steps:
+ logger.info(f" - {step.step_id}: {step.step_target}")
+ logger.info(
+ f" Available citations: {', '.join(step.available_cite) or '(none)'}"
+ )
+
+ return steps
diff --git a/src/agents/solve/solve_loop/precision_answer_agent.py b/src/agents/solve/solve_loop/precision_answer_agent.py
new file mode 100644
index 000000000..e05613d83
--- /dev/null
+++ b/src/agents/solve/solve_loop/precision_answer_agent.py
@@ -0,0 +1,86 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+"""
+PrecisionAnswerAgent - Precision answer generator (two-stage)
+"""
+
+from pathlib import Path
+import sys
+from typing import Any, Dict
+
+project_root = Path(__file__).parent.parent.parent.parent
+if str(project_root) not in sys.path:
+ sys.path.insert(0, str(project_root))
+
+from ..base_agent import BaseAgent
+
+
+class PrecisionAnswerAgent(BaseAgent):
+ """Staged precision answer"""
+
+ def __init__(self, config: Dict[str, Any], api_key: str, base_url: str, token_tracker=None):
+ super().__init__(
+ config=config,
+ api_key=api_key,
+ base_url=base_url,
+ agent_name="precision_answer_agent",
+ use_prompt_loader=True,
+ token_tracker=token_tracker,
+ )
+
+ async def process(
+ self, question: str, detailed_answer: str, verbose: bool = True
+ ) -> Dict[str, Any]:
+ decision = await self._should_generate(question, verbose)
+ if not decision["needs_precision"]:
+ return {
+ "needs_precision": False,
+ "precision_answer": "",
+ "final_answer": detailed_answer,
+ }
+
+ precision_answer = await self._generate_precision_answer(
+ question=question, detailed_answer=detailed_answer, verbose=verbose
+ )
+ return {
+ "needs_precision": True,
+ "precision_answer": precision_answer,
+ "final_answer": detailed_answer,
+ }
+
+ async def _should_generate(self, question: str, verbose: bool) -> Dict[str, Any]:
+ system_prompt = self.get_prompt("decision_system") if self.has_prompts() else None
+ if not system_prompt:
+ raise ValueError(
+ "PrecisionAnswerAgent missing decision_system prompt, please configure decision_system in prompts/{lang}/solve_loop/precision_answer_agent.yaml"
+ )
+ template = self.get_prompt("decision_user_template") if self.has_prompts() else None
+ if not template:
+ raise ValueError(
+ "PrecisionAnswerAgent missing decision_user_template, please configure decision_user_template in prompts/{lang}/solve_loop/precision_answer_agent.yaml"
+ )
+ user_prompt = template.format(question=question)
+ response = await self.call_llm(
+ user_prompt=user_prompt, system_prompt=system_prompt, verbose=verbose
+ )
+ needs_precision = response.strip().upper().startswith("Y")
+ return {"needs_precision": needs_precision, "raw_decision": response.strip()}
+
+ async def _generate_precision_answer(
+ self, question: str, detailed_answer: str, verbose: bool
+ ) -> str:
+ system_prompt = self.get_prompt("precision_system") if self.has_prompts() else None
+ if not system_prompt:
+ raise ValueError(
+ "PrecisionAnswerAgent missing precision_system prompt, please configure precision_system in prompts/{lang}/solve_loop/precision_answer_agent.yaml"
+ )
+ template = self.get_prompt("precision_user_template") if self.has_prompts() else None
+ if not template:
+ raise ValueError(
+ "PrecisionAnswerAgent missing precision_user_template, please configure precision_user_template in prompts/{lang}/solve_loop/precision_answer_agent.yaml"
+ )
+ user_prompt = template.format(question=question, detailed_answer=detailed_answer)
+ response = await self.call_llm(
+ user_prompt=user_prompt, system_prompt=system_prompt, verbose=verbose
+ )
+ return response.strip()
diff --git a/src/agents/solve/solve_loop/response_agent.py b/src/agents/solve/solve_loop/response_agent.py
new file mode 100644
index 000000000..9a9a5e8ab
--- /dev/null
+++ b/src/agents/solve/solve_loop/response_agent.py
@@ -0,0 +1,289 @@
+#!/usr/bin/env python
+"""
+ResponseAgent - Step response generator
+Based on materials in solve-chain, generates formal response for current step
+"""
+
+from pathlib import Path
+import re
+import sys
+from typing import Any
+
+project_root = Path(__file__).parent.parent.parent.parent
+if str(project_root) not in sys.path:
+ sys.path.insert(0, str(project_root))
+
+from ..base_agent import BaseAgent
+from ..memory import CitationMemory, InvestigateMemory, SolveChainStep, SolveMemory
+
+
+class ResponseAgent(BaseAgent):
+ """Response generator Agent"""
+
+ def __init__(self, config: dict[str, Any], api_key: str, base_url: str, token_tracker=None):
+ super().__init__(
+ config=config,
+ api_key=api_key,
+ base_url=base_url,
+ agent_name="response_agent",
+ use_prompt_loader=True,
+ token_tracker=token_tracker,
+ )
+ # Store citation configuration
+ self.enable_citations = config.get("system", {}).get("enable_citations", True)
+
+ async def process(
+ self,
+ question: str,
+ step: SolveChainStep,
+ solve_memory: SolveMemory,
+ investigate_memory: InvestigateMemory,
+ citation_memory: CitationMemory,
+ output_dir: str | None = None,
+ verbose: bool = True,
+ accumulated_response: str = "",
+ ) -> dict[str, Any]:
+ if not step:
+ return {"step_response": "(No pending step)"}
+
+ context = self._build_context(
+ question=question,
+ step=step,
+ solve_memory=solve_memory,
+ investigate_memory=investigate_memory,
+ citation_memory=citation_memory,
+ output_dir=output_dir,
+ accumulated_response=accumulated_response,
+ )
+
+ system_prompt = self._build_system_prompt(context["image_materials"])
+ user_prompt = self._build_user_prompt(context)
+
+ response = await self.call_llm(
+ user_prompt=user_prompt, system_prompt=system_prompt, verbose=verbose
+ )
+
+ # Directly use LLM's raw output as step_response, no parsing
+ step_response = response.strip() if response else ""
+ used_citations = self._extract_used_citations(step_response, step)
+ solve_memory.submit_step_response(
+ step_id=step.step_id, response=step_response, used_citations=used_citations
+ )
+ solve_memory.save()
+
+ return {
+ "step_id": step.step_id,
+ "step_response": step_response,
+ "used_citations": used_citations,
+ "raw_response": response,
+ }
+
+ # ------------------------------------------------------------------ #
+ # Prompt Building
+ # ------------------------------------------------------------------ #
+ def _build_context(
+ self,
+ question: str,
+ step: SolveChainStep,
+ solve_memory: SolveMemory,
+ investigate_memory: InvestigateMemory,
+ citation_memory: CitationMemory,
+ output_dir: str | None,
+ accumulated_response: str = "",
+ ) -> dict[str, Any]:
+ available_cite_details = self._format_available_cite(step, investigate_memory)
+ tool_materials, image_materials = self._format_tool_materials(step, output_dir)
+ citation_details = self._format_citation_details(step, citation_memory)
+
+ return {
+ "question": question,
+ "step_id": step.step_id,
+ "step_target": step.step_target,
+ "available_cite_details": available_cite_details,
+ "tool_materials": tool_materials,
+ "citation_details": citation_details,
+ "image_materials": image_materials,
+ "previous_context": accumulated_response
+ or "(No previous content, this is the first step)",
+ }
+
+ def _build_system_prompt(self, image_materials: list[str]) -> str:
+ base_prompt = self.get_prompt("system") if self.has_prompts() else None
+ if not base_prompt:
+ raise ValueError(
+ "ResponseAgent missing system prompt, please configure in prompts/zh/solve_loop/response_agent.yaml."
+ )
+
+ # Add citation disable instruction if citations are disabled
+ citation_instruction = ""
+ if not self.enable_citations:
+ citation_instruction_yaml = self.get_prompt("citation_instruction_disabled")
+ if citation_instruction_yaml:
+ citation_instruction = citation_instruction_yaml
+ else:
+ citation_instruction = "\n\n**Important: Citation Feature Disabled**\n"
+
+ if image_materials:
+ image_list = "\n".join([f" - {img}" for img in image_materials])
+ image_instruction_template = self.get_prompt("image_instruction")
+ if image_instruction_template:
+ image_instruction = image_instruction_template.format(image_list=image_list)
+ else:
+ image_instruction = f"\n\n**Image files to insert**:\n{image_list}\n"
+ return base_prompt + citation_instruction + image_instruction
+
+ return base_prompt + citation_instruction
+
+ def _build_user_prompt(self, context: dict[str, Any]) -> str:
+ template = self.get_prompt("user_template") if self.has_prompts() else None
+ if not template:
+ raise ValueError(
+ "ResponseAgent missing user_template, please configure user_template in prompts/{lang}/solve_loop/response_agent.yaml"
+ )
+
+ # Format image_materials as clear text list
+ image_materials = context.get("image_materials", [])
+ if image_materials:
+ image_text = "\n".join([f"- {img}" for img in image_materials])
+ else:
+ image_text = "(No image files)"
+
+ # Create new context, format image_materials as text
+ formatted_context = context.copy()
+ formatted_context["image_materials"] = image_text
+
+ return template.format(**formatted_context)
+
+ # ------------------------------------------------------------------ #
+ # Material Organization
+ # ------------------------------------------------------------------ #
+ def _format_available_cite(
+ self, step: SolveChainStep, investigate_memory: InvestigateMemory
+ ) -> str:
+ if not step.available_cite:
+ return "(No available knowledge chain)"
+ lines: list[str] = []
+ for cite in step.available_cite:
+ knowledge = next(
+ (k for k in investigate_memory.knowledge_chain if k.cite_id == cite), None
+ )
+ if not knowledge:
+ continue
+ summary = knowledge.summary or knowledge.raw_result[:300]
+ lines.append(
+ f"{cite} [{knowledge.tool_type}]\n"
+ f" Query: {knowledge.query}\n"
+ f" Summary: {summary}\n"
+ f" Raw: {knowledge.raw_result[:300]}..."
+ )
+ return "\n".join(lines) if lines else "(No matching knowledge)"
+
+ def _format_tool_materials(
+ self, step: SolveChainStep, output_dir: str | None
+ ) -> tuple[str, list[str]]:
+ if not step.tool_calls:
+ return "(No tool calls yet)", []
+
+ lines: list[str] = []
+ images: list[str] = []
+ seen_images: set[str] = set()
+
+ def _append_image(path_str: str):
+ normalized = str(path_str).replace("\\", "/")
+ if normalized and normalized not in seen_images:
+ images.append(normalized)
+ seen_images.add(normalized)
+
+ for call in step.tool_calls:
+ summary = call.summary or "(Summary pending)"
+ raw_preview = (call.raw_answer or "")[:500]
+ lines.append(
+ f"{call.tool_type} | cite_id={call.cite_id} | Status={call.status}\n"
+ f"Query: {call.query}\n"
+ f"Summary: {summary}\n"
+ f"Raw excerpt: {raw_preview}"
+ )
+ # Priority: use recorded relative paths, then absolute paths, finally fall back to original artifacts list
+ artifact_rel_paths = call.metadata.get("artifact_rel_paths") if call.metadata else None
+ artifact_paths = call.metadata.get("artifact_paths") if call.metadata else None
+ artifacts = call.metadata.get("artifacts") if call.metadata else None
+
+ if artifact_rel_paths:
+ for rel_path in artifact_rel_paths:
+ _append_image(rel_path)
+
+ if artifact_paths:
+ # Use absolute paths, but convert to relative paths relative to output_dir for display
+ for abs_path in artifact_paths:
+ path = Path(abs_path)
+ if path.suffix.lower() in {".png", ".jpg", ".jpeg", ".svg", ".gif", ".bmp"}:
+ # If output_dir exists, calculate relative path; otherwise use absolute path
+ if output_dir:
+ try:
+ rel_path = path.relative_to(Path(output_dir))
+ _append_image(str(rel_path))
+ except ValueError:
+ # If cannot calculate relative path, use filename
+ _append_image(path.name)
+ else:
+ _append_image(path.name)
+ elif artifacts:
+ # Fall back to using artifacts list
+ for artifact in artifacts:
+ path = Path(artifact)
+ if path.suffix.lower() in {".png", ".jpg", ".jpeg", ".svg", ".gif", ".bmp"}:
+ # Build relative path to artifacts directory
+ rel_path = Path("artifacts") / path.name
+ _append_image(str(rel_path))
+ return "\n\n".join(lines), images
+
+ def _format_citation_details(
+ self, step: SolveChainStep, citation_memory: CitationMemory
+ ) -> str:
+ # If citations are disabled, return empty string
+ if not self.enable_citations:
+ return "(Citations disabled)"
+
+ cite_ids = list(
+ dict.fromkeys(
+ step.available_cite + [tc.cite_id for tc in step.tool_calls if tc.cite_id]
+ )
+ )
+ if not cite_ids:
+ return "(No citations)"
+ lines: list[str] = []
+ for cite_id in cite_ids:
+ citation = citation_memory.get_citation(cite_id)
+ if not citation:
+ continue
+ summary = citation.content or citation.raw_result[:200]
+ lines.append(f"- {cite_id} [{citation.tool_type}] Query: {citation.query}")
+ if summary:
+ lines.append(f" Summary: {summary[:300]}")
+ return "\n".join(lines) if lines else "(Citation information missing)"
+
+ # ------------------------------------------------------------------ #
+ # Citation Extraction
+ # ------------------------------------------------------------------ #
+ def _extract_used_citations(self, content: str, step: SolveChainStep) -> list[str]:
+ # If citations are disabled, return empty list
+ if not self.enable_citations:
+ return []
+
+ if not content:
+ return []
+ # Allow standard English brackets [cite], also tolerate some error formats (like Chinese full-width brackets【cite】), uniformly normalize to [cite]
+ pattern = re.compile(r"\[([^\]\[]+)\](?!\()|【([^】\[]+)】")
+ matches = pattern.findall(content)
+ normalized: list[str] = []
+ for match in matches:
+ candidate = match[0] or match[1]
+ if not candidate:
+ continue
+ normalized.append(f"[{candidate.strip()}]")
+ allowed = set(step.available_cite + [tc.cite_id for tc in step.tool_calls if tc.cite_id])
+ ordered: list[str] = []
+ for cite in normalized:
+ if cite in allowed and cite not in ordered:
+ ordered.append(cite)
+ return ordered
diff --git a/src/agents/solve/solve_loop/solve_agent.py b/src/agents/solve/solve_loop/solve_agent.py
new file mode 100644
index 000000000..796915c83
--- /dev/null
+++ b/src/agents/solve/solve_loop/solve_agent.py
@@ -0,0 +1,340 @@
+#!/usr/bin/env python
+"""
+SolveAgent - Tool planner
+Responsible for evaluating existing materials based on step_target and generating tool call trajectories to execute
+"""
+
+from pathlib import Path
+import re
+import sys
+from typing import Any
+
+# Add project root to path
+project_root = Path(__file__).parent.parent.parent.parent
+if str(project_root) not in sys.path:
+ sys.path.insert(0, str(project_root))
+
+from ..base_agent import BaseAgent
+from ..memory import CitationMemory, InvestigateMemory, SolveChainStep, SolveMemory
+from ..utils.json_utils import extract_json_from_text
+
+
+class SolveAgent(BaseAgent):
+ """Solver Agent - Plans and records tool calls"""
+
+ SUPPORTED_TOOL_TYPES = {
+ "none",
+ "rag_naive",
+ "rag_hybrid",
+ "web_search",
+ "code_execution",
+ "finish",
+ }
+
+ def __init__(self, config: dict[str, Any], api_key: str, base_url: str, token_tracker=None):
+ super().__init__(
+ config=config,
+ api_key=api_key,
+ base_url=base_url,
+ agent_name="solve_agent",
+ use_prompt_loader=True,
+ token_tracker=token_tracker,
+ )
+
+ async def process(
+ self,
+ question: str,
+ current_step: SolveChainStep,
+ solve_memory: SolveMemory,
+ investigate_memory: InvestigateMemory,
+ citation_memory: CitationMemory,
+ kb_name: str = "ai_textbook",
+ output_dir: str | None = None,
+ verbose: bool = True,
+ ) -> dict[str, Any]:
+ if not current_step:
+ raise ValueError("No pending solve-chain step to execute")
+
+ context = self._build_context(
+ question=question,
+ current_step=current_step,
+ solve_memory=solve_memory,
+ investigate_memory=investigate_memory,
+ )
+
+ system_prompt = self._build_system_prompt()
+ user_prompt = self._build_user_prompt(context)
+
+ response = await self.call_llm(
+ user_prompt=user_prompt,
+ system_prompt=system_prompt,
+ verbose=verbose,
+ response_format={"type": "json_object"}, # Force JSON
+ )
+
+ tool_plan = self._parse_tool_plan(response)
+ if not tool_plan:
+ # Try to be compatible with old logic, or raise error
+ # For robustness, if JSON parsing fails, raise more specific error
+ self.logger.warning(
+ f"SolveAgent JSON parsing failed or empty, Raw: {response[:200]}..."
+ )
+ # If empty list, also treat as exception, because SolveAgent should output at least none or finish
+ raise ValueError(
+ "SolveAgent did not parse any valid tool_calls structure from LLM output"
+ )
+
+ finish_requested = any(item["type"] == "finish" for item in tool_plan)
+ newly_created: list[dict[str, Any]] = []
+ existing_calls = len(current_step.tool_calls)
+
+ for order, item in enumerate(tool_plan, start=1):
+ tool_type = item["type"]
+ query = item["query"]
+
+ if tool_type == "finish":
+ continue
+
+ normalized_query = self._prepare_query(tool_type, query, current_step)
+
+ cite_id = None
+ if tool_type != "none":
+ cite_id = citation_memory.add_citation(
+ tool_type=tool_type,
+ query=normalized_query,
+ raw_result="",
+ content="",
+ stage="solve",
+ step_id=current_step.step_id,
+ )
+
+ record = solve_memory.append_tool_call(
+ step_id=current_step.step_id,
+ tool_type=tool_type,
+ query=normalized_query,
+ cite_id=cite_id,
+ metadata={
+ "plan_order": existing_calls + order,
+ "kb_name": kb_name,
+ },
+ )
+
+ request_info = {
+ "call_id": record.call_id,
+ "tool_type": tool_type,
+ "query": normalized_query,
+ "cite_id": cite_id,
+ "status": record.status,
+ }
+
+ if tool_type == "none":
+ summary = self._summarize_none_answer(normalized_query)
+ solve_memory.update_tool_call_result(
+ step_id=current_step.step_id,
+ call_id=record.call_id,
+ raw_answer=normalized_query,
+ summary=summary,
+ status="none",
+ )
+ # none calls are not counted in citation system
+ request_info["status"] = "none"
+ request_info["summary"] = summary
+ # none type indicates tool call phase is finished, but step_response must be generated by ResponseAgent
+ finish_requested = True
+ newly_created.append(request_info)
+ # none type indicates no need to append additional tools, but won't directly write to step_response
+ break
+
+ newly_created.append(request_info)
+
+ solve_memory.save()
+ citation_memory.save()
+
+ return {
+ "step_id": current_step.step_id,
+ "requested_calls": newly_created,
+ "finish_requested": finish_requested,
+ "raw_llm_response": response,
+ "status": (
+ "waiting_tools"
+ if newly_created
+ else ("ready_for_response" if finish_requested else "idle")
+ ),
+ }
+
+ # ------------------------------------------------------------------ #
+ # Prompt Building
+ # ------------------------------------------------------------------ #
+ def _build_context(
+ self,
+ question: str,
+ current_step: SolveChainStep,
+ solve_memory: SolveMemory,
+ investigate_memory: InvestigateMemory,
+ ) -> dict[str, Any]:
+ return {
+ "question": question,
+ "current_step_id": current_step.step_id,
+ "step_target": current_step.step_target,
+ "available_cite_text": self._format_available_cite(current_step, investigate_memory),
+ "previous_steps": self._format_previous_steps(current_step, solve_memory),
+ "current_tool_history": self._format_tool_history(current_step),
+ }
+
+ def _build_system_prompt(self) -> str:
+ prompt = self.get_prompt("system") if self.has_prompts() else None
+ if not prompt:
+ raise ValueError(
+ "SolveAgent missing system prompt, please configure system in prompts/zh/solve_loop/solve_agent.yaml."
+ )
+ return prompt
+
+ def _build_user_prompt(self, context: dict[str, Any]) -> str:
+ template = self.get_prompt("user_template") if self.has_prompts() else None
+ if not template:
+ raise ValueError(
+ "SolveAgent missing user_template prompt, please configure user_template in prompts/zh/solve_loop/solve_agent.yaml."
+ )
+ return template.format(**context)
+
+ # ------------------------------------------------------------------ #
+ # Parsing and Formatting
+ # ------------------------------------------------------------------ #
+ def _format_available_cite(
+ self, current_step: SolveChainStep, investigate_memory: InvestigateMemory
+ ) -> str:
+ if not current_step.available_cite:
+ return "(No available knowledge chain)"
+
+ lines: list[str] = []
+ for cite_id in current_step.available_cite:
+ knowledge = next(
+ (k for k in investigate_memory.knowledge_chain if k.cite_id == cite_id), None
+ )
+ if not knowledge:
+ continue
+ summary = knowledge.summary or knowledge.raw_result[:300]
+ raw_preview = (
+ knowledge.raw_result[:300].replace("\n", " ") if knowledge.raw_result else ""
+ )
+ lines.append(
+ f"{cite_id} | {knowledge.tool_type}\n"
+ f" Query: {knowledge.query}\n"
+ f" Summary: {summary}\n"
+ f" Raw: {raw_preview}"
+ )
+ return "\n".join(lines) if lines else "(No matching knowledge)"
+
+ def _format_previous_steps(
+ self, current_step: SolveChainStep, solve_memory: SolveMemory
+ ) -> str:
+ snippets: list[str] = []
+ for step in solve_memory.solve_chains:
+ if step.step_id == current_step.step_id:
+ break
+ if step.step_response:
+ snippets.append(
+ f"[{step.step_id}] {step.step_target}\n{step.step_response[:300]}..."
+ )
+ return "\n\n".join(snippets[-3:]) if snippets else "(No completed steps yet)"
+
+ def _format_tool_history(self, current_step: SolveChainStep) -> str:
+ if not current_step.tool_calls:
+ return "(No tool calls have been made yet)"
+ lines: list[str] = []
+ for call in current_step.tool_calls:
+ summary = call.summary or "(Pending)"
+ lines.append(
+ f"{call.tool_type} | cite_id={call.cite_id or 'N/A'} | Status={call.status}\n"
+ f"Query: {call.query}\n"
+ f"Summary: {summary[:200]}"
+ )
+ return "\n\n".join(lines)
+
+ def _parse_tool_plan(self, response: str) -> list[dict[str, str]]:
+ """
+ Parse JSON plan returned by LLM
+ """
+ parsed_data = extract_json_from_text(response)
+
+ if not parsed_data or not isinstance(parsed_data, dict):
+ return []
+
+ tool_calls = parsed_data.get("tool_calls", [])
+ if not isinstance(tool_calls, list):
+ return []
+
+ actions: list[dict[str, str]] = []
+ for item in tool_calls:
+ if not isinstance(item, dict):
+ continue
+
+ tool_type = str(item.get("type", "")).strip().lower()
+ query = str(item.get("query", "")).strip()
+
+ if not tool_type:
+ continue
+
+ if tool_type not in self.SUPPORTED_TOOL_TYPES:
+ self.logger.warning(f"[SolveAgent] Ignoring unknown tool type: {tool_type}")
+ continue
+
+ actions.append({"type": tool_type, "query": query})
+
+ return actions
+
+ # ------------------------------------------------------------------ #
+ # Query preprocessing & helper
+ # ------------------------------------------------------------------ #
+ def _prepare_query(self, tool_type: str, query: str, current_step: SolveChainStep) -> str:
+ if tool_type == "code_execution":
+ return self._prepare_code_query(query)
+ return query.strip()
+
+ def _summarize_none_answer(self, text: str) -> str:
+ return text.strip()
+
+ def _prepare_code_query(self, raw_query: str | None) -> str:
+ if not raw_query:
+ return ""
+
+ text = raw_query.strip()
+
+ # In JSON format, raw_query is already a string.
+ # If LLM still outputs markdown code block markers (```python ... ```), we need to remove them.
+ # If LLM directly outputs code (without markdown markers), it should also be compatible.
+
+ # Check if code fence is present
+ fence_match = re.search(
+ r"```(?:[A-Za-z0-9_+\-]*)?\s*\n?(?P<code>[\s\S]*?)```", text, re.DOTALL
+ )
+
+ if fence_match:
+ code = fence_match.group("code").strip()
+ else:
+ # If no fence, assume entire text is code
+ # Exclude common non-code interference (though rare in JSON format, LLM may put reasoning in query)
+ code = text
+
+ # Clean up possible leading/trailing whitespace again
+ return code.strip()
+
+ def _normalize_latex_sequences(self, text: str) -> str:
+ if not text or not text.strip():
+ return ""
+ cleaned = text.strip()
+ cleaned = cleaned.replace("\\{", "{").replace("\\}", "}").replace("$", "")
+ pattern = re.compile(r"(?P<var>[A-Za-z_][A-Za-z0-9_\[\]]*)\s*=\s*\{(?P<values>[^\}]+)\}")
+
+ def replacer(match: re.Match) -> str:
+ var = match.group("var")
+ values = match.group("values")
+ base_var = re.sub(r"\[.*?\]", "", var).strip()
+ values = values.replace(";", ",")
+ items = [v.strip() for v in values.split(",") if v.strip()]
+ formatted_values = ", ".join(items)
+ return f"{base_var} = [{formatted_values}]"
+
+ normalized = re.sub(pattern, replacer, cleaned)
+ normalized = re.sub(r"\s+", " ", normalized).strip()
+ return normalized
diff --git a/src/agents/solve/solve_loop/tool_agent.py b/src/agents/solve/solve_loop/tool_agent.py
new file mode 100644
index 000000000..d2589e0b4
--- /dev/null
+++ b/src/agents/solve/solve_loop/tool_agent.py
@@ -0,0 +1,427 @@
+#!/usr/bin/env python
+"""
+ToolAgent - Tool executor
+Responsible for reading tool calls in solve-chain, actually executing tools and producing summary
+"""
+
+from pathlib import Path
+import re
+import sys
+import time
+from typing import Any
+
+project_root = Path(__file__).parent.parent.parent.parent
+if str(project_root) not in sys.path:
+ sys.path.insert(0, str(project_root))
+
+from src.tools.code_executor import run_code
+from src.tools.rag_tool import rag_search
+from src.tools.web_search import web_search
+
+from ..base_agent import BaseAgent
+from ..memory import CitationMemory, SolveChainStep, SolveMemory
+from ..memory.solve_memory import ToolCallRecord
+
+
+class ToolAgent(BaseAgent):
+ """Execute tool calls and generate summary"""
+
+ def __init__(self, config: dict[str, Any], api_key: str, base_url: str, token_tracker=None):
+ super().__init__(
+ config=config,
+ api_key=api_key,
+ base_url=base_url,
+ agent_name="tool_agent",
+ use_prompt_loader=True,
+ token_tracker=token_tracker,
+ )
+
+ async def process(
+ self,
+ step: SolveChainStep,
+ solve_memory: SolveMemory,
+ citation_memory: CitationMemory,
+ kb_name: str,
+ output_dir: str | None = None,
+ verbose: bool = True,
+ ) -> dict[str, Any]:
+ pending = [
+ call
+ for call in step.tool_calls
+ if call.tool_type not in {"none", "finish"} and call.status in {"pending", "running"}
+ ]
+
+ if not pending:
+ return {"step_id": step.step_id, "executed": [], "status": "idle"}
+
+ logs: list[dict[str, Any]] = []
+ base_dir = Path(output_dir).resolve() if output_dir else Path().resolve()
+ artifacts_dir = base_dir / "artifacts"
+ artifacts_dir.mkdir(parents=True, exist_ok=True)
+
+ self.logger.log_stage_progress(
+ "Tool", "start", f"step={step.step_id}, pending_calls={len(pending)}"
+ )
+
+ for record in pending:
+ call_label = f"{record.tool_type} | cite={record.cite_id or '-'}"
+ self.logger.log_stage_progress(
+ "Tool", "running", f"step={step.step_id}, call={call_label}"
+ )
+ start_ts = time.time()
+ try:
+ raw_answer, metadata = await self._execute_single_call(
+ record=record,
+ kb_name=kb_name,
+ output_dir=output_dir,
+ artifacts_dir=str(artifacts_dir),
+ verbose=verbose,
+ )
+
+ # Check if code execution failed
+ is_failed = False
+ if record.tool_type == "code_execution":
+ is_failed = metadata.get("execution_failed", False)
+ exit_code = metadata.get("exit_code", 0)
+ if exit_code != 0:
+ is_failed = True
+
+ summary = await self._summarize_tool_result(
+ tool_type=record.tool_type, query=record.query, raw_answer=raw_answer
+ )
+
+ # Set correct status based on execution result
+ status = "failed" if is_failed else "success"
+ solve_memory.update_tool_call_result(
+ step_id=step.step_id,
+ call_id=record.call_id,
+ raw_answer=raw_answer,
+ summary=summary,
+ status=status,
+ metadata=metadata, # Pass metadata to ensure artifacts are saved
+ )
+ citation_memory.update_citation(
+ cite_id=record.cite_id,
+ raw_result=raw_answer,
+ content=summary,
+ metadata=metadata,
+ step_id=step.step_id,
+ )
+ elapsed_ms = (time.time() - start_ts) * 1000
+ self.logger.log_tool_call(
+ tool_name=record.tool_type,
+ tool_input={
+ "step_id": step.step_id,
+ "call_id": record.call_id,
+ "query": record.query,
+ },
+ tool_output=raw_answer,
+ status="success",
+ elapsed_ms=elapsed_ms,
+ step_id=step.step_id,
+ cite_id=record.cite_id,
+ )
+ logs.append(
+ {
+ "call_id": record.call_id,
+ "tool_type": record.tool_type,
+ "cite_id": record.cite_id,
+ "status": "success",
+ "summary": summary,
+ }
+ )
+ except Exception as e:
+ error_msg = str(e)
+ elapsed_ms = (time.time() - start_ts) * 1000
+ solve_memory.update_tool_call_result(
+ step_id=step.step_id,
+ call_id=record.call_id,
+ raw_answer=error_msg,
+ summary=error_msg[:200],
+ status="failed",
+ metadata={"error": True},
+ )
+ citation_memory.update_citation(
+ cite_id=record.cite_id,
+ raw_result=error_msg,
+ content=error_msg[:200],
+ metadata={"error": True},
+ step_id=step.step_id,
+ )
+ self.logger.log_tool_call(
+ tool_name=record.tool_type,
+ tool_input={
+ "step_id": step.step_id,
+ "call_id": record.call_id,
+ "query": record.query,
+ },
+ tool_output=error_msg,
+ status="failed",
+ elapsed_ms=elapsed_ms,
+ step_id=step.step_id,
+ cite_id=record.cite_id,
+ )
+ self.logger.log_stage_progress(
+ "Tool", "warning", f"step={step.step_id}, call={call_label}, error={error_msg}"
+ )
+ logs.append(
+ {
+ "call_id": record.call_id,
+ "tool_type": record.tool_type,
+ "cite_id": record.cite_id,
+ "status": "failed",
+ "error": error_msg,
+ }
+ )
+
+ solve_memory.save()
+ citation_memory.save()
+
+ self.logger.log_stage_progress(
+ "Tool", "complete", f"step={step.step_id}, executed={len(logs)}"
+ )
+
+ return {"step_id": step.step_id, "executed": logs, "status": "completed"}
+
+ async def _execute_single_call(
+ self,
+ record: ToolCallRecord,
+ kb_name: str,
+ output_dir: str | None,
+ artifacts_dir: str,
+ verbose: bool,
+ ) -> tuple[str, dict[str, Any]]:
+ tool_type = record.tool_type
+ query = record.query
+
+ if tool_type == "rag_naive":
+ result = await rag_search(query=query, kb_name=kb_name, mode="naive")
+ answer = result.get("answer", "")
+ source, auto_sources = self._infer_sources(answer)
+ metadata = {"source": source, "auto_sources": auto_sources, "mode": "naive"}
+ return answer, metadata
+
+ if tool_type == "rag_hybrid":
+ result = await rag_search(query=query, kb_name=kb_name, mode="hybrid")
+ answer = result.get("answer", "")
+ source, auto_sources = self._infer_sources(answer)
+ metadata = {"source": source, "auto_sources": auto_sources, "mode": "hybrid"}
+ return answer, metadata
+
+ if tool_type == "web_search":
+ result = web_search(query=query, output_dir=output_dir, verbose=verbose)
+ answer = result.get("answer") or result.get("summary") or ""
+ used_citation_ids = self._extract_answer_citations(answer)
+ filtered_citations = self._select_web_citations(used_citation_ids, result)
+ metadata = {"result_file": result.get("result_file"), "citations": filtered_citations}
+ return answer, metadata
+
+ if tool_type == "code_execution":
+ artifacts_path = Path(artifacts_dir)
+ before_snapshot = self._snapshot_image_artifacts(artifacts_path)
+
+ if not query or not query.strip():
+ # If code is empty, directly return failure without execution
+ raw_answer = "【⚠️ Code execution failed】\nError: No valid code input received (Code is empty). Please check if [QUERY] contains a markdown code block."
+ metadata = {
+ "exit_code": 1,
+ "artifacts": [],
+ "artifact_paths": [],
+ "artifact_rel_paths": [],
+ "work_dir": artifacts_dir,
+ "execution_failed": True,
+ }
+ return raw_answer, metadata
+
+ exec_result = await run_code(
+ language="python",
+ code=query,
+ timeout=self.agent_config.get("code_timeout", 20),
+ assets_dir=artifacts_dir,
+ )
+ raw_answer = self._format_code_answer(exec_result, artifacts_dir)
+ exit_code = exec_result.get("exit_code", 0)
+
+ # Check if code execution failed
+ is_failed = exit_code != 0
+ if is_failed:
+ stderr = exec_result.get("stderr", "")
+ # Add obvious error prefix at the beginning of raw_answer
+ error_prefix = "【⚠️ Code execution failed】\n"
+ if "FileNotFoundError" in stderr and "artifacts/" in stderr:
+ error_prefix += "Path error detected: Code uses 'artifacts/xxx.png', but working directory is already the artifacts directory.\n"
+ error_prefix += "Please use 'xxx.png' instead of 'artifacts/xxx.png'.\n\n"
+ raw_answer = error_prefix + raw_answer
+
+ new_image_paths = self._collect_new_image_artifacts(
+ artifacts_path=artifacts_path,
+ before_snapshot=before_snapshot,
+ output_dir=output_dir,
+ )
+
+ metadata = {
+ "exit_code": exit_code,
+ "artifacts": exec_result.get("artifacts", []),
+ "artifact_paths": exec_result.get("artifact_paths", []),
+ "artifact_rel_paths": new_image_paths,
+ "work_dir": artifacts_dir,
+ "execution_failed": is_failed,
+ }
+ return raw_answer, metadata
+
+ raise ValueError(f"Unknown tool type: {tool_type}")
+
+ def _format_code_answer(self, exec_result: dict[str, Any], artifacts_dir: str) -> str:
+ stdout = exec_result.get("stdout", "")
+ stderr = exec_result.get("stderr", "")
+ artifacts = exec_result.get("artifacts", [])
+ artifact_paths = exec_result.get("artifact_paths", [])
+
+ lines = [
+ "【Code Execution Result】",
+ f"Exit code: {exec_result.get('exit_code')}",
+ f"Elapsed time: {exec_result.get('elapsed_ms', 0):.2f} ms",
+ f"Working directory: {artifacts_dir}",
+ "",
+ "stdout:",
+ stdout or "(empty)",
+ "",
+ "stderr:",
+ stderr or "(empty)",
+ ]
+
+ if artifacts:
+ lines.append("")
+ lines.append("Artifacts:")
+ for idx, artifact in enumerate(artifacts):
+ abs_path = (
+ artifact_paths[idx]
+ if idx < len(artifact_paths)
+ else str(Path(artifacts_dir) / artifact)
+ )
+ lines.append(f"- {abs_path}")
+
+ return "\n".join(lines)
+
+ async def _summarize_tool_result(self, tool_type: str, query: str, raw_answer: str) -> str:
+ system_prompt = self.get_prompt("system") if self.has_prompts() else None
+ if not system_prompt:
+ raise ValueError(
+ "ToolAgent missing system prompt, please configure system in prompts/{lang}/solve_loop/tool_agent.yaml"
+ )
+
+ template = self.get_prompt("user_template") if self.has_prompts() else None
+ if not template:
+ raise ValueError(
+ "ToolAgent missing user_template, please configure user_template in prompts/{lang}/solve_loop/tool_agent.yaml"
+ )
+
+ user_prompt = template.format(
+ tool_type=tool_type, query=query, raw_answer=raw_answer[:2000]
+ )
+
+ response = await self.call_llm(
+ user_prompt=user_prompt, system_prompt=system_prompt, verbose=False
+ )
+ return response.strip()
+
+ def _infer_sources(self, text: str) -> tuple[str, list[str]]:
+ if not text:
+ return "", []
+ matches = re.findall(r"(https?://[^\s\)\]]+)", text)
+ cleaned = []
+ for item in matches:
+ normalized = item.strip().strip(".,;:()[]{}")
+ if normalized and normalized not in cleaned:
+ cleaned.append(normalized)
+ return (", ".join(cleaned), cleaned)
+
+ def _extract_answer_citations(self, answer: str) -> list[str]:
+ if not answer:
+ return []
+ pattern = re.compile(r"\[(\d+)\]")
+ ids = pattern.findall(answer)
+ unique: list[str] = []
+ for cid in ids:
+ if cid not in unique:
+ unique.append(cid)
+ return unique
+
+ def _select_web_citations(
+ self, used_ids: list[str], result: dict[str, Any]
+ ) -> list[dict[str, Any]]:
+ if not used_ids:
+ return []
+ raw_citations = result.get("citations") or []
+ search_results = result.get("search_results") or []
+ search_map = {item.get("url"): item for item in search_results if item.get("url")}
+
+ selected: list[dict[str, Any]] = []
+ for cid in used_ids:
+ matched = None
+ for raw in raw_citations:
+ ref_id = str(raw.get("id")) if raw.get("id") is not None else ""
+ ref_token = (raw.get("reference") or "").strip()
+ normalized_token = ref_token.strip("[]")
+ if cid == ref_id or cid == normalized_token:
+ matched = dict(raw)
+ break
+ if not matched:
+ continue
+
+ url = matched.get("url")
+ if url and url in search_map:
+ fallback = search_map[url]
+ matched.setdefault("title", fallback.get("title", ""))
+ matched.setdefault("snippet", fallback.get("snippet", ""))
+
+ selected.append(
+ {
+ "id": matched.get("id") or (int(cid) if cid.isdigit() else cid),
+ "reference": matched.get("reference") or f"[{cid}]",
+ "url": matched.get("url"),
+ "title": matched.get("title", ""),
+ }
+ )
+ return selected
+
+ # ------------------------------------------------------------------ #
+ # Artifacts helpers
+ # ------------------------------------------------------------------ #
+ IMAGE_SUFFIXES = {".png", ".jpg", ".jpeg", ".svg", ".gif", ".bmp"}
+
+ def _snapshot_image_artifacts(self, artifacts_path: Path) -> set:
+ if not artifacts_path.exists():
+ return set()
+ snapshot = set()
+ for file_path in artifacts_path.rglob("*"):
+ if file_path.is_file() and file_path.suffix.lower() in self.IMAGE_SUFFIXES:
+ snapshot.add(file_path.resolve())
+ return snapshot
+
+ def _collect_new_image_artifacts(
+ self, artifacts_path: Path, before_snapshot: set, output_dir: str | None
+ ) -> list[str]:
+ after_snapshot = self._snapshot_image_artifacts(artifacts_path)
+ new_files = sorted(after_snapshot - before_snapshot)
+ if not new_files:
+ return []
+
+ rel_paths: list[str] = []
+ output_base = Path(output_dir).resolve() if output_dir else None
+
+ for file_path in new_files:
+ rel_path: str | None = None
+ if output_base:
+ try:
+ rel_path = str(file_path.relative_to(output_base)).replace("\\", "/")
+ except ValueError:
+ rel_path = None
+ if rel_path is None:
+ try:
+ rel_path = str(file_path.relative_to(artifacts_path.parent)).replace("\\", "/")
+ except ValueError:
+ rel_path = str(Path("artifacts") / file_path.name)
+ rel_paths.append(rel_path)
+
+ return rel_paths
diff --git a/src/agents/solve/utils/__init__.py b/src/agents/solve/utils/__init__.py
new file mode 100644
index 000000000..b1fecfa48
--- /dev/null
+++ b/src/agents/solve/utils/__init__.py
@@ -0,0 +1,66 @@
+#!/usr/bin/env python
+"""
+Utility Module
+Contains logging, performance monitoring, config validation, parsers, etc.
+"""
+
+# Logging system (from unified logs module)
+from pathlib import Path
+import sys
+
+# Add project root to path for imports
+project_root = Path(__file__).parent.parent.parent.parent
+if str(project_root) not in sys.path:
+ sys.path.insert(0, str(project_root))
+
+from src.core.logging import Logger, LogLevel, get_logger, reset_logger
+
+# Backwards compatibility alias
+SolveAgentLogger = Logger
+
+# Performance monitoring
+# Config validation
+from .config_validator import ConfigValidator
+from .error_handler import (
+ ParseError,
+ retry_on_parse_error,
+ validate_investigate_output,
+ validate_note_output,
+ validate_output,
+ validate_plan_output,
+ validate_reflect_output,
+)
+from .performance_monitor import PerformanceMonitor
+
+# Prompt loader
+from .prompt_loader import PromptLoader
+
+# Token tracker
+from .token_tracker import TokenTracker, calculate_cost, get_model_pricing
+
+__all__ = [
+ # Logging system
+ "Logger",
+ "get_logger",
+ "reset_logger",
+ "LogLevel",
+ "SolveAgentLogger", # Backwards compatibility
+ # Performance monitoring
+ "PerformanceMonitor",
+ # Config validation
+ "ConfigValidator",
+ # Prompt loader
+ "PromptLoader",
+ # Token tracker
+ "TokenTracker",
+ "calculate_cost",
+ "get_model_pricing",
+ # Error handling
+ "ParseError",
+ "retry_on_parse_error",
+ "validate_output",
+ "validate_investigate_output",
+ "validate_note_output",
+ "validate_reflect_output",
+ "validate_plan_output",
+]
diff --git a/src/agents/solve/utils/config_validator.py b/src/agents/solve/utils/config_validator.py
new file mode 100644
index 000000000..80981dee5
--- /dev/null
+++ b/src/agents/solve/utils/config_validator.py
@@ -0,0 +1,312 @@
+#!/usr/bin/env python
+"""
+Config Validator - Configuration validator
+Validates the completeness and correctness of config.yaml
+"""
+
+from pathlib import Path
+from typing import Any
+
+import yaml
+
+
+class ConfigValidator:
+ """Configuration validator"""
+
+ # Required top-level configuration items
+ # Note: llm configuration has been moved to environment variables (env_config.py), no longer required in config.yaml
+ REQUIRED_SECTIONS = ["system", "agents"]
+
+ # Required system configuration
+ REQUIRED_SYSTEM_CONFIGS = [
+ "output_base_dir",
+ "save_intermediate_results",
+ # Note: language is now unified in config/main.yaml, not required in sub-configs
+ ]
+
+ # Supported languages (supports multiple formats)
+ SUPPORTED_LANGUAGES = ["zh", "en", "English", "Chinese"]
+
+ # Supported log levels
+ SUPPORTED_LOG_LEVELS = ["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"]
+
+ # Agent list - dual-loop architecture
+ STANDARD_AGENTS = [
+ # Analysis Loop
+ "investigate_agent",
+ "note_agent",
+ # Solve Loop
+ "manager_agent",
+ "solve_agent",
+ "tool_agent",
+ "response_agent",
+ "precision_answer_agent",
+ ]
+
+ def __init__(self):
+ self.errors: list[str] = []
+ self.warnings: list[str] = []
+
+ def validate(self, config: dict[str, Any]) -> tuple[bool, list[str], list[str]]:
+ """
+ Validate configuration
+
+ Args:
+ config: Configuration dictionary
+
+ Returns:
+ (is_valid, errors, warnings)
+ """
+ self.errors = []
+ self.warnings = []
+
+ # 1. Validate top-level structure
+ self._validate_structure(config)
+
+ # 2. Validate system configuration
+ if "system" in config:
+ self._validate_system(config["system"])
+
+ # 3. Validate agents configuration
+ if "agents" in config:
+ self._validate_agents(config["agents"])
+
+ # 4. Validate llm configuration (optional, LLM config now mainly comes from environment variables)
+ if "llm" in config:
+ self._validate_llm(config["llm"])
+
+ # 5. Validate logging configuration (optional)
+ if "logging" in config:
+ self._validate_logging(config["logging"])
+
+ # 6. Validate monitoring configuration (optional)
+ if "monitoring" in config:
+ self._validate_monitoring(config["monitoring"])
+
+ is_valid = len(self.errors) == 0
+ return is_valid, self.errors, self.warnings
+
+ def _validate_structure(self, config: dict[str, Any]):
+ """Validate top-level structure"""
+ for section in self.REQUIRED_SECTIONS:
+ if section not in config:
+ self.errors.append(f"Missing required configuration section: {section}")
+
+ def _validate_system(self, system_config: dict[str, Any]):
+ """Validate system configuration"""
+ if system_config is None:
+ self.errors.append("system configuration cannot be None")
+ return
+
+ # Check required fields
+ for field in self.REQUIRED_SYSTEM_CONFIGS:
+ if field not in system_config:
+ self.errors.append(f"system config missing required field: {field}")
+
+ # Check language configuration (unified in config/main.yaml, optional in sub-configs)
+ if "language" in system_config:
+ lang = system_config["language"]
+ if lang not in self.SUPPORTED_LANGUAGES:
+ self.warnings.append(
+ f"language '{lang}' not in supported list: {self.SUPPORTED_LANGUAGES}. Suggest unified configuration in config/main.yaml."
+ )
+ # Backward compatibility: if output_language still exists, give warning
+ if "output_language" in system_config:
+ self.warnings.append(
+ "output_language is deprecated, please use language field. Language configuration has been unified to system.language in config/main.yaml"
+ )
+
+ # Check auto_solve configuration
+ if "auto_solve" in system_config:
+ if not isinstance(system_config["auto_solve"], bool):
+ self.errors.append("auto_solve must be a boolean value")
+
+ def _validate_agents(self, agents_config: dict[str, Any]):
+ """Validate agents configuration"""
+ if agents_config is None:
+ self.errors.append("agents config cannot be None")
+ return
+
+ # Check if standard agents are configured
+ for agent_name in self.STANDARD_AGENTS:
+ if agent_name not in agents_config:
+ self.warnings.append(f"Agent not configured: {agent_name}")
+ else:
+ self._validate_agent_config(agent_name, agents_config[agent_name])
+
+ def _validate_agent_config(self, agent_name: str, agent_config: dict[str, Any]):
+ """Validate single Agent configuration"""
+ if agent_config is None:
+ self.errors.append(f"{agent_name} config cannot be None")
+ return
+
+ # Check enabled field
+ if "enabled" in agent_config:
+ if not isinstance(agent_config["enabled"], bool):
+ self.errors.append(f"{agent_name}.enabled must be a boolean value")
+
+ # Check model field
+ if "model" in agent_config:
+ if not isinstance(agent_config["model"], str):
+ self.errors.append(f"{agent_name}.model must be a string")
+
+ # Check temperature field
+ if "temperature" in agent_config:
+ temp = agent_config["temperature"]
+ if not isinstance(temp, (int, float)):
+ self.errors.append(f"{agent_name}.temperature must be a number")
+ elif not 0 <= temp <= 2:
+ self.warnings.append(
+ f"{agent_name}.temperature={temp} exceeds recommended range [0, 2]"
+ )
+
+ # Check max_retries field
+ if "max_retries" in agent_config:
+ if not isinstance(agent_config["max_retries"], int):
+ self.errors.append(f"{agent_name}.max_retries must be an integer")
+ elif agent_config["max_retries"] < 0:
+ self.errors.append(f"{agent_name}.max_retries cannot be negative")
+
+ def _validate_llm(self, llm_config: dict[str, Any]):
+ """Validate llm configuration"""
+ if llm_config is None:
+ self.errors.append("llm config cannot be None")
+ return
+
+ # Check default_model
+ if "default_model" not in llm_config:
+ self.warnings.append("llm config missing default_model field")
+
+ # Check max_retries
+ if "max_retries" in llm_config:
+ if not isinstance(llm_config["max_retries"], int):
+ self.errors.append("llm.max_retries must be an integer")
+ elif llm_config["max_retries"] < 0:
+ self.errors.append("llm.max_retries cannot be negative")
+
+ # Check timeout
+ if "timeout" in llm_config:
+ if not isinstance(llm_config["timeout"], (int, float)):
+ self.errors.append("llm.timeout must be a number")
+ elif llm_config["timeout"] <= 0:
+ self.warnings.append("llm.timeout should not be negative or zero")
+
+ def _validate_logging(self, logging_config: dict[str, Any]):
+ """Validate logging configuration"""
+ if logging_config is None:
+ # logging is optional, if None but not empty key, may be considered error or ignored
+ self.errors.append("logging config cannot be None")
+ return
+
+ # Check level
+ if "level" in logging_config:
+ level = logging_config["level"]
+ if level not in self.SUPPORTED_LOG_LEVELS:
+ self.errors.append(
+ f"logging.level '{level}' not in supported list: {self.SUPPORTED_LOG_LEVELS}"
+ )
+
+ # Check save_to_file
+ if "save_to_file" in logging_config:
+ if not isinstance(logging_config["save_to_file"], bool):
+ self.errors.append("logging.save_to_file must be a boolean value")
+
+ # Check verbose
+ if "verbose" in logging_config:
+ if not isinstance(logging_config["verbose"], bool):
+ self.errors.append("logging.verbose must be a boolean value")
+
+ def _validate_monitoring(self, monitoring_config: dict[str, Any]):
+ """Validate monitoring configuration"""
+ if monitoring_config is None:
+ self.errors.append("monitoring config cannot be None")
+ return
+
+ # Check enabled
+ if "enabled" in monitoring_config:
+ if not isinstance(monitoring_config["enabled"], bool):
+ self.errors.append("monitoring.enabled must be a boolean value")
+
+ # Check track_token_usage
+ if "track_token_usage" in monitoring_config:
+ if not isinstance(monitoring_config["track_token_usage"], bool):
+ self.errors.append("monitoring.track_token_usage must be a boolean value")
+
+ # Check track_time
+ if "track_time" in monitoring_config:
+ if not isinstance(monitoring_config["track_time"], bool):
+ self.errors.append("monitoring.track_time must be a boolean value")
+
+
+def validate_config_file(config_path: str) -> tuple[bool, list[str], list[str]]:
+ """
+ Validate configuration file
+
+ Args:
+ config_path: Configuration file path
+
+ Returns:
+ (is_valid, errors, warnings)
+ """
+ try:
+ with open(config_path, encoding="utf-8") as f:
+ config = yaml.safe_load(f)
+ except FileNotFoundError:
+ return False, [f"Configuration file does not exist: {config_path}"], []
+ except yaml.YAMLError as e:
+ return False, [f"YAML parsing error: {e!s}"], []
+ except Exception as e:
+ return False, [f"Failed to load configuration file: {e!s}"], []
+
+ validator = ConfigValidator()
+ return validator.validate(config)
+
+
+def print_validation_result(is_valid: bool, errors: list[str], warnings: list[str]):
+ """
+ Print validation result
+
+ Args:
+ is_valid: Whether configuration is valid
+ errors: List of errors
+ warnings: List of warnings
+ """
+ print("=" * 60)
+ print("Configuration Validation Result")
+ print("=" * 60)
+
+ if is_valid:
+ print("✅ Configuration validation passed")
+ else:
+ print("❌ Configuration validation failed")
+
+ print()
+
+ if errors:
+ print(f"Errors ({len(errors)}):")
+ for i, error in enumerate(errors, 1):
+ print(f" {i}. {error}")
+ print()
+
+ if warnings:
+ print(f"Warnings ({len(warnings)}):")
+ for i, warning in enumerate(warnings, 1):
+ print(f" {i}. {warning}")
+ print()
+
+ print("=" * 60)
+
+
+if __name__ == "__main__":
+ # Test configuration validation
+ print("Configuration Validation Test")
+ print("=" * 60)
+
+ # Validate config.yaml in current directory
+ config_path = Path(__file__).parent.parent.parent.parent / "config.yaml"
+
+ if config_path.exists():
+ is_valid, errors, warnings = validate_config_file(str(config_path))
+ print_validation_result(is_valid, errors, warnings)
+ else:
+ print(f"Configuration file not found: {config_path}")
diff --git a/src/agents/solve/utils/display_manager.py b/src/agents/solve/utils/display_manager.py
new file mode 100644
index 000000000..8754c82de
--- /dev/null
+++ b/src/agents/solve/utils/display_manager.py
@@ -0,0 +1,220 @@
+"""
+Display Manager - Terminal display manager
+Uses rich library to implement beautiful terminal interface, including fixed header (status/statistics) and scrolling log area
+"""
+
+from datetime import datetime
+import sys
+from typing import Any
+
+try:
+ from rich import box
+ from rich.console import Console
+ from rich.layout import Layout
+ from rich.live import Live
+ from rich.logging import RichHandler
+ from rich.panel import Panel
+ from rich.table import Table
+ from rich.text import Text
+
+ RICH_AVAILABLE = True
+except ImportError:
+ RICH_AVAILABLE = False
+
+
+class DisplayManager:
+ """
+ Terminal display manager
+
+ If rich is available, use TUI interface:
+ - Top: Agent status checklist + Token/Cost statistics
+ - Bottom: Scrolling logs
+
+ If rich is not available, fall back to standard stdout output
+ """
+
+ def __init__(self):
+ self.rich_available = RICH_AVAILABLE
+ if not self.rich_available:
+ return
+
+ # Explicitly use raw stdout, bypass logger redirection
+ self.console = Console(file=sys.__stdout__)
+
+ # Status data
+ self.agents_status = {
+ "InvestigateAgent": "pending",
+ "NoteAgent": "pending",
+ "ManagerAgent": "pending",
+ "SolveAgent": "pending",
+ "ToolAgent": "pending",
+ "ResponseAgent": "pending",
+ "PrecisionAnswerAgent": "pending",
+ }
+
+ self.stats = {
+ "model": "Unknown",
+ "calls": 0,
+ "tokens": 0,
+ "input_tokens": 0,
+ "output_tokens": 0,
+ "cost": 0.0,
+ }
+
+ # Log buffer
+ self.log_buffer = []
+ self.max_log_lines = 20
+
+ # Layout
+ self.layout = self._make_layout()
+
+ # Live update context
+ self.live = None
+
+ def start(self):
+ """Start Live Display"""
+ if self.rich_available and self.live is None:
+ self.live = Live(
+ self.layout,
+ refresh_per_second=4,
+ console=self.console,
+ transient=True, # Remove interface on exit to avoid blocking subsequent input
+ )
+ self.live.start()
+
+ def stop(self):
+ """Stop Live Display"""
+ if self.rich_available and self.live:
+ self.live.stop()
+ self.live = None
+
+ def _make_layout(self) -> "Layout":
+ """Create layout"""
+ layout = Layout()
+
+ # Split into upper part (fixed info) and lower part (logs)
+ layout.split_column(Layout(name="header", size=10), Layout(name="body"))
+
+ # Split upper part into left (Agents) and right (Stats)
+ layout["header"].split_row(Layout(name="agents", ratio=1), Layout(name="stats", ratio=2))
+
+ return layout
+
+ def update(self):
+ """Update interface content"""
+ if not self.rich_available:
+ return
+
+ # Update Agents status panel
+ agents_table = Table(show_header=False, box=None, padding=(0, 1), expand=True)
+ agents_table.add_column("Status", width=2)
+ agents_table.add_column("Name")
+
+ for name, status in self.agents_status.items():
+ if status == "done":
+ icon = "✓"
+ style = "green"
+ elif status == "running":
+ icon = "…"
+ style = "yellow"
+ elif status == "error":
+ icon = "✗"
+ style = "red"
+ else:
+ icon = " "
+ style = "dim"
+
+ agents_table.add_row(Text(icon, style=style), Text(name, style=style))
+
+ self.layout["agents"].update(
+ Panel(
+ agents_table,
+ title="📦 Agents Status",
+ border_style="blue",
+ padding=(0, 1), # Increase panel padding
+ )
+ )
+
+ # Update statistics panel
+ stats_content = (
+ f"[bold]{self.stats['model']}[/bold]\n"
+ f"Calls: {self.stats['calls']}\n"
+ f"Tokens: {self.stats['tokens']:,} "
+ f"(Input: {self.stats['input_tokens']:,}, Output: {self.stats['output_tokens']:,})\n"
+ f"[bold yellow]Cost: ${self.stats['cost']:.6f} USD[/bold yellow]"
+ )
+
+ self.layout["stats"].update(
+ Panel(
+ stats_content,
+ title="📊 Performance & Cost",
+ border_style="green",
+ padding=(0, 1), # Increase panel padding
+ )
+ )
+
+ # Update log panel
+ log_text = "\n".join(self.log_buffer[-self.max_log_lines :])
+ self.layout["body"].update(
+ Panel(
+ log_text,
+ title="📝 Activity Log",
+ border_style="white",
+ padding=(0, 1), # Increase panel padding
+ )
+ )
+
+ def set_agent_status(self, agent_name: str, status: str):
+ """Set Agent status (pending, running, done, error)"""
+ self.agents_status[agent_name] = status
+ self.update()
+
+ def update_token_stats(self, summary: dict[str, Any]):
+ """Update Token statistics"""
+ self.stats["calls"] = summary.get("total_calls", 0)
+ self.stats["tokens"] = summary.get("total_tokens", 0)
+ self.stats["input_tokens"] = summary.get("total_prompt_tokens", 0)
+ self.stats["output_tokens"] = summary.get("total_completion_tokens", 0)
+ self.stats["cost"] = summary.get("total_cost_usd", 0.0)
+
+ # Try to get the main model used
+ by_model = summary.get("by_model", {})
+ if by_model:
+ # Find the most called model
+ top_model = max(by_model.items(), key=lambda x: x[1]["calls"])[0]
+ self.stats["model"] = top_model
+
+ self.update()
+
+ def log(self, message: str):
+ """Add log"""
+ if not self.rich_available:
+ print(message)
+ return
+
+ # Simple cleaning
+ clean_msg = message.rstrip()
+ if not clean_msg:
+ return
+
+ # Add timestamp
+ timestamp = datetime.now().strftime("%H:%M:%S")
+ formatted_msg = f"[{timestamp}] {clean_msg}"
+
+ self.log_buffer.append(formatted_msg)
+ # Maintain buffer size
+ if len(self.log_buffer) > 100:
+ self.log_buffer = self.log_buffer[-50:]
+
+ self.update()
+
+
+# Global instance
+_display_manager = None
+
+
+def get_display_manager() -> DisplayManager:
+ global _display_manager
+ if _display_manager is None:
+ _display_manager = DisplayManager()
+ return _display_manager
diff --git a/src/agents/solve/utils/error_handler.py b/src/agents/solve/utils/error_handler.py
new file mode 100644
index 000000000..ec9a7a5a6
--- /dev/null
+++ b/src/agents/solve/utils/error_handler.py
@@ -0,0 +1,252 @@
+#!/usr/bin/env python
+"""
+Error Handler - Error handling and retry mechanism
+"""
+
+import asyncio
+from collections.abc import Callable
+import functools
+from typing import Any
+
+
+class ParseError(Exception):
+ """Parse error"""
+
+
+def retry_on_parse_error(max_retries: int = 2, delay: float = 1.0, backoff: float = 2.0):
+ """
+ Parse error retry decorator
+
+ Args:
+ max_retries: Maximum retry count
+ delay: Initial delay time (seconds)
+ backoff: Delay multiplier factor
+ """
+
+ def decorator(func: Callable):
+ @functools.wraps(func)
+ async def wrapper(*args, **kwargs):
+ current_delay = delay
+
+ for attempt in range(max_retries + 1):
+ try:
+ return await func(*args, **kwargs)
+ except ParseError as e:
+ if attempt == max_retries:
+ # Last attempt failed, raise exception
+ raise e
+
+ # Wait and retry
+ print(
+ f"⚠️ Parse failed (attempt {attempt + 1}), retrying in {current_delay:.1f}s..."
+ )
+ await asyncio.sleep(current_delay)
+ current_delay *= backoff
+
+ # Should not reach here
+ raise ParseError("Retry attempts exhausted")
+
+ return wrapper
+
+ return decorator
+
+
+def validate_output(
+ output: dict[str, Any], required_fields: list, field_types: dict[str, type] | None = None
+) -> bool:
+ """
+ Validate output contains required fields and correct types
+
+ Args:
+ output: Output dictionary
+ required_fields: List of required fields
+ field_types: Field type dictionary (optional)
+
+ Returns:
+ bool: Whether valid
+
+ Raises:
+ ParseError: Raised when validation fails
+ """
+ # Check required fields
+ missing_fields = [field for field in required_fields if field not in output]
+
+ if missing_fields:
+ raise ParseError(f"Missing required fields: {', '.join(missing_fields)}")
+
+ # Check field types
+ if field_types:
+ for field, expected_type in field_types.items():
+ if field in output and not isinstance(output[field], expected_type):
+ actual_type = type(output[field]).__name__
+ expected_type_name = expected_type.__name__
+ raise ParseError(
+ f"Field '{field}' type error: expected {expected_type_name}, got {actual_type}"
+ )
+
+ return True
+
+
+def safe_parse(
+ parser_func: Callable, text: str, default: Any = None, raise_on_error: bool = False
+) -> Any:
+ """
+ Safe parsing (catch exceptions and return default value)
+
+ Args:
+ parser_func: Parser function
+ text: Text to parse
+ default: Default value
+ raise_on_error: Whether to raise exception on error
+
+ Returns:
+ Parsed result or default value
+ """
+ try:
+ return parser_func(text)
+ except Exception as e:
+ if raise_on_error:
+ raise ParseError(f"Parsing failed: {e!s}")
+
+ print(f"⚠️ Parsing failed, using default value: {e!s}")
+ return default
+
+
+def validate_investigate_output(output: dict[str, Any]) -> bool:
+ """Validate InvestigateAgent output (refactored: multi-tool intent)"""
+ required_fields = ["reasoning", "tools"]
+ field_types = {"reasoning": str, "tools": list}
+
+ validate_output(output, required_fields, field_types)
+
+ valid_tools = ["rag_naive", "rag_hybrid", "web_search", "query_item", "none"]
+ tools = output["tools"]
+ if not tools:
+ raise ParseError("tools list cannot be empty")
+
+ for idx, tool in enumerate(tools):
+ if not isinstance(tool, dict):
+ raise ParseError(f"tool[{idx}] must be a dictionary")
+
+ tool_type = tool.get("tool_type", "").lower()
+ query = tool.get("query", "")
+ identifier = tool.get("identifier", "")
+
+ if tool_type not in valid_tools:
+ raise ParseError(
+ f"tool[{idx}] tool_type must be one of {valid_tools}, got: {tool_type}"
+ )
+
+ if tool_type == "none":
+ if len(tools) > 1:
+ raise ParseError(
+ "When [TOOL] none exists, no other tool intents should be provided"
+ )
+ continue
+
+ if not query:
+ raise ParseError(f"tool[{idx}] missing query")
+
+ if tool_type == "query_item" and not (identifier or query):
+ raise ParseError("query_item must provide identifier or query")
+
+ return True
+
+
+def validate_note_output(output: dict[str, Any]) -> bool:
+ """Validate NoteAgent output (new format: only summary and citations)"""
+ required_fields = ["summary"]
+ field_types = {"summary": str, "citations": list}
+
+ validate_output(output, required_fields, field_types)
+
+ # Validate citations list
+ if "citations" in output:
+ for citation in output["citations"]:
+ if not isinstance(citation, dict):
+ raise ParseError(f"citation must be a dictionary, got: {type(citation)}")
+
+ # citations should contain reference_id, source, content
+ if "reference_id" not in citation and "source" not in citation:
+ raise ParseError("citation must contain reference_id or source")
+
+ return True
+
+
+def validate_reflect_output(output: dict[str, Any]) -> bool:
+ """Validate InvestigateReflectAgent output (new format: simplified)"""
+ required_fields = ["should_stop", "reason", "remaining_questions"]
+ field_types = {"should_stop": bool, "reason": str, "remaining_questions": list}
+
+ validate_output(output, required_fields, field_types)
+
+ # Validate remaining_questions list
+ if "remaining_questions" in output:
+ for question in output["remaining_questions"]:
+ if not isinstance(question, str):
+ raise ParseError(f"remaining_question must be a string, got: {type(question)}")
+
+ return True
+
+
+def validate_plan_output(output: dict[str, Any]) -> bool:
+ """Validate PlanAgent output"""
+ required_fields = ["answer_style", "blocks"]
+ field_types = {"answer_style": str, "blocks": list}
+
+ validate_output(output, required_fields, field_types)
+
+ # Validate blocks list is not empty (new)
+ if not output["blocks"] or len(output["blocks"]) == 0:
+ raise ParseError(
+ "blocks list is empty, PlanAgent must generate at least one block.\n"
+ "Possible reasons:\n"
+ "1. LLM did not output [Block-N] tags\n"
+ "2. Output format is incorrect\n"
+ "3. Prompt design has issues"
+ )
+
+ # Validate blocks list
+ for block in output["blocks"]:
+ if not isinstance(block, dict):
+ raise ParseError(f"block must be a dictionary, got: {type(block)}")
+
+ if "block_id" not in block or "format" not in block or "steps" not in block:
+ raise ParseError("block missing required fields: block_id, format, steps")
+
+ # Validate steps list
+ for step in block["steps"]:
+ if not isinstance(step, dict):
+ raise ParseError(f"step must be a dictionary, got: {type(step)}")
+
+ if "step_id" not in step or "plan" not in step:
+ raise ParseError("step missing required fields: step_id, plan")
+
+ return True
+
+
+# Example usage
+if __name__ == "__main__":
+ # Test validation functions
+ test_investigate_output = {
+ "investigation_summary": "This round investigation target...",
+ "actions": [
+ {"type": "rag_naive", "query": "What is linear convolution?", "priority": "high"}
+ ],
+ "followup_suggestions": "If definition is unclear..",
+ }
+
+ try:
+ validate_investigate_output(test_investigate_output)
+ print("✅ InvestigateAgent output validation passed")
+ except ParseError as e:
+ print(f"❌ InvestigateAgent output validation failed: {e}")
+
+ # Test missing required fields
+ test_invalid_output = {"actions": []}
+
+ try:
+ validate_investigate_output(test_invalid_output)
+ print("❌ Invalid output validation passed (should not happen)")
+ except ParseError as e:
+ print(f"✅ Invalid output validation failed (expected): {e}")
diff --git a/src/agents/solve/utils/json_utils.py b/src/agents/solve/utils/json_utils.py
new file mode 100644
index 000000000..010610f6b
--- /dev/null
+++ b/src/agents/solve/utils/json_utils.py
@@ -0,0 +1,98 @@
+#!/usr/bin/env python
+"""
+JSON Utils - JSON parsing utilities
+Specifically for extracting and parsing JSON data from LLM output, supports Markdown code block processing
+"""
+
+import json
+import re
+from typing import Any
+
+
+def extract_json_from_text(text: str) -> dict[str, Any] | list[Any] | None:
+ """
+ Extract JSON object or array from text
+
+ Supports the following formats:
+ 1. Code blocks wrapped in ```json ... ```
+ 2. Code blocks wrapped in ``` ... ```
+ 3. Pure JSON text
+
+ Args:
+ text: Original text containing JSON
+
+ Returns:
+ Parsed JSON object (dict) or array (list), returns None if parsing fails
+ """
+ if not text:
+ return None
+
+ # 1. Try matching Markdown code blocks
+ # Match ```json {...} ``` or ``` {...} ```
+ code_block_pattern = re.compile(r"```(?:json)?\s*([\s\S]*?)\s*```")
+ match = code_block_pattern.search(text)
+
+ if match:
+ json_str = match.group(1).strip()
+ try:
+ return json.loads(json_str)
+ except json.JSONDecodeError:
+ # If parsing fails in code block, may contain comments or illegal characters, try cleaning
+ # Can add more complex cleaning logic here, currently keep original and try next method
+ pass
+
+ # 2. If no code block or code block parsing failed, try finding JSON structure in entire text
+ # Find outermost {...} or [...]
+
+ # Remove possible comments // ... or # ... (simple handling)
+ # Note: This may mistakenly delete content in URLs or strings, use with caution.
+ # Do not aggressively remove comments, rely on LLM output standards.
+
+ # Find first { or [
+ start_idx = -1
+ stack = []
+
+ # Scan for valid JSON start and end
+ # This is a simplified search, assuming JSON is the main part of the text
+
+ try:
+ # Try direct parsing
+ return json.loads(text)
+ except json.JSONDecodeError:
+ pass
+
+ # Use regex to find outermost {} or []
+ # dotall mode
+ json_obj_pattern = re.compile(r"\{[\s\S]*\}")
+ json_arr_pattern = re.compile(r"\[[\s\S]*\]")
+
+ # Prefer finding object
+ match_obj = json_obj_pattern.search(text)
+ if match_obj:
+ try:
+ return json.loads(match_obj.group(0))
+ except json.JSONDecodeError:
+ pass
+
+ # Find array
+ match_arr = json_arr_pattern.search(text)
+ if match_arr:
+ try:
+ return json.loads(match_arr.group(0))
+ except json.JSONDecodeError:
+ pass
+
+ # 3. Try fixing common LLM JSON errors (e.g., trailing commas)
+ # This is a relatively complex task, can use specialized libraries like json_repair,
+ # but to avoid introducing new dependencies, do simple string processing here
+
+ return None
+
+
+def clean_json_string(json_str: str) -> str:
+ """
+ Clean JSON string, remove common illegal characters
+ """
+ # Remove control characters
+ json_str = re.sub(r"[\x00-\x1f\x7f-\x9f]", "", json_str)
+ return json_str
diff --git a/src/agents/solve/utils/performance_monitor.py b/src/agents/solve/utils/performance_monitor.py
new file mode 100644
index 000000000..40740ec0b
--- /dev/null
+++ b/src/agents/solve/utils/performance_monitor.py
@@ -0,0 +1,407 @@
+#!/usr/bin/env python
+"""
+Performance Monitor - Performance monitoring and tracking system
+Records Agent execution time, Token consumption and other metrics
+"""
+
+from collections.abc import Callable
+from contextlib import contextmanager
+from dataclasses import asdict, dataclass, field
+from datetime import datetime
+from functools import wraps
+import json
+from pathlib import Path
+import time
+from typing import Any
+
+
+@dataclass
+class PerformanceMetrics:
+ """Performance metrics"""
+
+ # Basic information
+ agent_name: str # Agent name
+ start_time: float # Start time (timestamp)
+ end_time: float | None = None # End time (timestamp)
+ duration: float | None = None # Duration (seconds)
+
+ # Token statistics
+ prompt_tokens: int = 0 # Prompt token count
+ completion_tokens: int = 0 # Generated token count
+ total_tokens: int = 0 # Total token count
+
+ # Request statistics
+ api_calls: int = 0 # API call count
+ errors: int = 0 # Error count
+
+ # Custom metrics
+ custom_metrics: dict[str, Any] = field(default_factory=dict)
+
+ def mark_end(self):
+ """Mark end time and calculate duration"""
+ self.end_time = time.time()
+ if self.start_time:
+ self.duration = self.end_time - self.start_time
+
+ def add_tokens(self, prompt: int = 0, completion: int = 0):
+ """Add Token statistics"""
+ self.prompt_tokens += prompt
+ self.completion_tokens += completion
+ self.total_tokens = self.prompt_tokens + self.completion_tokens
+
+ def add_api_call(self):
+ """Increment API call count"""
+ self.api_calls += 1
+
+ def add_error(self):
+ """Increment error count"""
+ self.errors += 1
+
+ def set_custom_metric(self, key: str, value: Any):
+ """Set custom metric"""
+ self.custom_metrics[key] = value
+
+ def to_dict(self) -> dict[str, Any]:
+ """Convert to dictionary"""
+ return asdict(self)
+
+ def summary(self) -> str:
+ """Generate summary"""
+ lines = [
+ f"Agent: {self.agent_name}",
+ f"Duration: {self.duration:.2f}s" if self.duration else "Duration: N/A",
+ f"Total Tokens: {self.total_tokens}",
+ f" Prompt: {self.prompt_tokens}",
+ f" Completion: {self.completion_tokens}",
+ f"API Calls: {self.api_calls}",
+ f"Errors: {self.errors}",
+ ]
+
+ if self.custom_metrics:
+ lines.append("Custom Metrics:")
+ for k, v in self.custom_metrics.items():
+ lines.append(f" {k}: {v}")
+
+ return "\n".join(lines)
+
+
+class PerformanceMonitor:
+ """Performance monitor"""
+
+ def __init__(self, enabled: bool = True, save_dir: str | None = None):
+ """
+ Initialize performance monitor
+
+ Args:
+ enabled: Whether to enable monitoring
+ save_dir: Save directory (None uses ./data/user/performance)
+ """
+ self.enabled = enabled
+
+ if save_dir is None:
+ # Default to data/user/performance (relative to project root)
+ project_root = Path(__file__).parent.parent.parent.parent.parent
+ self.save_dir = project_root / "data" / "user" / "performance"
+ else:
+ self.save_dir = Path(save_dir)
+
+ if self.enabled:
+ self.save_dir.mkdir(parents=True, exist_ok=True)
+
+ # Current session metrics
+ self.metrics: dict[str, PerformanceMetrics] = {}
+
+ # Overall statistics
+ self.total_duration = 0.0
+ self.total_tokens = 0
+ self.total_api_calls = 0
+ self.total_errors = 0
+
+ def start_tracking(self, agent_name: str) -> PerformanceMetrics:
+ """
+ Start tracking Agent performance
+
+ Args:
+ agent_name: Agent name
+
+ Returns:
+ PerformanceMetrics instance
+ """
+ if not self.enabled:
+ return PerformanceMetrics(agent_name=agent_name, start_time=time.time())
+
+ metrics = PerformanceMetrics(agent_name=agent_name, start_time=time.time())
+
+ self.metrics[agent_name] = metrics
+ return metrics
+
+ def end_tracking(self, agent_name: str):
+ """
+ End tracking and update statistics
+
+ Args:
+ agent_name: Agent name
+ """
+ if not self.enabled:
+ return
+
+ if agent_name in self.metrics:
+ metrics = self.metrics[agent_name]
+ metrics.mark_end()
+
+ # Update overall statistics
+ if metrics.duration:
+ self.total_duration += metrics.duration
+ self.total_tokens += metrics.total_tokens
+ self.total_api_calls += metrics.api_calls
+ self.total_errors += metrics.errors
+
+ @contextmanager
+ def track(self, agent_name: str):
+ """
+ Context manager: automatically track Agent performance
+
+ Args:
+ agent_name: Agent name
+
+ Usage:
+ with monitor.track("agent_name"):
+ # Agent execution logic
+ ...
+ """
+ # Start tracking
+ metrics = self.start_tracking(agent_name)
+ try:
+ yield metrics
+ except Exception:
+ # Record error
+ if self.enabled:
+ metrics.add_error()
+ raise
+ finally:
+ # End tracking
+ self.end_tracking(agent_name)
+
+ def get_metrics(self, agent_name: str) -> PerformanceMetrics | None:
+ """
+ Get Agent performance metrics
+
+ Args:
+ agent_name: Agent name
+
+ Returns:
+ PerformanceMetrics instance, or None if not found
+ """
+ return self.metrics.get(agent_name)
+
+ def get_all_metrics(self) -> dict[str, PerformanceMetrics]:
+ """Get all metrics"""
+ return self.metrics
+
+ def get_summary(self) -> dict[str, Any]:
+ """
+ Get overall statistics summary
+
+ Returns:
+ {
+ 'total_duration': float,
+ 'total_tokens': int,
+ 'total_api_calls': int,
+ 'total_errors': int,
+ 'agents': Dict[str, Dict]
+ }
+ """
+ return {
+ "total_duration": self.total_duration,
+ "total_tokens": self.total_tokens,
+ "total_api_calls": self.total_api_calls,
+ "total_errors": self.total_errors,
+ "agents": {name: metrics.to_dict() for name, metrics in self.metrics.items()},
+ }
+
+ def generate_report(self) -> dict[str, Any]:
+ """
+ Generate performance report (alias for get_summary)
+
+ Returns:
+ Performance report dictionary
+ """
+ return self.get_summary()
+
+ def save(self, filepath: str | None = None) -> str:
+ """
+ Save performance metrics to file
+
+ Args:
+ filepath: Save path (None for auto-generated)
+
+ Returns:
+ Saved file path
+ """
+ if not self.enabled:
+ return ""
+
+ if filepath is None:
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
+ filepath = self.save_dir / f"performance_{timestamp}.json"
+ else:
+ filepath = Path(filepath)
+
+ summary = self.get_summary()
+
+ with open(filepath, "w", encoding="utf-8") as f:
+ json.dump(summary, f, ensure_ascii=False, indent=2)
+
+ return str(filepath)
+
+ def print_summary(self):
+ """Print overall statistics summary"""
+ print("=" * 60)
+ print("Performance Monitoring Summary")
+ print("=" * 60)
+ print(f"Total Duration: {self.total_duration:.2f}s")
+ print(f"Total Tokens: {self.total_tokens}")
+ print(f"Total API Calls: {self.total_api_calls}")
+ print(f"Total Errors: {self.total_errors}")
+ print()
+ print("Agent Details:")
+ print("-" * 60)
+
+ for agent_name, metrics in self.metrics.items():
+ print(f"\n{agent_name}:")
+ print(f" Duration: {metrics.duration:.2f}s" if metrics.duration else " Duration: N/A")
+ print(f" Tokens: {metrics.total_tokens}")
+ print(f" API Calls: {metrics.api_calls}")
+ print(f" Errors: {metrics.errors}")
+
+ print("=" * 60)
+
+ def reset(self):
+ """Reset all statistics"""
+ self.metrics.clear()
+ self.total_duration = 0.0
+ self.total_tokens = 0
+ self.total_api_calls = 0
+ self.total_errors = 0
+
+
+# Decorator: automatically track Agent performance
+
+
+def track_performance(monitor: PerformanceMonitor):
+ """
+ Performance tracking decorator
+
+ Args:
+ monitor: PerformanceMonitor instance
+
+ Usage:
+ @track_performance(monitor)
+ async def my_agent_process(...):
+ ...
+ """
+
+ def decorator(func: Callable) -> Callable:
+ @wraps(func)
+ async def wrapper(self, *args, **kwargs):
+ agent_name = getattr(self, "agent_name", func.__name__)
+
+ # Start tracking
+ metrics = monitor.start_tracking(agent_name)
+
+ try:
+ result = await func(self, *args, **kwargs)
+ return result
+ except Exception:
+ metrics.add_error()
+ raise
+ finally:
+ # End tracking
+ monitor.end_tracking(agent_name)
+
+ return wrapper
+
+ return decorator
+
+
+# Global monitor instance
+
+_global_monitor: PerformanceMonitor | None = None
+
+
+def get_monitor(enabled: bool = True, save_dir: str | None = None) -> PerformanceMonitor:
+ """
+ Get global monitor instance (singleton pattern)
+
+ Args:
+ enabled: Whether to enable
+ save_dir: Save directory
+
+ Returns:
+ PerformanceMonitor instance
+ """
+ global _global_monitor
+
+ if _global_monitor is None:
+ _global_monitor = PerformanceMonitor(enabled=enabled, save_dir=save_dir)
+
+ return _global_monitor
+
+
+def init_monitor_from_config(config: dict) -> PerformanceMonitor:
+ """
+ Initialize monitor from configuration
+
+ Args:
+ config: Configuration dictionary
+
+ Returns:
+ PerformanceMonitor instance
+ """
+ monitoring_config = config.get("monitoring", {})
+
+ enabled = monitoring_config.get("enabled", True)
+ save_dir = monitoring_config.get("save_dir", "./logs/performance")
+
+ return get_monitor(enabled=enabled, save_dir=save_dir)
+
+
+if __name__ == "__main__":
+ # Test performance monitoring
+ print("Performance Monitoring Test")
+ print("=" * 60)
+
+ # Create monitor
+ monitor = PerformanceMonitor(enabled=True)
+
+ # Simulate Agent execution
+ import asyncio
+
+ async def simulate_agent(agent_name: str, duration: float, tokens: int):
+ """Simulate Agent execution"""
+ metrics = monitor.start_tracking(agent_name)
+
+ # Simulate work
+ await asyncio.sleep(duration)
+
+ # Record tokens
+ metrics.add_tokens(prompt=tokens // 2, completion=tokens // 2)
+ metrics.add_api_call()
+
+ monitor.end_tracking(agent_name)
+
+ # Run simulation
+ async def run_simulation():
+ await simulate_agent("decompose_agent", 0.5, 100)
+ await simulate_agent("rag_agent", 1.0, 500)
+ await simulate_agent("plan_agent", 0.8, 300)
+ await simulate_agent("execute_agent", 1.5, 800)
+
+ asyncio.run(run_simulation())
+
+ # Print summary
+ monitor.print_summary()
+
+ # Save results
+ saved_path = monitor.save()
+ print(f"\nPerformance metrics saved to: {saved_path}")
diff --git a/src/agents/solve/utils/prompt_loader.py b/src/agents/solve/utils/prompt_loader.py
new file mode 100644
index 000000000..fd41dbadb
--- /dev/null
+++ b/src/agents/solve/utils/prompt_loader.py
@@ -0,0 +1,324 @@
+#!/usr/bin/env python
+"""
+Prompt Loader - Unified Prompt loading and management system
+Supports multi-language, version control, and caching
+"""
+
+from pathlib import Path
+from typing import Any
+
+import yaml
+
+
+class PromptLoader:
+ """Prompt loader - Load Prompt configuration from YAML files"""
+
+ def __init__(self, base_dir: str | None = None, language: str = "zh"):
+ """
+ Initialize PromptLoader
+
+ Args:
+ base_dir: Base directory for Prompt config files (defaults to prompts directory of current module)
+ language: Language code ('zh' | 'en')
+ """
+ if base_dir is None:
+ base_dir = Path(__file__).parent.parent.parent.parent / "prompts"
+ else:
+ base_dir = Path(base_dir)
+
+ self.base_dir = base_dir
+ self.language = language
+ self._cache = {}
+
+ def set_language(self, language: str):
+ """
+ Set language
+
+ Args:
+ language: Language code ('zh' | 'en')
+ """
+ if language not in ["zh", "en"]:
+ raise ValueError(f"Unsupported language: {language}, only 'zh' or 'en' supported")
+
+ self.language = language
+ # Clear cache because language changed
+ self._cache.clear()
+
+ def load(self, agent_name: str, version: str = "latest") -> dict[str, str]:
+ """
+ Load Prompt configuration for specified Agent
+
+ Args:
+ agent_name: Agent name (corresponds to YAML filename without extension)
+ version: Version identifier (currently only 'latest' supported)
+
+ Returns:
+ {
+ 'system': str, # System prompt (fully constructed)
+ 'user_template': str, # User prompt template
+ 'output_format': str # Output format description
+ }
+
+ Raises:
+ FileNotFoundError: If corresponding YAML file not found
+ ValueError: If YAML format is incorrect
+ """
+ cache_key = f"{agent_name}_{version}_{self.language}"
+
+ # Check cache
+ if cache_key in self._cache:
+ return self._cache[cache_key]
+
+ # Build file path (supports subdirectory search)
+ # First try direct path
+ prompt_file = self.base_dir / self.language / f"{agent_name}.yaml"
+
+ # If not exists, try searching in subdirectories
+ if not prompt_file.exists():
+ lang_dir = self.base_dir / self.language
+ if lang_dir.exists():
+ # Search in all subdirectories
+ found_files = list(lang_dir.rglob(f"{agent_name}.yaml"))
+ if found_files:
+ prompt_file = found_files[0]
+ else:
+ raise FileNotFoundError(
+ f"Prompt config file not found: {agent_name}.yaml\n"
+ f"Please ensure file exists in {self.base_dir / self.language}/ or its subdirectories"
+ )
+ else:
+ raise FileNotFoundError(
+ f"Prompt config directory not found: {lang_dir}\nPlease ensure directory exists"
+ )
+
+ # Load YAML
+ try:
+ with open(prompt_file, encoding="utf-8") as f:
+ config = yaml.safe_load(f)
+ except Exception as e:
+ raise ValueError(f"Failed to parse YAML file ({prompt_file}): {e!s}")
+
+ # Validate configuration structure
+ config_type = self._validate_config(config, agent_name)
+
+ # Build Prompt
+ prompts = self._build_prompts(config, config_type)
+
+ # Cache result
+ self._cache[cache_key] = prompts
+
+ return prompts
+
+ def _validate_config(self, config: dict[str, Any], agent_name: str) -> str:
+ """
+ Validate configuration structure integrity
+
+ Args:
+ config: Loaded configuration dictionary
+ agent_name: Agent name (for error messages)
+
+ Raises:
+ ValueError: If configuration structure is incorrect
+ """
+ if "system" not in config:
+ raise ValueError(f"[{agent_name}] missing 'system' configuration section")
+
+ system_section = config["system"]
+
+ if isinstance(system_section, dict):
+ if "user" not in config:
+ raise ValueError(f"[{agent_name}] missing 'user' configuration section")
+
+ required_system_fields = ["role", "task"]
+ for field in required_system_fields:
+ if field not in system_section:
+ raise ValueError(
+ f"[{agent_name}] 'system' configuration section missing '{field}' field"
+ )
+
+ user_config = config["user"]
+ if "template" not in user_config:
+ raise ValueError(
+ f"[{agent_name}] 'user' configuration section missing 'template' field"
+ )
+
+ return "structured"
+
+ if not isinstance(system_section, str):
+ raise ValueError(f"[{agent_name}] 'system' must be a string or object")
+
+ if "user_template" not in config:
+ raise ValueError(f"[{agent_name}] raw format missing 'user_template'")
+
+ if not isinstance(config["user_template"], str):
+ raise ValueError(f"[{agent_name}] 'user_template' must be a string")
+
+ return "raw"
+
+ def _build_prompts(self, config: dict[str, Any], config_type: str) -> dict[str, str]:
+ """
+ Build complete Prompt from configuration
+
+ Args:
+ config: Loaded configuration dictionary
+
+ Returns:
+ {
+ 'system': str,
+ 'user_template': str,
+ 'output_format': str
+ }
+ """
+ if config_type == "structured":
+ system_config = config["system"]
+ user_config = config["user"]
+
+ system_parts = []
+ system_parts.append(f"You are {system_config['role']}.")
+ system_parts.append("")
+ system_parts.append(system_config["task"])
+
+ if system_config.get("requirements"):
+ system_parts.append("")
+ system_parts.append("Requirements:")
+ for req in system_config["requirements"]:
+ system_parts.append(f"- {req}")
+
+ if system_config.get("constraints"):
+ system_parts.append("")
+ system_parts.append("Constraints:")
+ for cons in system_config["constraints"]:
+ system_parts.append(f"- {cons}")
+
+ output_format = ""
+ if system_config.get("output_format"):
+ system_parts.append("")
+ system_parts.append("Output Format:")
+ system_parts.append(system_config["output_format"])
+ output_format = system_config["output_format"]
+
+ if system_config.get("notes"):
+ system_parts.append("")
+ system_parts.append("Notes:")
+ for note in system_config["notes"]:
+ system_parts.append(f"- {note}")
+
+ system_prompt = "\n".join(system_parts)
+ user_template = user_config["template"]
+
+ return {
+ "system": system_prompt,
+ "user_template": user_template,
+ "output_format": output_format,
+ }
+
+ prompts = {"system": config["system"], "user_template": config.get("user_template", "")}
+
+ for key, value in config.items():
+ if key in ["system", "user_template"]:
+ continue
+ prompts[key] = value
+
+ return prompts
+
+ def list_available_prompts(self, language: str | None = None) -> list:
+ """
+ List available prompt configuration files for specified language
+
+ Args:
+ language: Language code (None uses current language)
+
+ Returns:
+ List of available agent names
+ """
+ lang = language or self.language
+ prompts_dir = self.base_dir / lang
+
+ if not prompts_dir.exists():
+ return []
+
+ # Get all YAML files
+ yaml_files = list(prompts_dir.glob("*.yaml"))
+
+ # Extract filenames (without extension)
+ agent_names = [f.stem for f in yaml_files]
+
+ return sorted(agent_names)
+
+ def clear_cache(self):
+ """Clear cache"""
+ self._cache.clear()
+
+ def reload(self, agent_name: str, version: str = "latest") -> dict[str, str]:
+ """
+ Force reload prompt configuration (ignore cache)
+
+ Args:
+ agent_name: Agent name
+ version: Version identifier
+
+ Returns:
+ Prompt configuration
+ """
+ cache_key = f"{agent_name}_{version}_{self.language}"
+
+ # Delete cache
+ if cache_key in self._cache:
+ del self._cache[cache_key]
+
+ # Reload
+ return self.load(agent_name, version)
+
+
+# Global PromptLoader instance (singleton pattern)
+_global_loader = None
+
+
+def get_prompt_loader(language: str | None = None) -> PromptLoader:
+ """
+ Get global PromptLoader instance
+
+ Args:
+ language: Language code (None uses 'zh')
+
+ Returns:
+ PromptLoader instance
+ """
+ global _global_loader
+
+ if _global_loader is None:
+ lang = language or "zh"
+ _global_loader = PromptLoader(language=lang)
+ elif language is not None:
+ _global_loader.set_language(language)
+
+ return _global_loader
+
+
+if __name__ == "__main__":
+ # Test PromptLoader
+ print("PromptLoader Test")
+ print("=" * 60)
+
+ # Create loader
+ loader = PromptLoader(language="zh")
+
+ # List available prompts
+ available = loader.list_available_prompts()
+ print(f"Available Prompt configurations: {available}")
+ print()
+
+ # If available configurations exist, load first one for testing
+ if available:
+ test_agent = available[0]
+ print(f"Testing load: {test_agent}")
+ try:
+ prompts = loader.load(test_agent)
+ print("✅ Load successful")
+ print(f"System Prompt (first 200 chars):\n{prompts['system'][:200]}...")
+ print(f"\nUser Template (first 200 chars):\n{prompts['user_template'][:200]}...")
+ except Exception as e:
+ print(f"❌ Load failed: {e!s}")
+ else:
+ print("Hint: No available Prompt configuration files")
+ print("Please create YAML configuration files in prompts/zh/ directory")
diff --git a/src/agents/solve/utils/token_tracker.py b/src/agents/solve/utils/token_tracker.py
new file mode 100644
index 000000000..7a16b1e97
--- /dev/null
+++ b/src/agents/solve/utils/token_tracker.py
@@ -0,0 +1,540 @@
+#!/usr/bin/env python
+"""
+Token Tracker - LLM Token usage and cost tracking system (Advanced)
+Uses tiktoken for precise token counting, supports multiple models and more accurate cost calculation
+"""
+
+from dataclasses import asdict, dataclass, field
+from datetime import datetime
+import json
+from typing import Any
+
+# Try importing tiktoken (if available)
+try:
+ import tiktoken
+
+ TIKTOKEN_AVAILABLE = True
+except ImportError:
+ TIKTOKEN_AVAILABLE = False
+ tiktoken = None
+
+# Try importing litellm (optional advanced library)
+try:
+ import litellm
+ from litellm import completion_cost, token_counter
+
+ LITELLM_AVAILABLE = True
+except ImportError:
+ LITELLM_AVAILABLE = False
+ litellm = None
+
+
+# Model pricing table (price per 1K tokens, unit: USD)
+# Data source: Official pricing from various vendors (November 2024)
+MODEL_PRICING = {
+ # OpenAI GPT Series
+ "gpt-4o": {"input": 0.0025, "output": 0.010},
+ "gpt-4o-mini": {"input": 0.00015, "output": 0.0006},
+ "gpt-4-turbo": {"input": 0.01, "output": 0.03},
+ "gpt-4": {"input": 0.03, "output": 0.06},
+ "gpt-4-32k": {"input": 0.06, "output": 0.12},
+ "gpt-3.5-turbo": {"input": 0.0005, "output": 0.0015},
+ "gpt-3.5-turbo-16k": {"input": 0.003, "output": 0.004},
+ # DeepSeek Series
+ "deepseek-chat": {"input": 0.00014, "output": 0.00028},
+ "deepseek-coder": {"input": 0.00014, "output": 0.00028},
+ # Anthropic Claude Series
+ "claude-3-opus": {"input": 0.015, "output": 0.075},
+ "claude-3-sonnet": {"input": 0.003, "output": 0.015},
+ "claude-3-haiku": {"input": 0.00025, "output": 0.00125},
+ "claude-3-5-sonnet": {"input": 0.003, "output": 0.015},
+ # Google Gemini Series
+ "gemini-pro": {"input": 0.0005, "output": 0.0015},
+ "gemini-1.5-pro": {"input": 0.00125, "output": 0.005},
+ "gemini-1.5-flash": {"input": 0.000075, "output": 0.0003},
+}
+
+
+def get_tiktoken_encoding(model_name: str):
+ """
+ Get tiktoken encoder (for precise token counting)
+
+ Args:
+ model_name: Model name
+
+ Returns:
+ tiktoken.Encoding object, returns None if not available
+ """
+ if not TIKTOKEN_AVAILABLE:
+ return None
+
+ try:
+ # Try getting encoding based on model name
+ if "gpt-4" in model_name.lower() or "gpt-3.5" in model_name.lower():
+ return tiktoken.encoding_for_model(model_name)
+ if "gpt-4o" in model_name.lower():
+ return tiktoken.encoding_for_model("gpt-4o")
+ # Default to cl100k_base (encoding for GPT-3.5/GPT-4)
+ return tiktoken.get_encoding("cl100k_base")
+ except Exception:
+ # If fails, use default encoding
+ return tiktoken.get_encoding("cl100k_base")
+
+
+def count_tokens_with_tiktoken(text: str, model_name: str) -> int:
+ """
+ Precisely calculate token count using tiktoken
+
+ Args:
+ text: Text to calculate
+ model_name: Model name (for selecting correct encoding)
+
+ Returns:
+ Token count
+ """
+ if not TIKTOKEN_AVAILABLE:
+ return 0
+
+ encoding = get_tiktoken_encoding(model_name)
+ if encoding is None:
+ return 0
+
+ return len(encoding.encode(text))
+
+
+def count_tokens_with_litellm(messages: list[dict], model_name: str) -> dict[str, int]:
+ """
+ Calculate token count using litellm (if available)
+
+ Args:
+ messages: Message list
+ model_name: Model name
+
+ Returns:
+ {'prompt_tokens': int, 'completion_tokens': int, 'total_tokens': int}
+ """
+ if not LITELLM_AVAILABLE:
+ return {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0}
+
+ try:
+ # Use litellm's token_counter
+ token_count = token_counter(model=model_name, messages=messages)
+ return {
+ "prompt_tokens": token_count,
+ "completion_tokens": 0, # litellm only counts prompt tokens
+ "total_tokens": token_count,
+ }
+ except Exception:
+ return {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0}
+
+
+def calculate_cost_with_litellm(model: str, prompt_tokens: int, completion_tokens: int) -> float:
+ """
+ Calculate cost using litellm (more accurate if available)
+
+ Args:
+ model: Model name
+ prompt_tokens: Input tokens
+ completion_tokens: Output tokens
+
+ Returns:
+ Cost (USD)
+ """
+ if not LITELLM_AVAILABLE:
+ # Fall back to manual calculation
+ return calculate_cost(model, prompt_tokens, completion_tokens)
+
+ try:
+ # Use litellm's completion_cost function
+ cost = litellm.completion_cost(
+ model=model, prompt_tokens=prompt_tokens, completion_tokens=completion_tokens
+ )
+ return cost
+ except Exception:
+ # If failed, fall back to manual calculation
+ return calculate_cost(model, prompt_tokens, completion_tokens)
+
+
+def get_model_pricing(model_name: str) -> dict[str, float]:
+ """
+ Get model pricing information
+
+ Args:
+ model_name: Model name
+
+ Returns:
+ {'input': float, 'output': float} Price per 1K tokens (USD)
+ """
+ # Try exact match
+ if model_name in MODEL_PRICING:
+ return MODEL_PRICING[model_name]
+
+ # Try fuzzy match (handle model names with version numbers)
+ model_lower = model_name.lower()
+ for key, pricing in MODEL_PRICING.items():
+ if key.lower() in model_lower or model_lower in key.lower():
+ return pricing
+
+ # If using litellm, try to get price from litellm
+ if LITELLM_AVAILABLE:
+ try:
+ # litellm has built-in pricing table
+ model_info = litellm.get_model_info(model=model_name)
+ if model_info and "input_cost_per_token" in model_info:
+ return {
+ "input": model_info.get("input_cost_per_token", 0) * 1000,
+ "output": model_info.get("output_cost_per_token", 0) * 1000,
+ }
+ except Exception:
+ pass
+
+ # Default price (use gpt-4o-mini as conservative estimate)
+ return MODEL_PRICING.get("gpt-4o-mini", {"input": 0.00015, "output": 0.0006})
+
+
+def calculate_cost(model_name: str, prompt_tokens: int, completion_tokens: int) -> float:
+ """
+ Calculate LLM call cost (backward compatibility function)
+
+ Args:
+ model_name: Model name
+ prompt_tokens: Number of input tokens
+ completion_tokens: Number of output tokens
+
+ Returns:
+ Cost (USD)
+ """
+ pricing = get_model_pricing(model_name)
+
+ input_cost = (prompt_tokens / 1000.0) * pricing["input"]
+ output_cost = (completion_tokens / 1000.0) * pricing["output"]
+
+ return input_cost + output_cost
+
+
+@dataclass
+class TokenUsage:
+ """Token usage record for a single LLM call"""
+
+ agent_name: str
+ stage: str
+ model: str
+ prompt_tokens: int = 0
+ completion_tokens: int = 0
+ total_tokens: int = 0
+ cost_usd: float = 0.0
+ timestamp: str = field(default_factory=lambda: datetime.now().isoformat())
+ # New field
+ calculation_method: str = "api" # "api", "tiktoken", "litellm", "estimated"
+
+ def to_dict(self) -> dict[str, Any]:
+ return asdict(self)
+
+
+class TokenTracker:
+ """
+ Token Tracker (Advanced Version)
+ Supports multiple token counting methods: API response > tiktoken > litellm > estimation
+ """
+
+ def __init__(self, prefer_tiktoken: bool = True, prefer_litellm: bool = False):
+ """
+ Initialize tracker.
+
+ Args:
+ prefer_tiktoken: If API doesn't return usage, prefer tiktoken calculation (default True)
+ prefer_litellm: Whether to prefer litellm (requires litellm installation, default False)
+ """
+ self.usage_records: list[TokenUsage] = []
+ self.total_prompt_tokens = 0
+ self.total_completion_tokens = 0
+ self.total_tokens = 0
+ self.total_cost_usd = 0.0
+ self.prefer_tiktoken = prefer_tiktoken and TIKTOKEN_AVAILABLE
+ self.prefer_litellm = prefer_litellm and LITELLM_AVAILABLE
+
+ # Callback for real-time updates (e.g., to display_manager)
+ self._on_usage_added_callback = None
+
+ def set_on_usage_added_callback(self, callback):
+ """
+ Set a callback to be called whenever usage is added.
+ The callback receives the summary dict.
+
+ Args:
+ callback: Function that takes summary dict as argument
+ """
+ self._on_usage_added_callback = callback
+
+ def add_usage(
+ self,
+ agent_name: str,
+ stage: str,
+ model: str,
+ prompt_tokens: int = 0,
+ completion_tokens: int = 0,
+ token_counts: dict[str, int] | None = None,
+ # New parameters: for precise calculation
+ system_prompt: str | None = None,
+ user_prompt: str | None = None,
+ response_text: str | None = None,
+ messages: list[dict] | None = None,
+ ):
+ """
+ Add token usage record (supports multiple calculation methods)
+
+ Args:
+ agent_name: Agent name
+ stage: Stage name
+ model: Model name
+ prompt_tokens: Input tokens (will be overridden if token_counts is provided)
+ completion_tokens: Output tokens (will be overridden if token_counts is provided)
+ token_counts: Optional token count dictionary (from API response, most accurate)
+ system_prompt: System prompt (for tiktoken calculation)
+ user_prompt: User prompt (for tiktoken calculation)
+ response_text: Response text (for tiktoken calculation)
+ messages: Message list (for litellm calculation)
+ """
+ calculation_method = "api"
+
+ # If token_counts is provided (from API response), prioritize using it
+ if token_counts:
+ prompt_tokens = token_counts.get("prompt_tokens", prompt_tokens)
+ completion_tokens = token_counts.get("completion_tokens", completion_tokens)
+ calculation_method = "api"
+ # If no API data, try using tiktoken for precise calculation
+ elif self.prefer_tiktoken and system_prompt and user_prompt:
+ prompt_tokens = count_tokens_with_tiktoken(system_prompt + "\n" + user_prompt, model)
+ if response_text:
+ completion_tokens = count_tokens_with_tiktoken(response_text, model)
+ calculation_method = "tiktoken"
+ # If litellm is available and messages are provided
+ elif self.prefer_litellm and messages:
+ result = count_tokens_with_litellm(messages, model)
+ prompt_tokens = result["prompt_tokens"]
+ completion_tokens = result.get("completion_tokens", completion_tokens)
+ calculation_method = "litellm"
+ # If none available, use estimation (fallback)
+ elif system_prompt and user_prompt:
+ # Simple estimation
+ estimated_prompt_tokens = int(
+ (len(system_prompt.split()) + len(user_prompt.split())) * 1.3
+ )
+ prompt_tokens = estimated_prompt_tokens
+ if response_text:
+ completion_tokens = int(len(response_text.split()) * 1.3)
+ calculation_method = "estimated"
+
+ total_tokens = prompt_tokens + completion_tokens
+
+ # Calculate cost (prefer litellm, otherwise manual calculation)
+ if self.prefer_litellm and LITELLM_AVAILABLE:
+ cost_usd = calculate_cost_with_litellm(model, prompt_tokens, completion_tokens)
+ else:
+ cost_usd = calculate_cost(model, prompt_tokens, completion_tokens)
+
+ # Create usage record
+ usage = TokenUsage(
+ agent_name=agent_name,
+ stage=stage,
+ model=model,
+ prompt_tokens=prompt_tokens,
+ completion_tokens=completion_tokens,
+ total_tokens=total_tokens,
+ cost_usd=cost_usd,
+ calculation_method=calculation_method,
+ )
+
+ self.usage_records.append(usage)
+
+ # Update totals
+ self.total_prompt_tokens += prompt_tokens
+ self.total_completion_tokens += completion_tokens
+ self.total_tokens += total_tokens
+ self.total_cost_usd += cost_usd
+
+ # Invoke callback for real-time updates
+ if self._on_usage_added_callback:
+ try:
+ self._on_usage_added_callback(self.get_summary())
+ except Exception:
+ pass # Don't let callback errors affect main flow
+
+ def get_summary(self) -> dict[str, Any]:
+ """
+ Get usage summary
+
+ Returns:
+ {
+ 'total_prompt_tokens': int,
+ 'total_completion_tokens': int,
+ 'total_tokens': int,
+ 'total_cost_usd': float,
+ 'total_calls': int,
+ 'by_agent': Dict[str, Dict],
+ 'by_model': Dict[str, Dict],
+ 'by_method': Dict[str, Dict], # New: statistics by calculation method
+ 'tiktoken_available': bool,
+ 'litellm_available': bool
+ }
+ """
+ by_agent: dict[str, dict[str, Any]] = {}
+ by_model: dict[str, dict[str, Any]] = {}
+ by_method: dict[str, dict[str, Any]] = {}
+
+ for usage in self.usage_records:
+ # Statistics by Agent
+ if usage.agent_name not in by_agent:
+ by_agent[usage.agent_name] = {
+ "prompt_tokens": 0,
+ "completion_tokens": 0,
+ "total_tokens": 0,
+ "cost_usd": 0.0,
+ "calls": 0,
+ }
+ by_agent[usage.agent_name]["prompt_tokens"] += usage.prompt_tokens
+ by_agent[usage.agent_name]["completion_tokens"] += usage.completion_tokens
+ by_agent[usage.agent_name]["total_tokens"] += usage.total_tokens
+ by_agent[usage.agent_name]["cost_usd"] += usage.cost_usd
+ by_agent[usage.agent_name]["calls"] += 1
+
+ # Statistics by model
+ if usage.model not in by_model:
+ by_model[usage.model] = {
+ "prompt_tokens": 0,
+ "completion_tokens": 0,
+ "total_tokens": 0,
+ "cost_usd": 0.0,
+ "calls": 0,
+ }
+ by_model[usage.model]["prompt_tokens"] += usage.prompt_tokens
+ by_model[usage.model]["completion_tokens"] += usage.completion_tokens
+ by_model[usage.model]["total_tokens"] += usage.total_tokens
+ by_model[usage.model]["cost_usd"] += usage.cost_usd
+ by_model[usage.model]["calls"] += 1
+
+ # Statistics by calculation method
+ method = usage.calculation_method
+ if method not in by_method:
+ by_method[method] = {
+ "prompt_tokens": 0,
+ "completion_tokens": 0,
+ "total_tokens": 0,
+ "cost_usd": 0.0,
+ "calls": 0,
+ }
+ by_method[method]["prompt_tokens"] += usage.prompt_tokens
+ by_method[method]["completion_tokens"] += usage.completion_tokens
+ by_method[method]["total_tokens"] += usage.total_tokens
+ by_method[method]["cost_usd"] += usage.cost_usd
+ by_method[method]["calls"] += 1
+
+ return {
+ "total_prompt_tokens": self.total_prompt_tokens,
+ "total_completion_tokens": self.total_completion_tokens,
+ "total_tokens": self.total_tokens,
+ "total_cost_usd": self.total_cost_usd,
+ "total_calls": len(self.usage_records),
+ "by_agent": by_agent,
+ "by_model": by_model,
+ "by_method": by_method, # New: statistics by calculation method
+ "tiktoken_available": TIKTOKEN_AVAILABLE,
+ "litellm_available": LITELLM_AVAILABLE,
+ }
+
+ def format_summary(self) -> str:
+ """
+ Format usage summary as readable string
+
+ Returns:
+ Formatted summary string
+ """
+ summary = self.get_summary()
+
+ lines = [
+ "=" * 70,
+ "💰 LLM Cost Statistics",
+ "=" * 70,
+ f"Total calls: {summary['total_calls']}",
+ f"Total Tokens: {summary['total_tokens']:,}",
+ f" - Input: {summary['total_prompt_tokens']:,}",
+ f" - Output: {summary['total_completion_tokens']:,}",
+ f"Total cost: ${summary['total_cost_usd']:.6f} USD",
+ ]
+
+ # If advanced features are used, show tool status and calculation method statistics
+ if summary.get("tiktoken_available") or summary.get("litellm_available"):
+ lines.append("")
+ lines.append("Calculation Tool Status:")
+ lines.append(
+ f" - tiktoken: {'✓ Available' if summary['tiktoken_available'] else '✗ Unavailable'}"
+ )
+ lines.append(
+ f" - litellm: {'✓ Available' if summary['litellm_available'] else '✗ Unavailable'}"
+ )
+
+ if summary.get("by_method"):
+ lines.append("")
+ lines.append("Statistics by Calculation Method:")
+ lines.append("-" * 70)
+ for method, stats in sorted(summary["by_method"].items()):
+ method_name = {
+ "api": "API Response",
+ "tiktoken": "tiktoken Precise Calculation",
+ "litellm": "litellm Calculation",
+ "estimated": "Estimation",
+ }.get(method, method)
+ lines.append(f" {method_name}:")
+ lines.append(f" Calls: {stats['calls']}")
+ lines.append(f" Tokens: {stats['total_tokens']:,}")
+ lines.append(f" Cost: ${stats['cost_usd']:.6f} USD")
+ lines.append("")
+
+ lines.append("Statistics by Agent:")
+ lines.append("-" * 70)
+ for agent_name, stats in sorted(summary["by_agent"].items()):
+ lines.append(f" {agent_name}:")
+ lines.append(f" Calls: {stats['calls']}")
+ lines.append(
+ f" Tokens: {stats['total_tokens']:,} (Input: {stats['prompt_tokens']:,}, Output: {stats['completion_tokens']:,})"
+ )
+ lines.append(f" Cost: ${stats['cost_usd']:.6f} USD")
+ lines.append("")
+
+ lines.append("Statistics by Model:")
+ lines.append("-" * 70)
+ for model, stats in sorted(summary["by_model"].items()):
+ lines.append(f" {model}:")
+ lines.append(f" Calls: {stats['calls']}")
+ lines.append(
+ f" Tokens: {stats['total_tokens']:,} (Input: {stats['prompt_tokens']:,}, Output: {stats['completion_tokens']:,})"
+ )
+ lines.append(f" Cost: ${stats['cost_usd']:.6f} USD")
+ lines.append("")
+
+ lines.append("=" * 70)
+
+ return "\n".join(lines)
+
+ def reset(self):
+ """Reset all statistics"""
+ self.usage_records.clear()
+ self.total_prompt_tokens = 0
+ self.total_completion_tokens = 0
+ self.total_tokens = 0
+ self.total_cost_usd = 0.0
+
+ def save(self, filepath: str):
+ """
+ Save usage records to file
+
+ Args:
+ filepath: Save path
+ """
+ data = {
+ "summary": self.get_summary(),
+ "records": [usage.to_dict() for usage in self.usage_records],
+ }
+
+ with open(filepath, "w", encoding="utf-8") as f:
+ json.dump(data, f, ensure_ascii=False, indent=2)
diff --git a/src/api/README.md b/src/api/README.md
new file mode 100644
index 000000000..b27a6bbf3
--- /dev/null
+++ b/src/api/README.md
@@ -0,0 +1,275 @@
+# API Module
+
+The API module provides REST and WebSocket endpoints for the OpenTutor 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.core.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 gracefully
diff --git a/src/api/__init__.py b/src/api/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/src/api/main.py b/src/api/main.py
new file mode 100644
index 000000000..2ea3a0ea5
--- /dev/null
+++ b/src/api/main.py
@@ -0,0 +1,128 @@
+from contextlib import asynccontextmanager
+from pathlib import Path
+
+from fastapi import FastAPI
+from fastapi.middleware.cors import CORSMiddleware
+from fastapi.staticfiles import StaticFiles
+
+from src.api.routers import (
+ co_writer,
+ dashboard,
+ guide,
+ ideagen,
+ knowledge,
+ notebook,
+ question,
+ research,
+ settings,
+ solve,
+ system,
+)
+from src.core.logging import get_logger
+
+logger = get_logger("API")
+
+
+@asynccontextmanager
+async def lifespan(app: FastAPI):
+ """
+ Application lifecycle management
+ Gracefully handle startup and shutdown events, avoid CancelledError
+ """
+ # Execute on startup
+ logger.info("Application startup")
+ yield
+ # Execute on shutdown
+ logger.info("Application shutdown")
+
+
+app = FastAPI(title="OpenTutor API", version="1.0.0", lifespan=lifespan)
+
+# Configure CORS
+app.add_middleware(
+ CORSMiddleware,
+ allow_origins=["*"], # In production, replace with specific frontend origin
+ allow_credentials=True,
+ allow_methods=["*"],
+ allow_headers=["*"],
+)
+
+# Mount user directory as static root for generated artifacts
+# This allows frontend to access generated artifacts (images, PDFs, etc.)
+# URL: /api/outputs/solve/solve_xxx/artifacts/image.png
+# Physical Path: OpenTutor/data/user/solve/solve_xxx/artifacts/image.png
+project_root = Path(__file__).parent.parent.parent
+user_dir = project_root / "data" / "user"
+
+# Initialize user directories on startup
+try:
+ from src.core.setup import init_user_directories
+
+ init_user_directories(project_root)
+except Exception:
+ # Fallback: just create the main directory if it doesn't exist
+ if not user_dir.exists():
+ user_dir.mkdir(parents=True)
+
+app.mount("/api/outputs", StaticFiles(directory=str(user_dir)), name="outputs")
+
+# Include routers
+app.include_router(solve.router, prefix="/api/v1", tags=["solve"])
+app.include_router(question.router, prefix="/api/v1/question", tags=["question"])
+app.include_router(research.router, prefix="/api/v1/research", tags=["research"])
+app.include_router(knowledge.router, prefix="/api/v1/knowledge", tags=["knowledge"])
+app.include_router(dashboard.router, prefix="/api/v1/dashboard", tags=["dashboard"])
+app.include_router(co_writer.router, prefix="/api/v1/co_writer", tags=["co_writer"])
+app.include_router(notebook.router, prefix="/api/v1/notebook", tags=["notebook"])
+app.include_router(guide.router, prefix="/api/v1/guide", tags=["guide"])
+app.include_router(ideagen.router, prefix="/api/v1/ideagen", tags=["ideagen"])
+app.include_router(settings.router, prefix="/api/v1/settings", tags=["settings"])
+app.include_router(system.router, prefix="/api/v1/system", tags=["system"])
+
+
+async def root():
+ return {"message": "Welcome to OpenTutor API"}
+
+
+if __name__ == "__main__":
+ from pathlib import Path
+
+ import uvicorn
+
+ # Get project root directory
+ project_root = Path(__file__).parent.parent.parent
+
+ # Ensure project root is in Python path
+ import sys
+
+ if str(project_root) not in sys.path:
+ sys.path.insert(0, str(project_root))
+
+ # Get port from configuration
+ from src.core.setup import get_backend_port
+
+ backend_port = get_backend_port(project_root)
+
+ # Configure uvicorn, exclude run_code_workspace directory to avoid file monitoring triggering reload
+ # When code execution tool creates temporary files, it should not trigger service reload
+ # Note: Use relative path patterns to avoid Windows path issues
+ uvicorn.run(
+ "api.main:app",
+ host="0.0.0.0",
+ port=backend_port,
+ reload=True,
+ reload_excludes=[
+ # Code execution workspace - most important, must exclude
+ # Use glob patterns, relative to project root directory
+ "**/run_code_workspace/**",
+ "**/tmp*/**",
+ "**/__pycache__/**",
+ "**/*.pyc",
+ "**/user/solve/**",
+ "**/user/question/**",
+ "**/user/research/**",
+ "**/user/co-writer/**",
+ "**/logs/**",
+ ],
+ )
diff --git a/src/api/routers/__init__.py b/src/api/routers/__init__.py
new file mode 100644
index 000000000..d3bf4e7a0
--- /dev/null
+++ b/src/api/routers/__init__.py
@@ -0,0 +1 @@
+# Init file for routers
diff --git a/src/api/routers/co_writer.py b/src/api/routers/co_writer.py
new file mode 100644
index 000000000..28052383b
--- /dev/null
+++ b/src/api/routers/co_writer.py
@@ -0,0 +1,312 @@
+from pathlib import Path
+import sys
+from typing import Literal
+
+from fastapi import APIRouter, HTTPException
+from fastapi.responses import Response
+from pydantic import BaseModel
+
+# Ensure co_writer module can be imported
+project_root = Path(__file__).parent.parent.parent.parent
+if str(project_root) not in sys.path:
+ sys.path.insert(0, str(project_root))
+
+import json
+
+from src.agents.co_writer.edit_agent import (
+ TOOL_CALLS_DIR,
+ EditAgent,
+ load_history,
+ print_stats,
+)
+from src.core.core import load_config_with_main
+from src.core.logging import get_logger
+
+router = APIRouter()
+
+# Initialize logger with config
+project_root = Path(__file__).parent.parent.parent.parent
+config = load_config_with_main("solve_config.yaml", project_root) # Use any config to get main.yaml
+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)
+
+agent = EditAgent()
+
+# Lazy load NarratorAgent (because TTS config may not exist)
+_narrator_agent = None
+
+
+def get_narrator_agent():
+ global _narrator_agent
+ if _narrator_agent is None:
+ from src.agents.co_writer.narrator_agent import NarratorAgent
+
+ _narrator_agent = NarratorAgent()
+ return _narrator_agent
+
+
+class EditRequest(BaseModel):
+ text: str
+ instruction: str
+ action: Literal["rewrite", "shorten", "expand"] = "rewrite"
+ source: Literal["rag", "web"] | None = None
+ kb_name: str | None = None
+
+
+class EditResponse(BaseModel):
+ edited_text: str
+ operation_id: str
+
+
+class AutoMarkRequest(BaseModel):
+ text: str
+
+
+class AutoMarkResponse(BaseModel):
+ marked_text: str
+ operation_id: str
+
+
[email protected]("/edit", response_model=EditResponse)
+async def edit_text(request: EditRequest):
+ try:
+ result = await agent.process(
+ text=request.text,
+ instruction=request.instruction,
+ action=request.action,
+ source=request.source,
+ kb_name=request.kb_name,
+ )
+
+ # Print token stats
+ print_stats()
+
+ return result
+
+ except Exception as e:
+ import traceback
+
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+
[email protected]("/automark", response_model=AutoMarkResponse)
+async def auto_mark_text(request: AutoMarkRequest):
+ """AI auto-mark text"""
+ try:
+ result = await agent.auto_mark(text=request.text)
+
+ # Print token stats
+ print_stats()
+
+ return result
+ except Exception as e:
+ import traceback
+
+ traceback.print_exc()
+ raise HTTPException(status_code=500, detail=str(e))
+
+
[email protected]("/history")
+async def get_history():
+ """Get all operation history"""
+ try:
+ history = load_history()
+ return {"history": history, "total": len(history)}
+ except Exception as e:
+ raise HTTPException(status_code=500, detail=str(e))
+
+
[email protected]("/history/{operation_id}")
+async def get_operation(operation_id: str):
+ """Get single operation details"""
+ try:
+ history = load_history()
+ for op in history:
+ if op.get("id") == operation_id:
+ return op
+ raise HTTPException(status_code=404, detail="Operation not found")
+ except HTTPException:
+ raise
+ except Exception as e:
+ raise HTTPException(status_code=500, detail=str(e))
+
+
[email protected]("/tool_calls/{operation_id}")
+async def get_tool_call(operation_id: str):
+ """Get tool call details"""
+ try:
+ # Find matching file
+ for filepath in TOOL_CALLS_DIR.glob(f"{operation_id}_*.json"):
+ with open(filepath, encoding="utf-8") as f:
+ return json.load(f)
+ raise HTTPException(status_code=404, detail="Tool call not found")
+ except HTTPException:
+ raise
+ except Exception as e:
+ raise HTTPException(status_code=500, detail=str(e))
+
+
[email protected]("/export/markdown")
+async def export_markdown(content: dict):
+ """Export as Markdown file"""
+ try:
+ markdown_content = content.get("content", "")
+ filename = content.get("filename", "document.md")
+
+ return Response(
+ content=markdown_content,
+ media_type="text/markdown",
+ headers={"Content-Disposition": f"attachment; filename={filename}"},
+ )
+ 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:
+ import traceback
+
+ 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:
+ import traceback
+
+ 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:
+ from src.core.core import get_tts_config
+
+ 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/src/api/routers/dashboard.py
new file mode 100644
index 000000000..57c077f5d
--- /dev/null
+++ b/src/api/routers/dashboard.py
@@ -0,0 +1,18 @@
+from fastapi import APIRouter, HTTPException
+
+from src.api.utils.history import history_manager
+
+router = APIRouter()
+
+
+async def get_recent_history(limit: int = 10, type: str | None = None):
+ return history_manager.get_recent(limit, type)
+
+
[email protected]("/{entry_id}")
+async def get_history_entry(entry_id: str):
+ entry = history_manager.get_entry(entry_id)
+ if not entry:
+ raise HTTPException(status_code=404, detail="Entry not found")
+ return entry
diff --git a/src/api/routers/guide.py b/src/api/routers/guide.py
new file mode 100644
index 000000000..a93140691
--- /dev/null
+++ b/src/api/routers/guide.py
@@ -0,0 +1,336 @@
+"""
+Guided Learning API Router
+==========================
+
+Provides session creation, learning progress management, and chat interaction.
+"""
+
+from pathlib import Path
+import sys
+
+from fastapi import APIRouter, HTTPException, WebSocket, WebSocketDisconnect
+from pydantic import BaseModel
+
+project_root = Path(__file__).parent.parent.parent.parent
+if str(project_root) not in sys.path:
+ sys.path.insert(0, str(project_root))
+
+from pathlib import Path
+
+from src.agents.guide.agents.base_guide_agent import BaseGuideAgent
+from src.api.utils.notebook_manager import notebook_manager
+from src.core.core import load_config_with_main
+from src.core.logging import get_logger
+
+router = APIRouter()
+
+# Initialize logger with config
+project_root = Path(__file__).parent.parent.parent.parent
+config = load_config_with_main("guide_config.yaml", project_root)
+log_dir = config.get("paths", {}).get("user_log_dir") or config.get("logging", {}).get("log_dir")
+logger = get_logger("Guide", level="INFO", log_dir=log_dir)
+
+
+# === Request/Response Models ===
+
+
+class CreateSessionRequest(BaseModel):
+ """Create session request"""
+
+ notebook_id: str | None = None # Optional, single notebook mode
+ records: list[dict] | None = None # Optional, cross-notebook mode with direct records
+
+
+class ChatRequest(BaseModel):
+ """Chat request"""
+
+ session_id: str
+ message: str
+
+
+class FixHtmlRequest(BaseModel):
+ """Fix HTML request"""
+
+ session_id: str
+ bug_description: str
+
+
+class NextKnowledgeRequest(BaseModel):
+ """Next knowledge point request"""
+
+ session_id: str
+
+
+# === Helper Functions ===
+
+
+def get_guide_manager():
+ """Get GuideManager instance"""
+ try:
+ from src.core.core import get_llm_config
+
+ llm_config = get_llm_config()
+ api_key = llm_config["api_key"]
+ base_url = llm_config["base_url"]
+ except Exception as e:
+ raise HTTPException(status_code=500, detail=f"LLM config error: {e!s}")
+
+ from src.agents.guide.guide_manager import GuideManager
+
+ return GuideManager(api_key=api_key, base_url=base_url, language=None) # Read from config file
+
+
+# === REST API Endpoints ===
+
+
[email protected]("/create_session")
+async def create_session(request: CreateSessionRequest):
+ """
+ Create a new guided learning session.
+
+ Returns:
+ Session creation result with knowledge point list.
+ """
+ from src.api.utils.task_id_manager import TaskIDManager
+
+ task_manager = TaskIDManager.get_instance()
+
+ try:
+ records = []
+ notebook_name = "Unknown"
+
+ # Mode 1: Cross-notebook mode - use provided records directly
+ if request.records and isinstance(request.records, list):
+ records = request.records
+ notebook_name = f"Cross-notebook ({len(records)} records)"
+ # Mode 2: Single notebook mode - get records from notebook
+ elif request.notebook_id:
+ notebook = notebook_manager.get_notebook(request.notebook_id)
+ if not notebook:
+ raise HTTPException(status_code=404, detail="Notebook not found")
+
+ records = notebook.get("records", [])
+ notebook_name = notebook.get("name", "Unknown")
+ else:
+ raise HTTPException(status_code=400, detail="Must provide notebook_id or records")
+
+ if not records:
+ raise HTTPException(status_code=400, detail="No available records")
+
+ # Reset LLM stats for new session
+ BaseGuideAgent.reset_stats()
+
+ manager = get_guide_manager()
+ result = await manager.create_session(
+ notebook_id=request.notebook_id or "cross_notebook",
+ notebook_name=notebook_name,
+ records=records,
+ )
+
+ if result and "session_id" in result:
+ session_id = result["session_id"]
+ task_id = task_manager.generate_task_id("guide", session_id)
+ logger.info(f"[{task_id}] Session created: {session_id}")
+
+ return result
+
+ except HTTPException:
+ raise
+ except Exception as e:
+ logger.error(f"Create session failed: {e}")
+ raise HTTPException(status_code=500, detail=str(e))
+
+
+async def start_learning(request: NextKnowledgeRequest):
+ """
+ Start learning (get the first knowledge point).
+ """
+ try:
+ manager = get_guide_manager()
+ result = await manager.start_learning(request.session_id)
+ return result
+ except Exception as e:
+ logger.error(f"Start learning failed: {e}")
+ raise HTTPException(status_code=500, detail=str(e))
+
+
+async def next_knowledge(request: NextKnowledgeRequest):
+ """
+ Move to the next knowledge point.
+ """
+ try:
+ manager = get_guide_manager()
+ result = await manager.next_knowledge(request.session_id)
+
+ # Print stats if learning completed
+ if result.get("learning_complete", False):
+ BaseGuideAgent.print_stats()
+
+ return result
+ except Exception as e:
+ logger.error(f"Next knowledge failed: {e}")
+ raise HTTPException(status_code=500, detail=str(e))
+
+
+async def chat(request: ChatRequest):
+ """
+ Send a chat message.
+ """
+ try:
+ manager = get_guide_manager()
+ result = await manager.chat(request.session_id, request.message)
+ return result
+ except Exception as e:
+ logger.error(f"Chat failed: {e}")
+ raise HTTPException(status_code=500, detail=str(e))
+
+
[email protected]("/fix_html")
+async def fix_html(request: FixHtmlRequest):
+ """
+ Fix HTML page bugs.
+ """
+ try:
+ manager = get_guide_manager()
+ result = await manager.fix_html(request.session_id, request.bug_description)
+ return result
+ except Exception as e:
+ logger.error(f"Fix HTML failed: {e}")
+ raise HTTPException(status_code=500, detail=str(e))
+
+
[email protected]("/session/{session_id}")
+async def get_session(session_id: str):
+ """
+ Get session information.
+ """
+ try:
+ manager = get_guide_manager()
+ session = manager.get_session(session_id)
+ if not session:
+ raise HTTPException(status_code=404, detail="Session not found")
+ return session
+ except HTTPException:
+ raise
+ except Exception as e:
+ logger.error(f"Get session failed: {e}")
+ raise HTTPException(status_code=500, detail=str(e))
+
+
[email protected]("/session/{session_id}/html")
+async def get_current_html(session_id: str):
+ """
+ Get the current HTML page.
+ """
+ try:
+ manager = get_guide_manager()
+ html = manager.get_current_html(session_id)
+ if html is None:
+ raise HTTPException(status_code=404, detail="Session not found or no HTML content")
+ return {"html": html}
+ except HTTPException:
+ raise
+ except Exception as e:
+ logger.error(f"Get HTML failed: {e}")
+ raise HTTPException(status_code=500, detail=str(e))
+
+
+# === WebSocket Endpoint ===
+
+
[email protected]("/ws/{session_id}")
+async def websocket_guide(websocket: WebSocket, session_id: str):
+ """
+ WebSocket endpoint for real-time interaction.
+
+ Message types:
+ - start: Start learning
+ - next: Next knowledge point
+ - chat: Send chat message
+ - fix_html: Fix HTML
+ - get_session: Get session state
+ """
+ await websocket.accept()
+
+ from src.api.utils.task_id_manager import TaskIDManager
+
+ task_manager = TaskIDManager.get_instance()
+ task_id = task_manager.generate_task_id("guide", session_id)
+
+ try:
+ await websocket.send_json({"type": "task_id", "task_id": task_id})
+ except (RuntimeError, WebSocketDisconnect, ConnectionError) as e:
+ logger.debug(f"Failed to send task_id: {e}")
+
+ try:
+ manager = get_guide_manager()
+
+ session = manager.get_session(session_id)
+ if not session:
+ await websocket.send_json({"type": "error", "content": "Session not found"})
+ await websocket.close()
+ return
+
+ logger.info(f"[{task_id}] Guide session started: {session_id}")
+
+ await websocket.send_json({"type": "session_info", "data": session})
+
+ while True:
+ try:
+ data = await websocket.receive_json()
+ msg_type = data.get("type", "")
+
+ if msg_type == "start":
+ logger.debug(f"[{task_id}] Start learning")
+ result = await manager.start_learning(session_id)
+ await websocket.send_json({"type": "start_result", "data": result})
+
+ elif msg_type == "next":
+ logger.debug(f"[{task_id}] Next knowledge point")
+ result = await manager.next_knowledge(session_id)
+ await websocket.send_json({"type": "next_result", "data": result})
+
+ elif msg_type == "chat":
+ message = data.get("message", "")
+ if message:
+ logger.debug(f"[{task_id}] User message: {message[:50]}...")
+ result = await manager.chat(session_id, message)
+ await websocket.send_json({"type": "chat_result", "data": result})
+
+ elif msg_type == "fix_html":
+ bug_desc = data.get("bug_description", "")
+ logger.debug(f"[{task_id}] Fix HTML: {bug_desc[:50]}...")
+ result = await manager.fix_html(session_id, bug_desc)
+ await websocket.send_json({"type": "fix_result", "data": result})
+
+ elif msg_type == "get_session":
+ session = manager.get_session(session_id)
+ await websocket.send_json({"type": "session_info", "data": session})
+
+ else:
+ await websocket.send_json(
+ {"type": "error", "content": f"Unknown message type: {msg_type}"}
+ )
+
+ except WebSocketDisconnect:
+ logger.debug(f"WebSocket disconnected: {session_id}")
+ break
+ except Exception as e:
+ logger.error(f"WebSocket error: {e}")
+ await websocket.send_json({"type": "error", "content": str(e)})
+
+ except Exception as e:
+ logger.error(f"WebSocket connection error: {e}")
+ try:
+ await websocket.close()
+ except (RuntimeError, WebSocketDisconnect, ConnectionError):
+ pass # Connection already closed
+
+
+async def health_check():
+ """Health check"""
+ return {"status": "healthy", "service": "guide"}
diff --git a/src/api/routers/ideagen.py b/src/api/routers/ideagen.py
new file mode 100644
index 000000000..7f5fbbf06
--- /dev/null
+++ b/src/api/routers/ideagen.py
@@ -0,0 +1,413 @@
+"""
+IdeaGen API Router
+Used to generate research ideas from notebook content
+"""
+
+from datetime import datetime
+from pathlib import Path
+import sys
+
+from fastapi import APIRouter, WebSocket, WebSocketDisconnect
+from pydantic import BaseModel
+
+# Ensure project modules can be imported
+project_root = Path(__file__).parent.parent.parent.parent
+if str(project_root) not in sys.path:
+ sys.path.insert(0, str(project_root))
+
+from src.agents.ideagen.base_idea_agent import BaseIdeaAgent
+from src.agents.ideagen.idea_generation_workflow import IdeaGenerationWorkflow
+from src.agents.ideagen.material_organizer_agent import MaterialOrganizerAgent
+from src.api.utils.notebook_manager import NotebookManager
+from src.core.core import get_llm_config, load_config_with_main
+from src.core.logging import get_logger
+
+router = APIRouter()
+
+# Initialize logger with config
+project_root = Path(__file__).parent.parent.parent.parent
+config = load_config_with_main("solve_config.yaml", project_root) # Use any config to get main.yaml
+log_dir = config.get("paths", {}).get("user_log_dir") or config.get("logging", {}).get("log_dir")
+logger = get_logger("IdeaGen", level="INFO", log_dir=log_dir)
+
+
+class IdeaGenRequest(BaseModel):
+ notebook_id: str
+ record_ids: list[str] | None = None # If None, use all records
+
+
+# Define status constants to make state flow clearer
+class IdeaGenStage:
+ """IdeaGen status stages"""
+
+ INIT = "init" # Initialization
+ EXTRACTING = "extracting" # Extracting knowledge points
+ KNOWLEDGE_EXTRACTED = "knowledge_extracted" # Knowledge points extraction completed
+ FILTERING = "filtering" # Loose filtering
+ FILTERED = "filtered" # Filtering completed
+ EXPLORING = "exploring" # Exploring research ideas
+ EXPLORED = "explored" # Exploration completed
+ STRICT_FILTERING = "strict_filtering" # Strict filtering
+ GENERATING = "generating" # Generating statement
+ IDEA_READY = "idea_ready" # Single idea ready
+ COMPLETE = "complete" # All completed
+ ERROR = "error" # Error
+
+
+async def send_status(
+ websocket: WebSocket, stage: str, message: str, data: dict = None, task_id: str = None
+):
+ """Unified status sending function"""
+ payload = {
+ "type": "status",
+ "stage": stage,
+ "message": message,
+ "timestamp": datetime.now().isoformat(),
+ }
+ if data:
+ payload["data"] = data
+
+ await websocket.send_json(payload)
+
+ # Log to file
+ log_msg = f"[{stage}] {message}"
+ if task_id:
+ log_msg = f"[{task_id}] {log_msg}"
+ logger.info(log_msg)
+
+
[email protected]("/generate")
+async def websocket_ideagen(websocket: WebSocket):
+ """
+ WebSocket endpoint: Execute idea generation workflow
+
+ Status flow:
+ 1. init -> Initialization
+ 2. extracting -> Extract knowledge points
+ 3. knowledge_extracted -> Knowledge points extraction completed
+ 4. filtering -> Loose filtering
+ 5. filtered -> Filtering completed
+ 6. exploring -> Explore research ideas (loop)
+ 7. explored -> Exploration completed
+ 8. strict_filtering -> Strict filtering
+ 9. generating -> Generate statement
+ 10. idea_ready -> Single idea ready
+ 11. complete -> All completed
+
+ Request format:
+ {
+ "notebook_id": "string", // Optional, single notebook mode
+ "record_ids": ["id1", "id2"], // Optional, specify specific records
+ "records": [...], // Optional, cross-notebook mode directly provide records
+ "user_thoughts": "string" // Optional, user additional thoughts
+ }
+ """
+ await websocket.accept()
+ logger.info("=" * 60)
+ logger.info("WebSocket connection accepted")
+ logger.info("=" * 60)
+
+ # Get task ID manager
+ from src.api.utils.task_id_manager import TaskIDManager
+
+ task_manager = TaskIDManager.get_instance()
+ task_id = None
+
+ try:
+ # Receive request data
+ data = await websocket.receive_json()
+ notebook_id = data.get("notebook_id")
+ record_ids = data.get("record_ids")
+ direct_records = data.get("records")
+ user_thoughts = data.get("user_thoughts", "")
+
+ logger.info(
+ f"Received request: notebook_id={notebook_id}, record_ids={record_ids}, direct_records_count={len(direct_records) if direct_records else 0}"
+ )
+
+ # Generate task ID
+ task_key = (
+ f"ideagen_{notebook_id or 'cross_notebook'}_{hash(str(direct_records or record_ids))}"
+ )
+ task_id = task_manager.generate_task_id("ideagen", task_key)
+
+ # Send task ID to frontend
+ await websocket.send_json({"type": "task_id", "task_id": task_id})
+ logger.info(f"Task ID: {task_id}")
+
+ # ========== Stage 1: INIT ==========
+ await send_status(
+ websocket,
+ IdeaGenStage.INIT,
+ "Initializing idea generation workflow...",
+ task_id=task_id,
+ )
+
+ # Reset LLM stats for this session
+ BaseIdeaAgent.reset_stats()
+
+ # Get LLM configuration
+ llm_config = get_llm_config()
+
+ # Get records
+ records = []
+
+ if direct_records and isinstance(direct_records, list):
+ records = direct_records
+ logger.info(f"Using {len(records)} direct records")
+ elif notebook_id:
+ nb_manager = NotebookManager()
+ notebook = nb_manager.get_notebook(notebook_id)
+ if not notebook:
+ await send_status(
+ websocket, IdeaGenStage.ERROR, "Notebook not found", task_id=task_id
+ )
+ await websocket.close()
+ return
+
+ records = notebook.get("records", [])
+ if record_ids:
+ records = [r for r in records if r.get("id") in record_ids]
+ logger.info(f"Loaded {len(records)} records from notebook")
+ else:
+ await send_status(
+ websocket, IdeaGenStage.ERROR, "Missing notebook_id or records", task_id=task_id
+ )
+ await websocket.close()
+ return
+
+ if not records:
+ await send_status(websocket, IdeaGenStage.ERROR, "No records found", task_id=task_id)
+ await websocket.close()
+ return
+
+ # ========== Stage 2: EXTRACTING ==========
+ await send_status(
+ websocket,
+ IdeaGenStage.EXTRACTING,
+ f"Extracting knowledge points from {len(records)} records...",
+ {"record_count": len(records)},
+ task_id=task_id,
+ )
+
+ organizer = MaterialOrganizerAgent(
+ api_key=llm_config["api_key"],
+ base_url=llm_config["base_url"],
+ model=llm_config["model"],
+ )
+
+ knowledge_points = await organizer.process(
+ records, user_thoughts if user_thoughts else None
+ )
+ logger.info(f"Extracted {len(knowledge_points)} knowledge points")
+
+ # ========== Stage 3: KNOWLEDGE_EXTRACTED ==========
+ await send_status(
+ websocket,
+ IdeaGenStage.KNOWLEDGE_EXTRACTED,
+ f"Extracted {len(knowledge_points)} knowledge points",
+ {"knowledge_points": knowledge_points, "count": len(knowledge_points)},
+ task_id=task_id,
+ )
+
+ if not knowledge_points:
+ await send_status(
+ websocket,
+ IdeaGenStage.COMPLETE,
+ "No valid knowledge points extracted from notes",
+ {"ideas": [], "count": 0},
+ task_id=task_id,
+ )
+ await websocket.close()
+ return
+
+ # ========== Stage 4: FILTERING (Loose Filter) ==========
+ await send_status(
+ websocket,
+ IdeaGenStage.FILTERING,
+ f"Filtering {len(knowledge_points)} knowledge points (loose criteria)...",
+ {"total": len(knowledge_points)},
+ task_id=task_id,
+ )
+
+ workflow = IdeaGenerationWorkflow(
+ api_key=llm_config["api_key"],
+ base_url=llm_config["base_url"],
+ model=llm_config["model"],
+ progress_callback=None, # We manually manage status here
+ )
+
+ filtered_points = await workflow.loose_filter(knowledge_points)
+ logger.info(
+ f"Loose filter: {len(knowledge_points)} -> {len(filtered_points)} knowledge points"
+ )
+
+ # ========== Stage 5: FILTERED ==========
+ await send_status(
+ websocket,
+ IdeaGenStage.FILTERED,
+ f"Filtered to {len(filtered_points)} knowledge points",
+ {
+ "filtered_points": filtered_points,
+ "original": len(knowledge_points),
+ "filtered": len(filtered_points),
+ },
+ task_id=task_id,
+ )
+
+ if not filtered_points:
+ await send_status(
+ websocket,
+ IdeaGenStage.COMPLETE,
+ "All knowledge points were filtered out",
+ {"ideas": [], "count": 0},
+ task_id=task_id,
+ )
+ await websocket.close()
+ return
+
+ # ========== Stage 6-10: Process each knowledge point ==========
+ all_ideas = []
+ total_points = len(filtered_points)
+
+ for idx, point in enumerate(filtered_points):
+ point_name = point.get("knowledge_point", f"Point {idx + 1}")
+ logger.info(f"Processing knowledge point {idx + 1}/{total_points}: {point_name}")
+
+ # ========== Stage 6: EXPLORING ==========
+ await send_status(
+ websocket,
+ IdeaGenStage.EXPLORING,
+ f"Exploring research ideas for: {point_name} ({idx + 1}/{total_points})",
+ {"index": idx + 1, "total": total_points, "knowledge_point": point_name},
+ task_id=task_id,
+ )
+
+ research_ideas = await workflow.explore_ideas(point)
+ logger.info(f"Generated {len(research_ideas)} research ideas")
+
+ # ========== Stage 7: EXPLORED ==========
+ await send_status(
+ websocket,
+ IdeaGenStage.EXPLORED,
+ f"Generated {len(research_ideas)} research ideas for: {point_name}",
+ {
+ "index": idx + 1,
+ "ideas_count": len(research_ideas),
+ "knowledge_point": point_name,
+ },
+ task_id=task_id,
+ )
+
+ if not research_ideas:
+ logger.warning("No ideas generated, skipping")
+ continue
+
+ # ========== Stage 8: STRICT_FILTERING ==========
+ await send_status(
+ websocket,
+ IdeaGenStage.STRICT_FILTERING,
+ f"Strictly filtering {len(research_ideas)} ideas for: {point_name}",
+ {
+ "index": idx + 1,
+ "ideas_count": len(research_ideas),
+ "knowledge_point": point_name,
+ },
+ task_id=task_id,
+ )
+
+ kept_ideas = await workflow.strict_filter(point, research_ideas)
+ logger.info(f"Kept {len(kept_ideas)} ideas after strict filter")
+
+ if not kept_ideas:
+ logger.warning("No ideas kept, skipping")
+ continue
+
+ # ========== Stage 9: GENERATING ==========
+ await send_status(
+ websocket,
+ IdeaGenStage.GENERATING,
+ f"Generating statement for: {point_name}",
+ {"index": idx + 1, "kept_ideas": len(kept_ideas), "knowledge_point": point_name},
+ task_id=task_id,
+ )
+
+ statement = await workflow.generate_statement(point, kept_ideas)
+ logger.info(f"Statement generated ({len(statement)} chars)")
+
+ idea_result = {
+ "id": f"idea-{idx}",
+ "knowledge_point": point_name,
+ "description": point.get("description", ""),
+ "research_ideas": kept_ideas,
+ "statement": statement,
+ "expanded": False,
+ }
+ all_ideas.append(idea_result)
+
+ # ========== Stage 10: IDEA_READY ==========
+ # Send status message
+ await send_status(
+ websocket,
+ IdeaGenStage.IDEA_READY,
+ f"Research idea ready: {point_name}",
+ {"index": idx + 1, "total": total_points},
+ task_id=task_id,
+ )
+
+ # Important: Also send type="idea" message, frontend needs this to render ideas
+ await websocket.send_json({"type": "idea", "data": idea_result})
+ logger.info(f"Sent idea to frontend: {point_name}")
+
+ # ========== Stage 11: COMPLETE ==========
+ logger.success(
+ f"Workflow complete: generated {len(all_ideas)} ideas from {total_points} knowledge points"
+ )
+ await send_status(
+ websocket,
+ IdeaGenStage.COMPLETE,
+ f"Successfully generated {len(all_ideas)} research ideas",
+ {"ideas": all_ideas, "count": len(all_ideas)},
+ task_id=task_id,
+ )
+
+ # Print LLM usage stats
+ BaseIdeaAgent.print_stats()
+
+ # Update task status
+ task_manager.update_task_status(task_id, "completed")
+ logger.success(f"Task {task_id} completed")
+
+ except WebSocketDisconnect:
+ logger.info(f"WebSocket disconnected (task_id={task_id})")
+ except Exception as e:
+ logger.error(f"ERROR: {e}")
+
+ logger.exception("Exception details:")
+
+ if task_id:
+ task_manager.update_task_status(task_id, "error", error=str(e))
+
+ try:
+ await send_status(
+ websocket,
+ IdeaGenStage.ERROR,
+ f"Error: {e!s}",
+ {"error": str(e)},
+ task_id=task_id,
+ )
+ except (RuntimeError, WebSocketDisconnect, ConnectionError):
+ pass # Connection already closed
+ finally:
+ try:
+ await websocket.close()
+ logger.info("WebSocket closed")
+ except (RuntimeError, WebSocketDisconnect, ConnectionError):
+ pass # Connection already closed
+ logger.info("=" * 60)
+
+
+async def test_ideagen():
+ """Test endpoint"""
+ return {"status": "ok", "message": "IdeaGen API is working"}
diff --git a/src/api/routers/knowledge.py b/src/api/routers/knowledge.py
new file mode 100644
index 000000000..0dba1b531
--- /dev/null
+++ b/src/api/routers/knowledge.py
@@ -0,0 +1,534 @@
+"""
+Knowledge Base API Router
+=========================
+
+Handles knowledge base CRUD operations, file uploads, and initialization.
+"""
+
+import asyncio
+from pathlib import Path
+import shutil
+
+# Use unified logging system
+import sys
+
+from fastapi import (
+ APIRouter,
+ BackgroundTasks,
+ File,
+ Form,
+ HTTPException,
+ UploadFile,
+ WebSocket,
+ WebSocketDisconnect,
+)
+from pydantic import BaseModel
+
+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 ProgressTracker
+
+_project_root = Path(__file__).parent.parent.parent.parent
+sys.path.insert(0, str(_project_root))
+from src.core.core import load_config_with_main
+from src.core.logging import get_logger
+
+# Initialize logger with config
+project_root = Path(__file__).parent.parent.parent.parent
+config = load_config_with_main("solve_config.yaml", project_root) # Use any config to get main.yaml
+log_dir = config.get("paths", {}).get("user_log_dir") or config.get("logging", {}).get("log_dir")
+logger = get_logger("Knowledge", level="INFO", log_dir=log_dir)
+
+router = APIRouter()
+
+_kb_base_dir = _project_root / "data" / "knowledge_bases"
+
+# Lazy initialization
+kb_manager = None
+
+
+def get_kb_manager():
+ """Get KnowledgeBaseManager instance (lazy init)"""
+ global kb_manager
+ if kb_manager is None:
+ kb_manager = KnowledgeBaseManager(base_dir=str(_kb_base_dir))
+ return kb_manager
+
+
+class KnowledgeBaseInfo(BaseModel):
+ name: str
+ is_default: bool
+ statistics: dict
+
+
+async def run_initialization_task(initializer: KnowledgeBaseInitializer):
+ """Background task for knowledge base initialization"""
+ from src.api.utils.task_id_manager import TaskIDManager
+
+ task_manager = TaskIDManager.get_instance()
+ task_id = task_manager.generate_task_id("kb_init", initializer.kb_name)
+
+ try:
+ if not initializer.progress_tracker:
+ initializer.progress_tracker = ProgressTracker(
+ initializer.kb_name, initializer.base_dir
+ )
+
+ initializer.progress_tracker.task_id = task_id
+
+ logger.info(f"[{task_id}] Initializing KB: {initializer.kb_name}")
+
+ await initializer.process_documents()
+ initializer.extract_numbered_items()
+
+ from src.knowledge.progress_tracker import ProgressStage
+
+ initializer.progress_tracker.update(
+ ProgressStage.COMPLETED, "Knowledge base initialization complete!", current=1, total=1
+ )
+
+ logger.success(f"[{task_id}] KB '{initializer.kb_name}' initialized")
+ task_manager.update_task_status(task_id, "completed")
+ except Exception as e:
+ error_msg = str(e)
+
+ logger.error(f"[{task_id}] KB '{initializer.kb_name}' init failed: {error_msg}")
+
+ task_manager.update_task_status(task_id, "error", error=error_msg)
+
+ if initializer.progress_tracker:
+ from src.knowledge.progress_tracker import ProgressStage
+
+ initializer.progress_tracker.update(
+ ProgressStage.ERROR, f"Initialization failed: {error_msg}", error=error_msg
+ )
+
+
+async def run_upload_processing_task(
+ kb_name: str, base_dir: str, api_key: str, base_url: str, uploaded_file_paths: list[str]
+):
+ """Background task for processing uploaded files"""
+ from src.api.utils.task_id_manager import TaskIDManager
+
+ task_manager = TaskIDManager.get_instance()
+ task_key = f"{kb_name}_upload_{len(uploaded_file_paths)}"
+ task_id = task_manager.generate_task_id("kb_upload", task_key)
+
+ progress_tracker = ProgressTracker(kb_name, Path(base_dir))
+ progress_tracker.task_id = task_id
+ from src.knowledge.progress_tracker import ProgressStage
+
+ try:
+ logger.info(f"[{task_id}] Processing {len(uploaded_file_paths)} files to KB '{kb_name}'")
+ progress_tracker.update(
+ ProgressStage.PROCESSING_DOCUMENTS,
+ f"Processing {len(uploaded_file_paths)} files...",
+ current=0,
+ total=len(uploaded_file_paths),
+ )
+
+ adder = DocumentAdder(
+ kb_name=kb_name,
+ base_dir=base_dir,
+ api_key=api_key,
+ base_url=base_url,
+ progress_tracker=progress_tracker,
+ )
+
+ new_files = [Path(path) for path in uploaded_file_paths]
+ processed_files = await adder.process_new_documents(new_files)
+
+ if processed_files:
+ progress_tracker.update(
+ ProgressStage.EXTRACTING_ITEMS,
+ "Extracting numbered items...",
+ current=0,
+ total=len(processed_files),
+ )
+ adder.extract_numbered_items_for_new_docs(processed_files, batch_size=20)
+
+ adder.update_metadata(len(new_files))
+
+ progress_tracker.update(
+ ProgressStage.COMPLETED,
+ f"Successfully processed {len(processed_files)} files!",
+ current=len(processed_files),
+ total=len(processed_files),
+ )
+
+ logger.success(f"[{task_id}] Processed {len(processed_files)} files to KB '{kb_name}'")
+ task_manager.update_task_status(task_id, "completed")
+ except Exception as e:
+ error_msg = f"Upload processing failed (KB '{kb_name}'): {e}"
+ logger.error(f"[{task_id}] {error_msg}")
+
+ task_manager.update_task_status(task_id, "error", error=error_msg)
+
+ progress_tracker.update(
+ ProgressStage.ERROR, f"Processing failed: {error_msg}", error=error_msg
+ )
+
+
+async def health_check():
+ """Health check endpoint"""
+ try:
+ manager = get_kb_manager()
+ config_exists = manager.config_file.exists()
+ kb_count = len(manager.list_knowledge_bases())
+ return {
+ "status": "ok",
+ "config_file": str(manager.config_file),
+ "config_exists": config_exists,
+ "base_dir": str(manager.base_dir),
+ "base_dir_exists": manager.base_dir.exists(),
+ "knowledge_bases_count": kb_count,
+ }
+ except Exception as e:
+ import traceback
+
+ return {"status": "error", "error": str(e), "traceback": traceback.format_exc()}
+
+
[email protected]("/list", response_model=list[KnowledgeBaseInfo])
+async def list_knowledge_bases():
+ """List all available knowledge bases with their details."""
+ try:
+ manager = get_kb_manager()
+ kb_names = manager.list_knowledge_bases()
+
+ logger.info(f"Found {len(kb_names)} knowledge bases: {kb_names}")
+
+ if not kb_names:
+ logger.info("No knowledge bases found, returning empty list")
+ return []
+
+ result = []
+ errors = []
+
+ for name in kb_names:
+ try:
+ info = manager.get_info(name)
+ logger.debug(f"Successfully got info for KB '{name}': {info.get('statistics', {})}")
+ result.append(
+ KnowledgeBaseInfo(
+ name=info["name"],
+ is_default=info["is_default"],
+ statistics=info.get("statistics", {}),
+ )
+ )
+ except Exception as e:
+ import traceback
+
+ error_msg = f"Error getting info for KB '{name}': {e}"
+ errors.append(error_msg)
+ logger.warning(f"{error_msg}\n{traceback.format_exc()}")
+ try:
+ kb_dir = manager.base_dir / name
+ if kb_dir.exists():
+ logger.info(f"KB '{name}' directory exists, creating fallback info")
+ result.append(
+ KnowledgeBaseInfo(
+ name=name,
+ is_default=name == manager.get_default(),
+ statistics={
+ "raw_documents": 0,
+ "images": 0,
+ "content_lists": 0,
+ "rag_initialized": False,
+ },
+ )
+ )
+ except Exception as fallback_err:
+ logger.error(f"Fallback also failed for KB '{name}': {fallback_err}")
+
+ if errors and not result:
+ error_detail = f"Failed to load knowledge bases. Errors: {'; '.join(errors)}"
+ logger.error(error_detail)
+ raise HTTPException(status_code=500, detail=error_detail)
+
+ if errors:
+ logger.warning(
+ f"Some KBs had errors, returning {len(result)} results. Errors: {errors}"
+ )
+
+ logger.info(f"Returning {len(result)} knowledge bases")
+ return result
+ except HTTPException:
+ raise
+ except Exception as e:
+ import traceback
+
+ error_msg = f"Error listing knowledge bases: {e}"
+ logger.error(f"{error_msg}\n{traceback.format_exc()}")
+ raise HTTPException(status_code=500, detail=f"Failed to list knowledge bases: {e!s}")
+
+
[email protected]("/{kb_name}")
+async def get_knowledge_base_details(kb_name: str):
+ """Get detailed info for a specific KB."""
+ try:
+ manager = get_kb_manager()
+ return manager.get_info(kb_name)
+ except ValueError:
+ raise HTTPException(status_code=404, detail=f"Knowledge base '{kb_name}' not found")
+ except Exception as e:
+ raise HTTPException(status_code=500, detail=str(e))
+
+
[email protected]("/{kb_name}")
+async def delete_knowledge_base(kb_name: str):
+ """Delete a knowledge base."""
+ try:
+ manager = get_kb_manager()
+ success = manager.delete_knowledge_base(kb_name, confirm=True)
+ if not success:
+ raise HTTPException(status_code=400, detail="Failed to delete knowledge base")
+ logger.info(f"KB '{kb_name}' deleted")
+ return {"message": f"Knowledge base '{kb_name}' deleted successfully"}
+ except ValueError:
+ raise HTTPException(status_code=404, detail=f"Knowledge base '{kb_name}' not found")
+ except Exception as e:
+ raise HTTPException(status_code=500, detail=str(e))
+
+
[email protected]("/{kb_name}/upload")
+async def upload_files(
+ kb_name: str, background_tasks: BackgroundTasks, files: list[UploadFile] = File(...)
+):
+ """Upload files to a knowledge base and process them in background."""
+ try:
+ manager = get_kb_manager()
+ kb_path = manager.get_knowledge_base_path(kb_name)
+ raw_dir = kb_path / "raw"
+ raw_dir.mkdir(parents=True, exist_ok=True)
+
+ try:
+ from src.core.core import get_llm_config
+
+ llm_config = get_llm_config()
+ api_key = llm_config["api_key"]
+ base_url = llm_config["base_url"]
+ except ValueError as e:
+ raise HTTPException(status_code=500, detail=f"LLM config error: {e!s}")
+
+ uploaded_files = []
+ uploaded_file_paths = []
+ for file in files:
+ file_path = raw_dir / file.filename
+ with open(file_path, "wb") as buffer:
+ shutil.copyfileobj(file.file, buffer)
+ uploaded_files.append(file.filename)
+ uploaded_file_paths.append(str(file_path))
+
+ logger.info(f"Uploading {len(uploaded_files)} files to KB '{kb_name}'")
+
+ background_tasks.add_task(
+ run_upload_processing_task,
+ kb_name=kb_name,
+ base_dir=str(_kb_base_dir),
+ api_key=api_key,
+ base_url=base_url,
+ uploaded_file_paths=uploaded_file_paths,
+ )
+
+ return {
+ "message": f"Uploaded {len(uploaded_files)} files. Processing in background.",
+ "files": uploaded_files,
+ }
+ except ValueError:
+ raise HTTPException(status_code=404, detail=f"Knowledge base '{kb_name}' not found")
+ except Exception as e:
+ raise HTTPException(status_code=500, detail=str(e))
+
+
+async def create_knowledge_base(
+ background_tasks: BackgroundTasks, name: str = Form(...), files: list[UploadFile] = File(...)
+):
+ """Create a new knowledge base and initialize it with files."""
+ try:
+ manager = get_kb_manager()
+ if name in manager.list_knowledge_bases():
+ raise HTTPException(status_code=400, detail=f"Knowledge base '{name}' already exists")
+
+ try:
+ from src.core.core import get_llm_config
+
+ llm_config = get_llm_config()
+ api_key = llm_config["api_key"]
+ base_url = llm_config["base_url"]
+ except ValueError as e:
+ raise HTTPException(status_code=500, detail=f"LLM config error: {e!s}")
+
+ from src.knowledge.progress_tracker import ProgressStage
+
+ progress_tracker = ProgressTracker(name, _kb_base_dir)
+
+ logger.info(f"Creating KB: {name}")
+
+ progress_tracker.update(
+ ProgressStage.INITIALIZING, "Initializing knowledge base...", current=0, total=0
+ )
+
+ initializer = KnowledgeBaseInitializer(
+ kb_name=name,
+ base_dir=str(_kb_base_dir),
+ api_key=api_key,
+ base_url=base_url,
+ progress_tracker=progress_tracker,
+ )
+
+ initializer.create_directory_structure()
+
+ manager = get_kb_manager()
+ if name not in manager.list_knowledge_bases():
+ logger.warning(f"KB {name} not found in config, registering manually")
+ initializer._register_to_config()
+
+ uploaded_files = []
+ for file in files:
+ file_path = initializer.raw_dir / file.filename
+ with open(file_path, "wb") as buffer:
+ shutil.copyfileobj(file.file, buffer)
+ uploaded_files.append(file.filename)
+
+ progress_tracker.update(
+ ProgressStage.PROCESSING_DOCUMENTS,
+ f"Saved {len(uploaded_files)} files, preparing to process...",
+ current=0,
+ total=len(uploaded_files),
+ )
+
+ background_tasks.add_task(run_initialization_task, initializer)
+
+ logger.success(f"KB '{name}' created, processing {len(uploaded_files)} files in background")
+
+ return {
+ "message": f"Knowledge base '{name}' created. Processing {len(uploaded_files)} files in background.",
+ "name": name,
+ "files": uploaded_files,
+ }
+
+ except HTTPException:
+ raise
+ except Exception as e:
+ logger.error(f"Failed to create KB: {e}")
+ import traceback
+
+ logger.debug(traceback.format_exc())
+ raise HTTPException(status_code=500, detail=str(e))
+
+
[email protected]("/{kb_name}/progress")
+async def get_progress(kb_name: str):
+ """Get initialization progress for a knowledge base"""
+ try:
+ progress_tracker = ProgressTracker(kb_name, _kb_base_dir)
+ progress = progress_tracker.get_progress()
+
+ if progress is None:
+ return {"status": "not_started", "message": "Initialization not started"}
+
+ return progress
+ except Exception as e:
+ raise HTTPException(status_code=500, detail=str(e))
+
+
[email protected]("/{kb_name}/progress/clear")
+async def clear_progress(kb_name: str):
+ """Clear progress file for a knowledge base (useful for stuck states)"""
+ try:
+ progress_tracker = ProgressTracker(kb_name, _kb_base_dir)
+ progress_tracker.clear()
+ return {"status": "success", "message": f"Progress cleared for {kb_name}"}
+ except Exception as e:
+ raise HTTPException(status_code=500, detail=str(e))
+
+
[email protected]("/{kb_name}/progress/ws")
+async def websocket_progress(websocket: WebSocket, kb_name: str):
+ """WebSocket endpoint for real-time progress updates"""
+ await websocket.accept()
+
+ from src.api.utils.progress_broadcaster import ProgressBroadcaster
+
+ broadcaster = ProgressBroadcaster.get_instance()
+
+ try:
+ await broadcaster.connect(kb_name, websocket)
+
+ progress_tracker = ProgressTracker(kb_name, _kb_base_dir)
+ initial_progress = progress_tracker.get_progress()
+
+ # Check if KB is already ready (has rag_storage)
+ kb_dir = _kb_base_dir / kb_name
+ rag_storage_dir = kb_dir / "rag_storage"
+ kb_is_ready = rag_storage_dir.exists() and rag_storage_dir.is_dir()
+
+ # Only send non-completed progress if KB is not ready
+ # or if progress is recent (within 5 minutes)
+ if initial_progress:
+ stage = initial_progress.get("stage")
+ timestamp = initial_progress.get("timestamp")
+
+ should_send = False
+ if stage in ["completed", "error"] or not kb_is_ready:
+ should_send = True
+ elif timestamp:
+ # Check if progress is recent
+ from datetime import datetime
+
+ try:
+ progress_time = datetime.fromisoformat(timestamp)
+ now = datetime.now()
+ age_seconds = (now - progress_time).total_seconds()
+ if age_seconds < 300: # 5 minutes
+ should_send = True
+ except:
+ pass
+
+ if should_send:
+ await websocket.send_json({"type": "progress", "data": initial_progress})
+
+ last_progress = initial_progress
+ last_timestamp = initial_progress.get("timestamp") if initial_progress else None
+
+ while True:
+ try:
+ try:
+ await asyncio.wait_for(websocket.receive_text(), timeout=1.0)
+ except asyncio.TimeoutError:
+ current_progress = progress_tracker.get_progress()
+ if current_progress:
+ current_timestamp = current_progress.get("timestamp")
+ if current_timestamp != last_timestamp:
+ await websocket.send_json(
+ {"type": "progress", "data": current_progress}
+ )
+ last_progress = current_progress
+ last_timestamp = current_timestamp
+
+ if current_progress.get("stage") in ["completed", "error"]:
+ await asyncio.sleep(3)
+ break
+ continue
+
+ except WebSocketDisconnect:
+ break
+ except Exception:
+ break
+
+ except Exception as e:
+ logger.debug(f"Progress WS error: {e}")
+ try:
+ await websocket.send_json({"type": "error", "message": str(e)})
+ except:
+ pass
+ finally:
+ await broadcaster.disconnect(kb_name, websocket)
+ try:
+ await websocket.close()
+ except:
+ pass
diff --git a/src/api/routers/notebook.py b/src/api/routers/notebook.py
new file mode 100644
index 000000000..438e92c9b
--- /dev/null
+++ b/src/api/routers/notebook.py
@@ -0,0 +1,247 @@
+"""
+Notebook API Router
+Provides notebook creation, querying, updating, deletion, and record management functions
+"""
+
+from pathlib import Path
+import sys
+from typing import Literal
+
+from fastapi import APIRouter, HTTPException
+from pydantic import BaseModel
+
+# Ensure module can be imported
+project_root = Path(__file__).parent.parent.parent.parent
+if str(project_root) not in sys.path:
+ sys.path.insert(0, str(project_root))
+
+from src.api.utils.notebook_manager import notebook_manager
+
+router = APIRouter()
+
+
+# === Request/Response Models ===
+
+
+class CreateNotebookRequest(BaseModel):
+ """Create notebook request"""
+
+ name: str
+ description: str = ""
+ color: str = "#3B82F6"
+ icon: str = "book"
+
+
+class UpdateNotebookRequest(BaseModel):
+ """Update notebook request"""
+
+ name: str | None = None
+ description: str | None = None
+ color: str | None = None
+ icon: str | None = None
+
+
+class AddRecordRequest(BaseModel):
+ """Add record request"""
+
+ notebook_ids: list[str]
+ record_type: Literal["solve", "question", "research", "co_writer"]
+ title: str
+ user_query: str
+ output: str
+ metadata: dict = {}
+ kb_name: str | None = None
+
+
+class RemoveRecordRequest(BaseModel):
+ """Remove record request"""
+
+ record_id: str
+
+
+# === API Endpoints ===
+
+
+async def list_notebooks():
+ """
+ Get all notebook list
+
+ Returns:
+ Notebook list (includes summary information)
+ """
+ try:
+ notebooks = notebook_manager.list_notebooks()
+ return {"notebooks": notebooks, "total": len(notebooks)}
+ except Exception as e:
+ raise HTTPException(status_code=500, detail=str(e))
+
+
[email protected]("/statistics")
+async def get_statistics():
+ """
+ Get notebook statistics
+
+ Returns:
+ Statistics information
+ """
+ try:
+ stats = notebook_manager.get_statistics()
+ return stats
+ except Exception as e:
+ raise HTTPException(status_code=500, detail=str(e))
+
+
+async def create_notebook(request: CreateNotebookRequest):
+ """
+ Create new notebook
+
+ Args:
+ request: Create request
+
+ Returns:
+ Created notebook information
+ """
+ try:
+ notebook = notebook_manager.create_notebook(
+ name=request.name,
+ description=request.description,
+ color=request.color,
+ icon=request.icon,
+ )
+ return {"success": True, "notebook": notebook}
+ except Exception as e:
+ raise HTTPException(status_code=500, detail=str(e))
+
+
[email protected]("/{notebook_id}")
+async def get_notebook(notebook_id: str):
+ """
+ Get notebook details
+
+ Args:
+ notebook_id: Notebook ID
+
+ Returns:
+ Notebook details (includes all records)
+ """
+ try:
+ notebook = notebook_manager.get_notebook(notebook_id)
+ if not notebook:
+ raise HTTPException(status_code=404, detail="Notebook not found")
+ return notebook
+ except HTTPException:
+ raise
+ except Exception as e:
+ raise HTTPException(status_code=500, detail=str(e))
+
+
[email protected]("/{notebook_id}")
+async def update_notebook(notebook_id: str, request: UpdateNotebookRequest):
+ """
+ Update notebook information
+
+ Args:
+ notebook_id: Notebook ID
+ request: Update request
+
+ Returns:
+ Updated notebook information
+ """
+ try:
+ notebook = notebook_manager.update_notebook(
+ notebook_id=notebook_id,
+ name=request.name,
+ description=request.description,
+ color=request.color,
+ icon=request.icon,
+ )
+ if not notebook:
+ raise HTTPException(status_code=404, detail="Notebook not found")
+ return {"success": True, "notebook": notebook}
+ except HTTPException:
+ raise
+ except Exception as e:
+ raise HTTPException(status_code=500, detail=str(e))
+
+
[email protected]("/{notebook_id}")
+async def delete_notebook(notebook_id: str):
+ """
+ Delete notebook
+
+ Args:
+ notebook_id: Notebook ID
+
+ Returns:
+ Deletion result
+ """
+ try:
+ success = notebook_manager.delete_notebook(notebook_id)
+ if not success:
+ raise HTTPException(status_code=404, detail="Notebook not found")
+ return {"success": True, "message": "Notebook deleted successfully"}
+ except HTTPException:
+ raise
+ except Exception as e:
+ raise HTTPException(status_code=500, detail=str(e))
+
+
[email protected]("/add_record")
+async def add_record(request: AddRecordRequest):
+ """
+ Add record to notebook
+
+ Args:
+ request: Add record request
+
+ Returns:
+ Addition result
+ """
+ try:
+ result = notebook_manager.add_record(
+ notebook_ids=request.notebook_ids,
+ record_type=request.record_type,
+ title=request.title,
+ user_query=request.user_query,
+ output=request.output,
+ metadata=request.metadata,
+ kb_name=request.kb_name,
+ )
+ return {
+ "success": True,
+ "record": result["record"],
+ "added_to_notebooks": result["added_to_notebooks"],
+ }
+ except Exception as e:
+ raise HTTPException(status_code=500, detail=str(e))
+
+
[email protected]("/{notebook_id}/records/{record_id}")
+async def remove_record(notebook_id: str, record_id: str):
+ """
+ Remove record from notebook
+
+ Args:
+ notebook_id: Notebook ID
+ record_id: Record ID
+
+ Returns:
+ Deletion result
+ """
+ try:
+ success = notebook_manager.remove_record(notebook_id, record_id)
+ if not success:
+ raise HTTPException(status_code=404, detail="Record not found")
+ return {"success": True, "message": "Record removed successfully"}
+ except HTTPException:
+ raise
+ except Exception as e:
+ raise HTTPException(status_code=500, detail=str(e))
+
+
+async def health_check():
+ """Health check"""
+ return {"status": "healthy", "service": "notebook"}
diff --git a/src/api/routers/question.py b/src/api/routers/question.py
new file mode 100644
index 000000000..5ec83bb95
--- /dev/null
+++ b/src/api/routers/question.py
@@ -0,0 +1,464 @@
+import asyncio
+import base64
+from datetime import datetime
+from pathlib import Path
+import re
+import sys
+
+from fastapi import APIRouter, WebSocket, WebSocketDisconnect
+
+from src.agents.question import AgentCoordinator
+from src.api.utils.history import ActivityType, history_manager
+
+# Add project root for imports
+project_root = Path(__file__).parent.parent.parent.parent
+sys.path.insert(0, str(project_root))
+
+from src.core.core import load_config_with_main
+from src.core.logging import get_logger
+
+# Setup module logger with unified logging system (from config)
+project_root = Path(__file__).parent.parent.parent.parent
+config = load_config_with_main("question_config.yaml", project_root)
+log_dir = config.get("paths", {}).get("user_log_dir") or config.get("logging", {}).get("log_dir")
+logger = get_logger("QuestionAPI", log_dir=log_dir)
+
+router = APIRouter()
+
+# Output directory for mimic mode - use data/user/question
+PROJECT_ROOT = Path(__file__).parent.parent.parent.parent
+MIMIC_OUTPUT_DIR = PROJECT_ROOT / "data" / "user" / "question" / "mimic_papers"
+
+
+async def websocket_mimic_generate(websocket: WebSocket):
+ """
+ WebSocket endpoint for mimic exam paper question generation.
+
+ Supports two modes:
+ 1. Upload PDF directly via WebSocket (base64 encoded)
+ 2. Use a pre-parsed paper directory path
+
+ Message format for PDF upload:
+ {
+ "mode": "upload",
+ "pdf_data": "base64_encoded_pdf_content",
+ "pdf_name": "exam.pdf",
+ "kb_name": "knowledge_base_name",
+ "max_questions": 5 // optional
+ }
+
+ Message format for pre-parsed:
+ {
+ "mode": "parsed",
+ "paper_path": "directory_name",
+ "kb_name": "knowledge_base_name",
+ "max_questions": 5 // optional
+ }
+ """
+ await websocket.accept()
+
+ pusher_task = None
+ original_stdout = sys.stdout
+
+ try:
+ # 1. Wait for config
+ data = await websocket.receive_json()
+ mode = data.get("mode", "parsed") # "upload" or "parsed"
+ kb_name = data.get("kb_name", "ai_textbook")
+ max_questions = data.get("max_questions")
+
+ logger.info(f"Starting mimic generation (mode: {mode}, kb: {kb_name})")
+
+ # 2. Setup Log Queue
+ log_queue = asyncio.Queue()
+
+ async def log_pusher():
+ while True:
+ entry = await log_queue.get()
+ try:
+ await websocket.send_json(entry)
+ except Exception:
+ break
+ log_queue.task_done()
+
+ pusher_task = asyncio.create_task(log_pusher())
+
+ # 3. Stdout interceptor for capturing prints
+ # ANSI escape sequence pattern for stripping color codes
+ ANSI_ESCAPE_PATTERN = re.compile(r"\x1b\[[0-9;]*[a-zA-Z]")
+
+ class StdoutInterceptor:
+ def __init__(self, queue):
+ self.queue = queue
+ self.original_stdout = sys.stdout
+
+ def write(self, message):
+ # Write to terminal first (with ANSI codes for color)
+ self.original_stdout.write(message)
+ # Strip ANSI escape codes before sending to frontend
+ clean_message = ANSI_ESCAPE_PATTERN.sub("", message).strip()
+ # Then send to frontend (non-blocking)
+ if clean_message:
+ try:
+ self.queue.put_nowait(
+ {
+ "type": "log",
+ "content": clean_message,
+ "timestamp": asyncio.get_event_loop().time(),
+ }
+ )
+ except (asyncio.QueueFull, RuntimeError):
+ pass
+
+ def flush(self):
+ self.original_stdout.flush()
+
+ sys.stdout = StdoutInterceptor(log_queue)
+
+ try:
+ await websocket.send_json(
+ {"type": "status", "stage": "init", "content": "Initializing..."}
+ )
+
+ pdf_path = None
+ paper_dir = None
+
+ # Handle PDF upload mode
+ if mode == "upload":
+ pdf_data = data.get("pdf_data")
+ pdf_name = data.get("pdf_name", "exam.pdf")
+
+ if not pdf_data:
+ await websocket.send_json(
+ {"type": "error", "content": "PDF data is required for upload mode"}
+ )
+ return
+
+ # Create batch directory for this mimic session
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
+ pdf_stem = Path(pdf_name).stem
+ batch_dir = MIMIC_OUTPUT_DIR / f"mimic_{timestamp}_{pdf_stem}"
+ batch_dir.mkdir(parents=True, exist_ok=True)
+
+ # Save uploaded PDF in batch directory
+ pdf_path = batch_dir / pdf_name
+
+ await websocket.send_json(
+ {"type": "status", "stage": "upload", "content": f"Saving PDF: {pdf_name}"}
+ )
+
+ # Decode and save PDF
+ pdf_bytes = base64.b64decode(pdf_data)
+ with open(pdf_path, "wb") as f:
+ f.write(pdf_bytes)
+
+ await websocket.send_json(
+ {
+ "type": "status",
+ "stage": "parsing",
+ "content": "Parsing PDF exam paper (MinerU)...",
+ }
+ )
+ logger.info(f"Saved uploaded PDF to: {pdf_path}")
+
+ # Pass batch_dir as output directory
+ pdf_path = str(pdf_path)
+ output_dir = str(batch_dir)
+
+ elif mode == "parsed":
+ paper_path = data.get("paper_path")
+ if not paper_path:
+ await websocket.send_json(
+ {"type": "error", "content": "paper_path is required for parsed mode"}
+ )
+ return
+ paper_dir = paper_path
+
+ # Create batch directory for parsed mode too
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
+ batch_dir = MIMIC_OUTPUT_DIR / f"mimic_{timestamp}_{Path(paper_path).name}"
+ batch_dir.mkdir(parents=True, exist_ok=True)
+ output_dir = str(batch_dir)
+
+ else:
+ await websocket.send_json({"type": "error", "content": f"Unknown mode: {mode}"})
+ return
+
+ # Import mimic function
+ from src.agents.question.tools.exam_mimic import mimic_exam_questions
+
+ # Create WebSocket callback for real-time progress updates
+ async def ws_callback(event_type: str, data: dict):
+ """Send progress updates to the frontend via WebSocket."""
+ try:
+ message = {"type": event_type, **data}
+ await websocket.send_json(message)
+ except Exception as e:
+ logger.debug(f"WebSocket send failed: {e}")
+
+ # Run the complete mimic workflow with callback
+ await websocket.send_json(
+ {
+ "type": "status",
+ "stage": "processing",
+ "content": "Executing question generation workflow...",
+ }
+ )
+
+ result = await mimic_exam_questions(
+ pdf_path=pdf_path,
+ paper_dir=paper_dir,
+ kb_name=kb_name,
+ output_dir=output_dir,
+ max_questions=max_questions,
+ ws_callback=ws_callback,
+ )
+
+ if result.get("success"):
+ # Results are already sent via ws_callback during generation
+ # Just send the final complete signal
+ total_ref = result.get("total_reference_questions", 0)
+ generated = result.get("generated_questions", [])
+ failed = result.get("failed_questions", [])
+
+ logger.success(
+ f"Mimic generation complete: {len(generated)} succeeded, {len(failed)} failed"
+ )
+
+ await websocket.send_json({"type": "complete"})
+ else:
+ error_msg = result.get("error", "Unknown error")
+ await websocket.send_json({"type": "error", "content": error_msg})
+ logger.error(f"Mimic generation failed: {error_msg}")
+
+ finally:
+ sys.stdout = original_stdout
+
+ except WebSocketDisconnect:
+ logger.debug("Client disconnected during mimic generation")
+ except Exception as e:
+ logger.error(f"Mimic generation error: {e}")
+ try:
+ await websocket.send_json({"type": "error", "content": str(e)})
+ except:
+ pass
+ finally:
+ sys.stdout = original_stdout
+ if pusher_task:
+ try:
+ pusher_task.cancel()
+ await pusher_task
+ except:
+ pass
+ try:
+ await websocket.close()
+ except:
+ pass
+
+
[email protected]("/generate")
+async def websocket_question_generate(websocket: WebSocket):
+ await websocket.accept()
+
+ # Get task ID manager
+ from src.api.utils.task_id_manager import TaskIDManager
+
+ task_manager = TaskIDManager.get_instance()
+
+ try:
+ # 1. Wait for config
+ data = await websocket.receive_json()
+ requirement = data.get("requirement")
+ kb_name = data.get("kb_name", "ai_textbook")
+ count = data.get("count", 1)
+
+ if not requirement:
+ try:
+ await websocket.send_json({"type": "error", "content": "Requirement is required"})
+ except (RuntimeError, WebSocketDisconnect):
+ pass
+ return
+
+ # Generate task ID
+ task_key = f"question_{kb_name}_{hash(str(requirement))}"
+ task_id = task_manager.generate_task_id("question_gen", task_key)
+
+ # Send task ID to frontend
+ try:
+ await websocket.send_json({"type": "task_id", "task_id": task_id})
+ except (RuntimeError, WebSocketDisconnect):
+ logger.debug("WebSocket closed, cannot send task_id")
+ return
+
+ logger.info(
+ f"[{task_id}] Starting question generation: {requirement.get('knowledge_point', 'Unknown')}"
+ )
+
+ # 2. Initialize Coordinator
+ # Define unified output directory (OpenTutor/data/user/question)
+ root_dir = Path(__file__).parent.parent.parent.parent
+ output_base = root_dir / "data" / "user" / "question"
+
+ coordinator = AgentCoordinator(kb_name=kb_name, max_rounds=10, output_dir=str(output_base))
+
+ # 3. Setup Log Queue for WebSocket streaming
+ log_queue = asyncio.Queue()
+
+ # WebSocket callback for coordinator to send structured updates
+ async def ws_callback(data: dict):
+ try:
+ await log_queue.put(data)
+ except Exception:
+ pass
+
+ coordinator.set_ws_callback(ws_callback)
+
+ # 4. Define background pusher for logs
+ async def log_pusher():
+ while True:
+ entry = await log_queue.get()
+ try:
+ await websocket.send_json(entry)
+ except Exception:
+ break
+ log_queue.task_done()
+
+ pusher_task = asyncio.create_task(log_pusher())
+
+ # 5. Setup LogInterceptor for capturing logger output (same as solve.py)
+ from src.api.utils.log_interceptor import LogInterceptor
+
+ # Get the coordinator's logger to intercept
+ target_logger = coordinator.logger.logger
+ interceptor = LogInterceptor(target_logger, log_queue)
+
+ # 6. Run Generation with LogInterceptor
+ try:
+ with interceptor:
+ try:
+ await websocket.send_json({"type": "status", "content": "started"})
+ except (RuntimeError, WebSocketDisconnect):
+ logger.debug("WebSocket closed, stopping question generation")
+ return
+
+ # Send initial agent status
+ try:
+ await websocket.send_json(
+ {"type": "agent_status", "all_agents": coordinator.agent_status}
+ )
+ except (RuntimeError, WebSocketDisconnect):
+ logger.debug("WebSocket closed, stopping question generation")
+ return
+
+ # Use custom mode generation (new streamlined flow)
+ logger.info(f"Starting custom mode generation for {count} question(s)")
+
+ # Use the new custom generation method
+ batch_result = await coordinator.generate_questions_custom(
+ base_requirement=requirement,
+ num_questions=count,
+ )
+
+ # Results are already sent via WebSocket callbacks in the coordinator
+ # Just need to save to history for successful results
+ for result in batch_result.get("results", []):
+ # Save to history
+ history_manager.add_entry(
+ activity_type=ActivityType.QUESTION,
+ title=f"{requirement.get('knowledge_point', 'Question')} ({requirement.get('question_type')})",
+ content={
+ "requirement": requirement,
+ "question": result.get("question", {}),
+ "validation": result.get("validation", {}),
+ "kb_name": kb_name,
+ },
+ summary=result.get("question", {}).get("question", "")[:100],
+ )
+
+ # Send final token stats
+ try:
+ await websocket.send_json(
+ {"type": "token_stats", "stats": coordinator.token_stats}
+ )
+ except (RuntimeError, WebSocketDisconnect):
+ logger.debug("WebSocket closed, stopping question generation")
+
+ # Send batch summary
+ try:
+ await websocket.send_json(
+ {
+ "type": "batch_summary",
+ "requested": batch_result.get("requested", count),
+ "completed": batch_result.get("completed", 0),
+ "failed": batch_result.get("failed", 0),
+ "plan": batch_result.get("plan", {}),
+ }
+ )
+ except (RuntimeError, WebSocketDisconnect):
+ pass
+
+ if not batch_result.get("success"):
+ logger.warning(
+ f"Question generation had failures: {batch_result.get('failed', 0)} failed"
+ )
+
+ # Wait for any pending messages in the queue to be sent
+ # Give the pusher a moment to process remaining messages
+ await asyncio.sleep(0.1)
+ while not log_queue.empty():
+ await asyncio.sleep(0.05)
+
+ # Send complete signal
+ try:
+ await websocket.send_json({"type": "complete"})
+ logger.info(f"[{task_id}] Question generation completed")
+ task_manager.update_task_status(task_id, "completed")
+ except (RuntimeError, WebSocketDisconnect):
+ logger.debug("WebSocket closed, cannot send complete signal")
+
+ except Exception as e:
+ import traceback
+
+ error_traceback = traceback.format_exc()
+ logger.error(f"Question generation error: {e}")
+ logger.error(f"Error traceback:\n{error_traceback}")
+
+ # Log additional context if available
+ try:
+ if "result" in locals():
+ logger.error(
+ f"Result type: {type(result)}, result keys: {result.keys() if isinstance(result, dict) else 'N/A'}"
+ )
+ if isinstance(result, dict) and "validation" in result:
+ validation = result["validation"]
+ logger.error(f"Validation type: {type(validation)}")
+ if isinstance(validation, dict):
+ logger.error(f"Validation keys: {validation.keys()}")
+ logger.error(
+ f"Issues type: {type(validation.get('issues'))}, value: {validation.get('issues')}"
+ )
+ logger.error(
+ f"Suggestions type: {type(validation.get('suggestions'))}, value: {validation.get('suggestions')}"
+ )
+ except Exception as context_error:
+ logger.warning(f"Failed to log error context: {context_error}")
+
+ try:
+ await websocket.send_json({"type": "error", "content": str(e)})
+ except (RuntimeError, WebSocketDisconnect):
+ logger.debug("WebSocket closed, cannot send error message")
+ task_manager.update_task_status(task_id, "error", error=str(e))
+
+ finally:
+ pusher_task.cancel()
+ try:
+ await pusher_task
+ except asyncio.CancelledError:
+ pass
+ await websocket.close()
+
+ except WebSocketDisconnect:
+ logger.debug("Client disconnected")
+ except Exception as e:
+ logger.error(f"WebSocket error: {e}")
diff --git a/src/api/routers/research.py b/src/api/routers/research.py
new file mode 100644
index 000000000..869937a22
--- /dev/null
+++ b/src/api/routers/research.py
@@ -0,0 +1,406 @@
+import asyncio
+import logging
+from pathlib import Path
+import sys
+from typing import Any
+
+from fastapi import APIRouter, WebSocket
+from pydantic import BaseModel
+
+from src.api.utils.history import ActivityType, history_manager
+
+# Force stdout to use utf-8 to prevent encoding errors with emojis on Windows
+if sys.platform == "win32":
+ sys.stdout.reconfigure(encoding="utf-8")
+
+# Import research modules
+from src.agents.research.agents import RephraseAgent
+from src.agents.research.research_pipeline import ResearchPipeline
+from src.core.logging import get_logger
+
+router = APIRouter()
+
+
+# Helper to load config (with main.yaml merge)
+def load_config():
+ project_root = Path(__file__).parent.parent.parent.parent
+ from src.core.core import load_config_with_main
+
+ return load_config_with_main("research_config.yaml", project_root)
+
+
+# Initialize logger with config
+config = load_config()
+log_dir = config.get("paths", {}).get("user_log_dir") or config.get("logging", {}).get("log_dir")
+logger = get_logger("ResearchAPI", log_dir=log_dir)
+
+
+class OptimizeRequest(BaseModel):
+ topic: str
+ iteration: int = 0
+ previous_result: dict[str, Any] | None = None
+ kb_name: str | None = "ai_textbook"
+
+
[email protected]("/optimize_topic")
+async def optimize_topic(request: OptimizeRequest):
+ try:
+ config = load_config()
+
+ # Inject API keys
+ try:
+ from src.core.core import get_llm_config
+
+ llm_config = get_llm_config()
+ api_key = llm_config["api_key"]
+ base_url = llm_config["base_url"]
+ except Exception as e:
+ return {"error": f"LLM config error: {e!s}"}
+
+ # Init Agent
+ agent = RephraseAgent(config=config, api_key=api_key, base_url=base_url)
+
+ # Process
+ # If iteration > 0, topic is treated as feedback
+ if request.iteration == 0:
+ result = await agent.process(request.topic, iteration=0)
+ else:
+ result = await agent.process(
+ request.topic, iteration=request.iteration, previous_result=request.previous_result
+ )
+
+ return result
+
+ except Exception as e:
+ import traceback
+
+ traceback.print_exc()
+ return {"error": str(e)}
+
+
+async def websocket_research_run(websocket: WebSocket):
+ await websocket.accept()
+
+ # Get task ID manager
+ from src.api.utils.task_id_manager import TaskIDManager
+
+ task_manager = TaskIDManager.get_instance()
+
+ pusher_task = None
+ progress_pusher_task = None
+ original_stdout = sys.stdout # Save original stdout at the start
+
+ try:
+ # 1. Wait for config
+ data = await websocket.receive_json()
+ topic = data.get("topic")
+ kb_name = data.get("kb_name", "ai_textbook")
+ # New unified parameters
+ plan_mode = data.get("plan_mode", "medium") # quick, medium, deep, auto
+ enabled_tools = data.get("enabled_tools", ["RAG"]) # RAG, Paper, Web
+ skip_rephrase = data.get("skip_rephrase", False)
+ # Legacy support
+ preset = data.get("preset") # For backward compatibility
+ research_mode = data.get("research_mode")
+
+ if not topic:
+ await websocket.send_json({"type": "error", "content": "Topic is required"})
+ return
+
+ # Generate task ID
+ task_key = f"research_{kb_name}_{hash(str(topic))}"
+ task_id = task_manager.generate_task_id("research", task_key)
+
+ # Send task ID to frontend
+ await websocket.send_json({"type": "task_id", "task_id": task_id})
+
+ # Use unified logger
+ try:
+ from src.core.logging import get_logger
+
+ # Get log_dir from config
+ log_dir = config.get("paths", {}).get("user_log_dir") or config.get("logging", {}).get(
+ "log_dir"
+ )
+ research_logger = get_logger("Research", log_dir=log_dir)
+ research_logger.info(f"[{task_id}] Starting research flow: {topic[:50]}...")
+ except Exception as e:
+ logger.warning(f"Failed to initialize research logger: {e}")
+
+ # 2. Initialize Pipeline
+ config = load_config()
+
+ # Initialize nested config structures from research.* (main.yaml structure)
+ # This ensures all research module configs are properly inherited from main.yaml
+ research_config = config.get("research", {})
+
+ # Initialize planning config from research.planning
+ if "planning" not in config:
+ config["planning"] = research_config.get("planning", {}).copy()
+ else:
+ # Merge with research.planning defaults
+ default_planning = research_config.get("planning", {})
+ for key, value in default_planning.items():
+ if key not in config["planning"]:
+ config["planning"][key] = value if not isinstance(value, dict) else value.copy()
+ elif isinstance(value, dict) and isinstance(config["planning"][key], dict):
+ # Deep merge for nested dicts like decompose, rephrase
+ for k, v in value.items():
+ if k not in config["planning"][key]:
+ config["planning"][key][k] = v
+
+ # Ensure decompose and rephrase exist
+ if "decompose" not in config["planning"]:
+ config["planning"]["decompose"] = {}
+ if "rephrase" not in config["planning"]:
+ config["planning"]["rephrase"] = {}
+
+ # Initialize researching config from research.researching
+ # This ensures execution_mode, max_parallel_topics etc. are properly inherited
+ if "researching" not in config:
+ config["researching"] = research_config.get("researching", {}).copy()
+ else:
+ # Merge with research.researching defaults (research.researching has lower priority)
+ default_researching = research_config.get("researching", {})
+ for key, value in default_researching.items():
+ if key not in config["researching"]:
+ config["researching"][key] = value
+
+ # Initialize reporting config from research.reporting
+ # This ensures enable_citation_list, enable_inline_citations etc. are properly inherited
+ if "reporting" not in config:
+ config["reporting"] = research_config.get("reporting", {}).copy()
+ else:
+ # Merge with research.reporting defaults
+ default_reporting = research_config.get("reporting", {})
+ for key, value in default_reporting.items():
+ if key not in config["reporting"]:
+ config["reporting"][key] = value
+
+ # Apply plan_mode configuration (unified approach affecting both planning and researching)
+ # Each mode defines:
+ # - Planning: tree depth (subtopics count) and mode (manual/auto)
+ # - Researching: max iterations per topic and iteration_mode (fixed/flexible)
+ plan_mode_config = {
+ "quick": {
+ "planning": {"decompose": {"initial_subtopics": 2, "mode": "manual"}},
+ "researching": {"max_iterations": 2, "iteration_mode": "fixed"},
+ },
+ "medium": {
+ "planning": {"decompose": {"initial_subtopics": 5, "mode": "manual"}},
+ "researching": {"max_iterations": 4, "iteration_mode": "fixed"},
+ },
+ "deep": {
+ "planning": {"decompose": {"initial_subtopics": 8, "mode": "manual"}},
+ "researching": {"max_iterations": 7, "iteration_mode": "fixed"},
+ },
+ "auto": {
+ "planning": {"decompose": {"mode": "auto", "auto_max_subtopics": 8}},
+ "researching": {"max_iterations": 6, "iteration_mode": "flexible"},
+ },
+ }
+ if plan_mode in plan_mode_config:
+ mode_cfg = plan_mode_config[plan_mode]
+ # Apply planning configuration
+ if "planning" in mode_cfg:
+ for key, value in mode_cfg["planning"].items():
+ if key not in config["planning"]:
+ config["planning"][key] = {}
+ config["planning"][key].update(value)
+ # Apply researching configuration
+ if "researching" in mode_cfg:
+ config["researching"].update(mode_cfg["researching"])
+
+ # Legacy preset support (for backward compatibility)
+ if preset and "presets" in config and preset in config["presets"]:
+ preset_config = config["presets"][preset]
+ for key, value in preset_config.items():
+ if key in config and isinstance(value, dict):
+ config[key].update(value)
+
+ # Apply enabled_tools configuration
+ # RAG includes: rag_naive, rag_hybrid, query_item
+ # Paper includes: paper_search
+ # Web includes: web_search
+ # run_code is always enabled
+ config["researching"]["enable_rag_naive"] = "RAG" in enabled_tools
+ config["researching"]["enable_rag_hybrid"] = "RAG" in enabled_tools
+ config["researching"]["enable_query_item"] = "RAG" in enabled_tools
+ config["researching"]["enable_paper_search"] = "Paper" in enabled_tools
+ config["researching"]["enable_web_search"] = "Web" in enabled_tools
+ config["researching"]["enable_run_code"] = True # Always enabled
+
+ # Store enabled_tools for prompt generation
+ config["researching"]["enabled_tools"] = enabled_tools
+
+ # Legacy research_mode support
+ if research_mode:
+ config["researching"]["research_mode"] = research_mode
+
+ # If skip_rephrase is True, disable the internal rephrase step
+ if skip_rephrase:
+ config["planning"]["rephrase"]["enabled"] = False
+
+ # Define unified output directory
+ # Use project root directory user/research as unified output directory
+ root_dir = Path(__file__).parent.parent.parent.parent
+ output_base = root_dir / "data" / "user" / "research"
+
+ # Update config with unified output paths
+ if "system" not in config:
+ config["system"] = {}
+
+ config["system"]["output_base_dir"] = str(output_base / "cache")
+ config["system"]["reports_dir"] = str(output_base / "reports")
+
+ # Inject API keys from env if not in config
+ try:
+ from src.core.core import get_llm_config
+
+ llm_config = get_llm_config()
+ api_key = llm_config["api_key"]
+ base_url = llm_config["base_url"]
+ except ValueError as e:
+ await websocket.send_json({"error": f"LLM configuration error: {e!s}"})
+ await websocket.close()
+ return
+
+ # 3. Setup Queues for log and progress
+ log_queue = asyncio.Queue()
+ progress_queue = asyncio.Queue()
+
+ # Progress callback function
+ def progress_callback(event: dict[str, Any]):
+ """Progress callback function, puts progress events into queue"""
+ try:
+ asyncio.get_event_loop().call_soon_threadsafe(progress_queue.put_nowait, event)
+ except Exception as e:
+ logger.error(f"Progress callback error: {e}")
+
+ pipeline = ResearchPipeline(
+ config=config,
+ api_key=api_key,
+ base_url=base_url,
+ kb_name=kb_name,
+ progress_callback=progress_callback,
+ )
+
+ # 4. Background log pusher
+ async def log_pusher():
+ while True:
+ try:
+ log = await log_queue.get()
+ if log is None:
+ break
+ await websocket.send_json({"type": "log", "content": log})
+ log_queue.task_done()
+ except Exception as e:
+ logger.error(f"Log pusher error: {e}")
+ break
+
+ # 5. Background progress pusher
+ async def progress_pusher():
+ while True:
+ try:
+ event = await progress_queue.get()
+ if event is None:
+ break
+ await websocket.send_json(event)
+ progress_queue.task_done()
+ except Exception as e:
+ logger.error(f"Progress pusher error: {e}")
+ break
+
+ pusher_task = asyncio.create_task(log_pusher())
+ progress_pusher_task = asyncio.create_task(progress_pusher())
+
+ # 6. Run Pipeline with stdout interception
+ class ResearchStdoutInterceptor:
+ def __init__(self, queue):
+ self.queue = queue
+ self.original_stdout = sys.stdout
+
+ def write(self, message):
+ # Write to terminal first to ensure terminal output is not blocked
+ self.original_stdout.write(message)
+ # Then try to send to frontend (non-blocking, failure doesn't affect terminal output)
+ if message.strip():
+ try:
+ # Use call_soon_threadsafe for thread safety
+ loop = asyncio.get_event_loop()
+ loop.call_soon_threadsafe(self.queue.put_nowait, message)
+ except (asyncio.QueueFull, RuntimeError, AttributeError):
+ # Queue full, event loop closed, or no event loop, ignore error, doesn't affect terminal output
+ pass
+
+ def flush(self):
+ self.original_stdout.flush()
+
+ sys.stdout = ResearchStdoutInterceptor(log_queue)
+
+ try:
+ await websocket.send_json(
+ {"type": "status", "content": "started", "research_id": pipeline.research_id}
+ )
+
+ result = await pipeline.run(topic)
+
+ # Send final report content
+ with open(result["final_report_path"], encoding="utf-8") as f:
+ report_content = f.read()
+
+ # Save to history
+ history_manager.add_entry(
+ activity_type=ActivityType.RESEARCH,
+ title=topic,
+ content={"topic": topic, "report": report_content, "kb_name": kb_name},
+ summary=f"Research ID: {result['research_id']}",
+ )
+
+ await websocket.send_json(
+ {
+ "type": "result",
+ "report": report_content,
+ "metadata": result["metadata"],
+ "research_id": result["research_id"],
+ }
+ )
+
+ # Update task status to completed
+ try:
+ from src.core.logging import get_logger
+
+ log_dir = config.get("paths", {}).get("user_log_dir") or config.get(
+ "logging", {}
+ ).get("log_dir")
+ research_logger = get_logger("Research", log_dir=log_dir)
+ research_logger.success(f"[{task_id}] Research flow completed: {topic[:50]}...")
+ task_manager.update_task_status(task_id, "completed")
+ except Exception as e:
+ logger.warning(f"Failed to log completion: {e}")
+
+ finally:
+ sys.stdout = original_stdout # Safely restore using saved reference
+
+ except Exception as e:
+ await websocket.send_json({"type": "error", "content": str(e)})
+ logging.error(f"Research error: {e}", exc_info=True)
+
+ # Update task status to error
+ try:
+ from src.core.logging import get_logger
+
+ log_dir = config.get("paths", {}).get("user_log_dir") or config.get("logging", {}).get(
+ "log_dir"
+ )
+ research_logger = get_logger("Research", log_dir=log_dir)
+ research_logger.error(f"[{task_id}] Research flow failed: {e}")
+ task_manager.update_task_status(task_id, "error", error=str(e))
+ except Exception as log_err:
+ logger.warning(f"Failed to log error: {log_err}")
+ finally:
+ if pusher_task:
+ pusher_task.cancel()
+ if progress_pusher_task:
+ progress_pusher_task.cancel()
diff --git a/src/api/routers/settings.py b/src/api/routers/settings.py
new file mode 100644
index 000000000..577f6baf4
--- /dev/null
+++ b/src/api/routers/settings.py
@@ -0,0 +1,596 @@
+"""
+Settings API Router
+Manages user settings: theme, language, environment variables, etc.
+"""
+
+import json
+import os
+from pathlib import Path
+from typing import Any, Dict, Literal
+
+from fastapi import APIRouter, HTTPException
+from pydantic import BaseModel
+
+from src.utils.config_manager import ConfigManager
+
+router = APIRouter()
+config_manager = ConfigManager()
+
+# ==================== Environment Variables Configuration ====================
+# Define all supported environment variables with descriptions
+# These variables can be modified at runtime without restarting the server
+
+ENV_VAR_DEFINITIONS = {
+ # LLM Configuration
+ "LLM_BINDING": {
+ "description": "LLM service provider type (e.g., openai, azure_openai, ollama)",
+ "category": "llm",
+ "required": False,
+ "default": "openai",
+ "sensitive": False,
+ },
+ "LLM_MODEL": {
+ "description": "LLM model name (e.g., gpt-4o, deepseek-chat, qwen-plus)",
+ "category": "llm",
+ "required": True,
+ "default": "",
+ "sensitive": False,
+ },
+ "LLM_BINDING_HOST": {
+ "description": "LLM API endpoint URL (e.g., https://api.openai.com/v1)",
+ "category": "llm",
+ "required": True,
+ "default": "",
+ "sensitive": False,
+ },
+ "LLM_BINDING_API_KEY": {
+ "description": "LLM API authentication key",
+ "category": "llm",
+ "required": True,
+ "default": "",
+ "sensitive": True,
+ },
+ # Embedding Configuration
+ "EMBEDDING_BINDING": {
+ "description": "Embedding service provider type (openai, ollama, lollms, azure_openai)",
+ "category": "embedding",
+ "required": False,
+ "default": "openai",
+ "sensitive": False,
+ },
+ "EMBEDDING_MODEL": {
+ "description": "Embedding model name (e.g., text-embedding-3-large, text-embedding-ada-002)",
+ "category": "embedding",
+ "required": True,
+ "default": "",
+ "sensitive": False,
+ },
+ "EMBEDDING_DIM": {
+ "description": "Embedding vector dimension (e.g., 3072 for text-embedding-3-large)",
+ "category": "embedding",
+ "required": False,
+ "default": "3072",
+ "sensitive": False,
+ },
+ "EMBEDDING_BINDING_HOST": {
+ "description": "Embedding API endpoint URL",
+ "category": "embedding",
+ "required": True,
+ "default": "",
+ "sensitive": False,
+ },
+ "EMBEDDING_BINDING_API_KEY": {
+ "description": "Embedding API authentication key",
+ "category": "embedding",
+ "required": True,
+ "default": "",
+ "sensitive": True,
+ },
+ # TTS Configuration (OpenAI compatible API)
+ "TTS_MODEL": {
+ "description": "OpenAI TTS model (tts-1 for speed, tts-1-hd for quality)",
+ "category": "tts",
+ "required": False,
+ "default": "",
+ "sensitive": False,
+ },
+ "TTS_URL": {
+ "description": "OpenAI compatible API endpoint (e.g., https://api.openai.com/v1)",
+ "category": "tts",
+ "required": False,
+ "default": "",
+ "sensitive": False,
+ },
+ "TTS_API_KEY": {
+ "description": "TTS API authentication key (OpenAI API Key)",
+ "category": "tts",
+ "required": False,
+ "default": "",
+ "sensitive": True,
+ },
+ "TTS_VOICE": {
+ "description": "Default voice: alloy, echo, fable, onyx, nova, shimmer",
+ "category": "tts",
+ "required": False,
+ "default": "alloy",
+ "sensitive": False,
+ },
+ # Web Search Configuration
+ "PERPLEXITY_API_KEY": {
+ "description": "Perplexity API key for web search functionality",
+ "category": "search",
+ "required": False,
+ "default": "",
+ "sensitive": True,
+ },
+ # System Configuration
+ "DISABLE_SSL_VERIFY": {
+ "description": "Disable SSL certificate verification (set 'true' for self-signed certs)",
+ "category": "system",
+ "required": False,
+ "default": "false",
+ "sensitive": False,
+ },
+ "RAG_TOOL_MODULE_LOG_LEVEL": {
+ "description": "Log level for RAG tool module (DEBUG, INFO, WARNING, ERROR)",
+ "category": "system",
+ "required": False,
+ "default": "INFO",
+ "sensitive": False,
+ },
+}
+
+# Categories for organizing the UI
+ENV_CATEGORIES = {
+ "llm": {
+ "name": "LLM Configuration",
+ "description": "Large Language Model settings for AI reasoning and generation",
+ "icon": "brain",
+ },
+ "embedding": {
+ "name": "Embedding Configuration",
+ "description": "Text embedding model settings for semantic search and RAG",
+ "icon": "database",
+ },
+ "tts": {
+ "name": "TTS Configuration",
+ "description": "Text-to-Speech settings. Currently only supports Alibaba Cloud DashScope.",
+ "icon": "volume",
+ },
+ "search": {
+ "name": "Web Search Configuration",
+ "description": "External search API settings",
+ "icon": "search",
+ },
+ "system": {
+ "name": "System Configuration",
+ "description": "General system settings",
+ "icon": "settings",
+ },
+}
+
+# Settings file path (for local client/UI prefs not appropriate for main.yaml)
+SETTINGS_FILE = Path(__file__).parent.parent.parent.parent / "data" / "user" / "settings.json"
+
+# Default UI settings
+DEFAULT_UI_SETTINGS = {
+ "theme": "light",
+ "language": "en", # Interface language
+ "output_language": "en", # Output preference (legacy, might move to main.yaml)
+}
+
+
+class UISettings(BaseModel):
+ theme: Literal["light", "dark"] = "light"
+ language: Literal["zh", "en"] = "en"
+ output_language: Literal["zh", "en"] = "en"
+
+
+class FullSettingsResponse(BaseModel):
+ ui: UISettings
+ config: Dict[str, Any]
+ env: Dict[str, str]
+
+
+# Environment variable models
+class EnvVarInfo(BaseModel):
+ """Information about a single environment variable"""
+
+ key: str
+ value: str
+ description: str
+ category: str
+ required: bool
+ default: str
+ sensitive: bool
+ is_set: bool # Whether the variable has a non-empty value
+
+
+class EnvCategoryInfo(BaseModel):
+ """Information about an environment variable category"""
+
+ id: str
+ name: str
+ description: str
+ icon: str
+
+
+class EnvConfigResponse(BaseModel):
+ """Response for environment configuration"""
+
+ variables: list[EnvVarInfo]
+ categories: list[EnvCategoryInfo]
+
+
+class EnvVarUpdate(BaseModel):
+ """Single environment variable update"""
+
+ key: str
+ value: str
+
+
+class EnvConfigUpdate(BaseModel):
+ """Batch environment variables update"""
+
+ variables: list[EnvVarUpdate]
+
+
+class ConfigUpdate(BaseModel):
+ config: Dict[str, Any]
+
+
+class ThemeUpdate(BaseModel):
+ theme: Literal["light", "dark"]
+
+
+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)
+
+
[email protected]("", response_model=FullSettingsResponse)
+async def get_settings():
+ """
+ Get all settings:
+ 1. UI preferences (theme, etc)
+ 2. Backend Configuration (main.yaml)
+ 3. Environment Info (models, etc)
+ """
+ ui_settings = load_ui_settings()
+ main_config = config_manager.load_config()
+ env_info = config_manager.get_env_info()
+
+ return {"ui": ui_settings, "config": main_config, "env": env_info}
+
+
+async def update_config(update: ConfigUpdate):
+ """Update main.yaml configuration"""
+ # Filter out immutable sections if needed (e.g. server port),
+ # but for now we trust `save_config` to handle the merge.
+ # Ideally should validate against a schema.
+
+ success = config_manager.save_config(update.config)
+ if not success:
+ raise HTTPException(status_code=500, detail="Failed to save configuration")
+
+ return config_manager.load_config()
+
+
+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}
+
+
+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
+
+
+async def reset_settings():
+ """Reset UI settings to default"""
+ save_ui_settings(DEFAULT_UI_SETTINGS)
+ return DEFAULT_UI_SETTINGS
+
+
+async def get_themes():
+ """Get available theme list"""
+ return {
+ "themes": [
+ {"id": "light", "name": "Light"},
+ {"id": "dark", "name": "Dark"},
+ ]
+ }
+
+
+# Legacy/Specific endpoints required by current frontend (will be deprecated/updated)
+# Keeping them for now if needed, or rewriting them to use new logic if frontend calls them.
+# The user wants "Refactor entire backend logic", so I can break old endpoints if I update frontend.
+# But keeping some compatibility or simple redirect is good practice.
+
+
[email protected]("/system-language")
+async def get_system_language():
+ """Get system language from main.yaml"""
+ config = config_manager.load_config()
+ system_config = config.get("system", {})
+ language = system_config.get("language", "en")
+ return {"language": language}
+
+
+class SystemLanguageUpdate(BaseModel):
+ language: Literal["zh", "en"]
+
+
[email protected]("/system-language")
+async def update_system_language(update: SystemLanguageUpdate):
+ """Update system language in main.yaml"""
+ config = config_manager.load_config()
+ if "system" not in config:
+ config["system"] = {}
+ config["system"]["language"] = update.language
+ if config_manager.save_config(config):
+ return {"language": update.language}
+ raise HTTPException(status_code=500, detail="Failed to save system language")
+
+
[email protected]("/config-info")
+async def get_config_info():
+ """Get configuration information (paths, kb settings, etc.)"""
+ config = config_manager.load_config()
+
+ paths = config.get("paths", {})
+ user_data_dir = paths.get("user_data_dir", "./data/user")
+ kb_base_dir = (
+ config.get("tools", {}).get("rag_tool", {}).get("kb_base_dir", "./data/knowledge_bases")
+ )
+ default_kb = config.get("tools", {}).get("rag_tool", {}).get("default_kb", "ai_textbook")
+ workspace = (
+ config.get("tools", {})
+ .get("run_code", {})
+ .get("workspace", "./data/user/run_code_workspace")
+ )
+
+ return {
+ "kb_base_dir": kb_base_dir,
+ "user_data_dir": user_data_dir,
+ "default_kb": default_kb,
+ "workspace": workspace,
+ }
+
+
+# ==================== Environment Variables API ====================
+
+
+def _mask_sensitive_value(value: str, sensitive: bool) -> str:
+ """Mask sensitive values for display (show first 4 and last 4 chars)"""
+ if not sensitive or not value:
+ return value
+ if len(value) <= 8:
+ return "*" * len(value)
+ return f"{value[:4]}{'*' * (len(value) - 8)}{value[-4:]}"
+
+
[email protected]("/env", response_model=EnvConfigResponse)
+async def get_env_config():
+ """
+ Get all environment variables configuration.
+
+ Returns current values (with sensitive values masked), descriptions,
+ and category information for the frontend to display.
+
+ Note: This returns the runtime values, which may differ from .env file
+ if they have been updated via the API.
+ """
+ variables = []
+
+ for key, definition in ENV_VAR_DEFINITIONS.items():
+ current_value = os.environ.get(key, definition["default"])
+ is_set = bool(current_value and current_value.strip())
+
+ variables.append(
+ EnvVarInfo(
+ key=key,
+ value=_mask_sensitive_value(current_value, definition["sensitive"]),
+ description=definition["description"],
+ category=definition["category"],
+ required=definition["required"],
+ default=definition["default"],
+ sensitive=definition["sensitive"],
+ is_set=is_set,
+ )
+ )
+
+ categories = [
+ EnvCategoryInfo(id=cat_id, **cat_info) for cat_id, cat_info in ENV_CATEGORIES.items()
+ ]
+
+ return EnvConfigResponse(variables=variables, categories=categories)
+
+
[email protected]("/env/{key}")
+async def get_env_var(key: str):
+ """
+ Get a single environment variable value.
+
+ For sensitive variables, returns masked value.
+ """
+ if key not in ENV_VAR_DEFINITIONS:
+ raise HTTPException(status_code=404, detail=f"Unknown environment variable: {key}")
+
+ definition = ENV_VAR_DEFINITIONS[key]
+ current_value = os.environ.get(key, definition["default"])
+
+ return {
+ "key": key,
+ "value": _mask_sensitive_value(current_value, definition["sensitive"]),
+ "description": definition["description"],
+ "category": definition["category"],
+ "required": definition["required"],
+ "is_set": bool(current_value and current_value.strip()),
+ }
+
+
+async def update_env_config(update: EnvConfigUpdate):
+ """
+ Update environment variables at runtime.
+
+ This updates the process environment variables immediately.
+ The system will use the new values for subsequent operations.
+
+ Note: These changes are NOT persisted to .env file.
+ On system restart, values will be loaded from .env again.
+
+ Returns:
+ Updated variables configuration
+ """
+ updated_vars = []
+ errors = []
+
+ for var_update in update.variables:
+ key = var_update.key
+ value = var_update.value
+
+ # Validate the variable is known
+ if key not in ENV_VAR_DEFINITIONS:
+ errors.append(f"Unknown environment variable: {key}")
+ continue
+
+ definition = ENV_VAR_DEFINITIONS[key]
+
+ # Skip if value is masked (user didn't change it)
+ if definition["sensitive"] and "*" in value:
+ # Value is masked, skip update
+ continue
+
+ # Update the environment variable
+ if value:
+ os.environ[key] = value
+ elif key in os.environ:
+ # If value is empty and variable exists, remove it
+ del os.environ[key]
+
+ updated_vars.append(key)
+
+ if errors:
+ raise HTTPException(status_code=400, detail={"errors": errors, "updated": updated_vars})
+
+ # Return the updated configuration
+ return {
+ "success": True,
+ "updated": updated_vars,
+ "message": f"Updated {len(updated_vars)} environment variables. Changes are active immediately but not persisted to .env file.",
+ }
+
+
[email protected]("/env/{key}")
+async def update_single_env_var(key: str, value: str):
+ """
+ Update a single environment variable at runtime.
+
+ Note: Changes are NOT persisted to .env file.
+ """
+ if key not in ENV_VAR_DEFINITIONS:
+ raise HTTPException(status_code=404, detail=f"Unknown environment variable: {key}")
+
+ definition = ENV_VAR_DEFINITIONS[key]
+
+ # Skip if value is masked (user didn't change it)
+ if definition["sensitive"] and "*" in value:
+ return {"success": False, "message": "Cannot update with masked value"}
+
+ # Update the environment variable
+ if value:
+ os.environ[key] = value
+ elif key in os.environ:
+ del os.environ[key]
+
+ return {
+ "success": True,
+ "key": key,
+ "message": f"Environment variable {key} updated. Changes are active immediately.",
+ }
+
+
[email protected]("/env/test")
+async def test_env_config():
+ """
+ Test current environment configuration by validating all services.
+
+ Returns the status of each service (LLM, Embedding, TTS).
+ """
+ results = {
+ "llm": {"status": "unknown", "model": None, "error": None},
+ "embedding": {"status": "unknown", "model": None, "error": None},
+ "tts": {"status": "unknown", "model": None, "error": None},
+ }
+
+ # Test LLM configuration
+ try:
+ from src.core.core import get_llm_config
+
+ llm_config = get_llm_config()
+ results["llm"]["model"] = llm_config.get("model")
+ results["llm"]["status"] = "configured"
+ except ValueError as e:
+ results["llm"]["status"] = "not_configured"
+ results["llm"]["error"] = str(e)
+ except Exception as e:
+ results["llm"]["status"] = "error"
+ results["llm"]["error"] = str(e)
+
+ # Test Embedding configuration
+ try:
+ from src.core.core import get_embedding_config
+
+ embedding_config = get_embedding_config()
+ results["embedding"]["model"] = embedding_config.get("model")
+ results["embedding"]["status"] = "configured"
+ except ValueError as e:
+ results["embedding"]["status"] = "not_configured"
+ results["embedding"]["error"] = str(e)
+ except Exception as e:
+ results["embedding"]["status"] = "error"
+ results["embedding"]["error"] = str(e)
+
+ # Test TTS configuration
+ try:
+ from src.core.core import get_tts_config
+
+ tts_config = get_tts_config()
+ results["tts"]["model"] = tts_config.get("model")
+ results["tts"]["status"] = "configured"
+ except ValueError as e:
+ results["tts"]["status"] = "not_configured"
+ results["tts"]["error"] = str(e)
+ except Exception as e:
+ results["tts"]["status"] = "error"
+ results["tts"]["error"] = str(e)
+
+ return results
diff --git a/src/api/routers/solve.py b/src/api/routers/solve.py
new file mode 100644
index 000000000..7cfef1692
--- /dev/null
+++ b/src/api/routers/solve.py
@@ -0,0 +1,293 @@
+"""
+Solve API Router
+================
+
+WebSocket endpoint for real-time problem solving with streaming logs.
+"""
+
+import asyncio
+from pathlib import Path
+import re
+import sys
+from typing import Any
+
+from fastapi import APIRouter, WebSocket, WebSocketDisconnect
+
+from src.agents.solve import MainSolver
+from src.api.utils.history import ActivityType, history_manager
+from src.api.utils.log_interceptor import LogInterceptor
+
+_project_root = Path(__file__).parent.parent.parent.parent
+sys.path.insert(0, str(_project_root))
+from src.core.core import load_config_with_main
+from src.core.logging import get_logger
+
+# Initialize logger with config
+project_root = Path(__file__).parent.parent.parent.parent
+config = load_config_with_main("solve_config.yaml", project_root)
+log_dir = config.get("paths", {}).get("user_log_dir") or config.get("logging", {}).get("log_dir")
+logger = get_logger("SolveAPI", level="INFO", log_dir=log_dir)
+
+router = APIRouter()
+
+
+async def websocket_solve(websocket: WebSocket):
+ await websocket.accept()
+
+ from src.api.utils.task_id_manager import TaskIDManager
+
+ task_manager = TaskIDManager.get_instance()
+
+ try:
+ # 1. Wait for the initial message with the question and config
+ data = await websocket.receive_json()
+ question = data.get("question")
+ kb_name = data.get("kb_name", "ai_textbook")
+
+ if not question:
+ await websocket.send_json({"type": "error", "content": "Question is required"})
+ return
+
+ task_key = f"solve_{kb_name}_{hash(str(question))}"
+ task_id = task_manager.generate_task_id("solve", task_key)
+
+ await websocket.send_json({"type": "task_id", "task_id": task_id})
+
+ # 2. Initialize Solver
+ root_dir = Path(__file__).parent.parent.parent.parent
+ output_base = root_dir / "data" / "user" / "solve"
+
+ solver = MainSolver(kb_name=kb_name, output_base_dir=str(output_base))
+
+ logger.info(f"[{task_id}] Solving: {question[:50]}...")
+
+ target_logger = solver.logger.logger
+
+ # Note: System log forwarder removed - all logs now go to unified log file
+ # The main logger already writes to data/user/logs/ai_tutor_YYYYMMDD.log
+
+ # 3. Setup Log Queue
+ log_queue = asyncio.Queue()
+
+ # 4. Setup status update mechanism
+ display_manager = None
+ if hasattr(solver.logger, "display_manager") and solver.logger.display_manager:
+ display_manager = solver.logger.display_manager
+
+ original_set_status = display_manager.set_agent_status
+
+ def wrapped_set_status(agent_name: str, status: str):
+ original_set_status(agent_name, status)
+ try:
+ log_queue.put_nowait(
+ {
+ "type": "agent_status",
+ "agent": agent_name,
+ "status": status,
+ "all_agents": display_manager.agents_status.copy(),
+ }
+ )
+ except Exception:
+ pass
+
+ display_manager.set_agent_status = wrapped_set_status
+
+ original_update_stats = display_manager.update_token_stats
+
+ def wrapped_update_stats(summary: dict[str, Any]):
+ original_update_stats(summary)
+ try:
+ stats_copy = display_manager.stats.copy()
+ logger.debug(
+ f"Sending token_stats: model={stats_copy.get('model')}, calls={stats_copy.get('calls')}, cost={stats_copy.get('cost')}"
+ )
+ log_queue.put_nowait({"type": "token_stats", "stats": stats_copy})
+ except Exception as e:
+ logger.debug(f"Failed to send token_stats: {e}")
+
+ display_manager.update_token_stats = wrapped_update_stats
+
+ # Re-register the callback to use the wrapped method
+ # (The callback was set before wrapping in main_solver.py)
+ if hasattr(solver, "token_tracker") and solver.token_tracker:
+ solver.token_tracker.set_on_usage_added_callback(wrapped_update_stats)
+
+ def send_progress_update(stage: str, progress: dict[str, Any]):
+ """Send progress update to frontend"""
+ try:
+ log_queue.put_nowait({"type": "progress", "stage": stage, "progress": progress})
+ except Exception:
+ pass
+
+ solver._send_progress_update = send_progress_update
+
+ # 5. Background task to push logs to WebSocket
+ connection_closed = asyncio.Event()
+
+ async def log_pusher():
+ while not connection_closed.is_set():
+ try:
+ # Use timeout to periodically check if connection is closed
+ entry = await asyncio.wait_for(log_queue.get(), timeout=0.5)
+ try:
+ await websocket.send_json(entry)
+ except (WebSocketDisconnect, RuntimeError, ConnectionError) as e:
+ # Connection closed, stop pushing
+ logger.debug(f"WebSocket connection closed in log_pusher: {e}")
+ connection_closed.set()
+ break
+ except Exception as e:
+ logger.debug(f"Error sending log entry: {e}")
+ # Continue to next entry
+ log_queue.task_done()
+ except asyncio.TimeoutError:
+ # Timeout, check if connection is still open
+ continue
+ except Exception as e:
+ logger.debug(f"Error in log_pusher: {e}")
+ break
+
+ pusher_task = asyncio.create_task(log_pusher())
+
+ # Helper function to safely send WebSocket messages
+ async def safe_send_json(data: dict[str, Any]):
+ """Safely send JSON to WebSocket, checking if connection is closed"""
+ if connection_closed.is_set():
+ return False
+ try:
+ await websocket.send_json(data)
+ return True
+ except (WebSocketDisconnect, RuntimeError, ConnectionError) as e:
+ logger.debug(f"WebSocket connection closed: {e}")
+ connection_closed.set()
+ return False
+ except Exception as e:
+ logger.debug(f"Error sending WebSocket message: {e}")
+ return False
+
+ # 6. Run Solver within the LogInterceptor context
+ try:
+ interceptor = LogInterceptor(target_logger, log_queue)
+ with interceptor:
+ await safe_send_json({"type": "status", "content": "started"})
+
+ if display_manager:
+ await safe_send_json(
+ {
+ "type": "agent_status",
+ "agent": "all",
+ "status": "initial",
+ "all_agents": display_manager.agents_status.copy(),
+ }
+ )
+ await safe_send_json(
+ {"type": "token_stats", "stats": display_manager.stats.copy()}
+ )
+
+ logger.progress(f"[{task_id}] Solving started")
+
+ result = await solver.solve(question, verbose=True)
+
+ logger.success(f"[{task_id}] Solving completed")
+ task_manager.update_task_status(task_id, "completed")
+
+ # Process Markdown content to fix image paths
+ final_answer = result.get("final_answer", "")
+ output_dir_str = result.get("output_dir", "")
+
+ if output_dir_str and final_answer:
+ try:
+ output_dir = Path(output_dir_str)
+
+ if not output_dir.is_absolute():
+ output_dir = output_dir.resolve()
+
+ path_str = str(output_dir).replace("\\", "/")
+ parts = path_str.split("/")
+
+ if "user" in parts:
+ idx = parts.index("user")
+ rel_path = "/".join(parts[idx + 1 :])
+ base_url = f"/api/outputs/{rel_path}"
+
+ pattern = r"\]\(artifacts/([^)]+)\)"
+ replacement = rf"]({base_url}/artifacts/\1)"
+ final_answer = re.sub(pattern, replacement, final_answer)
+ except Exception as e:
+ logger.debug(f"Error processing image paths: {e}")
+
+ # Send final agent status update
+ if display_manager:
+ final_agent_status = dict.fromkeys(display_manager.agents_status.keys(), "done")
+ await safe_send_json(
+ {
+ "type": "agent_status",
+ "agent": "all",
+ "status": "complete",
+ "all_agents": final_agent_status,
+ }
+ )
+
+ # Send final result
+ final_res = {
+ "type": "result",
+ "final_answer": final_answer,
+ "output_dir": output_dir_str,
+ "metadata": result.get("metadata"),
+ }
+ await safe_send_json(final_res)
+
+ # Save to history
+ history_manager.add_entry(
+ activity_type=ActivityType.SOLVE,
+ title=question[:50] + "..." if len(question) > 50 else question,
+ content={
+ "question": question,
+ "answer": result.get("final_answer"),
+ "kb_name": kb_name,
+ },
+ summary=(
+ result.get("final_answer")[:100] + "..."
+ if result.get("final_answer")
+ else ""
+ ),
+ )
+
+ except Exception as e:
+ # Mark connection as closed before sending error (to prevent log_pusher from interfering)
+ connection_closed.set()
+ await safe_send_json({"type": "error", "content": str(e)})
+ logger.error(f"[{task_id}] Solving failed: {e}")
+ task_manager.update_task_status(task_id, "error", error=str(e))
+ finally:
+ # Stop log pusher first
+ connection_closed.set()
+ pusher_task.cancel()
+ try:
+ await pusher_task
+ except asyncio.CancelledError:
+ pass
+ except Exception as e:
+ logger.debug(f"Error waiting for pusher task: {e}")
+
+ # Close WebSocket connection
+ try:
+ # Check if connection is still open before closing
+ if hasattr(websocket, "client_state"):
+ state = websocket.client_state
+ if hasattr(state, "name") and state.name != "DISCONNECTED":
+ await websocket.close()
+ else:
+ # Fallback: try to close anyway
+ await websocket.close()
+ except (WebSocketDisconnect, RuntimeError, ConnectionError):
+ # Connection already closed, ignore
+ pass
+ except Exception as e:
+ logger.debug(f"Error closing WebSocket: {e}")
+
+ except WebSocketDisconnect:
+ logger.debug("Client disconnected")
+ except Exception as e:
+ logger.error(f"WebSocket error: {e}")
diff --git a/src/api/routers/system.py b/src/api/routers/system.py
new file mode 100644
index 000000000..76bbb7ffc
--- /dev/null
+++ b/src/api/routers/system.py
@@ -0,0 +1,255 @@
+"""
+System Status API Router
+Manages system status checks and model connection tests
+"""
+
+from datetime import datetime
+import time
+
+from fastapi import APIRouter
+from pydantic import BaseModel
+
+router = APIRouter()
+
+
+class TestResponse(BaseModel):
+ success: bool
+ message: str
+ model: str | None = None
+ response_time_ms: float | None = None
+ error: str | None = None
+
+
+async def get_system_status():
+ """
+ Get overall system status including backend and model configurations
+
+ Returns:
+ Dictionary containing status of backend, LLM, embeddings, and TTS
+ """
+ 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},
+ }
+
+ # Check backend status (this endpoint itself proves backend is online)
+ result["backend"]["status"] = "online"
+
+ # Check LLM configuration
+ try:
+ from src.core.core import get_llm_config
+
+ llm_config = get_llm_config()
+ result["llm"]["model"] = llm_config.get("model")
+ result["llm"]["status"] = "configured"
+ except ValueError as e:
+ result["llm"]["status"] = "not_configured"
+ result["llm"]["error"] = str(e)
+ except Exception as e:
+ result["llm"]["status"] = "error"
+ result["llm"]["error"] = str(e)
+
+ # Check Embeddings configuration
+ try:
+ from src.core.core import get_embedding_config
+
+ embedding_config = get_embedding_config()
+ result["embeddings"]["model"] = embedding_config.get("model")
+ result["embeddings"]["status"] = "configured"
+ except ValueError as e:
+ result["embeddings"]["status"] = "not_configured"
+ result["embeddings"]["error"] = str(e)
+ except Exception as e:
+ result["embeddings"]["status"] = "error"
+ result["embeddings"]["error"] = str(e)
+
+ # Check TTS configuration
+ try:
+ from src.core.core import get_tts_config
+
+ 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)
+
+ return result
+
+
[email protected]("/test/llm", response_model=TestResponse)
+async def test_llm_connection():
+ """
+ Test LLM model connection by sending a simple completion request
+
+ Returns:
+ Test result with success status and response time
+ """
+ start_time = time.time()
+
+ try:
+ from src.core.core import get_llm_config
+
+ llm_config = get_llm_config()
+ model = llm_config["model"]
+ api_key = llm_config["api_key"]
+ base_url = llm_config["base_url"]
+
+ # Import LLM completion function
+ from lightrag.llm.openai import openai_complete_if_cache
+
+ # Send a minimal test request
+ test_prompt = "test"
+ response = await openai_complete_if_cache(
+ model=model,
+ prompt=test_prompt,
+ system_prompt="You are a helpful assistant.",
+ api_key=api_key,
+ base_url=base_url,
+ temperature=0.1,
+ max_tokens=5, # Minimal tokens for testing
+ )
+
+ response_time = (time.time() - start_time) * 1000
+
+ if response and len(response.strip()) > 0:
+ return TestResponse(
+ success=True,
+ message="LLM connection successful",
+ model=model,
+ response_time_ms=round(response_time, 2),
+ )
+ return TestResponse(
+ success=False,
+ message="LLM connection failed: Empty response",
+ model=model,
+ error="Empty response from API",
+ )
+
+ except ValueError as e:
+ return TestResponse(success=False, message=f"LLM configuration error: {e!s}", error=str(e))
+ except Exception as e:
+ response_time = (time.time() - start_time) * 1000
+ return TestResponse(
+ success=False,
+ message=f"LLM connection failed: {e!s}",
+ response_time_ms=round(response_time, 2),
+ error=str(e),
+ )
+
+
[email protected]("/test/embeddings", response_model=TestResponse)
+async def test_embeddings_connection():
+ """
+ Test Embeddings model connection by sending a simple embedding request
+
+ Returns:
+ Test result with success status and response time
+ """
+ start_time = time.time()
+
+ try:
+ from src.core.core import get_embedding_config
+
+ embedding_config = get_embedding_config()
+ model = embedding_config["model"]
+ api_key = embedding_config["api_key"]
+ base_url = embedding_config["base_url"]
+
+ # Import embedding function
+ from lightrag.llm.openai import openai_embed
+
+ # Send a minimal test request
+ test_texts = ["test"]
+ # openai_embed returns a coroutine, so we need to await it
+ embeddings = await openai_embed(
+ texts=test_texts, model=model, api_key=api_key, base_url=base_url
+ )
+
+ response_time = (time.time() - start_time) * 1000
+
+ if embeddings and len(embeddings) > 0 and len(embeddings[0]) > 0:
+ return TestResponse(
+ success=True,
+ message="Embeddings connection successful",
+ model=model,
+ response_time_ms=round(response_time, 2),
+ )
+ return TestResponse(
+ success=False,
+ message="Embeddings connection failed: Empty response",
+ model=model,
+ error="Empty embedding vector",
+ )
+
+ except ValueError as e:
+ return TestResponse(
+ success=False, message=f"Embeddings configuration error: {e!s}", error=str(e)
+ )
+ except Exception as e:
+ response_time = (time.time() - start_time) * 1000
+ return TestResponse(
+ success=False,
+ message=f"Embeddings connection failed: {e!s}",
+ response_time_ms=round(response_time, 2),
+ error=str(e),
+ )
+
+
[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
+ """
+ start_time = time.time()
+
+ try:
+ from src.core.core import get_tts_config
+
+ 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:
+ return TestResponse(
+ success=False,
+ message="TTS configuration incomplete",
+ model=model,
+ error="Missing required configuration",
+ )
+
+ # For TTS, we just verify the config is valid
+ # Actual audio generation would be expensive, so we skip it
+ response_time = (time.time() - start_time) * 1000
+
+ return TestResponse(
+ success=True,
+ message="TTS configuration valid",
+ model=model,
+ 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))
+ except Exception as e:
+ response_time = (time.time() - start_time) * 1000
+ return TestResponse(
+ success=False,
+ message=f"TTS connection check failed: {e!s}",
+ response_time_ms=round(response_time, 2),
+ error=str(e),
+ )
diff --git a/src/api/run_server.py b/src/api/run_server.py
new file mode 100644
index 000000000..2d6c925c4
--- /dev/null
+++ b/src/api/run_server.py
@@ -0,0 +1,59 @@
+#!/usr/bin/env python
+"""
+Uvicorn Server Startup Script
+Uses Python API instead of command line to avoid Windows path parsing issues.
+"""
+
+import os
+import sys
+
+# Force unbuffered output
+os.environ["PYTHONUNBUFFERED"] = "1"
+if hasattr(sys.stdout, "reconfigure"):
+ sys.stdout.reconfigure(line_buffering=True)
+if hasattr(sys.stderr, "reconfigure"):
+ sys.stderr.reconfigure(line_buffering=True)
+
+from pathlib import Path
+
+import uvicorn
+
+if __name__ == "__main__":
+ # Get project root directory
+ project_root = Path(__file__).parent.parent.parent
+
+ # Change to project root to ensure correct module imports
+ os.chdir(str(project_root))
+
+ # Ensure project root is in Python path
+ if str(project_root) not in sys.path:
+ sys.path.insert(0, str(project_root))
+
+ # Get port from configuration
+ from src.core.setup import get_backend_port
+
+ backend_port = get_backend_port(project_root)
+
+ # Configure reload_excludes to skip temporary files and output directories
+ reload_excludes = [
+ "**/run_code_workspace/**", # Code execution workspace
+ "**/tmp*/**", # All temp directories
+ "**/__pycache__/**", # Python cache
+ "**/*.pyc", # Python compiled files
+ "**/user/solve/**", # Solve output directory
+ "**/user/question/**", # Question output directory
+ "**/user/research/**", # Research output directory
+ "**/user/co-writer/**", # Co-Writer output directory
+ "**/logs/**", # Logs directory
+ "**/user/logs/**", # User logs directory
+ ]
+
+ # Start uvicorn server with reload enabled
+ uvicorn.run(
+ "src.api.main:app",
+ host="0.0.0.0",
+ port=backend_port,
+ reload=True,
+ reload_excludes=reload_excludes,
+ log_level="info",
+ )
diff --git a/src/api/utils/history.py b/src/api/utils/history.py
new file mode 100644
index 000000000..aef03b05b
--- /dev/null
+++ b/src/api/utils/history.py
@@ -0,0 +1,171 @@
+from enum import Enum
+import json
+from pathlib import Path
+import time
+
+
+class ActivityType(str, Enum):
+ SOLVE = "solve"
+ QUESTION = "question"
+ RESEARCH = "research"
+
+
+class HistoryManager:
+ def __init__(self, base_dir: str | None = None):
+ """
+ History record manager
+
+ Args:
+ base_dir: History record directory. Default fixed to "project root/user",
+ at the same level as user/question, user/solve, user/research,
+ does not depend on current working directory, avoids path misalignment
+ when uvicorn / IDE start differently.
+ """
+ if base_dir is None:
+ # Current file: OpenTutor/src/api/utils/history.py
+ # Project root should be three levels up: OpenTutor/
+ project_root = Path(__file__).resolve().parents[3]
+ base_dir_path = project_root / "data" / "user"
+ else:
+ base_dir_path = Path(base_dir)
+
+ self.base_dir = base_dir_path
+ self.base_dir.mkdir(parents=True, exist_ok=True)
+
+ self.history_file = self.base_dir / "user_history.json"
+ self._ensure_file()
+
+ def _ensure_file(self):
+ """
+ Ensure history file exists with correct format.
+ If file exists but has wrong format, it will be fixed on next save.
+ """
+ if not self.history_file.exists():
+ # Create file with correct dict format (matching user_dir_init.py)
+ initial_history = {"version": "1.0", "created_at": None, "sessions": []}
+ try:
+ with open(self.history_file, "w", encoding="utf-8") as f:
+ json.dump(initial_history, f, indent=2, ensure_ascii=False)
+ except Exception:
+ # If we can't create the file, that's okay - it will be handled in _load_history
+ pass
+ else:
+ # File exists, verify it's in correct format
+ # If not, it will be fixed on next save operation
+ try:
+ with open(self.history_file, encoding="utf-8") as f:
+ data = json.load(f)
+ # If file is in old list format, we'll convert it on next save
+ if isinstance(data, list):
+ # File is in old format, but that's okay - _load_history handles it
+ pass
+ except Exception:
+ # File exists but is corrupted, will be recreated on next save
+ pass
+
+ def _load_history(self) -> list[dict]:
+ """
+ Load history from file. Handles multiple formats for backward compatibility.
+ Returns a list of history entries.
+ """
+ try:
+ if not self.history_file.exists():
+ return []
+
+ with open(self.history_file, encoding="utf-8") as f:
+ data = json.load(f)
+
+ # Handle both list format and dict format (with 'sessions' key)
+ if isinstance(data, dict):
+ # If it's a dict, try to get 'sessions' field
+ sessions = data.get("sessions", [])
+ # Ensure sessions is a list
+ if isinstance(sessions, list):
+ return sessions
+ # If sessions is not a list, return empty list and log warning
+ return []
+ if isinstance(data, list):
+ # Legacy format: direct list
+ return data
+ # Unknown format, return empty list
+ return []
+ except json.JSONDecodeError:
+ # File exists but is corrupted, return empty list
+ # Could log this error in production
+ return []
+ except Exception:
+ # Any other error, return empty list
+ return []
+
+ def _save_history(self, history: list[dict]):
+ # Load existing file to preserve metadata if it's in dict format
+ try:
+ with open(self.history_file, encoding="utf-8") as f:
+ existing_data = json.load(f)
+ if isinstance(existing_data, dict):
+ # Preserve dict structure, update sessions
+ existing_data["sessions"] = history
+ data_to_save = existing_data
+ else:
+ # If it was a list, convert to dict format
+ data_to_save = {
+ "version": "1.0",
+ "created_at": existing_data[0].get("timestamp") if existing_data else None,
+ "sessions": history,
+ }
+ except Exception:
+ # If file doesn't exist or can't be read, create new dict format
+ data_to_save = {
+ "version": "1.0",
+ "created_at": history[0].get("timestamp") if history else None,
+ "sessions": history,
+ }
+
+ with open(self.history_file, "w", encoding="utf-8") as f:
+ json.dump(data_to_save, f, indent=2, ensure_ascii=False)
+
+ def add_entry(self, activity_type: ActivityType, title: str, content: dict, summary: str = ""):
+ """
+ Add a new history entry.
+
+ Args:
+ activity_type: The type of activity (solve, question, research)
+ title: A short title (e.g. the question asked, or topic)
+ content: The full result/payload
+ summary: A short summary if applicable
+ """
+ entry = {
+ "id": str(int(time.time() * 1000)),
+ "timestamp": time.time(),
+ "type": activity_type,
+ "title": title,
+ "summary": summary,
+ "content": content,
+ }
+
+ history = self._load_history()
+ history.insert(0, entry) # Prepend to show latest first
+
+ # Optional: Limit history size
+ if len(history) > 100:
+ history = history[:100]
+
+ self._save_history(history)
+ return entry
+
+ def get_recent(self, limit: int = 10, type_filter: str | None = None) -> list[dict]:
+ history = self._load_history()
+ if type_filter:
+ history = [h for h in history if h["type"] == type_filter]
+ return history[:limit]
+
+ def get_entry(self, entry_id: str) -> dict | None:
+ history = self._load_history()
+ for entry in history:
+ if entry["id"] == entry_id:
+ return entry
+ return None
+
+
+# Global instance
+history_manager = HistoryManager()
diff --git a/src/api/utils/log_interceptor.py b/src/api/utils/log_interceptor.py
new file mode 100644
index 000000000..6380b9cd2
--- /dev/null
+++ b/src/api/utils/log_interceptor.py
@@ -0,0 +1,30 @@
+"""
+Log Interceptor for WebSocket streaming
+=======================================
+
+Re-exports handlers from the unified logging system.
+Kept for backwards compatibility.
+"""
+
+from pathlib import Path
+import sys
+
+# Add project root to path
+project_root = Path(__file__).parent.parent.parent.parent
+if str(project_root) not in sys.path:
+ sys.path.insert(0, str(project_root))
+
+# Re-export from unified logging system
+from src.core.logging.handlers import (
+ JSONFileHandler,
+ LogInterceptor,
+ WebSocketLogHandler,
+ create_task_logger,
+)
+
+__all__ = [
+ "WebSocketLogHandler",
+ "LogInterceptor",
+ "JSONFileHandler",
+ "create_task_logger",
+]
diff --git a/src/api/utils/notebook_manager.py b/src/api/utils/notebook_manager.py
new file mode 100644
index 000000000..61c9322e3
--- /dev/null
+++ b/src/api/utils/notebook_manager.py
@@ -0,0 +1,415 @@
+"""
+Notebook Manager - Manages user notebooks and records
+All notebook data is stored in user/notebook/ directory
+"""
+
+from enum import Enum
+import json
+from pathlib import Path
+import time
+import uuid
+
+from pydantic import BaseModel
+
+
+class RecordType(str, Enum):
+ """Record type"""
+
+ SOLVE = "solve"
+ QUESTION = "question"
+ RESEARCH = "research"
+ CO_WRITER = "co_writer"
+
+
+class NotebookRecord(BaseModel):
+ """Single record in notebook"""
+
+ id: str
+ type: RecordType
+ title: str
+ user_query: str
+ output: str
+ metadata: dict = {}
+ created_at: float
+ kb_name: str | None = None
+
+
+class Notebook(BaseModel):
+ """Notebook model"""
+
+ id: str
+ name: str
+ description: str = ""
+ created_at: float
+ updated_at: float
+ records: list[NotebookRecord] = []
+ color: str = "#3B82F6" # Default blue
+ icon: str = "book" # Default icon
+
+
+class NotebookManager:
+ """Notebook manager"""
+
+ def __init__(self, base_dir: str | None = None):
+ """
+ Initialize notebook manager
+
+ Args:
+ base_dir: Notebook storage directory, defaults to project root/user/notebook
+ """
+ if base_dir is None:
+ # Current file: OpenTutor/src/api/utils/notebook_manager.py
+ # Project root should be three levels up: OpenTutor/
+ project_root = Path(__file__).resolve().parents[3]
+ base_dir_path = project_root / "data" / "user" / "notebook"
+ else:
+ base_dir_path = Path(base_dir)
+
+ self.base_dir = base_dir_path
+ self.base_dir.mkdir(parents=True, exist_ok=True)
+
+ # Notebook index file
+ self.index_file = self.base_dir / "notebooks_index.json"
+ self._ensure_index()
+
+ def _ensure_index(self):
+ """Ensure index file exists"""
+ 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"""
+ 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
+ try:
+ with open(filepath, encoding="utf-8") as f:
+ return json.load(f)
+ except Exception:
+ return None
+
+ def _save_notebook(self, notebook: dict):
+ """Save single notebook"""
+ 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)
+
+ # === 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()
+
+ notebook = {
+ "id": notebook_id,
+ "name": name,
+ "description": description,
+ "created_at": now,
+ "updated_at": now,
+ "records": [],
+ "color": color,
+ "icon": icon,
+ }
+
+ # Save notebook file
+ self._save_notebook(notebook)
+
+ # Update index
+ index = self._load_index()
+ index["notebooks"].append(
+ {
+ "id": notebook_id,
+ "name": name,
+ "description": description,
+ "created_at": now,
+ "updated_at": now,
+ "record_count": 0,
+ "color": color,
+ "icon": icon,
+ }
+ )
+ self._save_index(index)
+
+ return notebook
+
+ def list_notebooks(self) -> list[dict]:
+ """
+ List all notebooks (summary information)
+
+ Returns:
+ Notebook list
+ """
+ index = self._load_index()
+ notebooks = []
+
+ for nb_info in index.get("notebooks", []):
+ # Get latest information from actual file
+ notebook = self._load_notebook(nb_info["id"])
+ if notebook:
+ notebooks.append(
+ {
+ "id": notebook["id"],
+ "name": notebook["name"],
+ "description": notebook.get("description", ""),
+ "created_at": notebook["created_at"],
+ "updated_at": notebook["updated_at"],
+ "record_count": len(notebook.get("records", [])),
+ "color": notebook.get("color", "#3B82F6"),
+ "icon": notebook.get("icon", "book"),
+ }
+ )
+
+ # Sort by update time
+ notebooks.sort(key=lambda x: x["updated_at"], reverse=True)
+ return notebooks
+
+ def 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(
+ self,
+ notebook_id: str,
+ name: str | None = None,
+ description: str | None = None,
+ 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
+
+ if name is not None:
+ notebook["name"] = name
+ if description is not None:
+ notebook["description"] = description
+ if color is not None:
+ notebook["color"] = color
+ if icon is not None:
+ notebook["icon"] = icon
+
+ 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)
+
+ return notebook
+
+ def 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 file
+ filepath.unlink()
+
+ # Update index
+ index = self._load_index()
+ index["notebooks"] = [nb for nb in index["notebooks"] if nb["id"] != notebook_id]
+ self._save_index(index)
+
+ return True
+
+ # === Record Operations ===
+
+ def add_record(
+ self,
+ notebook_ids: list[str],
+ record_type: RecordType,
+ title: str,
+ user_query: str,
+ output: str,
+ metadata: dict = None,
+ kb_name: str = 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()
+
+ record = {
+ "id": record_id,
+ "type": record_type,
+ "title": title,
+ "user_query": user_query,
+ "output": output,
+ "metadata": metadata or {},
+ "created_at": now,
+ "kb_name": kb_name,
+ }
+
+ added_to = []
+ 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)
+
+ return {"record": record, "added_to_notebooks": added_to}
+
+ def 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
+
+ original_count = len(notebook["records"])
+ notebook["records"] = [r for r in notebook["records"] if r["id"] != record_id]
+
+ if len(notebook["records"]) == original_count:
+ return False
+
+ 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)
+
+ return True
+
+ def get_statistics(self) -> dict:
+ """
+ Get notebook statistics
+
+ Returns:
+ Statistics information
+ """
+ notebooks = self.list_notebooks()
+
+ total_records = 0
+ type_counts = {"solve": 0, "question": 0, "research": 0, "co_writer": 0}
+
+ for nb_info in notebooks:
+ notebook = self._load_notebook(nb_info["id"])
+ if notebook:
+ for record in notebook.get("records", []):
+ total_records += 1
+ record_type = record.get("type", "")
+ if record_type in type_counts:
+ type_counts[record_type] += 1
+
+ return {
+ "total_notebooks": len(notebooks),
+ "total_records": total_records,
+ "records_by_type": type_counts,
+ "recent_notebooks": notebooks[:5],
+ }
+
+
+# Global instance
+notebook_manager = NotebookManager()
diff --git a/src/api/utils/progress_broadcaster.py b/src/api/utils/progress_broadcaster.py
new file mode 100644
index 000000000..97c661bd7
--- /dev/null
+++ b/src/api/utils/progress_broadcaster.py
@@ -0,0 +1,72 @@
+"""
+Progress Broadcaster - Manages WebSocket broadcasting of knowledge base progress
+"""
+
+import asyncio
+from typing import Optional
+
+from fastapi import WebSocket
+
+
+class ProgressBroadcaster:
+ """Manages WebSocket broadcasting of knowledge base progress"""
+
+ _instance: Optional["ProgressBroadcaster"] = None
+ _connections: dict[str, set[WebSocket]] = {} # kb_name -> Set[WebSocket]
+ _lock = asyncio.Lock()
+
+ @classmethod
+ def get_instance(cls) -> "ProgressBroadcaster":
+ """Get singleton instance"""
+ if cls._instance is None:
+ cls._instance = cls()
+ return cls._instance
+
+ async def connect(self, kb_name: str, websocket: WebSocket):
+ """Connect WebSocket to specified knowledge base"""
+ async with self._lock:
+ if kb_name not in self._connections:
+ self._connections[kb_name] = set()
+ self._connections[kb_name].add(websocket)
+ print(
+ f"[ProgressBroadcaster] Connected WebSocket for KB '{kb_name}' (total: {len(self._connections[kb_name])})"
+ )
+
+ async def disconnect(self, kb_name: str, websocket: WebSocket):
+ """Disconnect WebSocket connection"""
+ async with self._lock:
+ if kb_name in self._connections:
+ self._connections[kb_name].discard(websocket)
+ if not self._connections[kb_name]:
+ del self._connections[kb_name]
+ print(f"[ProgressBroadcaster] Disconnected WebSocket for KB '{kb_name}'")
+
+ async def broadcast(self, kb_name: str, progress: dict):
+ """Broadcast progress update to all WebSocket connections for specified knowledge base"""
+ async with self._lock:
+ if kb_name not in self._connections:
+ return
+
+ # Create list of connections to remove (closed connections)
+ to_remove = []
+
+ for websocket in self._connections[kb_name]:
+ try:
+ await websocket.send_json({"type": "progress", "data": progress})
+ except Exception as e:
+ # Connection closed or error, mark for removal
+ print(
+ f"[ProgressBroadcaster] Error sending to WebSocket for KB '{kb_name}': {e}"
+ )
+ to_remove.append(websocket)
+
+ # Remove closed connections
+ for ws in to_remove:
+ self._connections[kb_name].discard(ws)
+
+ if not self._connections[kb_name]:
+ del self._connections[kb_name]
+
+ def get_connection_count(self, kb_name: str) -> int:
+ """Get connection count for specified knowledge base"""
+ return len(self._connections.get(kb_name, set()))
diff --git a/src/api/utils/task_id_manager.py b/src/api/utils/task_id_manager.py
new file mode 100644
index 000000000..45f902550
--- /dev/null
+++ b/src/api/utils/task_id_manager.py
@@ -0,0 +1,102 @@
+"""
+Task ID Manager - Assigns unique IDs to each background task
+"""
+
+from datetime import datetime
+import threading
+from typing import Optional
+import uuid
+
+
+class TaskIDManager:
+ """Singleton class for managing task IDs"""
+
+ _instance: Optional["TaskIDManager"] = None
+ _lock = threading.Lock()
+ _task_ids: dict[str, str] = {} # task_key -> task_id
+ _task_metadata: dict[str, dict] = {} # task_id -> metadata
+
+ @classmethod
+ def get_instance(cls) -> "TaskIDManager":
+ """Get singleton instance"""
+ if cls._instance is None:
+ with cls._lock:
+ if cls._instance is None:
+ cls._instance = cls()
+ return cls._instance
+
+ def generate_task_id(self, task_type: str, task_key: str) -> str:
+ """
+ Generate unique ID for task
+
+ Args:
+ task_type: Task type (e.g., 'kb_init', 'kb_upload', 'question_gen', 'solve', 'research')
+ task_key: Task unique identifier (e.g., knowledge base name, question ID, etc.)
+
+ Returns:
+ Task ID (format: {task_type}_{timestamp}_{uuid})
+ """
+ with self._lock:
+ # If task already exists, return existing ID
+ if task_key in self._task_ids:
+ return self._task_ids[task_key]
+
+ # Generate new ID
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
+ unique_id = str(uuid.uuid4())[:8]
+ task_id = f"{task_type}_{timestamp}_{unique_id}"
+
+ # Save mapping and metadata
+ self._task_ids[task_key] = task_id
+ self._task_metadata[task_id] = {
+ "task_type": task_type,
+ "task_key": task_key,
+ "created_at": datetime.now().isoformat(),
+ "status": "running",
+ }
+
+ return task_id
+
+ def get_task_id(self, task_key: str) -> str | None:
+ """Get task ID"""
+ with self._lock:
+ return self._task_ids.get(task_key)
+
+ def update_task_status(self, task_id: str, status: str, **kwargs):
+ """Update task status"""
+ with self._lock:
+ if task_id in self._task_metadata:
+ self._task_metadata[task_id]["status"] = status
+ self._task_metadata[task_id].update(kwargs)
+ if status in ["completed", "error", "cancelled"]:
+ self._task_metadata[task_id]["finished_at"] = datetime.now().isoformat()
+
+ def get_task_metadata(self, task_id: str) -> dict | None:
+ """Get task metadata"""
+ with self._lock:
+ return self._task_metadata.get(task_id, {}).copy()
+
+ def cleanup_old_tasks(self, max_age_hours: int = 24):
+ """Clean up old tasks (completed tasks older than specified hours)"""
+ with self._lock:
+ from datetime import timedelta
+
+ cutoff = datetime.now() - timedelta(hours=max_age_hours)
+
+ to_remove = []
+ for task_id, metadata in self._task_metadata.items():
+ if metadata.get("status") in ["completed", "error", "cancelled"]:
+ finished_at = metadata.get("finished_at")
+ if finished_at:
+ try:
+ finished_time = datetime.fromisoformat(finished_at)
+ if finished_time < cutoff:
+ to_remove.append(task_id)
+ except:
+ pass
+
+ for task_id in to_remove:
+ metadata = self._task_metadata.pop(task_id, {})
+ task_key = metadata.get("task_key")
+ if task_key:
+ self._task_ids.pop(task_key, None)
diff --git a/src/core/README.md b/src/core/README.md
new file mode 100644
index 000000000..d4341b813
--- /dev/null
+++ b/src/core/README.md
@@ -0,0 +1,293 @@
+# Core Module
+
+The Core module provides essential system services including configuration management, logging, and system initialization.
+
+## 📋 Overview
+
+The Core module is the foundation of the OpenTutor system, providing:
+- Unified configuration management (environment variables + YAML)
+- Comprehensive logging system
+- System initialization and setup
+- Path management utilities
+
+## 🏗️ Architecture
+
+```
+core/
+├── __init__.py
+├── core.py # Configuration management
+├── setup.py # System initialization
+└── logging/ # Logging system
+ ├── __init__.py
+ ├── logger.py # Logger implementation
+ ├── handlers.py # Log handlers
+ ├── llm_stats.py # LLM usage statistics
+ ├── log_forwarder.py # Log forwarding
+ ├── lightrag_forward.py # LightRAG log forwarding
+ └── terminal_display.py # Terminal display utilities
+```
+
+## 🔧 Components
+
+### core.py
+
+**Configuration Management**
+
+Provides unified configuration loading from environment variables and YAML files.
+
+**Key Functions**:
+
+#### `get_llm_config() -> dict`
+Returns LLM configuration from environment variables:
+```python
+{
+ "binding": "openai",
+ "model": "gpt-4o",
+ "api_key": "...",
+ "base_url": "https://api.openai.com/v1"
+}
+```
+
+#### `get_tts_config() -> dict`
+Returns TTS configuration from environment variables:
+```python
+{
+ "model": "sambert-zhichu-v1",
+ "api_key": "...",
+ "base_url": "https://dashscope.aliyuncs.com/api/v1",
+ "voice": "Cherry"
+}
+```
+
+#### `get_embedding_config() -> dict`
+Returns embedding model configuration from environment variables.
+
+#### `load_config_with_main(config_file: str, project_root: Path) -> dict`
+Loads configuration from `main.yaml`:
+1. Loads `config/main.yaml` as configuration
+2. Returns the configuration dictionary
+
+**Usage**:
+```python
+from src.core.core import load_config_with_main
+from pathlib import Path
+
+config = load_config_with_main("main.yaml", Path(__file__).parent.parent.parent)
+```
+
+#### `get_agent_params(module_name: str) -> dict`
+Gets agent parameters (temperature, max_tokens) from `agents.yaml`:
+
+**Usage**:
+```python
+from src.core.core import get_agent_params
+
+params = get_agent_params("solve")
+# Returns: {"temperature": 0.3, "max_tokens": 8192}
+```
+
+### setup.py
+
+**System Initialization**
+
+Handles system setup and initialization tasks.
+
+**Key Functions**:
+
+#### `init_user_directories(project_root: Optional[Path] = None) -> None`
+Initializes all required user data directories:
+- `data/user/solve/`
+- `data/user/question/`
+- `data/user/research/`
+- `data/user/guide/`
+- `data/user/notebook/`
+- `data/user/co-writer/`
+- `data/user/logs/`
+- `data/user/run_code_workspace/`
+
+#### `get_backend_port(project_root: Optional[Path] = None) -> int`
+Gets backend port from configuration.
+
+#### `get_frontend_port(project_root: Optional[Path] = None) -> int`
+Gets frontend port from configuration.
+
+### logging/
+
+**Comprehensive Logging System**
+
+#### logger.py
+
+**Main Logger Implementation**
+
+Provides `get_logger()` function for creating loggers:
+
+```python
+from src.core.logging import get_logger
+
+logger = get_logger("MyModule", level="INFO", log_dir="./logs")
+```
+
+**Features**:
+- File and console output
+- Configurable log levels
+- Automatic log rotation
+- Module-specific loggers
+
+#### llm_stats.py
+
+**LLM Usage Statistics**
+
+Tracks LLM API usage:
+- Token counts (input/output)
+- API calls
+- Cost estimation
+
+**Usage**:
+```python
+from src.core.logging import LLMStats
+
+stats = LLMStats(module_name="MyModule")
+stats.add_call(model="gpt-4o", system_prompt="...", user_prompt="...", response="...")
+stats.print_summary()
+```
+
+#### log_forwarder.py
+
+**Log Forwarding**
+
+Forwards logs from external libraries (e.g., LightRAG) to the main logging system.
+
+#### handlers.py
+
+**Custom Log Handlers**
+
+Custom handlers for file and console output.
+
+## ⚙️ Configuration
+
+### Environment Variables
+
+Required in `.env` or `OpenTutor.env`:
+
+```bash
+# LLM Configuration
+LLM_BINDING_API_KEY=your_api_key
+LLM_BINDING_HOST=https://api.openai.com/v1
+LLM_MODEL=gpt-4o
+
+# TTS Configuration (optional)
+TTS_API_KEY=your_tts_key
+TTS_URL=https://dashscope.aliyuncs.com/api/v1
+TTS_MODEL=sambert-zhichu-v1
+
+# Embedding Configuration (optional)
+EMBEDDING_BINDING_API_KEY=your_embedding_key
+EMBEDDING_BINDING_HOST=https://api.openai.com/v1
+EMBEDDING_MODEL=text-embedding-3-large
+```
+
+### YAML Configuration
+
+Configuration files in `config/`:
+- `main.yaml` - Main system configuration
+- `solve_config.yaml` - Solve module configuration
+- `research_config.yaml` - Research module configuration
+- etc.
+
+## 📝 Usage Examples
+
+### Loading Configuration
+
+```python
+from src.core.core import load_config_with_main
+from pathlib import Path
+
+project_root = Path(__file__).parent.parent.parent
+config = load_config_with_main("solve_config.yaml", project_root)
+
+# Access configuration
+output_dir = config.get('paths', {}).get('user_data_dir')
+max_iterations = config.get('system', {}).get('max_analysis_iterations', 5)
+```
+
+### Getting LLM Config
+
+```python
+from src.core.core import get_llm_config
+
+llm_config = get_llm_config()
+api_key = llm_config["api_key"]
+base_url = llm_config["base_url"]
+model = llm_config["model"]
+```
+
+### Using Logger
+
+```python
+from src.core.logging import get_logger
+
+logger = get_logger("MyModule", level="DEBUG")
+logger.info("Information message")
+logger.error("Error message")
+```
+
+### Tracking LLM Usage
+
+```python
+from src.core.logging import LLMStats
+
+stats = LLMStats(module_name="MyModule")
+# After LLM call
+stats.add_call(
+ model="gpt-4o",
+ system_prompt="You are a helpful assistant.",
+ user_prompt="What is AI?",
+ response="AI is..."
+)
+# Print summary
+stats.print_summary()
+```
+
+### Initializing System
+
+```python
+from src.core.setup import init_user_directories
+from pathlib import Path
+
+project_root = Path(__file__).parent.parent.parent
+init_user_directories(project_root)
+```
+
+## 🔗 Related Modules
+
+- **Config Files**: `config/` - YAML configuration files
+- **API**: `src/api/` - Uses core for configuration
+- **Agents**: `src/agents/` - Use core for logging and config
+
+## 🛠️ Development
+
+### Adding New Configuration
+
+1. Add to environment variables if it's a secret or API key
+2. Add to `main.yaml` if it's a system-wide setting
+3. Add to module config if it's module-specific
+4. Update `core.py` if needed for loading
+
+### Adding New Logger
+
+```python
+from src.core.logging import get_logger
+
+logger = get_logger("NewModule", level="INFO", log_dir="./logs")
+```
+
+### Custom Log Handler
+
+Extend `handlers.py` to add custom handlers.
+
+## ⚠️ Notes
+
+1. **Configuration Priority**: Environment variables override YAML config
+2. **Path Resolution**: Always use `load_config_with_main()` for proper path resolution
+3. **Logging**: Use module-specific loggers for better organization
+4. **Statistics**: LLM stats are tracked per module
diff --git a/src/core/__init__.py b/src/core/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/src/core/core.py b/src/core/core.py
new file mode 100644
index 000000000..e5fe0984b
--- /dev/null
+++ b/src/core/core.py
@@ -0,0 +1,356 @@
+#!/usr/bin/env python
+"""
+Unified Configuration Management
+Combines environment variable configuration and YAML configuration loading.
+"""
+
+import os
+from pathlib import Path
+from typing import Any
+
+from dotenv import load_dotenv
+import yaml
+
+PROJECT_ROOT = Path(__file__).resolve().parent
+# Load OpenTutor.env first, then fallback to .env
+load_dotenv(PROJECT_ROOT / "OpenTutor.env", override=False)
+load_dotenv(PROJECT_ROOT / ".env", override=False)
+
+
+# ============================================================================
+# Environment Variable Configuration (from config.py)
+# ============================================================================
+
+
+def _to_int(value: str | None, default: int) -> int:
+ """Convert environment variable to int, fallback to default value on failure."""
+ try:
+ return int(value) if value is not None else default
+ except (TypeError, ValueError):
+ return default
+
+
+def _strip_value(value: str | None) -> str | None:
+ """Remove leading/trailing whitespace and quotes from string."""
+ if value is None:
+ return None
+ return value.strip().strip("\"'")
+
+
+def get_llm_config() -> dict:
+ """
+ Return complete environment configuration for LLM.
+
+ Returns:
+ dict: Dictionary containing the following keys:
+ - binding: LLM service provider
+ - model: LLM model name
+ - api_key: LLM API key
+ - base_url: LLM API endpoint URL
+
+ Raises:
+ ValueError: If required configuration is missing
+ """
+ binding = _strip_value(os.getenv("LLM_BINDING", "openai"))
+ model = _strip_value(os.getenv("LLM_MODEL"))
+ api_key = _strip_value(os.getenv("LLM_BINDING_API_KEY"))
+ base_url = _strip_value(os.getenv("LLM_BINDING_HOST"))
+
+ # Validate required configuration
+ if not model:
+ raise ValueError("Error: LLM_MODEL not set, please configure it in .env file")
+ if not api_key:
+ raise ValueError("Error: LLM_BINDING_API_KEY not set, please configure it in .env file")
+ if not base_url:
+ raise ValueError("Error: LLM_BINDING_HOST not set, please configure it in .env file")
+
+ return {
+ "binding": binding,
+ "model": model,
+ "api_key": api_key,
+ "base_url": base_url,
+ }
+
+
+def get_tts_config() -> dict:
+ """
+ Return complete environment configuration for TTS (Text-to-Speech).
+
+ Returns:
+ dict: Dictionary containing the following keys:
+ - model: TTS model name
+ - api_key: TTS API key
+ - base_url: TTS API endpoint URL
+ - voice: Default voice character
+
+ Raises:
+ ValueError: If required configuration is missing
+ """
+ model = _strip_value(os.getenv("TTS_MODEL"))
+ api_key = _strip_value(os.getenv("TTS_API_KEY"))
+ base_url = _strip_value(os.getenv("TTS_URL"))
+ voice = _strip_value(os.getenv("TTS_VOICE", "alloy"))
+
+ # Validate required configuration
+ if not model:
+ raise ValueError(
+ "Error: TTS_MODEL not set, please configure it in .env file (e.g., tts-1 or tts-1-hd)"
+ )
+ if not api_key:
+ raise ValueError("Error: TTS_API_KEY not set, please configure it in .env file")
+ if not base_url:
+ raise ValueError(
+ "Error: TTS_URL not set, please configure it in .env file (e.g., https://api.openai.com/v1)"
+ )
+
+ return {
+ "model": model,
+ "api_key": api_key,
+ "base_url": base_url,
+ "voice": voice,
+ }
+
+
+def get_agent_params(module_name: str) -> dict:
+ """
+ Get agent parameters (temperature, max_tokens) for a specific module.
+
+ This function loads parameters from config/agents.yaml which serves as the
+ SINGLE source of truth for all agent temperature and max_tokens settings.
+
+ Args:
+ module_name: Module name, one of:
+ - "guide": Guide module agents
+ - "solve": Solve module agents
+ - "research": Research module agents
+ - "question": Question module agents
+ - "ideagen": IdeaGen module agents
+ - "co_writer": CoWriter module agents
+ - "narrator": Narrator agent (independent, for TTS)
+
+ Returns:
+ dict: Dictionary containing:
+ - temperature: float, default 0.5
+ - max_tokens: int, default 4096
+
+ Example:
+ >>> params = get_agent_params("guide")
+ >>> params["temperature"] # 0.5
+ >>> params["max_tokens"] # 8192
+ """
+ # Default values
+ defaults = {
+ "temperature": 0.5,
+ "max_tokens": 4096,
+ }
+
+ # Try to load from agents.yaml
+ try:
+ config_path = PROJECT_ROOT.parent / "config" / "agents.yaml"
+ if not config_path.exists():
+ # Try alternative path (when PROJECT_ROOT is src/core)
+ config_path = PROJECT_ROOT.parent.parent / "config" / "agents.yaml"
+
+ 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
+
+
+def get_embedding_config() -> dict:
+ """
+ Return complete environment configuration for embedding models.
+
+ Returns:
+ dict: Dictionary containing the following keys:
+ - binding: Embedding service provider
+ - model: Embedding model name
+ - api_key: Embedding API key
+ - base_url: Embedding API endpoint URL
+ - dim: Embedding dimension
+ - max_tokens: Maximum tokens for embedding
+
+ Raises:
+ ValueError: If required configuration is missing
+ """
+ binding = _strip_value(os.getenv("EMBEDDING_BINDING", "openai"))
+ model = _strip_value(os.getenv("EMBEDDING_MODEL"))
+ api_key = _strip_value(os.getenv("EMBEDDING_BINDING_API_KEY"))
+ base_url = _strip_value(os.getenv("EMBEDDING_BINDING_HOST"))
+
+ # Strict mode: All model configuration must come from .env, no automatic fallback or default inference
+ if not model:
+ raise ValueError("Error: EMBEDDING_MODEL not set, please configure it in .env file")
+ if not api_key:
+ raise ValueError(
+ "Error: EMBEDDING_BINDING_API_KEY not set, please configure it in .env file"
+ )
+ if not base_url:
+ raise ValueError("Error: EMBEDDING_BINDING_HOST not set, please configure it in .env file")
+
+ # Get optional configuration
+ dim = _to_int(_strip_value(os.getenv("EMBEDDING_DIM")), 3072)
+ max_tokens = _to_int(_strip_value(os.getenv("EMBEDDING_MAX_TOKENS")), 8192)
+
+ return {
+ "binding": binding,
+ "model": model,
+ "api_key": api_key,
+ "base_url": base_url,
+ "dim": dim,
+ "max_tokens": max_tokens,
+ }
+
+
+# ============================================================================
+# YAML Configuration Loading (from config_loader.py)
+# ============================================================================
+
+
+def load_config_with_main(config_file: str, project_root: Path | None = None) -> dict[str, Any]:
+ """
+ Load configuration file, automatically merge with main.yaml common configuration
+
+ Args:
+ config_file: Sub-module configuration file name (e.g., "solve_config.yaml")
+ project_root: Project root directory (if None, will try to auto-detect)
+
+ Returns:
+ Merged configuration dictionary
+ """
+ if project_root is None:
+ # Try to infer project root from current file location
+ # From src/core/core.py -> project root
+ project_root = Path(__file__).parent.parent.parent
+
+ config_dir = project_root / "config"
+
+ # 1. Load main.yaml (common configuration)
+ main_config = {}
+ main_config_path = config_dir / "main.yaml"
+ if main_config_path.exists():
+ try:
+ with open(main_config_path, encoding="utf-8") as f:
+ main_config = yaml.safe_load(f) or {}
+ except Exception as e:
+ print(f"⚠️ Failed to load main.yaml: {e}")
+
+ # 2. Load sub-module configuration file
+ module_config = {}
+ module_config_path = config_dir / config_file
+ if module_config_path.exists():
+ try:
+ with open(module_config_path, encoding="utf-8") as f:
+ module_config = yaml.safe_load(f) or {}
+ 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 merged_config
+
+
+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
+
+ Args:
+ base: Base configuration
+ override: Override configuration
+
+ Returns:
+ Merged configuration
+ """
+ result = base.copy()
+
+ for key, value in override.items():
+ if key in result and isinstance(result[key], dict) and isinstance(value, dict):
+ # Recursively merge dictionaries
+ result[key] = _deep_merge(result[key], value)
+ else:
+ # Direct override
+ result[key] = value
+
+ return result
+
+
+def get_path_from_config(config: dict[str, Any], path_key: str, default: str = None) -> str:
+ """
+ Get path from configuration, supports searching in paths and system
+
+ Args:
+ config: Configuration dictionary
+ path_key: Path key name (e.g., "log_dir", "workspace")
+ default: Default value
+
+ Returns:
+ Path string
+ """
+ # Priority: search in paths
+ if "paths" in config and path_key in config["paths"]:
+ return config["paths"][path_key]
+
+ # Search in system (backward compatibility)
+ if "system" in config and path_key in config["system"]:
+ return config["system"][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)
+
+ return default
+
+
+def parse_language(language: Any) -> str:
+ """
+ Unified language configuration parser, supports multiple input formats
+
+ Supported language representations:
+ - English: "en", "english", "English"
+ - Chinese: "zh", "chinese", "Chinese"
+
+ Args:
+ language: Language configuration value (can be "zh"/"en"/"Chinese"/"English" etc.)
+
+ Returns:
+ Standardized language code: 'zh' or 'en', defaults to 'zh'
+ """
+ if not language:
+ return "zh"
+
+ if isinstance(language, str):
+ lang_lower = language.lower()
+ if lang_lower in ["en", "english"]:
+ return "en"
+ if lang_lower in ["zh", "chinese"]:
+ return "zh"
+
+ return "zh" # Default Chinese
+
+
+__all__ = [
+ # Environment variable configuration
+ "get_llm_config",
+ "get_embedding_config",
+ "get_tts_config",
+ # Agent parameters
+ "get_agent_params",
+ # YAML configuration loading
+ "load_config_with_main",
+ "get_path_from_config",
+ "_deep_merge",
+ # Language parsing
+ "parse_language",
+]
diff --git a/src/core/logging/__init__.py b/src/core/logging/__init__.py
new file mode 100644
index 000000000..1b07ec82d
--- /dev/null
+++ b/src/core/logging/__init__.py
@@ -0,0 +1,47 @@
+"""
+Unified Logging System for OpenTutor
+=====================================
+
+A clean, consistent logging system with:
+- Unified format: [Module] Symbol Message
+- English-only output
+- File output to ../user/logs/
+- WebSocket streaming support
+- Color-coded console output
+
+Usage:
+ from src.core.logging import get_logger
+
+ logger = get_logger("Solver")
+ logger.info("Processing started")
+ logger.success("Task completed in 2.3s")
+ logger.error("Something went wrong")
+"""
+
+from .handlers import (
+ LogInterceptor,
+ WebSocketLogHandler,
+)
+from .lightrag_forward import (
+ LightRAGLogContext,
+)
+from .llm_stats import (
+ LLMStats,
+)
+from .logger import (
+ Logger,
+ LogLevel,
+ get_logger,
+ reset_logger,
+)
+
+__all__ = [
+ "LLMStats",
+ "LightRAGLogContext",
+ "LogInterceptor",
+ "LogLevel",
+ "Logger",
+ "WebSocketLogHandler",
+ "get_logger",
+ "reset_logger",
+]
diff --git a/src/core/logging/handlers.py b/src/core/logging/handlers.py
new file mode 100644
index 000000000..1bd73d766
--- /dev/null
+++ b/src/core/logging/handlers.py
@@ -0,0 +1,218 @@
+"""
+Custom Log Handlers
+===================
+
+Handlers for streaming logs to WebSocket, file, etc.
+"""
+
+import asyncio
+from datetime import datetime
+import json
+import logging
+
+
+class WebSocketLogHandler(logging.Handler):
+ """
+ A logging handler that streams log records to a WebSocket via asyncio Queue.
+
+ Usage:
+ queue = asyncio.Queue()
+ handler = WebSocketLogHandler(queue)
+ logger.addHandler(handler)
+
+ # In WebSocket endpoint:
+ while True:
+ log_entry = await queue.get()
+ await websocket.send_json(log_entry)
+ """
+
+ # Symbols for different log types (matching ConsoleFormatter)
+ SYMBOLS = {
+ "DEBUG": "·",
+ "INFO": "○",
+ "SUCCESS": "✓",
+ "WARNING": "⚠",
+ "ERROR": "✗",
+ "CRITICAL": "✗",
+ }
+
+ def __init__(self, queue: asyncio.Queue, include_module: bool = True):
+ """
+ Initialize WebSocket log handler.
+
+ Args:
+ queue: asyncio.Queue to put log entries into
+ include_module: Whether to include module name in output
+ """
+ super().__init__()
+ self.queue = queue
+ self.include_module = include_module
+ self.setFormatter(logging.Formatter("%(message)s"))
+
+ def emit(self, record: logging.LogRecord):
+ """Emit a log record to the queue."""
+ try:
+ msg = self.format(record)
+
+ # Get symbol
+ display_level = getattr(record, "display_level", record.levelname)
+ symbol = getattr(record, "symbol", self.SYMBOLS.get(display_level, "○"))
+
+ # Get module name
+ module_name = getattr(record, "module_name", record.name)
+
+ # Build formatted content
+ if self.include_module:
+ content = f"[{module_name}] {symbol} {msg}"
+ else:
+ content = f"{symbol} {msg}"
+
+ # Construct structured message
+ log_entry = {
+ "type": "log",
+ "level": display_level,
+ "module": module_name,
+ "symbol": symbol,
+ "content": content,
+ "message": msg,
+ "timestamp": record.created,
+ }
+
+ # Put into queue non-blocking
+ try:
+ self.queue.put_nowait(log_entry)
+ except asyncio.QueueFull:
+ pass # Drop log if queue is full
+
+ except Exception:
+ self.handleError(record)
+
+
+class LogInterceptor:
+ """
+ Context manager to temporarily attach a WebSocketLogHandler to a logger.
+
+ Usage:
+ queue = asyncio.Queue()
+ logger = logging.getLogger("ai_tutor.Solver")
+
+ with LogInterceptor(logger, queue):
+ # All logs from this logger will be streamed to queue
+ solver.solve(problem)
+ """
+
+ def __init__(self, logger: logging.Logger, queue: asyncio.Queue, include_module: bool = True):
+ """
+ Initialize log interceptor.
+
+ Args:
+ logger: Logger to intercept
+ queue: Queue to stream logs to
+ include_module: Whether to include module name in output
+ """
+ self.logger = logger
+ self.handler = WebSocketLogHandler(queue, include_module)
+
+ def __enter__(self):
+ """Attach handler on context enter."""
+ self.logger.addHandler(self.handler)
+ return self.handler
+
+ def __exit__(self, exc_type, exc_val, exc_tb):
+ """Remove handler on context exit."""
+ self.logger.removeHandler(self.handler)
+
+
+class JSONFileHandler(logging.Handler):
+ """
+ A logging handler that writes structured JSON logs to a file.
+ Each line is a valid JSON object (JSONL format).
+
+ Useful for:
+ - LLM call logging
+ - Structured analysis
+ - Log parsing and analysis
+ """
+
+ def __init__(self, filepath: str, encoding: str = "utf-8"):
+ """
+ Initialize JSON file handler.
+
+ Args:
+ filepath: Path to log file
+ encoding: File encoding
+ """
+ super().__init__()
+ self.filepath = filepath
+ self.encoding = encoding
+ self.setFormatter(logging.Formatter("%(message)s"))
+
+ def emit(self, record: logging.LogRecord):
+ """Emit a log record as JSON."""
+ try:
+ # Build JSON entry
+ entry = {
+ "timestamp": datetime.fromtimestamp(record.created).isoformat(),
+ "level": record.levelname,
+ "module": getattr(record, "module_name", record.name),
+ "message": self.format(record),
+ }
+
+ # Add extra fields if present
+ for key in ["symbol", "display_level", "tool_name", "elapsed_ms", "tokens"]:
+ if hasattr(record, key):
+ entry[key] = getattr(record, key)
+
+ # Write to file
+ with open(self.filepath, "a", encoding=self.encoding) as f:
+ f.write(json.dumps(entry, ensure_ascii=False) + "\n")
+
+ except Exception:
+ self.handleError(record)
+
+
+def create_task_logger(
+ task_id: str, module_name: str, log_dir: str, queue: asyncio.Queue | None = None
+) -> logging.Logger:
+ """
+ Create a logger for a specific task with file and optional WebSocket output.
+
+ Args:
+ task_id: Unique task identifier
+ module_name: Module name (e.g., "Solver", "Research")
+ log_dir: Directory for log files
+ queue: Optional asyncio.Queue for WebSocket streaming
+
+ Returns:
+ Configured logger
+ """
+ from pathlib import Path
+
+ # Create log directory
+ log_path = Path(log_dir)
+ log_path.mkdir(parents=True, exist_ok=True)
+
+ # Create logger
+ logger = logging.getLogger(f"ai_tutor.{module_name}.{task_id}")
+ logger.setLevel(logging.DEBUG)
+ logger.handlers.clear()
+ logger.propagate = False
+
+ # File handler
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
+ log_file = log_path / f"{module_name}_{task_id}_{timestamp}.log"
+
+ file_handler = logging.FileHandler(log_file, encoding="utf-8")
+ file_handler.setLevel(logging.DEBUG)
+ file_handler.setFormatter(
+ logging.Formatter("%(asctime)s [%(levelname)-8s] %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
+ )
+ logger.addHandler(file_handler)
+
+ # WebSocket handler if queue provided
+ if queue is not None:
+ ws_handler = WebSocketLogHandler(queue)
+ ws_handler.setLevel(logging.INFO)
+ logger.addHandler(ws_handler)
+
+ return logger
diff --git a/src/core/logging/lightrag_forward.py b/src/core/logging/lightrag_forward.py
new file mode 100644
index 000000000..7bf452e1b
--- /dev/null
+++ b/src/core/logging/lightrag_forward.py
@@ -0,0 +1,182 @@
+#!/usr/bin/env python
+"""
+LightRAG Log Forwarder
+
+Forwards LightRAG and RAG-Anything logs to OpenTutor's unified logging system.
+"""
+
+from contextlib import contextmanager
+import logging
+from pathlib import Path
+
+from src.core.core import load_config_with_main
+
+from .logger import get_logger
+
+
+class LightRAGLogForwarder(logging.Handler):
+ """
+ Handler that forwards LightRAG logger messages to OpenTutor logger.
+ """
+
+ def __init__(self, ai_tutor_logger, add_prefix: bool = True):
+ """
+ Args:
+ ai_tutor_logger: OpenTutor Logger instance
+ add_prefix: Whether to add [LightRAG] prefix to messages
+ """
+ super().__init__()
+ self.ai_tutor_logger = ai_tutor_logger
+ self.add_prefix = add_prefix
+ # Capture all log levels
+ self.setLevel(logging.DEBUG)
+
+ def emit(self, record: logging.LogRecord):
+ """
+ Forward log record to OpenTutor logger.
+ All logs are forwarded as info level to maintain consistent format.
+ """
+ try:
+ # Get the original message directly without adding [LightRAG] prefix
+ # LightRAG already formats messages appropriately (e.g., "DEBUG: xxx" for debug logs)
+ message = record.getMessage()
+
+ # Use info() for all levels to maintain consistent format
+ # This ensures all logs appear as [RAGTool] ... (or [RAGTool] DEBUG: ... for debug)
+ self.ai_tutor_logger.info(message)
+
+ except Exception:
+ # Avoid errors in forwarding from affecting main flow
+ self.handleError(record)
+
+
+def get_lightrag_forwarding_config():
+ """
+ Load LightRAG forwarding configuration from main.yaml.
+
+ Returns:
+ dict: Configuration dictionary with defaults if not found
+ """
+ try:
+ # Use resolve() to get absolute path, ensuring correct project root regardless of working directory
+ project_root = Path(__file__).resolve().parent.parent.parent.parent
+ config = load_config_with_main("solve_config.yaml", project_root)
+
+ forwarding_config = config.get("logging", {}).get("lightrag_forwarding", {})
+
+ return {
+ "enabled": forwarding_config.get("enabled", True),
+ "min_level": forwarding_config.get("min_level", "INFO"),
+ "add_prefix": forwarding_config.get("add_prefix", True),
+ "logger_names": forwarding_config.get(
+ "logger_names", {"knowledge_init": "KnowledgeInit", "rag_tool": "RAGTool"}
+ ),
+ }
+ except Exception:
+ # Return defaults if config loading fails
+ return {
+ "enabled": True,
+ "min_level": "INFO",
+ "add_prefix": True,
+ "logger_names": {"knowledge_init": "KnowledgeInit", "rag_tool": "RAGTool"},
+ }
+
+
+@contextmanager
+def LightRAGLogContext(logger_name: str | None = None, scene: str | None = None):
+ """
+ Context manager for LightRAG log forwarding.
+
+ Automatically sets up and tears down log forwarding.
+
+ Args:
+ logger_name: Explicit logger name (overrides scene-based lookup)
+ scene: Scene name ('knowledge_init' or 'rag_tool') for logger name lookup
+
+ Usage:
+ with LightRAGLogContext("RAGTool"):
+ # RAG operations
+ rag = RAGAnything(...)
+ """
+ # Get configuration
+ config = get_lightrag_forwarding_config()
+
+ # Check if forwarding is enabled
+ if not config.get("enabled", True):
+ # If disabled, just pass through without forwarding
+ yield
+ return
+
+ # Debug: Log that forwarding is being set up (only if we have a logger)
+ # This helps verify the context manager is being called
+ try:
+ debug_logger = get_logger("RAGForward")
+ debug_logger.debug(
+ f"Setting up LightRAG log forwarding (scene={scene}, logger_name={logger_name})"
+ )
+ except:
+ pass # Ignore if logger setup fails
+
+ # Determine logger name
+ if logger_name is None:
+ if scene:
+ logger_names = config.get("logger_names", {})
+ logger_name = logger_names.get(scene, "Main")
+ else:
+ logger_name = "Main"
+
+ # Get OpenTutor logger
+ ai_tutor_logger = get_logger(logger_name)
+
+ # Get forwarding settings
+ add_prefix = config.get("add_prefix", True)
+ min_level_str = config.get("min_level", "INFO")
+ min_level = getattr(logging, min_level_str.upper(), logging.INFO)
+
+ # Get LightRAG logger
+ lightrag_logger = logging.getLogger("lightrag")
+
+ # Store original handlers and level to restore later if needed
+ original_handlers = lightrag_logger.handlers[:] # Copy list
+ original_level = lightrag_logger.level
+
+ # Temporarily remove existing console handlers to avoid duplicate output
+ # We'll forward all logs through our handler instead
+ console_handlers_to_remove = []
+ for handler in original_handlers:
+ if isinstance(handler, logging.StreamHandler):
+ console_handlers_to_remove.append(handler)
+
+ for handler in console_handlers_to_remove:
+ lightrag_logger.removeHandler(handler)
+
+ # Ensure LightRAG logger level is set low enough to capture all logs
+ # The logger level controls which logs are created, handler level controls which are processed
+ # Set to DEBUG to ensure we capture everything, then filter at handler level
+ if lightrag_logger.level > logging.DEBUG:
+ lightrag_logger.setLevel(logging.DEBUG)
+
+ # Create and add forwarder
+ forwarder = LightRAGLogForwarder(ai_tutor_logger, add_prefix=add_prefix)
+ forwarder.setLevel(min_level)
+ lightrag_logger.addHandler(forwarder)
+
+ # Test that forwarding works by sending a test log
+ try:
+ test_msg = "LightRAG log forwarding enabled"
+ lightrag_logger.info(test_msg)
+ except:
+ pass # Ignore test log errors
+
+ try:
+ yield
+ finally:
+ # Clean up: remove our forwarder
+ if forwarder in lightrag_logger.handlers:
+ lightrag_logger.removeHandler(forwarder)
+ forwarder.close()
+
+ # Restore original console handlers if they were removed
+ for handler in console_handlers_to_remove:
+ if handler not in lightrag_logger.handlers:
+ lightrag_logger.addHandler(handler)
diff --git a/src/core/logging/llm_stats.py b/src/core/logging/llm_stats.py
new file mode 100644
index 000000000..e8d9bf710
--- /dev/null
+++ b/src/core/logging/llm_stats.py
@@ -0,0 +1,176 @@
+"""
+LLM Stats Tracker
+=================
+
+Simple utility for tracking LLM token usage and costs across all modules.
+Outputs summary to terminal at the end of processing.
+
+Usage:
+ from logs.llm_stats import LLMStats
+
+ stats = LLMStats()
+
+ # After each LLM call:
+ stats.add_call(
+ model="gpt-4o-mini",
+ prompt_tokens=100,
+ completion_tokens=50
+ )
+
+ # At the end:
+ stats.print_summary()
+"""
+
+from dataclasses import dataclass, field
+from datetime import datetime
+from typing import Any
+
+# Model pricing per 1K tokens (USD)
+MODEL_PRICING = {
+ "gpt-4o": {"input": 0.0025, "output": 0.010},
+ "gpt-4o-mini": {"input": 0.00015, "output": 0.0006},
+ "gpt-4-turbo": {"input": 0.01, "output": 0.03},
+ "gpt-4": {"input": 0.03, "output": 0.06},
+ "gpt-3.5-turbo": {"input": 0.0005, "output": 0.0015},
+ "deepseek-chat": {"input": 0.00014, "output": 0.00028},
+ "claude-3-5-sonnet": {"input": 0.003, "output": 0.015},
+}
+
+
+def get_pricing(model: str) -> dict[str, float]:
+ """Get pricing for a model (fuzzy match)."""
+ model_lower = model.lower()
+ for key, pricing in MODEL_PRICING.items():
+ if key in model_lower or model_lower in key:
+ return pricing
+ return MODEL_PRICING.get("gpt-4o-mini", {"input": 0.00015, "output": 0.0006})
+
+
+def estimate_tokens(text: str) -> int:
+ """Rough estimate of tokens (1.3 tokens per word)."""
+ return int(len(text.split()) * 1.3)
+
+
+@dataclass
+class LLMCall:
+ """Single LLM call record."""
+
+ model: str
+ prompt_tokens: int
+ completion_tokens: int
+ cost: float
+ timestamp: str = field(default_factory=lambda: datetime.now().isoformat())
+
+
+class LLMStats:
+ """
+ LLM usage statistics tracker.
+ Tracks token usage and costs, outputs summary to terminal.
+ """
+
+ def __init__(self, module_name: str = "Module"):
+ """
+ Initialize stats tracker.
+
+ Args:
+ module_name: Name of the module (for display)
+ """
+ self.module_name = module_name
+ self.calls: list[LLMCall] = []
+ self.total_prompt_tokens = 0
+ self.total_completion_tokens = 0
+ self.total_cost = 0.0
+ self.model_used = None
+
+ def add_call(
+ self,
+ model: str,
+ prompt_tokens: int | None = None,
+ completion_tokens: int | None = None,
+ # Alternative: estimate from text
+ system_prompt: str | None = None,
+ user_prompt: str | None = None,
+ response: str | None = None,
+ ):
+ """
+ Add an LLM call to the stats.
+
+ Args:
+ model: Model name
+ prompt_tokens: Number of prompt tokens (if known)
+ completion_tokens: Number of completion tokens (if known)
+ system_prompt: System prompt text (for estimation)
+ user_prompt: User prompt text (for estimation)
+ response: Response text (for estimation)
+ """
+ # Estimate tokens if not provided
+ if prompt_tokens is None and (system_prompt or user_prompt):
+ prompt_text = (system_prompt or "") + "\n" + (user_prompt or "")
+ prompt_tokens = estimate_tokens(prompt_text)
+
+ if completion_tokens is None and response:
+ completion_tokens = estimate_tokens(response)
+
+ prompt_tokens = prompt_tokens or 0
+ completion_tokens = completion_tokens or 0
+
+ # Calculate cost
+ pricing = get_pricing(model)
+ cost = (prompt_tokens / 1000.0) * pricing["input"] + (completion_tokens / 1000.0) * pricing[
+ "output"
+ ]
+
+ # Record call
+ call = LLMCall(
+ model=model, prompt_tokens=prompt_tokens, completion_tokens=completion_tokens, cost=cost
+ )
+ self.calls.append(call)
+
+ # Update totals
+ self.total_prompt_tokens += prompt_tokens
+ self.total_completion_tokens += completion_tokens
+ self.total_cost += cost
+
+ # Track primary model
+ if self.model_used is None:
+ self.model_used = model
+
+ def get_summary(self) -> dict[str, Any]:
+ """Get summary as dictionary."""
+ return {
+ "module": self.module_name,
+ "model": self.model_used or "Unknown",
+ "calls": len(self.calls),
+ "prompt_tokens": self.total_prompt_tokens,
+ "completion_tokens": self.total_completion_tokens,
+ "total_tokens": self.total_prompt_tokens + self.total_completion_tokens,
+ "cost_usd": self.total_cost,
+ }
+
+ def print_summary(self):
+ """Print summary to terminal."""
+ if len(self.calls) == 0:
+ return
+
+ total_tokens = self.total_prompt_tokens + self.total_completion_tokens
+
+ print()
+ print("=" * 60)
+ print(f"📊 [{self.module_name}] LLM Usage Summary")
+ print("=" * 60)
+ print(f" Model : {self.model_used or 'Unknown'}")
+ print(f" API Calls : {len(self.calls)}")
+ print(
+ f" Tokens : {total_tokens:,} (Input: {self.total_prompt_tokens:,}, Output: {self.total_completion_tokens:,})"
+ )
+ print(f" Cost : ${self.total_cost:.6f} USD")
+ print("=" * 60)
+ print()
+
+ def reset(self):
+ """Reset all statistics."""
+ self.calls.clear()
+ self.total_prompt_tokens = 0
+ self.total_completion_tokens = 0
+ self.total_cost = 0.0
+ self.model_used = None
diff --git a/src/core/logging/log_forwarder.py b/src/core/logging/log_forwarder.py
new file mode 100644
index 000000000..5b4835f9f
--- /dev/null
+++ b/src/core/logging/log_forwarder.py
@@ -0,0 +1,133 @@
+"""
+Log Forwarder - Forward logs from question generation and problem solving to unified system log file
+"""
+
+from datetime import datetime
+import logging
+from logging.handlers import RotatingFileHandler
+from pathlib import Path
+
+
+class SystemLogForwarder(logging.Handler):
+ """
+ Forward logs to unified system log file
+ Used for question generation and problem solving modules, keeping their own logging systems while also writing to unified log
+ """
+
+ _system_logger: logging.Logger | None = None
+ _initialized = False
+
+ @classmethod
+ def get_system_logger(cls) -> logging.Logger:
+ """Get unified system logger"""
+ if cls._system_logger is None:
+ # Get log directory from config (same logic as logger.py)
+ try:
+ from src.core.core import get_path_from_config, load_config_with_main
+
+ # Use resolve() to get absolute path, ensuring correct project root regardless of working directory
+ project_root = Path(__file__).resolve().parent.parent.parent.parent
+ config = load_config_with_main("solve_config.yaml", project_root)
+ log_dir = get_path_from_config(config, "user_log_dir") or config.get(
+ "paths", {}
+ ).get("user_log_dir")
+ if log_dir:
+ # Convert relative path to absolute based on project root
+ log_dir_path = Path(log_dir)
+ if not log_dir_path.is_absolute():
+ # Remove leading ./ if present
+ log_dir_str = str(log_dir_path).lstrip("./")
+ log_dir = project_root / log_dir_str
+ else:
+ log_dir = log_dir_path
+ else:
+ # Fallback to default: data/user/logs
+ log_dir = project_root / "data" / "user" / "logs"
+ except Exception:
+ # Fallback to default: data/user/logs
+ # Use resolve() to get absolute path
+ project_root = Path(__file__).resolve().parent.parent.parent.parent
+ log_dir = project_root / "data" / "user" / "logs"
+
+ # Ensure log directory exists
+ log_dir.mkdir(parents=True, exist_ok=True)
+
+ today = datetime.now().strftime("%Y%m%d")
+ log_file = log_dir / f"ai_tutor_system_{today}.log"
+
+ # Create system logger
+ cls._system_logger = logging.getLogger("ai_tutor.system")
+ cls._system_logger.setLevel(logging.DEBUG)
+
+ # Only add file handler, don't add console handler (avoid duplicate output)
+ if not cls._system_logger.handlers:
+ file_handler = RotatingFileHandler(
+ log_file,
+ maxBytes=10 * 1024 * 1024,
+ backupCount=5,
+ encoding="utf-8", # 10MB
+ )
+ file_handler.setLevel(logging.DEBUG)
+
+ # Custom formatter supporting module_name field
+ class SystemLogFormatter(logging.Formatter):
+ def format(self, record):
+ # If no module_name, use default value
+ if not hasattr(record, "module_name"):
+ record.module_name = "system"
+ return super().format(record)
+
+ file_format = SystemLogFormatter(
+ "%(asctime)s | [%(module_name)s] | %(levelname)-8s | %(message)s",
+ datefmt="%Y-%m-%d %H:%M:%S",
+ )
+ file_handler.setFormatter(file_format)
+ cls._system_logger.addHandler(file_handler)
+
+ cls._initialized = True
+
+ return cls._system_logger
+
+ def __init__(self, module_name: str):
+ """
+ Initialize log forwarder
+
+ Args:
+ module_name: Module name (e.g., 'question', 'solve')
+ """
+ super().__init__()
+ self.module_name = module_name
+ self.setLevel(logging.DEBUG)
+
+ def emit(self, record: logging.LogRecord):
+ """Forward log to unified system log file"""
+ try:
+ # Get system logger
+ system_logger = self.get_system_logger()
+
+ # Add module name to record
+ record.module_name = self.module_name
+
+ # Forward log (using same level)
+ system_logger.handle(record)
+ except Exception:
+ # Forward failure should not affect original log
+ self.handleError(record)
+
+
+def attach_system_log_forwarder(logger: logging.Logger, module_name: str):
+ """
+ Attach system log forwarder to specified logger
+
+ Args:
+ logger: Logger to attach forwarder to
+ module_name: Module name (e.g., 'question', 'solve')
+ """
+ # Check if already attached
+ for handler in logger.handlers:
+ if isinstance(handler, SystemLogForwarder) and handler.module_name == module_name:
+ return # Already attached
+
+ # Add forwarder
+ forwarder = SystemLogForwarder(module_name)
+ logger.addHandler(forwarder)
diff --git a/src/core/logging/logger.py b/src/core/logging/logger.py
new file mode 100644
index 000000000..24232957c
--- /dev/null
+++ b/src/core/logging/logger.py
@@ -0,0 +1,711 @@
+"""
+Core Logger Implementation
+==========================
+
+Unified logging with consistent format across all modules.
+Format: [Module] Symbol Message
+
+Example outputs:
+ [Solver] ✓ Ready in 2.3s
+ [Research] → Starting deep research...
+ [Guide] ○ Compiling knowledge points
+ [Knowledge] ✓ Indexed 150 documents
+"""
+
+from datetime import datetime
+from enum import Enum
+import json
+import logging
+from pathlib import Path
+import sys
+from typing import Any
+
+
+class LogLevel(Enum):
+ """Log levels with associated symbols"""
+
+ DEBUG = ("DEBUG", "·") # Dot for debug
+ INFO = ("INFO", "○") # Circle for info
+ SUCCESS = ("SUCCESS", "✓") # Checkmark for success
+ WARNING = ("WARNING", "⚠") # Warning sign
+ ERROR = ("ERROR", "✗") # X for error
+ CRITICAL = ("CRITICAL", "✗") # X for critical
+ PROGRESS = ("INFO", "→") # Arrow for progress
+ COMPLETE = ("INFO", "✓") # Checkmark for completion
+
+
+class ConsoleFormatter(logging.Formatter):
+ """
+ Clean console formatter with colors and symbols.
+ Format: [Module] Symbol Message
+ """
+
+ # ANSI color codes
+ COLORS = {
+ "DEBUG": "\033[90m", # Gray
+ "INFO": "\033[37m", # White
+ "SUCCESS": "\033[32m", # Green
+ "WARNING": "\033[33m", # Yellow
+ "ERROR": "\033[31m", # Red
+ "CRITICAL": "\033[35m", # Magenta
+ }
+ RESET = "\033[0m"
+ BOLD = "\033[1m"
+ DIM = "\033[2m"
+
+ # Symbols for different log types
+ SYMBOLS = {
+ "DEBUG": "·",
+ "INFO": "○",
+ "SUCCESS": "✓",
+ "WARNING": "⚠",
+ "ERROR": "✗",
+ "CRITICAL": "✗",
+ }
+
+ def format(self, record: logging.LogRecord) -> str:
+ # Get module name (padded to 12 chars for alignment)
+ module = getattr(record, "module_name", record.name)
+ module_padded = f"[{module}]".ljust(14)
+
+ # Get symbol (can be overridden via record.symbol)
+ symbol = getattr(record, "symbol", self.SYMBOLS.get(record.levelname, "○"))
+
+ # Get color
+ level = getattr(record, "display_level", record.levelname)
+ color = self.COLORS.get(level, self.COLORS["INFO"])
+
+ # Format message
+ message = record.getMessage()
+
+ # Build output: [Module] ✓ Message
+ return f"{self.DIM}{module_padded}{self.RESET} {color}{symbol}{self.RESET} {message}"
+
+
+class FileFormatter(logging.Formatter):
+ """
+ Detailed file formatter for log files.
+ Format: TIMESTAMP [LEVEL] [Module] Message
+ """
+
+ def __init__(self):
+ super().__init__(
+ fmt="%(asctime)s [%(levelname)-8s] [%(module_name)-12s] %(message)s",
+ datefmt="%Y-%m-%d %H:%M:%S",
+ )
+
+ def format(self, record: logging.LogRecord) -> str:
+ # Ensure module_name exists
+ if not hasattr(record, "module_name"):
+ record.module_name = record.name
+ return super().format(record)
+
+
+class Logger:
+ """
+ Unified logger for OpenTutor.
+
+ Features:
+ - Consistent format across all modules
+ - Color-coded console output
+ - File logging to user/logs/
+ - WebSocket streaming support
+ - Success/progress/complete convenience methods
+
+ Usage:
+ logger = Logger("Solver")
+ logger.info("Processing...")
+ logger.success("Done!", elapsed=2.3)
+ logger.progress("Step 1/5")
+ """
+
+ def __init__(
+ self,
+ name: str,
+ level: str = "INFO",
+ console_output: bool = True,
+ file_output: bool = True,
+ log_dir: str | None = None,
+ ):
+ """
+ Initialize logger.
+
+ Args:
+ name: Module name (e.g., "Solver", "Research", "Guide")
+ level: Log level (DEBUG, INFO, WARNING, ERROR, CRITICAL)
+ console_output: Whether to output to console
+ file_output: Whether to output to file
+ log_dir: Log directory (default: ../user/logs/)
+ """
+ self.name = name
+ self.level = getattr(logging, level.upper(), logging.INFO)
+
+ # Create underlying Python logger
+ self.logger = logging.getLogger(f"ai_tutor.{name}")
+ self.logger.setLevel(logging.DEBUG) # Capture all, filter at handlers
+ self.logger.handlers.clear()
+ self.logger.propagate = False
+
+ # Setup log directory
+ if log_dir is None:
+ # Default: OpenTutor/data/user/logs/
+ # Use resolve() to get absolute path, ensuring correct project root regardless of working directory
+ project_root = Path(__file__).resolve().parent.parent.parent.parent
+ log_dir = project_root / "data" / "user" / "logs"
+ else:
+ log_dir = Path(log_dir)
+ # If relative path, resolve it relative to project root
+ if not log_dir.is_absolute():
+ project_root = Path(__file__).resolve().parent.parent.parent.parent
+ log_dir = project_root / log_dir
+
+ log_dir.mkdir(parents=True, exist_ok=True)
+ self.log_dir = log_dir
+
+ # Console handler
+ if console_output:
+ console_handler = logging.StreamHandler(sys.stdout)
+ console_handler.setLevel(self.level)
+ console_handler.setFormatter(ConsoleFormatter())
+ self.logger.addHandler(console_handler)
+
+ # File handler
+ if file_output:
+ timestamp = datetime.now().strftime("%Y%m%d")
+ log_file = log_dir / f"ai_tutor_{timestamp}.log"
+
+ file_handler = logging.FileHandler(log_file, encoding="utf-8")
+ file_handler.setLevel(logging.DEBUG) # Log everything to file
+ file_handler.setFormatter(FileFormatter())
+ self.logger.addHandler(file_handler)
+
+ self._log_file = log_file
+
+ # For backwards compatibility with task-specific logging
+ self._task_handlers = []
+
+ # Display manager for TUI (optional, used by solve_agents)
+ self.display_manager = None
+
+ def add_task_log_handler(
+ self, task_log_file: str, capture_stdout: bool = False, capture_stderr: bool = False
+ ):
+ """
+ Add a task-specific log file handler.
+ For backwards compatibility with old SolveAgentLogger.
+
+ Args:
+ task_log_file: Path to the task log file
+ capture_stdout: Ignored (kept for API compatibility)
+ capture_stderr: Ignored (kept for API compatibility)
+ """
+ from pathlib import Path
+
+ task_path = Path(task_log_file)
+ task_path.parent.mkdir(parents=True, exist_ok=True)
+
+ handler = logging.FileHandler(task_log_file, encoding="utf-8")
+ handler.setLevel(logging.DEBUG)
+ handler.setFormatter(FileFormatter())
+ self.logger.addHandler(handler)
+ self._task_handlers.append(handler)
+
+ def remove_task_log_handlers(self):
+ """Remove all task-specific log handlers."""
+ for handler in self._task_handlers:
+ self.logger.removeHandler(handler)
+ handler.close()
+ self._task_handlers.clear()
+
+ def log_stage_progress(self, stage: str, status: str, detail: str | None = None):
+ """Backwards compatibility alias for stage()"""
+ self.stage(stage, status, detail)
+
+ def section(self, title: str, char: str = "=", length: int = 60):
+ """Print a section header"""
+ self.info(char * length)
+ self.info(title)
+ self.info(char * length)
+
+ def _log(
+ self,
+ level: int,
+ message: str,
+ symbol: str | None = None,
+ display_level: str | None = None,
+ **kwargs,
+ ):
+ """Internal logging method with extra attributes."""
+ extra = {
+ "module_name": self.name,
+ "symbol": symbol,
+ "display_level": display_level or logging.getLevelName(level),
+ }
+ # Extract standard logging parameters from kwargs
+ log_kwargs = {
+ "extra": extra,
+ "exc_info": kwargs.get("exc_info", False),
+ "stack_info": kwargs.get("stack_info", False),
+ "stacklevel": kwargs.get("stacklevel", 1),
+ }
+ self.logger.log(level, message, **log_kwargs)
+
+ # Standard logging methods
+ def debug(self, message: str, **kwargs):
+ """Debug level log (·)"""
+ self._log(logging.DEBUG, message, symbol="·", **kwargs)
+
+ def info(self, message: str, **kwargs):
+ """Info level log (○)"""
+ self._log(logging.INFO, message, symbol="○", **kwargs)
+
+ def warning(self, message: str, **kwargs):
+ """Warning level log (⚠)"""
+ self._log(logging.WARNING, message, symbol="⚠", **kwargs)
+
+ def error(self, message: str, **kwargs):
+ """Error level log (✗)"""
+ self._log(logging.ERROR, message, symbol="✗", **kwargs)
+
+ def critical(self, message: str, **kwargs):
+ """Critical level log (✗)"""
+ self._log(logging.CRITICAL, message, symbol="✗", **kwargs)
+
+ def exception(self, message: str, **kwargs):
+ """Log exception with traceback"""
+ self.logger.exception(
+ message, extra={"module_name": self.name, "symbol": "✗", "display_level": "ERROR"}
+ )
+
+ # Convenience methods
+ def success(self, message: str, elapsed: float | None = None, **kwargs):
+ """Success log with checkmark (✓)"""
+ if elapsed is not None:
+ message = f"{message} in {elapsed:.1f}s"
+ self._log(logging.INFO, message, symbol="✓", display_level="SUCCESS", **kwargs)
+
+ def progress(self, message: str, **kwargs):
+ """Progress log with arrow (→)"""
+ self._log(logging.INFO, message, symbol="→", **kwargs)
+
+ def complete(self, message: str, **kwargs):
+ """Completion log with checkmark (✓)"""
+ self._log(logging.INFO, message, symbol="✓", display_level="SUCCESS", **kwargs)
+
+ def stage(self, stage_name: str, status: str = "start", detail: str | None = None):
+ """
+ Log stage progress.
+
+ Args:
+ stage_name: Name of the stage (e.g., "Analysis", "Synthesis")
+ status: One of "start", "running", "complete", "skip", "error"
+ detail: Optional detail message
+ """
+ symbols = {
+ "start": "▶",
+ "running": "○",
+ "complete": "✓",
+ "skip": "↷",
+ "error": "✗",
+ "warning": "⚠",
+ }
+ symbol = symbols.get(status, "○")
+
+ message = f"{stage_name}"
+ if status == "complete":
+ message += " completed"
+ elif status == "start":
+ message += " started"
+ elif status == "running":
+ message += " running"
+ elif status == "skip":
+ message += " skipped"
+ elif status == "error":
+ message += " failed"
+
+ if detail:
+ message += f" | {detail}"
+
+ level = logging.ERROR if status == "error" else logging.INFO
+ display_level = (
+ "ERROR" if status == "error" else ("SUCCESS" if status == "complete" else "INFO")
+ )
+ self._log(level, message, symbol=symbol, display_level=display_level)
+
+ def tool_call(
+ self, tool_name: str, status: str = "success", elapsed_ms: float | None = None, **kwargs
+ ):
+ """
+ Log tool call.
+
+ Args:
+ tool_name: Name of the tool
+ status: "success", "error", or "running"
+ elapsed_ms: Execution time in milliseconds
+ """
+ symbol = "✓" if status == "success" else ("✗" if status == "error" else "→")
+ display_level = (
+ "SUCCESS" if status == "success" else ("ERROR" if status == "error" else "INFO")
+ )
+
+ message = f"Tool: {tool_name}"
+ if elapsed_ms is not None:
+ message += f" ({elapsed_ms:.0f}ms)"
+ if status == "error":
+ message += " [FAILED]"
+
+ self._log(
+ logging.INFO if status != "error" else logging.ERROR,
+ message,
+ symbol=symbol,
+ display_level=display_level,
+ )
+
+ def llm_call(
+ self,
+ model: str,
+ agent: str | None = None,
+ tokens_in: int | None = None,
+ tokens_out: int | None = None,
+ elapsed: float | None = None,
+ **kwargs,
+ ):
+ """
+ Log LLM API call.
+
+ Args:
+ model: Model name
+ agent: Agent making the call
+ tokens_in: Input tokens
+ tokens_out: Output tokens
+ elapsed: Call duration in seconds
+ """
+ parts = [f"LLM: {model}"]
+ if agent:
+ parts.append(f"agent={agent}")
+ if tokens_in is not None:
+ parts.append(f"in={tokens_in}")
+ if tokens_out is not None:
+ parts.append(f"out={tokens_out}")
+ if elapsed is not None:
+ parts.append(f"{elapsed:.2f}s")
+
+ message = " | ".join(parts)
+ self._log(logging.DEBUG, message, symbol="◇")
+
+ def separator(self, char: str = "─", length: int = 50):
+ """Print a separator line"""
+ self.info(char * length)
+
+ def log_tool_call(
+ self,
+ tool_name: str,
+ tool_input: Any = None,
+ tool_output: Any = None,
+ status: str = "success",
+ elapsed_ms: float | None = None,
+ **kwargs,
+ ):
+ """
+ Log a tool call with input/output details.
+ Backwards compatible with old SolveAgentLogger.
+
+ Args:
+ tool_name: Name of the tool
+ tool_input: Tool input (logged to file only)
+ tool_output: Tool output (logged to file only)
+ status: "success", "error", or "running"
+ elapsed_ms: Execution time in milliseconds
+ """
+ symbol = "✓" if status == "success" else ("✗" if status == "error" else "→")
+ display_level = (
+ "SUCCESS" if status == "success" else ("ERROR" if status == "error" else "INFO")
+ )
+
+ # Console message (brief)
+ message = f"Tool: {tool_name}"
+ if elapsed_ms is not None:
+ message += f" ({elapsed_ms:.0f}ms)"
+ if status == "error":
+ message += " [FAILED]"
+
+ self._log(
+ logging.INFO if status != "error" else logging.ERROR,
+ message,
+ symbol=symbol,
+ display_level=display_level,
+ )
+
+ # Debug log with full details (file only)
+ if tool_input is not None:
+ try:
+ input_str = (
+ json.dumps(tool_input, ensure_ascii=False, indent=2)
+ if isinstance(tool_input, (dict, list))
+ else str(tool_input)
+ )
+ self.debug(f"Tool Input: {input_str[:500]}...")
+ except:
+ pass
+ if tool_output is not None:
+ try:
+ output_str = (
+ json.dumps(tool_output, ensure_ascii=False, indent=2)
+ if isinstance(tool_output, (dict, list))
+ else str(tool_output)
+ )
+ self.debug(f"Tool Output: {output_str[:500]}...")
+ except:
+ pass
+
+ def log_llm_input(
+ self,
+ agent_name: str,
+ stage: str,
+ system_prompt: str,
+ user_prompt: str,
+ metadata: dict[str, Any] | None = None,
+ ):
+ """Log LLM input (debug level, file only)"""
+ self.debug(
+ f"LLM Input [{agent_name}:{stage}] system={len(system_prompt)}chars, user={len(user_prompt)}chars"
+ )
+
+ def log_llm_output(
+ self, agent_name: str, stage: str, response: str, metadata: dict[str, Any] | None = None
+ ):
+ """Log LLM output (debug level, file only)"""
+ self.debug(f"LLM Output [{agent_name}:{stage}] response={len(response)}chars")
+
+ def log_llm_call(
+ self,
+ model: str,
+ stage: str,
+ system_prompt: str,
+ user_prompt: str,
+ response: str,
+ agent_name: str | None = None,
+ input_tokens: int | None = None,
+ output_tokens: int | None = None,
+ cost: float | None = None,
+ level: str = "INFO",
+ ):
+ """
+ Log complete LLM call with formatted output.
+
+ Args:
+ model: Model name
+ stage: Stage name (e.g., "generate_question", "validate")
+ system_prompt: System prompt content
+ user_prompt: User prompt content
+ response: LLM response content
+ agent_name: Agent name (optional)
+ input_tokens: Input token count (optional)
+ output_tokens: Output token count (optional)
+ cost: Estimated cost (optional)
+ level: Log level ("DEBUG" for full details, "INFO" for summary)
+ """
+ # Build header
+ header_parts = ["[LLM-CALL]"]
+ if agent_name:
+ header_parts.append(f"[Agent: {agent_name}]")
+ header_parts.append(f"[Stage: {stage}]")
+ header_parts.append(f"[Model: {model}]")
+ header = " ".join(header_parts)
+
+ # Log at appropriate level
+ log_level = logging.DEBUG if level == "DEBUG" else logging.INFO
+
+ if level == "DEBUG":
+ # Full detailed output
+ self._log(log_level, header, symbol="◇")
+ self._log(
+ log_level, "┌─ Input ──────────────────────────────────────────────", symbol=" "
+ )
+ self._log(
+ log_level,
+ (
+ f"System: {system_prompt[:200]}..."
+ if len(system_prompt) > 200
+ else f"System: {system_prompt}"
+ ),
+ symbol=" ",
+ )
+ self._log(
+ log_level,
+ (
+ f"User: {user_prompt[:500]}..."
+ if len(user_prompt) > 500
+ else f"User: {user_prompt}"
+ ),
+ symbol=" ",
+ )
+ self._log(
+ log_level, "└──────────────────────────────────────────────────────", symbol=" "
+ )
+ self._log(
+ log_level, "┌─ Output ─────────────────────────────────────────────", symbol=" "
+ )
+ self._log(
+ log_level, f"{response[:1000]}..." if len(response) > 1000 else response, symbol=" "
+ )
+ self._log(
+ log_level, "└──────────────────────────────────────────────────────", symbol=" "
+ )
+
+ # Token and cost info
+ token_info_parts = []
+ if input_tokens is not None:
+ token_info_parts.append(f"in={input_tokens}")
+ if output_tokens is not None:
+ token_info_parts.append(f"out={output_tokens}")
+ if input_tokens is not None and output_tokens is not None:
+ token_info_parts.append(f"total={input_tokens + output_tokens}")
+ if cost is not None:
+ token_info_parts.append(f"cost=${cost:.6f}")
+
+ if token_info_parts:
+ self._log(log_level, f"[Tokens: {' '.join(token_info_parts)}]", symbol=" ")
+ else:
+ # Summary output
+ token_info = ""
+ if input_tokens is not None and output_tokens is not None:
+ token_info = f" [Tokens: in={input_tokens}, out={output_tokens}, total={input_tokens + output_tokens}]"
+ if cost is not None:
+ token_info += f" [Cost: ${cost:.6f}]"
+
+ message = f"{header}{token_info}"
+ self._log(log_level, message, symbol="◇")
+
+ def update_token_stats(self, summary: dict[str, Any]):
+ """Update token statistics (for display manager compatibility)"""
+ # Log token stats at debug level
+ if summary:
+ total_tokens = summary.get("total_tokens", 0)
+ self.debug(f"Token Stats: {total_tokens} tokens")
+
+ def shutdown(self):
+ """Shutdown the logger and cleanup resources"""
+ self.remove_task_log_handlers()
+ # Close all handlers
+ for handler in self.logger.handlers[:]:
+ handler.close()
+ self.logger.removeHandler(handler)
+
+
+# Global logger registry
+_loggers: dict[str, Logger] = {}
+
+
+def get_logger(
+ name: str = "Main",
+ level: str = "INFO",
+ console_output: bool = True,
+ file_output: bool = True,
+ log_dir: str | None = None,
+) -> Logger:
+ """
+ Get or create a logger instance.
+
+ Args:
+ name: Module name
+ level: Log level
+ console_output: Enable console output
+ file_output: Enable file output
+ log_dir: Log directory (if None, will try to load from config/main.yaml)
+
+ Returns:
+ Logger instance
+ """
+ global _loggers
+
+ # If log_dir not provided, try to load from config
+ if log_dir is None:
+ try:
+ from pathlib import Path
+
+ from src.core.core import get_path_from_config, load_config_with_main
+
+ # Use resolve() to get absolute path, ensuring correct project root regardless of working directory
+ project_root = Path(__file__).resolve().parent.parent.parent.parent
+ config = load_config_with_main(
+ "solve_config.yaml", project_root
+ ) # Use any config to get main.yaml
+ log_dir = get_path_from_config(config, "user_log_dir") or config.get("paths", {}).get(
+ "user_log_dir"
+ )
+ if log_dir:
+ # Convert relative path to absolute based on project root
+ log_dir_path = Path(log_dir)
+ if not log_dir_path.is_absolute():
+ # Remove leading ./ if present
+ log_dir_str = str(log_dir_path).lstrip("./")
+ log_dir = str(project_root / log_dir_str)
+ else:
+ log_dir = str(log_dir_path)
+ except Exception:
+ # Fallback to default
+ pass
+
+ if name not in _loggers:
+ _loggers[name] = Logger(
+ name=name,
+ level=level,
+ console_output=console_output,
+ file_output=file_output,
+ log_dir=log_dir,
+ )
+
+ return _loggers[name]
+
+
+def reset_logger(name: str | None = None):
+ """
+ Reset logger(s).
+
+ Args:
+ name: Logger name to reset, or None to reset all
+ """
+ global _loggers
+
+ if name is None:
+ _loggers.clear()
+ elif name in _loggers:
+ del _loggers[name]
+
+
+if __name__ == "__main__":
+ # Demo
+ print("\n" + "=" * 60)
+ print("OpenTutor Unified Logging System Demo")
+ print("=" * 60 + "\n")
+
+ # Create loggers for different modules
+ solver = get_logger("Solver")
+ research = get_logger("Research")
+ guide = get_logger("Guide")
+
+ # Standard logging
+ solver.info("Initializing solver...")
+ solver.progress("Loading knowledge base")
+ solver.success("Ready", elapsed=2.3)
+
+ # Stage logging
+ research.stage("Analysis", "start")
+ research.stage("Analysis", "running", "Processing 5 sources")
+ research.stage("Analysis", "complete")
+
+ # Tool calls
+ guide.tool_call("RAG Search", status="success", elapsed_ms=150)
+ guide.tool_call("Web Search", status="error", elapsed_ms=3000)
+
+ # LLM calls
+ solver.llm_call("gpt-4", agent="Planner", tokens_in=500, tokens_out=200, elapsed=1.5)
+
+ # Warnings and errors
+ research.warning("Rate limit approaching")
+ guide.error("Failed to connect to database")
+
+ print("\n" + "=" * 60)
+ print("Demo complete! Logs saved to: user/logs/")
+ print("=" * 60)
diff --git a/src/core/logging/terminal_display.py b/src/core/logging/terminal_display.py
new file mode 100644
index 000000000..aded5c5a7
--- /dev/null
+++ b/src/core/logging/terminal_display.py
@@ -0,0 +1,323 @@
+"""
+Unified Terminal Output Management System
+Reference solve_agents display design, providing unified terminal visualization for all modules
+"""
+
+from dataclasses import dataclass
+from datetime import datetime
+from enum import Enum
+import sys
+import time
+
+
+class AgentStatus(Enum):
+ PENDING = "pending"
+ RUNNING = "running"
+ DONE = "done"
+ ERROR = "error"
+
+
+@dataclass
+class TokenUsage:
+ """Token usage statistics"""
+
+ model: str = ""
+ input_tokens: int = 0
+ output_tokens: int = 0
+ cost: float = 0.0
+
+ @property
+ def total_tokens(self) -> int:
+ return self.input_tokens + self.output_tokens
+
+
+@dataclass
+class AgentInfo:
+ """Agent information"""
+
+ name: str
+ status: AgentStatus = AgentStatus.PENDING
+ message: str = ""
+ start_time: float | None = None
+ end_time: float | None = None
+
+
+class TerminalDisplay:
+ """
+ Unified terminal display manager
+ Provides visualization of workflow progress, Agent status, Token consumption, etc.
+ """
+
+ def __init__(
+ self,
+ module_name: str,
+ agents: list[str] | None = None,
+ show_tokens: bool = True,
+ show_time: bool = True,
+ ):
+ """
+ Initialize terminal display manager
+
+ Args:
+ module_name: Module name
+ agents: Agent name list
+ show_tokens: Whether to show token statistics
+ show_time: Whether to show time information
+ """
+ self.module_name = module_name
+ self.show_tokens = show_tokens
+ self.show_time = show_time
+ self.start_time = time.time()
+
+ # Agent status tracking
+ self.agents: dict[str, AgentInfo] = {}
+ if agents:
+ for agent in agents:
+ self.agents[agent] = AgentInfo(name=agent)
+
+ # Token statistics
+ self.token_usage: dict[str, TokenUsage] = {}
+ self.total_tokens = TokenUsage()
+
+ # Log buffer
+ self.log_buffer: list[str] = []
+ self.max_log_lines = 10
+
+ def _get_status_symbol(self, status: AgentStatus) -> str:
+ """Get status symbol"""
+ symbols = {
+ AgentStatus.PENDING: "○",
+ AgentStatus.RUNNING: "●",
+ AgentStatus.DONE: "✓",
+ AgentStatus.ERROR: "✗",
+ }
+ return symbols.get(status, "?")
+
+ def _get_status_color(self, status: AgentStatus) -> str:
+ """Get status color ANSI code"""
+ colors = {
+ AgentStatus.PENDING: "\033[90m", # Gray
+ AgentStatus.RUNNING: "\033[33m", # Yellow
+ AgentStatus.DONE: "\033[32m", # Green
+ AgentStatus.ERROR: "\033[31m", # Red
+ }
+ return colors.get(status, "\033[0m")
+
+ def _reset_color(self) -> str:
+ """Reset color"""
+ return "\033[0m"
+
+ def set_agent_status(self, agent_name: str, status: str, message: str = ""):
+ """
+ Set Agent status
+
+ Args:
+ agent_name: Agent name
+ status: Status (pending, running, done, error)
+ message: Status message
+ """
+ status_enum = AgentStatus(status) if isinstance(status, str) else status
+
+ if agent_name not in self.agents:
+ self.agents[agent_name] = AgentInfo(name=agent_name)
+
+ agent = self.agents[agent_name]
+ old_status = agent.status
+ agent.status = status_enum
+ agent.message = message
+
+ if status_enum == AgentStatus.RUNNING and agent.start_time is None:
+ agent.start_time = time.time()
+ elif status_enum in (AgentStatus.DONE, AgentStatus.ERROR):
+ agent.end_time = time.time()
+
+ self._refresh_display()
+
+ def add_token_usage(self, model: str, input_tokens: int, output_tokens: int, cost: float = 0.0):
+ """
+ Add token usage record
+
+ Args:
+ model: Model name
+ input_tokens: Input token count
+ output_tokens: Output token count
+ cost: Cost (USD)
+ """
+ if model not in self.token_usage:
+ self.token_usage[model] = TokenUsage(model=model)
+
+ usage = self.token_usage[model]
+ usage.input_tokens += input_tokens
+ usage.output_tokens += output_tokens
+ usage.cost += cost
+
+ # Update total
+ self.total_tokens.input_tokens += input_tokens
+ self.total_tokens.output_tokens += output_tokens
+ self.total_tokens.cost += cost
+
+ self._refresh_display()
+
+ def log(self, message: str):
+ """Add log message"""
+ timestamp = datetime.now().strftime("%H:%M:%S")
+ log_line = f"[{timestamp}] {message}"
+ self.log_buffer.append(log_line)
+
+ # Maintain log buffer size
+ if len(self.log_buffer) > self.max_log_lines:
+ self.log_buffer = self.log_buffer[-self.max_log_lines :]
+
+ self._refresh_display()
+
+ def _refresh_display(self):
+ """Refresh terminal display"""
+ # Clear screen and move to top
+ print("\033[2J\033[H", end="")
+
+ # Title
+ elapsed = time.time() - self.start_time
+ print("\033[1;34m╔══════════════════════════════════════════════════════════════╗\033[0m")
+ print(f"\033[1;34m║\033[0m \033[1m{self.module_name:^56}\033[0m \033[1;34m║\033[0m")
+ if self.show_time:
+ time_str = f"Running: {elapsed:.1f}s"
+ print(f"\033[1;34m║\033[0m {time_str:^56} \033[1;34m║\033[0m")
+ print("\033[1;34m╠══════════════════════════════════════════════════════════════╣\033[0m")
+
+ # Agent status
+ if self.agents:
+ print(f"\033[1;34m║\033[0m \033[1mAgent Status\033[0m{'':43} \033[1;34m║\033[0m")
+ for agent in self.agents.values():
+ symbol = self._get_status_symbol(agent.status)
+ color = self._get_status_color(agent.status)
+ reset = self._reset_color()
+
+ status_str = f"{color}{symbol} {agent.name}{reset}"
+ if agent.message:
+ status_str += f" - {agent.message[:30]}"
+
+ # Calculate display time
+ if agent.start_time and agent.end_time:
+ duration = agent.end_time - agent.start_time
+ status_str += f" ({duration:.1f}s)"
+ elif agent.start_time:
+ duration = time.time() - agent.start_time
+ status_str += f" ({duration:.1f}s...)"
+
+ # Need to handle ANSI escape sequence length when printing
+ print(f"\033[1;34m║\033[0m {status_str:56} \033[1;34m║\033[0m")
+
+ print(
+ "\033[1;34m╠══════════════════════════════════════════════════════════════╣\033[0m"
+ )
+
+ # Token statistics
+ if self.show_tokens and self.token_usage:
+ print(f"\033[1;34m║\033[0m \033[1mToken Usage\033[0m{'':44} \033[1;34m║\033[0m")
+ for model, usage in self.token_usage.items():
+ model_short = model[:20] + "..." if len(model) > 20 else model
+ tokens_str = f"{model_short}: {usage.total_tokens:,} tokens"
+ if usage.cost > 0:
+ tokens_str += f" (${usage.cost:.4f})"
+ print(f"\033[1;34m║\033[0m {tokens_str:54} \033[1;34m║\033[0m")
+
+ # Total
+ total_str = f"Total: {self.total_tokens.total_tokens:,} tokens"
+ if self.total_tokens.cost > 0:
+ total_str += f" (${self.total_tokens.cost:.4f})"
+ print(f"\033[1;34m║\033[0m \033[1m{total_str:54}\033[0m \033[1;34m║\033[0m")
+
+ print(
+ "\033[1;34m╠══════════════════════════════════════════════════════════════╣\033[0m"
+ )
+
+ # Logs
+ if self.log_buffer:
+ print(f"\033[1;34m║\033[0m \033[1mRecent Logs\033[0m{'':44} \033[1;34m║\033[0m")
+ for log_line in self.log_buffer[-5:]: # Only show last 5
+ log_short = log_line[:52] + "..." if len(log_line) > 52 else log_line
+ print(f"\033[1;34m║\033[0m \033[90m{log_short:54}\033[0m \033[1;34m║\033[0m")
+ print(
+ "\033[1;34m╠══════════════════════════════════════════════════════════════╣\033[0m"
+ )
+
+ # Bottom
+ print("\033[1;34m╚══════════════════════════════════════════════════════════════╝\033[0m")
+
+ sys.stdout.flush()
+
+ def complete(self, message: str = "Complete"):
+ """Mark task as complete"""
+ elapsed = time.time() - self.start_time
+ self.log(f"✓ {message} ({elapsed:.1f}s)")
+ self._refresh_display()
+
+ def error(self, message: str):
+ """Mark task as error"""
+ self.log(f"✗ Error: {message}")
+ self._refresh_display()
+
+
+class SimpleProgress:
+ """
+ Simple progress displayer (no screen clearing)
+ Suitable for scenarios that don't need full TUI
+ """
+
+ def __init__(self, module_name: str):
+ self.module_name = module_name
+ self.start_time = time.time()
+
+ def log(self, message: str, level: str = "INFO"):
+ """Output log"""
+ timestamp = datetime.now().strftime("%H:%M:%S")
+ elapsed = time.time() - self.start_time
+
+ color = {
+ "INFO": "\033[0m",
+ "SUCCESS": "\033[32m",
+ "WARNING": "\033[33m",
+ "ERROR": "\033[31m",
+ }.get(level, "\033[0m")
+
+ reset = "\033[0m"
+ print(f"[{timestamp}] [{self.module_name}] {color}{message}{reset} ({elapsed:.1f}s)")
+
+ def progress(self, current: int, total: int, message: str = ""):
+ """Display progress bar"""
+ percentage = (current / total) * 100 if total > 0 else 0
+ bar_length = 30
+ filled = int(bar_length * current / total) if total > 0 else 0
+ bar = "█" * filled + "░" * (bar_length - filled)
+
+ print(f"\r[{bar}] {percentage:5.1f}% ({current}/{total}) {message}", end="", flush=True)
+ if current >= total:
+ print() # New line
+
+ def complete(self, message: str = "Complete"):
+ """Complete"""
+ self.log(f"✓ {message}", "SUCCESS")
+
+ def error(self, message: str):
+ """Error"""
+ self.log(f"✗ {message}", "ERROR")
+
+
+# Convenience functions
+def create_display(
+ module_name: str, agents: list[str] | None = None, use_tui: bool = True
+) -> TerminalDisplay | SimpleProgress:
+ """
+ Create terminal displayer
+
+ Args:
+ module_name: Module name
+ agents: Agent list
+ use_tui: Whether to use full TUI
+
+ Returns:
+ Displayer instance
+ """
+ if use_tui:
+ return TerminalDisplay(module_name, agents)
+ return SimpleProgress(module_name)
diff --git a/src/core/setup.py b/src/core/setup.py
new file mode 100644
index 000000000..f6572aec5
--- /dev/null
+++ b/src/core/setup.py
@@ -0,0 +1,353 @@
+#!/usr/bin/env python
+"""
+System Setup and Initialization
+Combines user directory initialization and port configuration management.
+"""
+
+import json
+from pathlib import Path
+import sys
+
+from src.core.logging import get_logger
+
+# Initialize logger for setup operations
+_setup_logger = None
+
+
+def _get_setup_logger():
+ """Get logger for setup operations"""
+ global _setup_logger
+ if _setup_logger is None:
+ _setup_logger = get_logger("Setup")
+ return _setup_logger
+
+
+# ============================================================================
+# User Directory Initialization (from user_dir_init.py)
+# ============================================================================
+
+
+def init_user_directories(project_root: Path | None = None) -> None:
+ """
+ Initialize user data directories if they don't exist.
+
+ Creates the following directory structure:
+ data/user/
+ ├── solve/ # Problem solving outputs
+ ├── question/ # Question generation outputs
+ ├── research/ # Research outputs
+ │ ├── cache/ # Research cache
+ │ └── reports/ # Research reports
+ ├── guide/ # Guided learning outputs
+ ├── notebook/ # Notebook data
+ ├── co-writer/ # Co-writer outputs
+ │ ├── audio/ # TTS audio files
+ │ └── tool_calls/ # Tool call history
+ ├── logs/ # User logs
+ ├── run_code_workspace/ # Code execution workspace
+ └── user_history.json # User history file
+
+ Args:
+ project_root: Project root directory (if None, will try to detect)
+ """
+ if project_root is None:
+ project_root = Path(__file__).parent.parent.parent
+
+ # Get user data directory from config
+ try:
+ from src.core.core import load_config_with_main
+
+ config = load_config_with_main("solve_config.yaml", project_root)
+ user_data_dir = config.get("paths", {}).get("user_data_dir", "./data/user")
+
+ # Convert relative path to absolute
+ if not Path(user_data_dir).is_absolute():
+ user_data_dir = project_root / user_data_dir
+ else:
+ user_data_dir = Path(user_data_dir)
+ except Exception:
+ # Fallback to default
+ user_data_dir = project_root / "data" / "user"
+
+ # Required subdirectories (based on actual usage in the codebase)
+ required_dirs = [
+ "solve", # Problem solving outputs
+ "question", # Question generation outputs
+ "research", # Research outputs (will have cache/ and reports/ subdirs)
+ "guide", # Guided learning outputs
+ "notebook", # Notebook data
+ "co-writer", # Co-writer outputs
+ "logs", # User logs
+ "run_code_workspace", # Code execution workspace
+ ]
+
+ # Additional subdirectories for specific modules
+ co_writer_subdirs = [
+ "audio", # TTS audio files
+ "tool_calls", # Tool call history
+ ]
+
+ research_subdirs = [
+ "cache", # Research cache
+ "reports", # Research reports
+ ]
+
+ # Check if user directory exists and is empty
+ user_dir_exists = user_data_dir.exists()
+ user_dir_empty = False
+ if user_dir_exists:
+ try:
+ # Check if directory is empty (no files or subdirectories)
+ user_dir_empty = not any(user_data_dir.iterdir())
+ except (OSError, PermissionError) as e:
+ # If we can't check directory contents, assume it's not empty
+ logger = _get_setup_logger()
+ logger.warning(f"Cannot check if user directory is empty: {e}")
+ user_dir_empty = False
+
+ if not user_dir_exists or user_dir_empty:
+ logger = _get_setup_logger()
+ logger.info("\n" + "=" * 80)
+ logger.info("INITIALIZING USER DATA DIRECTORY")
+ logger.info("=" * 80)
+
+ if not user_dir_exists:
+ logger.info(f"Creating user data directory: {user_data_dir}")
+ else:
+ logger.info(f"User data directory is empty, initializing: {user_data_dir}")
+
+ # Create main user directory
+ user_data_dir.mkdir(parents=True, exist_ok=True)
+
+ # Create all required subdirectories
+ for dir_name in required_dirs:
+ dir_path = user_data_dir / dir_name
+ dir_path.mkdir(parents=True, exist_ok=True)
+ logger.success(f"Created: {dir_name}/")
+
+ # Create co-writer subdirectories
+ co_writer_dir = user_data_dir / "co-writer"
+ for subdir_name in co_writer_subdirs:
+ subdir_path = co_writer_dir / subdir_name
+ subdir_path.mkdir(parents=True, exist_ok=True)
+ logger.success(f"Created: co-writer/{subdir_name}/")
+
+ # Create research subdirectories
+ research_dir = user_data_dir / "research"
+ for subdir_name in research_subdirs:
+ subdir_path = research_dir / subdir_name
+ subdir_path.mkdir(parents=True, exist_ok=True)
+ logger.success(f"Created: research/{subdir_name}/")
+
+ # Create user_history.json if it doesn't exist
+ user_history_file = user_data_dir / "user_history.json"
+ if not user_history_file.exists():
+ initial_history = {"version": "1.0", "created_at": None, "sessions": []}
+ try:
+ with open(user_history_file, "w", encoding="utf-8") as f:
+ json.dump(initial_history, f, indent=2, ensure_ascii=False)
+ logger.success("Created: user_history.json")
+ except Exception as e:
+ logger.warning(f"Failed to create user_history.json: {e}")
+
+ # Create settings.json if it doesn't exist (default to English)
+ settings_file = user_data_dir / "settings.json"
+ if not settings_file.exists():
+ initial_settings = {
+ "theme": "light",
+ "language": "en",
+ "output_language": "en"
+ }
+ try:
+ with open(settings_file, "w", encoding="utf-8") as f:
+ json.dump(initial_settings, f, indent=2, ensure_ascii=False)
+ logger.success("Created: settings.json")
+ except Exception as e:
+ logger.warning(f"Failed to create settings.json: {e}")
+
+ logger.info("=" * 80)
+ logger.success("User data directory initialization complete!")
+ logger.info("=" * 80 + "\n")
+ else:
+ # Directory exists and is not empty, just ensure all subdirectories exist
+ for dir_name in required_dirs:
+ dir_path = user_data_dir / dir_name
+ dir_path.mkdir(parents=True, exist_ok=True)
+
+ # Ensure co-writer subdirectories exist
+ co_writer_dir = user_data_dir / "co-writer"
+ for subdir_name in co_writer_subdirs:
+ subdir_path = co_writer_dir / subdir_name
+ subdir_path.mkdir(parents=True, exist_ok=True)
+
+ # Ensure research subdirectories exist
+ research_dir = user_data_dir / "research"
+ for subdir_name in research_subdirs:
+ subdir_path = research_dir / subdir_name
+ subdir_path.mkdir(parents=True, exist_ok=True)
+
+ # Ensure user_history.json exists
+ user_history_file = user_data_dir / "user_history.json"
+ if not user_history_file.exists():
+ initial_history = {"version": "1.0", "created_at": None, "sessions": []}
+ try:
+ with open(user_history_file, "w", encoding="utf-8") as f:
+ json.dump(initial_history, f, indent=2, ensure_ascii=False)
+ except Exception:
+ pass # Silent fail if file creation fails but directory exists
+
+ # Ensure settings.json exists (default to English)
+ settings_file = user_data_dir / "settings.json"
+ if not settings_file.exists():
+ initial_settings = {
+ "theme": "light",
+ "language": "en",
+ "output_language": "en"
+ }
+ try:
+ with open(settings_file, "w", encoding="utf-8") as f:
+ json.dump(initial_settings, f, indent=2, ensure_ascii=False)
+ except Exception:
+ pass # Silent fail if file creation fails but directory exists
+
+
+# ============================================================================
+# Port Configuration Management (from port_config.py)
+# ============================================================================
+
+
+def print_port_config_tutorial():
+ """Print tutorial for configuring ports"""
+ logger = _get_setup_logger()
+ logger.error("\n" + "=" * 80)
+ logger.error("PORT CONFIGURATION REQUIRED")
+ logger.error("=" * 80)
+ logger.error("")
+ logger.error("Please configure the server ports in config/main.yaml:")
+ logger.error("")
+ logger.error("Add the following section to config/main.yaml:")
+ logger.error("")
+ logger.error(" server:")
+ logger.error(" # Backend API server port (FastAPI/Uvicorn)")
+ logger.error(" backend_port: 8000")
+ logger.error("")
+ logger.error(" # Frontend development server port (Next.js)")
+ logger.error(" frontend_port: 3000")
+ logger.error("")
+ logger.error("Example:")
+ logger.error(" - Open config/main.yaml")
+ logger.error(" - Add the 'server' section with 'backend_port' and 'frontend_port'")
+ logger.error(" - Save the file and restart the application")
+ logger.error("")
+ logger.error("Note:")
+ logger.error(" - Backend port: Port for the FastAPI backend server (default: 8000)")
+ logger.error(" - Frontend port: Port for the Next.js frontend server (default: 3000)")
+ logger.error(" - Make sure the ports are not already in use by other applications")
+ logger.error("")
+ logger.error("=" * 80)
+ logger.error("")
+
+
+def get_backend_port(project_root: Path | None = None) -> int:
+ """
+ Get backend port from configuration.
+
+ Args:
+ project_root: Project root directory (if None, will try to detect)
+
+ Returns:
+ Backend port number
+
+ Raises:
+ SystemExit: If port is not configured
+ """
+ if project_root is None:
+ project_root = Path(__file__).parent.parent.parent
+
+ try:
+ from src.core.core import load_config_with_main
+
+ config = load_config_with_main(
+ "solve_config.yaml", project_root
+ ) # Use any config to get main.yaml
+
+ server_config = config.get("server", {})
+ backend_port = server_config.get("backend_port")
+
+ if backend_port is None:
+ print_port_config_tutorial()
+ sys.exit(1)
+
+ return int(backend_port)
+ except Exception as e:
+ logger = _get_setup_logger()
+ logger.error(f"\nError reading port configuration: {e}")
+ print_port_config_tutorial()
+ sys.exit(1)
+
+
+def get_frontend_port(project_root: Path | None = None) -> int:
+ """
+ Get frontend port from configuration.
+
+ Args:
+ project_root: Project root directory (if None, will try to detect)
+
+ Returns:
+ Frontend port number
+
+ Raises:
+ SystemExit: If port is not configured
+ """
+ if project_root is None:
+ project_root = Path(__file__).parent.parent.parent
+
+ try:
+ from src.core.core import load_config_with_main
+
+ config = load_config_with_main(
+ "solve_config.yaml", project_root
+ ) # Use any config to get main.yaml
+
+ server_config = config.get("server", {})
+ frontend_port = server_config.get("frontend_port")
+
+ if frontend_port is None:
+ print_port_config_tutorial()
+ sys.exit(1)
+
+ return int(frontend_port)
+ except Exception as e:
+ logger = _get_setup_logger()
+ logger.error(f"\nError reading port configuration: {e}")
+ print_port_config_tutorial()
+ sys.exit(1)
+
+
+def get_ports(project_root: Path | None = None) -> tuple[int, int]:
+ """
+ Get both backend and frontend ports from configuration.
+
+ Args:
+ project_root: Project root directory (if None, will try to detect)
+
+ Returns:
+ Tuple of (backend_port, frontend_port)
+
+ Raises:
+ SystemExit: If ports are not configured
+ """
+ backend_port = get_backend_port(project_root)
+ frontend_port = get_frontend_port(project_root)
+ return (backend_port, frontend_port)
+
+
+__all__ = [
+ # User directory initialization
+ "init_user_directories",
+ # Port configuration
+ "get_backend_port",
+ "get_frontend_port",
+ "get_ports",
+ "print_port_config_tutorial",
+]
diff --git a/src/knowledge/README.md b/src/knowledge/README.md
new file mode 100644
index 000000000..5866ea1d6
--- /dev/null
+++ b/src/knowledge/README.md
@@ -0,0 +1,449 @@
+# 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 (OpenTutor/)
+python -m src.knowledge.start_kb [command]
+```
+
+**Or using module import:**
+
+```bash
+# Ensure in project root directory (OpenTutor/)
+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_BINDING_API_KEY=your_openai_api_key
+LLM_BINDING_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_BINDING_API_KEY` and `LLM_BINDING_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/tools/query_item_tool.py` - Query numbered items
+- `src/agents/solve/` - Problem solving system
+- `src/agents/research/` - Deep research system
diff --git a/src/knowledge/__init__.py b/src/knowledge/__init__.py
new file mode 100644
index 000000000..f934a2da1
--- /dev/null
+++ b/src/knowledge/__init__.py
@@ -0,0 +1,23 @@
+#!/usr/bin/env python
+"""
+Knowledge Base Initialization Module
+
+Includes:
+- init_knowledge_base: Knowledge base initializer
+- add_documents: Incremental document addition (new feature)
+- kb_manager: Knowledge base manager
+- extract_numbered_items: Extract numbered items
+- config: Path configuration
+"""
+
+from . import config
+from .add_documents import DocumentAdder
+from .initializer import KnowledgeBaseInitializer
+from .manager import KnowledgeBaseManager
+
+__all__ = [
+ "DocumentAdder",
+ "KnowledgeBaseInitializer",
+ "KnowledgeBaseManager",
+ "config",
+]
diff --git a/src/knowledge/add_documents.py b/src/knowledge/add_documents.py
new file mode 100644
index 000000000..0465480c8
--- /dev/null
+++ b/src/knowledge/add_documents.py
@@ -0,0 +1,621 @@
+#!/usr/bin/env python
+"""
+Incrementally add documents to existing knowledge base
+
+This script allows adding new documents to an existing knowledge base,
+rather than recreating the entire knowledge base.
+Only newly added documents will be processed, without affecting the existing knowledge graph.
+"""
+
+import argparse
+import asyncio
+from datetime import datetime
+import json
+import os
+from pathlib import Path
+import shutil
+import sys
+
+project_root = Path(__file__).parent.parent.parent
+sys.path.insert(0, str(project_root))
+# Add raganything module path
+raganything_path = project_root.parent / "raganything" / "RAG-Anything"
+if raganything_path.exists():
+ sys.path.insert(0, str(raganything_path))
+
+from dotenv import load_dotenv
+from lightrag.llm.openai import openai_complete_if_cache, openai_embed
+from lightrag.utils import EmbeddingFunc
+from raganything import RAGAnything, RAGAnythingConfig
+
+from src.core.core import get_embedding_config, get_llm_config
+
+load_dotenv(dotenv_path=".env", override=False)
+
+# Use unified logging system
+from src.core.logging import LightRAGLogContext, get_logger
+
+logger = get_logger("KnowledgeInit")
+
+# Import numbered items extraction functionality
+from src.knowledge.extract_numbered_items import process_content_list
+
+
+class DocumentAdder:
+ """Add documents to existing knowledge base"""
+
+ def __init__(
+ self,
+ kb_name: str,
+ base_dir="./data/knowledge_bases",
+ api_key: str = None,
+ base_url: str = None,
+ progress_tracker=None,
+ ):
+ self.kb_name = kb_name
+ self.base_dir = Path(base_dir)
+ self.kb_dir = self.base_dir / kb_name
+
+ # Check if knowledge base exists
+ if not self.kb_dir.exists():
+ raise ValueError(f"Knowledge base does not exist: {kb_name}")
+
+ # Directory structure
+ self.raw_dir = self.kb_dir / "raw"
+ self.images_dir = self.kb_dir / "images"
+ self.rag_storage_dir = self.kb_dir / "rag_storage"
+ self.content_list_dir = self.kb_dir / "content_list"
+
+ # Check directory structure
+ if not self.rag_storage_dir.exists():
+ raise ValueError(
+ f"Knowledge base not initialized: {kb_name}, please create knowledge base first"
+ )
+
+ self.api_key = api_key
+ self.base_url = base_url
+ self.embedding_cfg = get_embedding_config()
+ self.progress_tracker = progress_tracker
+
+ def get_existing_files(self) -> set:
+ """Get list of existing documents"""
+ existing_files = set()
+ if self.raw_dir.exists():
+ for file_path in self.raw_dir.glob("*"):
+ if file_path.is_file():
+ existing_files.add(file_path.name)
+ return existing_files
+
+ def add_documents(self, source_files: list[str], skip_duplicates: bool = True) -> list[Path]:
+ """
+ Add documents to knowledge base
+
+ Args:
+ source_files: List of document files to add
+ skip_duplicates: Whether to skip duplicate files (files with same name)
+
+ Returns:
+ List of successfully added new file paths
+ """
+ logger.info(f"Adding documents to knowledge base '{self.kb_name}'...")
+
+ existing_files = self.get_existing_files()
+ new_files = []
+ skipped_files = []
+
+ for source in source_files:
+ source_path = Path(source)
+ if not source_path.exists():
+ logger.warning(f" ✗ Source file does not exist: {source}")
+ continue
+
+ # Check if already exists
+ if source_path.name in existing_files:
+ if skip_duplicates:
+ logger.info(f" ⊗ Skipped (already exists): {source_path.name}")
+ skipped_files.append(source_path.name)
+ continue
+ logger.warning(f" ⚠ Overwriting existing file: {source_path.name}")
+
+ # Copy to raw directory
+ dest_path = self.raw_dir / source_path.name
+ shutil.copy2(source_path, dest_path)
+ new_files.append(dest_path)
+ logger.info(f" ✓ Added: {source_path.name}")
+
+ if skipped_files:
+ logger.info(f"\nSkipped {len(skipped_files)} existing files")
+
+ logger.info(f"Successfully added {len(new_files)} new files")
+ return new_files
+
+ async def process_new_documents(self, new_files: list[Path]):
+ """
+ Process newly added documents
+
+ Only process specified new files, insert content into existing knowledge graph
+ """
+ if not new_files:
+ logger.warning("No new files to process")
+ return None
+
+ logger.info(f"\nProcessing {len(new_files)} new documents...")
+
+ # Create RAGAnything configuration
+ config = RAGAnythingConfig(
+ working_dir=str(self.rag_storage_dir),
+ enable_image_processing=True,
+ enable_table_processing=True,
+ enable_equation_processing=True,
+ )
+
+ # Get model configuration
+ llm_cfg = get_llm_config()
+ model = llm_cfg["model"]
+
+ # Define LLM model function
+ def llm_model_func(prompt, system_prompt=None, history_messages=[], **kwargs):
+ return openai_complete_if_cache(
+ model,
+ prompt,
+ system_prompt=system_prompt,
+ history_messages=history_messages,
+ api_key=self.api_key,
+ base_url=self.base_url,
+ **kwargs,
+ )
+
+ # Define vision model function for image processing
+ def vision_model_func(
+ prompt,
+ system_prompt=None,
+ history_messages=[],
+ image_data=None,
+ messages=None,
+ **kwargs,
+ ):
+ # If messages format is provided, use it directly
+ if messages:
+ # Remove 'messages' and other message-related params from kwargs to avoid duplicate parameter
+ clean_kwargs = {
+ k: v
+ for k, v in kwargs.items()
+ if k not in ["messages", "prompt", "system_prompt", "history_messages"]
+ }
+ return openai_complete_if_cache(
+ model,
+ prompt="", # Empty prompt when using messages
+ system_prompt=None,
+ history_messages=[],
+ messages=messages,
+ api_key=self.api_key,
+ base_url=self.base_url,
+ **clean_kwargs,
+ )
+ # Traditional single image format
+ if image_data:
+ # Remove message-related params from kwargs to avoid duplicate parameter
+ clean_kwargs = {
+ k: v
+ for k, v in kwargs.items()
+ if k not in ["messages", "prompt", "system_prompt", "history_messages"]
+ }
+ return openai_complete_if_cache(
+ model,
+ prompt="", # Empty prompt when using messages
+ system_prompt=None,
+ history_messages=[],
+ messages=[
+ {"role": "system", "content": system_prompt} if system_prompt else None,
+ (
+ {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": prompt},
+ {
+ "type": "image_url",
+ "image_url": {
+ "url": f"data:image/jpeg;base64,{image_data}"
+ },
+ },
+ ],
+ }
+ if image_data
+ else {"role": "user", "content": prompt}
+ ),
+ ],
+ api_key=self.api_key,
+ base_url=self.base_url,
+ **clean_kwargs,
+ )
+ # Pure text format
+ return llm_model_func(prompt, system_prompt, history_messages, **kwargs)
+
+ # Define embedding function
+ embedding_cfg = self.embedding_cfg
+ embedding_api_key = embedding_cfg["api_key"] or self.api_key
+ embedding_base_url = embedding_cfg["base_url"] or self.base_url
+ embedding_func = EmbeddingFunc(
+ embedding_dim=embedding_cfg["dim"],
+ max_token_size=embedding_cfg["max_tokens"],
+ func=lambda texts: openai_embed(
+ texts,
+ model=embedding_cfg["model"],
+ api_key=embedding_api_key,
+ base_url=embedding_base_url,
+ ),
+ )
+
+ # Initialize RAGAnything with existing storage and log forwarding
+ with LightRAGLogContext(scene="knowledge_init"):
+ rag = RAGAnything(
+ config=config,
+ llm_model_func=llm_model_func,
+ vision_model_func=vision_model_func,
+ embedding_func=embedding_func,
+ )
+
+ # Ensure LightRAG is initialized (will load existing knowledge base)
+ await rag._ensure_lightrag_initialized()
+ logger.info("✓ Loaded existing knowledge base")
+
+ # Process each new document
+ processed_files = []
+ total_files = len(new_files)
+ for idx, doc_file in enumerate(new_files, 1):
+ logger.info(f"\nProcessing: {doc_file.name}")
+
+ # Update progress
+ if self.progress_tracker:
+ from src.knowledge.progress_tracker import ProgressStage
+
+ self.progress_tracker.update(
+ ProgressStage.PROCESSING_FILE,
+ f"Processing: {doc_file.name}",
+ current=idx,
+ total=total_files,
+ file_name=doc_file.name,
+ )
+
+ try:
+ # Use RAGAnything's process_document_complete method
+ await rag.process_document_complete(
+ file_path=str(doc_file),
+ output_dir=str(self.content_list_dir),
+ parse_method="auto",
+ )
+ logger.info(f" ✓ Successfully processed: {doc_file.name}")
+ processed_files.append(doc_file)
+
+ # Content list should be automatically saved
+ doc_name = doc_file.stem
+ content_list_file = self.content_list_dir / f"{doc_name}.json"
+ if content_list_file.exists():
+ logger.info(f" ✓ Content list saved: {content_list_file.name}")
+
+ except Exception as e:
+ logger.error(f" ✗ Processing failed {doc_file.name}: {e!s}")
+ import traceback
+
+ logger.error(traceback.format_exc())
+
+ # Copy extracted images
+ rag_images_dir = self.rag_storage_dir / "images"
+ if rag_images_dir.exists():
+ logger.info("\nCopying extracted images...")
+ image_count = 0
+ for img_file in rag_images_dir.glob("*"):
+ if img_file.is_file():
+ dest = self.images_dir / img_file.name
+ if not dest.exists():
+ shutil.copy2(img_file, dest)
+ image_count += 1
+ if image_count > 0:
+ logger.info(f" ✓ Copied {image_count} images")
+
+ # Fix structure
+ await self.fix_structure()
+
+ logger.info("\n✓ Document processing completed!")
+
+ return processed_files
+
+ async def fix_structure(self):
+ """Fix nested directory structure"""
+ logger.info("\nFixing directory structure...")
+
+ # Find nested content lists
+ content_list_moves = []
+ for doc_dir in self.content_list_dir.glob("*"):
+ if not doc_dir.is_dir():
+ continue
+
+ auto_dir = doc_dir / "auto"
+ if not auto_dir.exists():
+ continue
+
+ # Find the _content_list.json file
+ for json_file in auto_dir.glob("*_content_list.json"):
+ target_file = self.content_list_dir / f"{doc_dir.name}.json"
+ content_list_moves.append((json_file, target_file))
+
+ # Move content list files
+ for source, target in content_list_moves:
+ try:
+ shutil.copy2(source, target)
+ logger.info(f" ✓ Moved: {source.name} -> {target.name}")
+ except Exception as e:
+ logger.error(f" ✗ Move failed {source.name}: {e!s}")
+
+ # Find and move nested images
+ for doc_dir in self.content_list_dir.glob("*"):
+ if not doc_dir.is_dir():
+ continue
+
+ auto_dir = doc_dir / "auto"
+ if not auto_dir.exists():
+ continue
+
+ images_dir = auto_dir / "images"
+ if images_dir.exists() and images_dir.is_dir():
+ image_count = 0
+ # Ensure target directory exists
+ self.images_dir.mkdir(parents=True, exist_ok=True)
+
+ for img_file in images_dir.glob("*"):
+ if img_file.is_file() and img_file.exists():
+ target_img = self.images_dir / img_file.name
+ if not target_img.exists():
+ try:
+ # Ensure source file exists
+ if not img_file.exists():
+ logger.warning(f" ⚠ Source image does not exist: {img_file}")
+ continue
+ shutil.copy2(img_file, target_img)
+ image_count += 1
+ except FileNotFoundError:
+ logger.error(
+ f" ✗ Failed to move image {img_file.name}: Source file does not exist: {img_file}"
+ )
+ except Exception as e:
+ logger.error(f" ✗ Failed to move image {img_file.name}: {e!s}")
+
+ if image_count > 0:
+ logger.info(f" ✓ Moved {image_count} images from {doc_dir.name}/auto/images/")
+
+ # Clean up nested directories
+ for doc_dir in self.content_list_dir.glob("*"):
+ if doc_dir.is_dir():
+ try:
+ shutil.rmtree(doc_dir)
+ logger.info(f" ✓ Cleaned: {doc_dir.name}/")
+ except Exception as e:
+ logger.error(f" ✗ Cleanup failed {doc_dir.name}: {e!s}")
+
+ logger.info("✓ Directory structure fixed!")
+
+ def extract_numbered_items_for_new_docs(
+ self, processed_files: list[Path], batch_size: int = 20
+ ):
+ """
+ Extract numbered items for newly added documents
+
+ Args:
+ processed_files: List of newly processed files
+ batch_size: Number of items to process per batch
+ """
+ if not processed_files:
+ logger.info("No new files need numbered items extraction")
+ return
+
+ logger.info("\n" + "=" * 60)
+ logger.info("🔍 Extracting numbered items for new documents...")
+ logger.info("=" * 60 + "\n")
+
+ output_file = self.kb_dir / "numbered_items.json"
+
+ try:
+ for idx, doc_file in enumerate(processed_files, 1):
+ doc_name = doc_file.stem
+ content_list_file = self.content_list_dir / f"{doc_name}.json"
+
+ if not content_list_file.exists():
+ logger.warning(f"Content list file not found: {content_list_file.name}")
+ continue
+
+ logger.info(
+ f"\nProcessing file [{idx}/{len(processed_files)}]: {content_list_file.name}"
+ )
+
+ # Always merge to existing file (if exists)
+ merge = output_file.exists()
+
+ process_content_list(
+ content_list_file=content_list_file,
+ output_file=output_file,
+ api_key=self.api_key,
+ base_url=self.base_url,
+ batch_size=batch_size,
+ merge=merge,
+ )
+
+ logger.info(f"\n{'=' * 60}")
+ logger.info("✓ Numbered items extraction complete!")
+ logger.info(f"Output file: {output_file}")
+ logger.info(f"{'=' * 60}\n")
+
+ except Exception as e:
+ logger.error(f"\n✗ Numbered items extraction failed: {e}")
+ import traceback
+
+ traceback.print_exc()
+
+ def update_metadata(self, added_count: int):
+ """Update knowledge base metadata"""
+ metadata_file = self.kb_dir / "metadata.json"
+
+ try:
+ if metadata_file.exists():
+ with open(metadata_file, encoding="utf-8") as f:
+ metadata = json.load(f)
+ else:
+ metadata = {}
+
+ # Update modification time
+ metadata["last_updated"] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
+
+ # Record add operation
+ if "update_history" not in metadata:
+ metadata["update_history"] = []
+
+ metadata["update_history"].append(
+ {
+ "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
+ "action": "add_documents",
+ "files_added": added_count,
+ }
+ )
+
+ with open(metadata_file, "w", encoding="utf-8") as f:
+ json.dump(metadata, f, indent=2, ensure_ascii=False)
+
+ logger.info("✓ Metadata updated")
+
+ except Exception as e:
+ logger.warning(f"Failed to update metadata: {e!s}")
+
+
+async def main():
+ """Main function"""
+ parser = argparse.ArgumentParser(
+ description="Incrementally add documents to existing knowledge base",
+ formatter_class=argparse.RawDescriptionHelpFormatter,
+ epilog="""
+Usage examples:
+ # Add a single document to knowledge base
+ python add_documents.py ai_textbook --docs new_chapter.pdf
+
+ # Add multiple documents to knowledge base
+ python add_documents.py math2211 --docs chapter1.pdf chapter2.pdf
+
+ # Add documents from directory
+ python add_documents.py ai_textbook --docs-dir ./new_materials/
+
+ # Allow overwriting files with same name
+ python add_documents.py ai_textbook --docs document.pdf --allow-duplicates
+
+ # Only add files, skip processing (process manually later)
+ python add_documents.py ai_textbook --docs file.pdf --skip-processing
+
+ # Skip numbered items extraction
+ python add_documents.py ai_textbook --docs file.pdf --skip-extract
+ """,
+ )
+
+ parser.add_argument("kb_name", help="Knowledge base name")
+ parser.add_argument("--docs", nargs="+", help="Document files to add")
+ parser.add_argument("--docs-dir", help="Directory containing documents to add")
+ parser.add_argument(
+ "--base-dir",
+ default="./knowledge_bases",
+ help="Knowledge base base directory (default: ./knowledge_bases)",
+ )
+ parser.add_argument(
+ "--api-key", default=os.getenv("LLM_BINDING_API_KEY"), help="OpenAI API key"
+ )
+ parser.add_argument("--base-url", default=os.getenv("LLM_BINDING_HOST"), help="API base URL")
+ parser.add_argument(
+ "--allow-duplicates",
+ action="store_true",
+ help="Allow overwriting files with same name (default: skip)",
+ )
+ parser.add_argument(
+ "--skip-processing", action="store_true", help="Only add files, skip document processing"
+ )
+ parser.add_argument(
+ "--skip-extract", action="store_true", help="Skip numbered items extraction"
+ )
+ parser.add_argument(
+ "--batch-size",
+ type=int,
+ default=20,
+ help="Batch size for numbered items extraction (default: 20)",
+ )
+
+ args = parser.parse_args()
+
+ # Check API key
+ if not args.skip_processing and not args.api_key:
+ logger.error("Error: OpenAI API key required")
+ logger.error("Please set LLM_BINDING_API_KEY environment variable or use --api-key option")
+ return
+
+ # Collect document files
+ doc_files = []
+ if args.docs:
+ doc_files.extend(args.docs)
+
+ if args.docs_dir:
+ docs_dir = Path(args.docs_dir)
+ if docs_dir.exists() and docs_dir.is_dir():
+ for ext in ["*.pdf", "*.docx", "*.doc", "*.txt", "*.md"]:
+ doc_files.extend([str(f) for f in docs_dir.glob(ext)])
+ else:
+ logger.error(f"Error: Document directory does not exist: {args.docs_dir}")
+ return
+
+ if not doc_files:
+ logger.error("Error: No documents specified")
+ logger.error("Use --docs or --docs-dir to specify documents to add")
+ return
+
+ # Initialize document adder
+ try:
+ adder = DocumentAdder(
+ kb_name=args.kb_name,
+ base_dir=args.base_dir,
+ api_key=args.api_key,
+ base_url=args.base_url,
+ )
+ except ValueError as e:
+ logger.error(f"Error: {e!s}")
+ return
+
+ logger.info(f"\n{'=' * 60}")
+ logger.info(f"Adding documents to knowledge base: {args.kb_name}")
+ logger.info(f"{'=' * 60}\n")
+
+ # Add documents to raw directory
+ new_files = adder.add_documents(doc_files, skip_duplicates=not args.allow_duplicates)
+
+ if not new_files:
+ logger.info("\nNo new files need processing")
+ return
+
+ # Process new documents
+ processed_files = []
+ if not args.skip_processing:
+ processed_files = await adder.process_new_documents(new_files)
+ else:
+ logger.info("\nSkipping document processing (--skip-processing specified)")
+ processed_files = new_files
+
+ # Extract numbered items for new documents
+ if not args.skip_processing and not args.skip_extract and processed_files:
+ adder.extract_numbered_items_for_new_docs(processed_files, batch_size=args.batch_size)
+ elif args.skip_extract:
+ logger.info("\nSkipping numbered items extraction (--skip-extract specified)")
+
+ # Update metadata
+ adder.update_metadata(len(new_files))
+
+ logger.info(f"\n{'=' * 60}")
+ logger.info(
+ f"✓ Successfully added {len(new_files)} documents to knowledge base '{args.kb_name}'!"
+ )
+ logger.info(f"{'=' * 60}\n")
+
+
+if __name__ == "__main__":
+ # Logging configuration is done during module import, no need to configure again here
+ asyncio.run(main())
diff --git a/src/knowledge/config.py b/src/knowledge/config.py
new file mode 100644
index 000000000..9e8429aa6
--- /dev/null
+++ b/src/knowledge/config.py
@@ -0,0 +1,65 @@
+#!/usr/bin/env python
+"""
+Knowledge Base Path Configuration Module - Unified management of all paths
+"""
+
+import os
+from pathlib import Path
+
+# Project root directory (OpenTutor/)
+PROJECT_ROOT = Path(__file__).parent.parent.parent.resolve()
+
+# Knowledge base base directory
+KNOWLEDGE_BASES_DIR = PROJECT_ROOT / "data" / "knowledge_bases"
+
+# raganything module path
+RAGANYTHING_PATH = PROJECT_ROOT.parent / "raganything" / "RAG-Anything"
+
+
+# Ensure raganything path existence check
+def check_raganything():
+ """Check if raganything module exists"""
+ return RAGANYTHING_PATH.exists()
+
+
+# Environment variable configuration
+def get_env_config():
+ """Get environment variable configuration (unified read from env_config)"""
+ try:
+ from src.core.core import get_llm_config
+
+ cfg = get_llm_config()
+ return {
+ "api_key": cfg.get("api_key"),
+ "base_url": cfg.get("base_url"),
+ }
+ except Exception:
+ # Compatibility fallback: directly read environment variables
+ return {
+ "api_key": os.getenv("LLM_BINDING_API_KEY"),
+ "base_url": os.getenv("LLM_BINDING_HOST"),
+ }
+
+
+# Add necessary paths to sys.path
+def setup_paths():
+ """Set Python module search paths"""
+ import sys
+
+ # Add project root directory
+ if str(PROJECT_ROOT) not in sys.path:
+ sys.path.insert(0, str(PROJECT_ROOT))
+
+ # Add raganything path (if exists)
+ if check_raganything() and str(RAGANYTHING_PATH) not in sys.path:
+ sys.path.insert(0, str(RAGANYTHING_PATH))
+
+
+__all__ = [
+ "KNOWLEDGE_BASES_DIR",
+ "PROJECT_ROOT",
+ "RAGANYTHING_PATH",
+ "check_raganything",
+ "get_env_config",
+ "setup_paths",
+]
diff --git a/src/knowledge/example_add_documents.py b/src/knowledge/example_add_documents.py
new file mode 100644
index 000000000..5855259a1
--- /dev/null
+++ b/src/knowledge/example_add_documents.py
@@ -0,0 +1,235 @@
+#!/usr/bin/env python
+"""
+Incremental Document Addition Usage Example
+
+Demonstrates how to add new documents to an existing knowledge base
+"""
+
+import asyncio
+import os
+from pathlib import Path
+import sys
+
+# Add project root directory to path
+project_root = Path(__file__).parent.parent.parent
+sys.path.insert(0, str(project_root))
+
+from src.knowledge.add_documents import DocumentAdder
+
+
+async def example_add_single_document():
+ """Example 1: Add single document"""
+ print("\n" + "=" * 60)
+ print("Example 1: Add single document to knowledge base")
+ print("=" * 60)
+
+ adder = DocumentAdder(
+ kb_name="ai_textbook",
+ base_dir="./data/knowledge_bases",
+ api_key=os.getenv("LLM_BINDING_API_KEY"),
+ base_url=os.getenv("LLM_BINDING_HOST"),
+ )
+
+ # Add documents
+ new_files = adder.add_documents(
+ source_files=["./new_chapter.pdf"],
+ skip_duplicates=True, # Skip files with same name
+ )
+
+ if new_files:
+ # Process new documents
+ processed = await adder.process_new_documents(new_files)
+
+ # Extract numbered items
+ adder.extract_numbered_items_for_new_docs(processed)
+
+ # Update metadata
+ adder.update_metadata(len(new_files))
+
+ print("\n✅ Completed!")
+
+
+async def example_add_multiple_documents():
+ """Example 2: Add multiple documents"""
+ print("\n" + "=" * 60)
+ print("Example 2: Batch add documents to knowledge base")
+ print("=" * 60)
+
+ adder = DocumentAdder(
+ kb_name="math2211",
+ base_dir="./data/knowledge_bases",
+ api_key=os.getenv("LLM_BINDING_API_KEY"),
+ base_url=os.getenv("LLM_BINDING_HOST"),
+ )
+
+ # Add multiple documents
+ new_files = adder.add_documents(
+ source_files=[
+ "./materials/chapter1.pdf",
+ "./materials/chapter2.pdf",
+ "./materials/exercises.pdf",
+ ],
+ skip_duplicates=True,
+ )
+
+ if new_files:
+ # Process new documents
+ processed = await adder.process_new_documents(new_files)
+
+ # Extract numbered items (use larger batch size)
+ adder.extract_numbered_items_for_new_docs(
+ processed,
+ batch_size=30, # Increase batch size for efficiency
+ )
+
+ # Update metadata
+ adder.update_metadata(len(new_files))
+
+ print("\n✅ Completed!")
+
+
+async def example_add_from_directory():
+ """Example 3: Add all documents from directory"""
+ print("\n" + "=" * 60)
+ print("Example 3: Add all documents from directory")
+ print("=" * 60)
+
+ adder = DocumentAdder(
+ kb_name="ai_textbook",
+ base_dir="./data/knowledge_bases",
+ api_key=os.getenv("LLM_BINDING_API_KEY"),
+ base_url=os.getenv("LLM_BINDING_HOST"),
+ )
+
+ # Collect all documents in directory
+ docs_dir = Path("./new_materials")
+ doc_files = []
+
+ for ext in ["*.pdf", "*.docx", "*.doc"]:
+ doc_files.extend([str(f) for f in docs_dir.glob(ext)])
+
+ print(f"Found {len(doc_files)} documents")
+
+ # Add documents
+ new_files = adder.add_documents(source_files=doc_files, skip_duplicates=True)
+
+ if new_files:
+ # Process new documents
+ processed = await adder.process_new_documents(new_files)
+
+ # Extract numbered items
+ adder.extract_numbered_items_for_new_docs(processed)
+
+ # Update metadata
+ adder.update_metadata(len(new_files))
+
+ print("\n✅ Completed!")
+
+
+async def example_add_only_no_processing():
+ """Example 4: Only add files, no processing (process manually later)"""
+ print("\n" + "=" * 60)
+ print("Example 4: Only add files, no processing")
+ print("=" * 60)
+
+ adder = DocumentAdder(
+ kb_name="ai_textbook",
+ base_dir="./data/knowledge_bases",
+ api_key=os.getenv("LLM_BINDING_API_KEY"),
+ base_url=os.getenv("LLM_BINDING_HOST"),
+ )
+
+ # Only add files to raw directory
+ new_files = adder.add_documents(source_files=["./chapter.pdf"], skip_duplicates=True)
+
+ print(f"Added {len(new_files)} files to raw directory")
+ print("These files can be processed manually later")
+
+ # Don't call process_new_documents()
+ # Can process manually later or use other tools
+
+
+async def example_check_existing_files():
+ """Example 5: Check existing files"""
+ print("\n" + "=" * 60)
+ print("Example 5: Check existing files in knowledge base")
+ print("=" * 60)
+
+ adder = DocumentAdder(kb_name="ai_textbook", base_dir="./data/knowledge_bases")
+
+ existing_files = adder.get_existing_files()
+
+ print(f"\nKnowledge base 'ai_textbook' already has {len(existing_files)} files:")
+ for filename in sorted(existing_files):
+ print(f" • {filename}")
+
+
+def example_with_error_handling():
+ """Example 6: Complete error handling"""
+ print("\n" + "=" * 60)
+ print("Example 6: Incremental addition with error handling")
+ print("=" * 60)
+
+ try:
+ adder = DocumentAdder(
+ kb_name="ai_textbook",
+ base_dir="./data/knowledge_bases",
+ api_key=os.getenv("LLM_BINDING_API_KEY"),
+ base_url=os.getenv("LLM_BINDING_HOST"),
+ )
+
+ # Check if file exists
+ source_file = Path("./new_chapter.pdf")
+ if not source_file.exists():
+ print(f"❌ Error: Source file does not exist: {source_file}")
+ return
+
+ # Add documents
+ new_files = adder.add_documents(source_files=[str(source_file)], skip_duplicates=True)
+
+ if not new_files:
+ print("ℹ️ No new files to add (may already exist)")
+ return
+
+ # Async processing
+ async def process():
+ processed = await adder.process_new_documents(new_files)
+ adder.extract_numbered_items_for_new_docs(processed)
+ adder.update_metadata(len(new_files))
+
+ asyncio.run(process())
+
+ print("\n✅ Successfully added documents!")
+
+ except ValueError as e:
+ print(f"❌ Configuration error: {e}")
+ except FileNotFoundError as e:
+ print(f"❌ File error: {e}")
+ except Exception as e:
+ print(f"❌ Unknown error: {e}")
+ import traceback
+
+ traceback.print_exc()
+
+
+if __name__ == "__main__":
+ print("\nIncremental Document Addition Usage Examples")
+ print("=" * 60)
+
+ # Select example to run
+ example = 5 # Change this number to run different examples
+
+ if example == 1:
+ asyncio.run(example_add_single_document())
+ elif example == 2:
+ asyncio.run(example_add_multiple_documents())
+ elif example == 3:
+ asyncio.run(example_add_from_directory())
+ elif example == 4:
+ asyncio.run(example_add_only_no_processing())
+ elif example == 5:
+ asyncio.run(example_check_existing_files())
+ elif example == 6:
+ example_with_error_handling()
+ else:
+ print("Please select example number 1-6")
diff --git a/src/knowledge/extract_numbered_items.py b/src/knowledge/extract_numbered_items.py
new file mode 100644
index 000000000..d322ab4b1
--- /dev/null
+++ b/src/knowledge/extract_numbered_items.py
@@ -0,0 +1,1035 @@
+#!/usr/bin/env python
+"""
+Extract numbered important content from knowledge base content_list
+Such as: Definition 1.5., Proposition 1.3., Theorem x.x., Equation x.x., Formula x.x., etc.
+
+Use LLM to identify these contents and store the mapping between numbers and original text in JSON file
+"""
+
+import argparse
+import asyncio
+import inspect
+import json
+import os
+from pathlib import Path
+import sys
+from typing import Any
+
+sys.path.append(str(Path(__file__).parent.parent.parent))
+
+from dotenv import load_dotenv
+from lightrag.llm.openai import openai_complete_if_cache
+
+from src.core.core import get_llm_config
+
+load_dotenv(dotenv_path=".env", override=False)
+
+# Use project unified logging system
+try:
+ from pathlib import Path
+
+ from src.core.core import load_config_with_main
+ from src.core.logging import get_logger
+
+ project_root = Path(__file__).parent.parent.parent.parent
+ config = load_config_with_main(
+ "solve_config.yaml", project_root
+ ) # Use any config to get main.yaml
+ log_dir = config.get("paths", {}).get("user_log_dir") or config.get("logging", {}).get(
+ "log_dir"
+ )
+ logger = get_logger("Knowledge", log_dir=log_dir)
+except ImportError:
+ # If import fails, use basic logging
+ import logging
+
+ logger = logging.getLogger("knowledge_init.extract_items")
+ logging.basicConfig(
+ level=logging.INFO, format="%(asctime)s | %(levelname)-8s | %(name)s | %(message)s"
+ )
+
+
+async def _call_llm_async(
+ prompt: str,
+ system_prompt: str,
+ api_key: str,
+ base_url: str | None,
+ max_tokens: int = 2000,
+ temperature: float = 0.1,
+ model: str = None,
+) -> str:
+ """Asynchronously call LLM"""
+ # If model not specified, get from env_config
+ if model is None:
+ llm_cfg = get_llm_config()
+ model = llm_cfg["model"]
+
+ result = openai_complete_if_cache(
+ model,
+ prompt,
+ system_prompt=system_prompt,
+ api_key=api_key,
+ base_url=base_url,
+ max_tokens=max_tokens,
+ temperature=temperature,
+ )
+
+ if inspect.isawaitable(result):
+ return await result
+ return str(result)
+
+
+def _extract_json_block(text: str) -> str:
+ """Extract JSON block from text"""
+ try:
+ s = str(text).strip()
+ # Remove code block markers
+ if s.startswith("```") and s.endswith("```"):
+ lines = s.split("\n")
+ if lines[0].startswith("```"):
+ lines = lines[1:]
+ if lines and lines[-1].strip() == "```":
+ lines = lines[:-1]
+ s = "\n".join(lines).strip()
+
+ # Try to extract JSON object or array
+ if (s.startswith("{") and s.endswith("}")) or (s.startswith("[") and s.endswith("]")):
+ return s
+
+ o_start, o_end = s.find("{"), s.rfind("}")
+ a_start, a_end = s.find("["), s.rfind("]")
+
+ candidates = []
+ if o_start != -1 and o_end != -1 and o_end > o_start:
+ candidates.append((o_start, s[o_start : o_end + 1]))
+ if a_start != -1 and a_end != -1 and a_end > a_start:
+ candidates.append((a_start, s[a_start : a_end + 1]))
+
+ if candidates:
+ candidates.sort(key=lambda x: x[0])
+ return candidates[0][1]
+
+ return s
+ except Exception:
+ return text
+
+
+async def _check_content_belongs_async(
+ start_text: str, candidate_text: str, api_key: str, base_url: str | None
+) -> bool:
+ """
+ Use LLM to determine if candidate content belongs to (is part of) the starting content
+
+ Args:
+ start_text: Starting content (beginning part of numbered item)
+ candidate_text: Candidate content (subsequent content block)
+ api_key: OpenAI API key
+ base_url: API base URL
+
+ Returns:
+ True means candidate content belongs to starting content, False means it's new independent content
+ """
+ system_prompt = """You are an expert at analyzing the structure of academic mathematical texts.
+Your task is to determine if a candidate text block belongs to (is a continuation of) a starting numbered item, or if it's a new independent item.
+
+Numbered items include: Definitions, Propositions, Theorems, Lemmas, Corollaries, Examples, Remarks, Figures, Equations, etc.
+
+Rules:
+- Equations, formulas, and images that follow a numbered item usually belong to that item
+- Explanatory text that continues the same topic belongs to the item
+- A new numbered item (starting with "Definition X.Y", "Theorem X.Y", etc.) is independent
+- Text that starts a completely different topic is independent
+
+Return ONLY "YES" if the candidate belongs to the starting item, or "NO" if it's independent."""
+
+ user_prompt = f"""Starting item:
+{start_text[:500]}
+
+Candidate block:
+{candidate_text[:300]}
+
+Does the candidate block belong to (continue) the starting item?
+Answer with ONLY "YES" or "NO"."""
+
+ try:
+ llm_cfg = get_llm_config()
+ response = await _call_llm_async(
+ user_prompt,
+ system_prompt,
+ api_key,
+ base_url,
+ max_tokens=10,
+ temperature=0.0,
+ model=llm_cfg["model"],
+ )
+ answer = response.strip().upper()
+ return answer == "YES"
+ except Exception as e:
+ logger.warning(f"LLM judgment failed, default to not include: {e}")
+ # Default to conservative strategy: don't include
+ return False
+
+
+async def _get_complete_content_async(
+ content_items: list[dict[str, Any]],
+ start_index: int,
+ api_key: str,
+ base_url: str | None,
+ max_following: int = 5,
+) -> tuple[str, list[str]]:
+ """
+ Get complete content, including subsequent formulas, text, etc., and all related image paths
+ Use LLM to determine if subsequent content belongs to current numbered item
+
+ Args:
+ content_items: Complete content_list
+ start_index: Starting index
+ api_key: OpenAI API key
+ base_url: API base URL
+ max_following: Maximum number of subsequent entries to check
+
+ Returns:
+ (Complete text content, image path list)
+ """
+ complete_text = content_items[start_index].get("text", "")
+ img_paths = []
+
+ # Collect image paths from starting item
+ start_img_path = content_items[start_index].get("img_path", "")
+ if start_img_path:
+ img_paths.append(start_img_path)
+
+ logger.debug(
+ f"Starting to use LLM to determine content boundaries, starting text (first 50 chars): {complete_text[:50]}..."
+ )
+
+ # Check subsequent entries
+ for i in range(1, max_following + 1):
+ next_index = start_index + i
+ if next_index >= len(content_items):
+ break
+
+ next_item = content_items[next_index]
+ next_type = next_item.get("type", "")
+
+ # If encountering title-level text, definitely stop
+ if next_type == "text" and next_item.get("text_level", 0) > 0:
+ break
+
+ # If it's a formula, usually belongs to current content, add directly
+ if next_type == "equation":
+ equation_text = next_item.get("text", "")
+ if equation_text:
+ complete_text += " " + equation_text
+ # Collect formula image paths
+ eq_img_path = next_item.get("img_path", "")
+ if eq_img_path:
+ img_paths.append(eq_img_path)
+ # If it's an image, collect image paths
+ elif next_type == "image":
+ img_path = next_item.get("img_path", "")
+ if img_path:
+ img_paths.append(img_path)
+ # Can also add image captions to text
+ captions = next_item.get("image_caption", [])
+ if captions:
+ caption_text = " ".join(captions) if isinstance(captions, list) else str(captions)
+ complete_text += " " + caption_text
+ # If it's regular text, use LLM to judge
+ elif next_type == "text" and next_item.get("text_level", 0) == 0:
+ next_text = next_item.get("text", "").strip()
+ if not next_text:
+ continue
+
+ # Use LLM to determine if this text belongs to current numbered item
+ belongs = await _check_content_belongs_async(
+ complete_text, next_text, api_key, base_url
+ )
+
+ if belongs:
+ complete_text += " " + next_text
+ logger.debug(
+ f"LLM judgment: Subsequent text belongs to current content, added (first 30 chars: {next_text[:30]}...)"
+ )
+ else:
+ # Doesn't belong to current content, stop collecting
+ logger.debug(
+ f"LLM judgment: Subsequent text doesn't belong to current content, stop collecting (first 30 chars: {next_text[:30]}...)"
+ )
+ break
+
+ return complete_text.strip(), img_paths
+
+
+def _get_complete_content(
+ content_items: list[dict[str, Any]],
+ start_index: int,
+ api_key: str,
+ base_url: str | None,
+ max_following: int = 5,
+) -> tuple[str, list[str]]:
+ """
+ Synchronous wrapper for async function to get complete content
+ """
+ try:
+ loop = asyncio.get_event_loop()
+ if loop.is_running():
+ # If event loop is already running, check if it's uvloop
+ loop_type = type(loop).__name__
+ if "uvloop" in loop_type.lower():
+ # uvloop doesn't support nest_asyncio, use threading approach
+ import concurrent.futures
+
+ def run_in_new_loop():
+ # Create a new asyncio event loop in a new thread
+ new_loop = asyncio.new_event_loop()
+ asyncio.set_event_loop(new_loop)
+ try:
+ return new_loop.run_until_complete(
+ _get_complete_content_async(
+ content_items, start_index, api_key, base_url, max_following
+ )
+ )
+ finally:
+ new_loop.close()
+
+ # Run in a thread with a new event loop
+ with concurrent.futures.ThreadPoolExecutor() as executor:
+ future = executor.submit(run_in_new_loop)
+ return future.result()
+ else:
+ # Try nest_asyncio for standard event loops
+ try:
+ import nest_asyncio
+
+ nest_asyncio.apply()
+ return loop.run_until_complete(
+ _get_complete_content_async(
+ content_items, start_index, api_key, base_url, max_following
+ )
+ )
+ except (ValueError, TypeError) as e:
+ # nest_asyncio failed, fall back to threading approach
+ logger.debug(f"nest_asyncio failed ({e}), using threading fallback")
+ import concurrent.futures
+
+ def run_in_new_loop():
+ new_loop = asyncio.new_event_loop()
+ asyncio.set_event_loop(new_loop)
+ try:
+ return new_loop.run_until_complete(
+ _get_complete_content_async(
+ content_items, start_index, api_key, base_url, max_following
+ )
+ )
+ finally:
+ new_loop.close()
+
+ with concurrent.futures.ThreadPoolExecutor() as executor:
+ future = executor.submit(run_in_new_loop)
+ return future.result()
+ else:
+ return loop.run_until_complete(
+ _get_complete_content_async(
+ content_items, start_index, api_key, base_url, max_following
+ )
+ )
+ except RuntimeError:
+ # No event loop, create new one
+ return asyncio.run(
+ _get_complete_content_async(
+ content_items, start_index, api_key, base_url, max_following
+ )
+ )
+
+
+async def _process_single_batch(
+ batch_idx: int,
+ batch: list[dict[str, Any]],
+ batch_start: int,
+ content_items: list[dict[str, Any]],
+ text_item_to_full_index: dict[int, int],
+ api_key: str,
+ base_url: str | None,
+ total_batches: int,
+) -> dict[str, dict[str, Any]]:
+ """Asynchronously process a single batch"""
+ numbered_items = {}
+
+ # Build batch processing text
+ batch_texts = []
+ for idx, item in enumerate(batch):
+ batch_texts.append(f"[{batch_start + idx}] {item.get('text', '')}")
+
+ combined_text = "\n\n".join(batch_texts)
+
+ system_prompt = """You are an expert at identifying numbered mathematical and scientific content in academic texts.
+You need to extract items like:
+- Definitions (e.g., "Definition 1.5.", "Definition 1.1")
+- Propositions (e.g., "Proposition 1.3.")
+- Theorems (e.g., "Theorem 2.1.")
+- Lemmas (e.g., "Lemma 3.2.")
+- Corollaries (e.g., "Corollary 1.4.")
+- Examples (e.g., "Example 2.3.")
+- Remarks (e.g., "Remark 1.6.")
+- Figures (e.g., "Figure 1.1", "Fig. 2.3")
+- Equations (formulas with \\tag{x.y.z})
+- Tables (e.g., "Table 1.1")
+
+Note: Do NOT extract section titles or headings.
+
+IMPORTANT:
+- For equations with tags like \\tag{1.2.1}, extract identifier as "(1.2.1)" (only the number in parentheses)
+- For figures, extract the figure number from the caption
+- Return ONLY a valid JSON array
+- Ensure all backslashes in LaTeX formulas are properly escaped (use \\\\ instead of \\)."""
+
+ user_prompt = f"""Analyze the following text segments and extract all numbered items (definitions, propositions, theorems, lemmas, corollaries, examples, remarks, figures, equations, tables, etc.).
+
+Each segment starts with [N] where N is the segment index number.
+
+For each numbered item found, extract:
+1. The index number N from the brackets [N] at the start of that segment
+2. The identifier (e.g., "Definition 1.5", "Figure 1.1", "(1.2.1)")
+3. The item type (e.g., "Definition", "Proposition", "Theorem", "Figure", "Equation", "Table")
+4. The complete text of that item
+
+Special cases:
+- For equations with \\tag{{x.y.z}}, extract identifier as "(x.y.z)" - ONLY the number in parentheses, no "Equation" prefix
+- For figures, extract the figure number from captions like "Figure 1.1: ..."
+- For tables, extract table numbers like "Table 2.1"
+
+Return a JSON array of objects with this structure:
+[
+ {{
+ "index": 152,
+ "identifier": "Figure 1.1",
+ "type": "Figure",
+ "full_text": "Figure 1.1: Evolution of phylogenetic intelligence..."
+ }},
+ {{
+ "index": 185,
+ "identifier": "(1.2.1)",
+ "type": "Equation",
+ "full_text": "$$S = 1,2,3,4,5,6,\\\\ldots ,n,n + 1,\\\\ldots \\\\tag{{1.2.1}}$$"
+ }},
+ ...
+]
+
+CRITICAL REQUIREMENTS:
+- The "index" field MUST be the number N from [N] in brackets, NOT a relative position
+- For equations, identifier must be ONLY "(x.y.z)" format, not "Equation (x.y.z)"
+- Ensure all backslashes in LaTeX are properly escaped for JSON (double them: \\\\ instead of \\).
+
+Text segments:
+{combined_text}
+
+Return ONLY the JSON array, no other text. Ensure it is valid JSON."""
+
+ # Asynchronously call LLM
+ try:
+ llm_cfg = get_llm_config()
+ response = await _call_llm_async(
+ user_prompt,
+ system_prompt,
+ api_key,
+ base_url,
+ max_tokens=4000,
+ temperature=0.1,
+ model=llm_cfg["model"],
+ )
+
+ # Parse response
+ json_str = _extract_json_block(response)
+ # Try direct parsing
+ try:
+ extracted = json.loads(json_str)
+ except json.JSONDecodeError as e_first:
+ # If parsing fails, try to fix common issues
+ logger.warning(f"Batch {batch_idx}: Initial JSON parsing failed, attempting to fix...")
+
+ # Try 1: Use strict=False
+ try:
+ from json.decoder import JSONDecoder
+
+ decoder = JSONDecoder(strict=False)
+ extracted = decoder.decode(json_str)
+ logger.info(f"Batch {batch_idx}: Parsed successfully using non-strict mode")
+ except Exception:
+ # Try 2: Use ast.literal_eval
+ try:
+ import ast
+
+ extracted = ast.literal_eval(json_str)
+ logger.info(f"Batch {batch_idx}: Parsed successfully using literal_eval")
+ except Exception:
+ # All methods failed, skip this batch
+ logger.warning(f"Batch {batch_idx}: All parsing methods failed, skipping batch")
+ logger.error(f"Original error: {e_first!s}")
+ logger.error(f"Response content (first 500 chars): {response[:500]}")
+ return numbered_items
+
+ if not isinstance(extracted, list):
+ logger.warning(f"Batch {batch_idx}: LLM returned non-array")
+ return numbered_items
+
+ # Process extracted results
+ for item in extracted:
+ index = item.get("index")
+ if index is None or index < batch_start or index >= batch_start + len(batch):
+ continue
+
+ # Convert to index relative to batch
+ relative_index = index - batch_start
+ original_item = batch[relative_index]
+ identifier = item.get("identifier", "").strip()
+
+ if not identifier:
+ continue
+
+ # Get complete content and related images
+ # Prefer LLM-extracted full_text (contains complete content)
+ llm_extracted_text = item.get("full_text", "").strip()
+ img_paths = []
+
+ # For image or equation types, use LLM-extracted content directly (no need to complete)
+ original_type = original_item.get("_original_type", original_item.get("type", ""))
+ if original_type in ["image", "equation"]:
+ complete_text = llm_extracted_text
+ # Collect image path for current item
+ img_path = original_item.get("img_path", "")
+ if img_path:
+ img_paths.append(img_path)
+ else:
+ # For plain text, get index in full content_items and complete
+ full_index = text_item_to_full_index.get(index)
+ if full_index is not None:
+ # Get complete content (including subsequent equations, etc.) and all related images
+ # Use LLM to intelligently determine content boundaries
+ complete_text, img_paths = await _get_complete_content_async(
+ content_items, full_index, api_key, base_url
+ )
+ else:
+ complete_text = original_item.get("text", "")
+ # Collect image path for current item
+ img_path = original_item.get("img_path", "")
+ if img_path:
+ img_paths.append(img_path)
+
+ # If completed content is shorter than LLM-extracted, use LLM-extracted
+ if len(llm_extracted_text) > len(complete_text):
+ complete_text = llm_extracted_text
+
+ numbered_items[identifier] = {
+ "text": complete_text,
+ "type": item.get("type", "Unknown"),
+ "page": original_item.get("page_idx", 0) + 1,
+ "img_paths": img_paths if img_paths else [],
+ }
+
+ extracted_count = len([e for e in extracted if e.get("identifier", "").strip()])
+ logger.info(
+ f" Batch {batch_idx}/{total_batches}: Extracted {extracted_count} numbered items"
+ )
+
+ except Exception as e:
+ logger.error(f"Batch {batch_idx}: Processing failed: {e}")
+
+ return numbered_items
+
+
+async def extract_numbered_items_with_llm_async(
+ content_items: list[dict[str, Any]],
+ api_key: str,
+ base_url: str | None,
+ batch_size: int = 20,
+ max_concurrent: int = 5,
+) -> dict[str, dict[str, Any]]:
+ """
+ Use LLM to asynchronously batch extract numbered important content
+
+ Args:
+ content_items: List of content items from content_list
+ api_key: OpenAI API key
+ base_url: API base URL
+ batch_size: Number of items to process per batch
+ max_concurrent: Maximum concurrency
+
+ Returns:
+ Dict[identifier, {text: original text, type: type, page: page number}]
+ """
+ numbered_items = {}
+
+ # Create index mapping: from text_items index to full content_items index
+ text_item_to_full_index = {}
+ text_items = []
+
+ for idx, item in enumerate(content_items):
+ item_type = item.get("type", "")
+
+ # Process plain text
+ if item_type == "text" and item.get("text_level", 0) == 0:
+ text_item_to_full_index[len(text_items)] = idx
+ text_items.append(item)
+
+ # Process images (extract Figure number from caption)
+ elif item_type == "image":
+ captions = item.get("image_caption", [])
+ if captions:
+ # Create a virtual text item
+ caption_text = " ".join(captions) if isinstance(captions, list) else str(captions)
+ virtual_item = {
+ "type": "image",
+ "text": caption_text,
+ "page_idx": item.get("page_idx", 0),
+ "bbox": item.get("bbox", []),
+ "img_path": item.get("img_path", ""),
+ "_original_type": "image",
+ }
+ text_item_to_full_index[len(text_items)] = idx
+ text_items.append(virtual_item)
+
+ # Process numbered equations (extract from tag)
+ elif item_type == "equation":
+ equation_text = item.get("text", "")
+ # Check if there's a number tag, like \tag{1.2.1} or other forms
+ if "\\tag{" in equation_text or "tag{" in equation_text:
+ virtual_item = {
+ "type": "equation",
+ "text": equation_text,
+ "page_idx": item.get("page_idx", 0),
+ "bbox": item.get("bbox", []),
+ "img_path": item.get("img_path", ""),
+ "_original_type": "equation",
+ }
+ text_item_to_full_index[len(text_items)] = idx
+ text_items.append(virtual_item)
+
+ # Statistics
+ text_count = sum(
+ 1 for item in content_items if item.get("type") == "text" and item.get("text_level", 0) == 0
+ )
+ image_count = sum(
+ 1 for item in content_items if item.get("type") == "image" and item.get("image_caption")
+ )
+ equation_count = sum(
+ 1
+ for item in content_items
+ if item.get("type") == "equation"
+ and ("\\tag{" in item.get("text", "") or "tag{" in item.get("text", ""))
+ )
+
+ logger.info(f"Total {len(text_items)} items to process")
+ logger.info(f" - Plain text: {text_count}")
+ logger.info(f" - Images with captions: {image_count}")
+ logger.info(f" - Numbered equations: {equation_count}")
+
+ # Prepare all batches
+ batches = []
+ for batch_start in range(0, len(text_items), batch_size):
+ batch_end = min(batch_start + batch_size, len(text_items))
+ batch = text_items[batch_start:batch_end]
+ batches.append((batch_start, batch))
+
+ total_batches = len(batches)
+ logger.info(f"Using {max_concurrent} concurrent tasks to process {total_batches} batches")
+
+ # Use semaphore to control concurrency
+ semaphore = asyncio.Semaphore(max_concurrent)
+
+ async def process_with_semaphore(batch_idx, batch_start, batch):
+ async with semaphore:
+ return await _process_single_batch(
+ batch_idx + 1,
+ batch,
+ batch_start,
+ content_items,
+ text_item_to_full_index,
+ api_key,
+ base_url,
+ total_batches,
+ )
+
+ # Create all tasks
+ tasks = [
+ process_with_semaphore(idx, batch_start, batch)
+ for idx, (batch_start, batch) in enumerate(batches)
+ ]
+
+ # Execute all batches concurrently
+ results = await asyncio.gather(*tasks)
+
+ # Merge all results
+ for result in results:
+ numbered_items.update(result)
+
+ # Count results
+ type_stats = {}
+ for item_data in numbered_items.values():
+ item_type = item_data.get("type", "Unknown")
+ type_stats[item_type] = type_stats.get(item_type, 0) + 1
+
+ logger.info(f"\nExtraction complete, total {len(numbered_items)} numbered items")
+ logger.info("Statistics by type:")
+ for item_type, count in sorted(type_stats.items()):
+ logger.info(f" - {item_type}: {count}")
+
+ return numbered_items
+
+
+def extract_numbered_items_with_llm(
+ content_items: list[dict[str, Any]],
+ api_key: str,
+ base_url: str | None,
+ batch_size: int = 20,
+ max_concurrent: int = 5,
+) -> dict[str, dict[str, Any]]:
+ """
+ Synchronous wrapper for async extraction function
+ """
+ try:
+ loop = asyncio.get_event_loop()
+ if loop.is_running():
+ # If event loop is already running, check if it's uvloop
+ loop_type = type(loop).__name__
+ if "uvloop" in loop_type.lower():
+ # uvloop doesn't support nest_asyncio, use threading approach
+ import concurrent.futures
+
+ def run_in_new_loop():
+ # Create a new asyncio event loop in a new thread
+ new_loop = asyncio.new_event_loop()
+ asyncio.set_event_loop(new_loop)
+ try:
+ return new_loop.run_until_complete(
+ extract_numbered_items_with_llm_async(
+ content_items, api_key, base_url, batch_size, max_concurrent
+ )
+ )
+ finally:
+ new_loop.close()
+
+ # Run in a thread with a new event loop
+ with concurrent.futures.ThreadPoolExecutor() as executor:
+ future = executor.submit(run_in_new_loop)
+ return future.result()
+ else:
+ # Try nest_asyncio for standard event loops
+ try:
+ import nest_asyncio
+
+ nest_asyncio.apply()
+ return loop.run_until_complete(
+ extract_numbered_items_with_llm_async(
+ content_items, api_key, base_url, batch_size, max_concurrent
+ )
+ )
+ except (ValueError, TypeError) as e:
+ # nest_asyncio failed, fall back to threading approach
+ logger.debug(f"nest_asyncio failed ({e}), using threading fallback")
+ import concurrent.futures
+
+ def run_in_new_loop():
+ new_loop = asyncio.new_event_loop()
+ asyncio.set_event_loop(new_loop)
+ try:
+ return new_loop.run_until_complete(
+ extract_numbered_items_with_llm_async(
+ content_items, api_key, base_url, batch_size, max_concurrent
+ )
+ )
+ finally:
+ new_loop.close()
+
+ with concurrent.futures.ThreadPoolExecutor() as executor:
+ future = executor.submit(run_in_new_loop)
+ return future.result()
+ else:
+ return loop.run_until_complete(
+ extract_numbered_items_with_llm_async(
+ content_items, api_key, base_url, batch_size, max_concurrent
+ )
+ )
+ except RuntimeError:
+ # No event loop, create new one
+ return asyncio.run(
+ extract_numbered_items_with_llm_async(
+ content_items, api_key, base_url, batch_size, max_concurrent
+ )
+ )
+
+
+def process_content_list(
+ content_list_file: Path,
+ output_file: Path,
+ api_key: str,
+ base_url: str | None,
+ batch_size: int = 20,
+ merge: bool = True,
+):
+ """
+ Process content_list file and extract numbered items
+
+ Args:
+ content_list_file: Path to content_list JSON file
+ output_file: Path to output JSON file
+ api_key: OpenAI API key
+ base_url: API base URL
+ batch_size: Batch processing size
+ merge: Whether to merge with existing results (default True)
+ """
+ logger.info(f"Reading file: {content_list_file}")
+
+ # Read content_list
+ with open(content_list_file, encoding="utf-8") as f:
+ content_items = json.load(f)
+
+ logger.info(f"File contains {len(content_items)} items")
+
+ # Extract numbered items
+ logger.info("Starting numbered items extraction...")
+ new_items = extract_numbered_items_with_llm(
+ content_items,
+ api_key,
+ base_url,
+ batch_size,
+ max_concurrent=5, # Default concurrency
+ )
+
+ logger.info(f"Extracted {len(new_items)} numbered items this time")
+
+ # If merge is needed and file exists
+ if merge and output_file.exists():
+ logger.info(f"Existing file detected: {output_file}")
+ try:
+ with open(output_file, encoding="utf-8") as f:
+ existing_items = json.load(f)
+ logger.info(f"Loaded {len(existing_items)} existing numbered items")
+
+ # Merge (new items will override old items with same identifier)
+ merged_count = 0
+ for identifier, data in new_items.items():
+ if identifier in existing_items:
+ merged_count += 1
+ existing_items[identifier] = data
+
+ numbered_items = existing_items
+ logger.info(
+ f"Merge complete: Updated {merged_count} existing items, added {len(new_items) - merged_count} new items"
+ )
+ logger.info(f"Total {len(numbered_items)} numbered items after merge")
+ except Exception as e:
+ logger.warning(f"Could not read existing file, will create new file: {e}")
+ numbered_items = new_items
+ else:
+ numbered_items = new_items
+
+ # Save results
+ output_file.parent.mkdir(parents=True, exist_ok=True)
+ with open(output_file, "w", encoding="utf-8") as f:
+ json.dump(numbered_items, f, indent=2, ensure_ascii=False)
+
+ logger.info(f"Results saved to: {output_file}")
+
+ # Print statistics
+ type_counts = {}
+ for identifier in numbered_items.keys():
+ # Identify equations: starting with parenthesis, e.g., (1.2.1)
+ if identifier.startswith("(") and ")" in identifier:
+ item_type = "Equation"
+ else:
+ # Extract type from identifier (e.g., "Definition 1.1" -> "Definition")
+ parts = identifier.split()
+ if parts:
+ item_type = parts[0]
+ else:
+ item_type = "Unknown"
+ type_counts[item_type] = type_counts.get(item_type, 0) + 1
+
+ logger.info("\n=== Extraction Statistics ===")
+ for item_type, count in sorted(type_counts.items()):
+ logger.info(f" {item_type}: {count}")
+
+ return numbered_items
+
+
+def main():
+ parser = argparse.ArgumentParser(
+ description="Extract numbered important content from knowledge base content_list"
+ )
+ parser.add_argument(
+ "--kb", required=True, help="Knowledge base name (under knowledge_bases directory)"
+ )
+ parser.add_argument(
+ "--content-file",
+ help="content_list file name (optional, if not specified, automatically process all JSON files)",
+ default=None,
+ )
+ parser.add_argument(
+ "--debug",
+ action="store_true",
+ help="Debug mode: only process first file (for quick testing)",
+ )
+ parser.add_argument(
+ "--output-name",
+ help="Output file name (default: numbered_items.json)",
+ default="numbered_items.json",
+ )
+ parser.add_argument(
+ "--base-dir",
+ help="Data storage base directory (default: ./knowledge_bases)",
+ default="./knowledge_bases",
+ )
+ parser.add_argument(
+ "--batch-size",
+ type=int,
+ help="Number of items to process per batch (default: 20)",
+ default=20,
+ )
+ parser.add_argument(
+ "--max-concurrent", type=int, help="Maximum concurrent tasks (default: 5)", default=5
+ )
+ parser.add_argument(
+ "--no-merge",
+ action="store_true",
+ help="Do not merge existing results, directly overwrite (default will merge)",
+ )
+ parser.add_argument(
+ "--api-key",
+ default=os.getenv("LLM_BINDING_API_KEY"),
+ help="OpenAI API key (default reads from LLM_BINDING_API_KEY)",
+ )
+ parser.add_argument(
+ "--base-url",
+ default=os.getenv("LLM_BINDING_HOST"),
+ help="OpenAI API Base URL (default reads from LLM_BINDING_HOST)",
+ )
+
+ args = parser.parse_args()
+
+ # Get API configuration
+ api_key = args.api_key
+ base_url = args.base_url
+
+ # Validate API key
+ if not api_key:
+ raise SystemExit(
+ "Missing API Key: Please set environment variable LLM_BINDING_API_KEY or pass via --api-key"
+ )
+
+ # Build paths
+ base_dir = Path(args.base_dir)
+ kb_dir = base_dir / args.kb
+ content_list_dir = kb_dir / "content_list"
+
+ # Check if content_list directory exists
+ if not content_list_dir.exists():
+ logger.error(f"content_list directory does not exist: {content_list_dir}")
+ sys.exit(1)
+
+ # Get list of files to process
+ if args.content_file:
+ # If file is specified, only process that file
+ content_list_files = [content_list_dir / args.content_file]
+ if not content_list_files[0].exists():
+ logger.error(f"content_list file does not exist: {content_list_files[0]}")
+ sys.exit(1)
+ else:
+ # Otherwise automatically scan all JSON files
+ content_list_files = sorted(content_list_dir.glob("*.json"))
+ if not content_list_files:
+ logger.error(f"No JSON files found in {content_list_dir}")
+ sys.exit(1)
+
+ # Debug mode: only process first file
+ if args.debug:
+ logger.info(f"⚠️ Debug mode: Only processing first file {content_list_files[0].name}")
+ content_list_files = content_list_files[:1]
+
+ # Output file fixed as numbered_items.json (shared across entire knowledge base)
+ output_file = kb_dir / args.output_name
+
+ # Display configuration information
+ logger.info("=" * 60)
+ logger.info("📋 Configuration Information")
+ logger.info("=" * 60)
+ logger.info(f"Knowledge base: {args.kb}")
+ logger.info(f"Content files: {len(content_list_files)} files")
+ for f in content_list_files:
+ logger.info(f" - {f.name}")
+ logger.info(f"Output file: {output_file}")
+ logger.info(f"Batch size: {args.batch_size}")
+ logger.info(f"Max concurrent: {args.max_concurrent}")
+ logger.info(f"Auto merge: {'Yes' if not args.no_merge else 'No'}")
+ logger.info(f"Debug mode: {'Yes' if args.debug else 'No'}")
+ logger.info(
+ f"API key: {'Set (' + api_key[:8] + '...' + api_key[-4:] + ')' if api_key else 'Not set'}"
+ )
+ logger.info(f"API base URL: {base_url if base_url else 'Default (https://api.openai.com/v1)'}")
+ logger.info("=" * 60)
+ logger.info("")
+
+ try:
+ # Process all files
+ for idx, content_list_file in enumerate(content_list_files, 1):
+ logger.info(f"\n{'=' * 60}")
+ logger.info(
+ f"Processing file [{idx}/{len(content_list_files)}]: {content_list_file.name}"
+ )
+ logger.info(f"{'=' * 60}\n")
+
+ process_content_list(
+ content_list_file,
+ output_file,
+ api_key,
+ base_url,
+ args.batch_size,
+ merge=not args.no_merge, # Auto-merge after first file
+ )
+
+ # From second file onwards, force merge mode
+ if idx == 1 and len(content_list_files) > 1:
+ args.no_merge = False
+ logger.info(f"\nSubsequent files will be automatically merged to {output_file}\n")
+
+ logger.info("\n" + "=" * 60)
+ logger.info("✓ All files processed!")
+ logger.info("=" * 60)
+
+ # Display final statistics
+ if output_file.exists():
+ with open(output_file, encoding="utf-8") as f:
+ final_items = json.load(f)
+
+ logger.info(f"\nFinal result: {output_file}")
+ logger.info(f"Total extracted {len(final_items)} numbered items")
+
+ # Statistics by type
+ type_counts = {}
+ for identifier in final_items.keys():
+ # Identify equations: starting with parenthesis, e.g., (1.2.1)
+ if identifier.startswith("(") and ")" in identifier:
+ item_type = "Equation"
+ else:
+ # Extract type from identifier (e.g., "Definition 1.1" -> "Definition")
+ parts = identifier.split()
+ if parts:
+ item_type = parts[0]
+ else:
+ item_type = "Unknown"
+ type_counts[item_type] = type_counts.get(item_type, 0) + 1
+
+ logger.info("\n=== Final Statistics ===")
+ for item_type, count in sorted(type_counts.items()):
+ logger.info(f" {item_type}: {count}")
+
+ except Exception as e:
+ logger.error(f"\n✗ Processing failed: {e}")
+ import traceback
+
+ traceback.print_exc()
+ sys.exit(1)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/src/knowledge/initializer.py b/src/knowledge/initializer.py
new file mode 100644
index 000000000..6ffa0bd86
--- /dev/null
+++ b/src/knowledge/initializer.py
@@ -0,0 +1,683 @@
+#!/usr/bin/env python
+"""
+Knowledge Base Initialization Script
+
+This script initializes a new knowledge base from given documents:
+1. Creates directory structure
+2. Processes documents using RAG-Anything
+3. Builds knowledge graph database
+4. Extracts images and content lists
+"""
+
+import argparse
+import asyncio
+from datetime import datetime
+import json
+import os
+from pathlib import Path
+import shutil
+import sys
+
+project_root = Path(__file__).parent.parent.parent
+sys.path.insert(0, str(project_root))
+# Add raganything module path
+raganything_path = project_root.parent / "raganything" / "RAG-Anything"
+if raganything_path.exists():
+ sys.path.insert(0, str(raganything_path))
+
+from dotenv import load_dotenv
+from lightrag.llm.openai import openai_complete_if_cache, openai_embed
+from lightrag.utils import EmbeddingFunc
+from raganything import RAGAnything, RAGAnythingConfig
+
+from src.core.core import get_embedding_config, get_llm_config
+
+load_dotenv(dotenv_path=".env", override=False)
+
+# Use unified logging system
+from src.core.logging import LightRAGLogContext, get_logger
+
+logger = 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
+
+
+class KnowledgeBaseInitializer:
+ """Knowledge base initializer"""
+
+ def __init__(
+ self,
+ kb_name: str,
+ base_dir="./data/knowledge_bases",
+ api_key: str = None,
+ base_url: str = None,
+ progress_tracker: ProgressTracker = None,
+ ):
+ self.kb_name = kb_name
+ self.base_dir = Path(base_dir)
+ self.kb_dir = self.base_dir / kb_name
+
+ # Directory structure
+ self.raw_dir = self.kb_dir / "raw"
+ self.images_dir = self.kb_dir / "images"
+ self.rag_storage_dir = self.kb_dir / "rag_storage"
+ self.content_list_dir = self.kb_dir / "content_list"
+
+ self.api_key = api_key
+ self.base_url = base_url
+ self.embedding_cfg = get_embedding_config()
+ self.progress_tracker = progress_tracker or ProgressTracker(kb_name, self.base_dir)
+
+ def _register_to_config(self):
+ """Register knowledge base to kb_config.json"""
+ config_file = self.base_dir / "kb_config.json"
+
+ # Read existing config
+ if config_file.exists():
+ try:
+ with open(config_file, encoding="utf-8") as f:
+ config = json.load(f)
+ except Exception as e:
+ logger.warning(f"Failed to read config file: {e}, creating new config")
+ config = {"knowledge_bases": {}, "default": None}
+ else:
+ config = {"knowledge_bases": {}, "default": None}
+
+ # Add new knowledge base
+ if "knowledge_bases" not in config:
+ config["knowledge_bases"] = {}
+
+ if self.kb_name not in config.get("knowledge_bases", {}):
+ config["knowledge_bases"][self.kb_name] = {
+ "path": self.kb_name,
+ "description": f"Knowledge base: {self.kb_name}",
+ }
+
+ # If first knowledge base, set as default
+ if not config.get("default"):
+ config["default"] = self.kb_name
+
+ # Save config
+ try:
+ with open(config_file, "w", encoding="utf-8") as f:
+ json.dump(config, indent=2, ensure_ascii=False, fp=f)
+ logger.info(" ✓ Registered to kb_config.json")
+ except Exception as e:
+ logger.warning(f"Failed to update config file: {e}")
+ else:
+ logger.info(" ✓ Already registered in kb_config.json")
+
+ def create_directory_structure(self):
+ """Create knowledge base directory structure"""
+ logger.info(f"Creating directory structure for knowledge base: {self.kb_name}")
+
+ for dir_path in [
+ self.raw_dir,
+ self.images_dir,
+ self.rag_storage_dir,
+ self.content_list_dir,
+ ]:
+ dir_path.mkdir(parents=True, exist_ok=True)
+ logger.info(f" ✓ Created: {dir_path}")
+
+ # Create metadata file
+ metadata = {
+ "name": self.kb_name,
+ "created_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
+ "description": f"Knowledge base: {self.kb_name}",
+ "version": "1.0",
+ }
+
+ metadata_file = self.kb_dir / "metadata.json"
+ with open(metadata_file, "w", encoding="utf-8") as f:
+ json.dump(metadata, indent=2, ensure_ascii=False, fp=f)
+
+ logger.info(f" ✓ Created metadata file: {metadata_file}")
+
+ # Automatically register to kb_config.json
+ self._register_to_config()
+
+ def copy_documents(self, source_files: list[str]):
+ """Copy documents to raw directory"""
+ logger.info(f"Copying {len(source_files)} documents to {self.raw_dir}")
+
+ copied_files = []
+ for source in source_files:
+ source_path = Path(source)
+ if not source_path.exists():
+ logger.warning(f" ✗ Source file not found: {source}")
+ continue
+
+ dest_path = self.raw_dir / source_path.name
+ shutil.copy2(source_path, dest_path)
+ copied_files.append(str(dest_path))
+ logger.info(f" ✓ Copied: {source_path.name}")
+
+ return copied_files
+
+ async def process_documents(self):
+ """Process documents using RAG-Anything"""
+ logger.info("Processing documents with RAG-Anything...")
+ self.progress_tracker.update(
+ ProgressStage.PROCESSING_DOCUMENTS,
+ "Starting to process documents...",
+ current=0,
+ total=0,
+ )
+
+ # Get all documents in raw directory
+ doc_files = []
+ for ext in ["*.pdf", "*.docx", "*.doc", "*.txt", "*.md"]:
+ doc_files.extend(list(self.raw_dir.glob(ext)))
+
+ if not doc_files:
+ logger.warning("No documents found to process")
+ self.progress_tracker.update(
+ ProgressStage.ERROR, "No documents found to process", error="No documents found"
+ )
+ return
+
+ logger.info(f"Found {len(doc_files)} document(s) to process")
+ self.progress_tracker.update(
+ ProgressStage.PROCESSING_DOCUMENTS,
+ f"Found {len(doc_files)} documents, starting to process...",
+ current=0,
+ total=len(doc_files),
+ )
+
+ # Create RAGAnything configuration
+ config = RAGAnythingConfig(
+ working_dir=str(self.rag_storage_dir),
+ enable_image_processing=True,
+ enable_table_processing=True,
+ enable_equation_processing=True,
+ )
+
+ # Get LLM configuration from env_config
+ llm_cfg = get_llm_config()
+ llm_model = llm_cfg["model"]
+
+ # Define LLM model function
+ def llm_model_func(prompt, system_prompt=None, history_messages=[], **kwargs):
+ return openai_complete_if_cache(
+ llm_model,
+ prompt,
+ system_prompt=system_prompt,
+ history_messages=history_messages,
+ api_key=self.api_key,
+ base_url=self.base_url,
+ **kwargs,
+ )
+
+ # Define vision model function for image processing
+ def vision_model_func(
+ prompt,
+ system_prompt=None,
+ history_messages=[],
+ image_data=None,
+ messages=None,
+ **kwargs,
+ ):
+ # If messages format is provided, use it directly
+ if messages:
+ # Remove 'messages' and other message-related params from kwargs to avoid duplicate parameter
+ clean_kwargs = {
+ k: v
+ for k, v in kwargs.items()
+ if k not in ["messages", "prompt", "system_prompt", "history_messages"]
+ }
+ return openai_complete_if_cache(
+ llm_model,
+ prompt="", # Empty prompt when using messages
+ system_prompt=None,
+ history_messages=[],
+ messages=messages,
+ api_key=self.api_key,
+ base_url=self.base_url,
+ **clean_kwargs,
+ )
+ # Traditional single image format
+ if image_data:
+ # Remove message-related params from kwargs to avoid duplicate parameter
+ clean_kwargs = {
+ k: v
+ for k, v in kwargs.items()
+ if k not in ["messages", "prompt", "system_prompt", "history_messages"]
+ }
+ return openai_complete_if_cache(
+ llm_model,
+ prompt="", # Empty prompt when using messages
+ system_prompt=None,
+ history_messages=[],
+ messages=[
+ {"role": "system", "content": system_prompt} if system_prompt else None,
+ (
+ {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": prompt},
+ {
+ "type": "image_url",
+ "image_url": {
+ "url": f"data:image/jpeg;base64,{image_data}"
+ },
+ },
+ ],
+ }
+ if image_data
+ else {"role": "user", "content": prompt}
+ ),
+ ],
+ api_key=self.api_key,
+ base_url=self.base_url,
+ **clean_kwargs,
+ )
+ # Pure text format
+ return llm_model_func(prompt, system_prompt, history_messages, **kwargs)
+
+ # Define embedding function
+ embedding_cfg = self.embedding_cfg
+ embedding_api_key = embedding_cfg["api_key"] or self.api_key
+ embedding_base_url = embedding_cfg["base_url"] or self.base_url
+ embedding_func = EmbeddingFunc(
+ embedding_dim=embedding_cfg["dim"],
+ max_token_size=embedding_cfg["max_tokens"],
+ func=lambda texts: openai_embed(
+ texts,
+ model=embedding_cfg["model"],
+ api_key=embedding_api_key,
+ base_url=embedding_base_url,
+ ),
+ )
+
+ # Initialize RAGAnything with log forwarding
+ with LightRAGLogContext(scene="knowledge_init"):
+ rag = RAGAnything(
+ config=config,
+ llm_model_func=llm_model_func,
+ vision_model_func=vision_model_func,
+ embedding_func=embedding_func,
+ )
+
+ # Ensure LightRAG is initialized
+ await rag._ensure_lightrag_initialized()
+
+ # Process each document using RAGAnything's process_document_complete
+ for idx, doc_file in enumerate(doc_files, 1):
+ logger.info(f"\nProcessing: {doc_file.name}")
+ self.progress_tracker.update(
+ ProgressStage.PROCESSING_FILE,
+ f"Processing: {doc_file.name}",
+ current=idx,
+ total=len(doc_files),
+ file_name=doc_file.name,
+ )
+
+ try:
+ # Use RAGAnything's process_document_complete method
+ # This method handles document parsing, content extraction, and insertion
+ await rag.process_document_complete(
+ file_path=str(doc_file),
+ output_dir=str(self.content_list_dir),
+ parse_method="auto",
+ )
+ logger.info(f" ✓ Successfully processed: {doc_file.name}")
+
+ # Content list should be automatically saved in output_dir
+ doc_name = doc_file.stem
+ content_list_file = self.content_list_dir / f"{doc_name}.json"
+ if content_list_file.exists():
+ logger.info(f" ✓ Content list saved: {content_list_file.name}")
+
+ except Exception as e:
+ error_msg = str(e)
+ logger.error(f" ✗ Error processing {doc_file.name}: {error_msg}")
+ import traceback
+
+ logger.error(traceback.format_exc())
+ self.progress_tracker.update(
+ ProgressStage.ERROR,
+ f"Failed to process file: {doc_file.name}",
+ current=idx,
+ total=len(doc_files),
+ file_name=doc_file.name,
+ error=error_msg,
+ )
+
+ # Copy extracted images
+ rag_images_dir = self.rag_storage_dir / "images"
+ if rag_images_dir.exists():
+ logger.info(f"\nCopying extracted images to {self.images_dir}")
+ for img_file in rag_images_dir.glob("*"):
+ if img_file.is_file():
+ dest = self.images_dir / img_file.name
+ shutil.copy2(img_file, dest)
+ logger.info(" ✓ Copied images")
+
+ logger.info("\n✓ Document processing completed!")
+
+ # Fix structure: flatten nested content_list directories
+ await self.fix_structure()
+
+ # Display statistics
+ await self.display_statistics(rag)
+
+ async def fix_structure(self):
+ """
+ Fix the nested structure created by process_document_complete.
+ Flattens content_list directories and moves images to the correct location.
+ """
+ logger.info("\nFixing directory structure...")
+
+ # Find nested content lists
+ content_list_moves = []
+ for doc_dir in self.content_list_dir.glob("*"):
+ if not doc_dir.is_dir():
+ continue
+
+ auto_dir = doc_dir / "auto"
+ if not auto_dir.exists():
+ continue
+
+ # Find the _content_list.json file
+ for json_file in auto_dir.glob("*_content_list.json"):
+ target_file = self.content_list_dir / f"{doc_dir.name}.json"
+ content_list_moves.append((json_file, target_file))
+
+ # Move content list files
+ for source, target in content_list_moves:
+ try:
+ shutil.copy2(source, target)
+ logger.info(f" ✓ Moved: {source.name} -> {target.name}")
+ except Exception as e:
+ logger.error(f" ✗ Error moving {source.name}: {e!s}")
+
+ # Find and move nested images
+ for doc_dir in self.content_list_dir.glob("*"):
+ if not doc_dir.is_dir():
+ continue
+
+ auto_dir = doc_dir / "auto"
+ if not auto_dir.exists():
+ continue
+
+ images_dir = auto_dir / "images"
+ if images_dir.exists() and images_dir.is_dir():
+ image_count = 0
+ # Ensure target directory exists
+ self.images_dir.mkdir(parents=True, exist_ok=True)
+
+ for img_file in images_dir.glob("*"):
+ if img_file.is_file() and img_file.exists():
+ target_img = self.images_dir / img_file.name
+ if not target_img.exists():
+ try:
+ # Ensure source file exists
+ if not img_file.exists():
+ logger.warning(f" ⚠ Source image not found: {img_file}")
+ continue
+ shutil.copy2(img_file, target_img)
+ image_count += 1
+ except FileNotFoundError:
+ logger.error(
+ f" ✗ Error moving image {img_file.name}: Source file not found: {img_file}"
+ )
+ except Exception as e:
+ logger.error(f" ✗ Error moving image {img_file.name}: {e!s}")
+
+ if image_count > 0:
+ logger.info(f" ✓ Moved {image_count} images from {doc_dir.name}/auto/images/")
+
+ # Clean up nested directories
+ for doc_dir in self.content_list_dir.glob("*"):
+ if doc_dir.is_dir():
+ try:
+ shutil.rmtree(doc_dir)
+ logger.info(f" ✓ Cleaned up: {doc_dir.name}/")
+ except Exception as e:
+ logger.error(f" ✗ Error removing {doc_dir.name}: {e!s}")
+
+ logger.info("✓ Structure fixed!")
+
+ def extract_numbered_items(self, batch_size: int = 20):
+ """
+ Extract numbered items from knowledge base (Definition, Proposition, Equation, Figure, etc.)
+
+ Args:
+ batch_size: Number of items to process per batch
+ """
+ logger.info("\n" + "=" * 60)
+ logger.info("🔍 Starting to extract numbered items...")
+ logger.info("=" * 60 + "\n")
+
+ self.progress_tracker.update(
+ ProgressStage.EXTRACTING_ITEMS,
+ "Starting to extract numbered items...",
+ current=0,
+ total=0,
+ )
+
+ output_file = self.kb_dir / "numbered_items.json"
+ content_list_files = sorted(self.content_list_dir.glob("*.json"))
+
+ if not content_list_files:
+ logger.warning("No content_list files found, skipping numbered items extraction")
+ return
+
+ logger.info(f"Found {len(content_list_files)} content_list files")
+ self.progress_tracker.update(
+ ProgressStage.EXTRACTING_ITEMS,
+ f"Found {len(content_list_files)} files, starting extraction...",
+ current=0,
+ total=len(content_list_files),
+ )
+
+ try:
+ # Process all content_list files
+ for idx, content_list_file in enumerate(content_list_files, 1):
+ logger.info(
+ f"\nProcessing file [{idx}/{len(content_list_files)}]: {content_list_file.name}"
+ )
+ self.progress_tracker.update(
+ ProgressStage.EXTRACTING_ITEMS,
+ f"Extracting: {content_list_file.name}",
+ current=idx,
+ total=len(content_list_files),
+ file_name=content_list_file.name,
+ )
+
+ # First file doesn't merge (creates new file), subsequent files merge into existing results
+ merge = idx > 1
+
+ process_content_list(
+ content_list_file=content_list_file,
+ output_file=output_file,
+ api_key=self.api_key,
+ base_url=self.base_url,
+ batch_size=batch_size,
+ merge=merge,
+ )
+
+ logger.info(f"\n{'=' * 60}")
+ logger.info("✓ Numbered items extraction completed!")
+ logger.info(f"Output file: {output_file}")
+ logger.info(f"{'=' * 60}\n")
+
+ self.progress_tracker.update(
+ ProgressStage.COMPLETED,
+ "Knowledge base initialization completed!",
+ current=len(content_list_files),
+ total=len(content_list_files),
+ )
+
+ except Exception as e:
+ error_msg = str(e)
+ logger.error(f"\n✗ Numbered items extraction failed: {error_msg}")
+ import traceback
+
+ traceback.print_exc()
+ self.progress_tracker.update(
+ ProgressStage.ERROR, "Numbered items extraction failed", error=error_msg
+ )
+
+ async def display_statistics(self, rag: RAGAnything):
+ """Display knowledge base statistics"""
+ logger.info("\n" + "=" * 50)
+ logger.info("Knowledge Base Statistics")
+ logger.info("=" * 50)
+
+ # Count files
+ raw_files = list(self.raw_dir.glob("*"))
+ image_files = list(self.images_dir.glob("*"))
+ content_files = list(self.content_list_dir.glob("*.json"))
+
+ logger.info(f"Raw documents: {len(raw_files)}")
+ logger.info(f"Extracted images: {len(image_files)}")
+ logger.info(f"Content lists: {len(content_files)}")
+
+ # RAG storage info
+ if hasattr(rag, "lightrag") and rag.lightrag:
+ try:
+ # Try to get entity and relation counts
+ entities_file = self.rag_storage_dir / "kv_store_full_entities.json"
+ relations_file = self.rag_storage_dir / "kv_store_full_relations.json"
+ chunks_file = self.rag_storage_dir / "kv_store_text_chunks.json"
+
+ if entities_file.exists():
+ with open(entities_file, encoding="utf-8") as f:
+ entities = json.load(f)
+ logger.info(f"Knowledge entities: {len(entities)}")
+
+ if relations_file.exists():
+ with open(relations_file, encoding="utf-8") as f:
+ relations = json.load(f)
+ logger.info(f"Knowledge relations: {len(relations)}")
+
+ if chunks_file.exists():
+ with open(chunks_file, encoding="utf-8") as f:
+ chunks = json.load(f)
+ logger.info(f"Text chunks: {len(chunks)}")
+
+ except Exception as e:
+ logger.warning(f"Could not retrieve statistics: {e!s}")
+
+ logger.info("=" * 50)
+
+
+async def main():
+ """Main function"""
+ parser = argparse.ArgumentParser(
+ description="Initialize a new knowledge base from documents",
+ formatter_class=argparse.RawDescriptionHelpFormatter,
+ epilog="""
+Example usage:
+ # Initialize new knowledge base from documents (with auto extraction)
+ python init_knowledge_base.py my_kb --docs document1.pdf document2.pdf
+
+ # Initialize from a directory
+ python init_knowledge_base.py my_kb --docs-dir ./my_documents/
+
+ # Initialize without numbered items extraction
+ python init_knowledge_base.py my_kb --docs document.pdf --skip-extract
+
+ # Adjust batch size for extraction (for large knowledge bases)
+ python init_knowledge_base.py my_kb --docs document.pdf --batch-size 30
+ """,
+ )
+
+ parser.add_argument("name", help="Knowledge base name")
+ parser.add_argument("--docs", nargs="+", help="Document files to process")
+ parser.add_argument("--docs-dir", help="Directory containing documents to process")
+ parser.add_argument(
+ "--base-dir",
+ default="./knowledge_bases",
+ help="Base directory for knowledge bases (default: ./knowledge_bases)",
+ )
+ parser.add_argument(
+ "--api-key", default=os.getenv("LLM_BINDING_API_KEY"), help="OpenAI API key"
+ )
+ parser.add_argument("--base-url", default=os.getenv("LLM_BINDING_HOST"), help="API base URL")
+ parser.add_argument(
+ "--skip-processing",
+ action="store_true",
+ help="Skip document processing (only create structure)",
+ )
+ parser.add_argument(
+ "--skip-extract",
+ action="store_true",
+ help="Skip numbered items extraction after initialization",
+ )
+ parser.add_argument(
+ "--batch-size",
+ type=int,
+ default=20,
+ help="Batch size for numbered items extraction (default: 20)",
+ )
+
+ args = parser.parse_args()
+
+ # Check API key
+ if not args.skip_processing and not args.api_key:
+ logger.error("Error: OpenAI API key required")
+ logger.error("Set LLM_BINDING_API_KEY environment variable or use --api-key option")
+ return
+
+ # Collect document files
+ doc_files = []
+ if args.docs:
+ doc_files.extend(args.docs)
+
+ if args.docs_dir:
+ docs_dir = Path(args.docs_dir)
+ if docs_dir.exists() and docs_dir.is_dir():
+ for ext in ["*.pdf", "*.docx", "*.doc", "*.txt", "*.md"]:
+ doc_files.extend([str(f) for f in docs_dir.glob(ext)])
+ else:
+ logger.error(f"Error: Documents directory not found: {args.docs_dir}")
+ return
+
+ if not args.skip_processing and not doc_files:
+ logger.error("Error: No documents specified")
+ logger.error("Use --docs or --docs-dir to specify documents")
+ return
+
+ # Initialize knowledge base
+ logger.info(f"\n{'=' * 60}")
+ logger.info(f"Initializing Knowledge Base: {args.name}")
+ logger.info(f"{'=' * 60}\n")
+
+ initializer = KnowledgeBaseInitializer(
+ kb_name=args.name, base_dir=args.base_dir, api_key=args.api_key, base_url=args.base_url
+ )
+
+ # Create directory structure
+ initializer.create_directory_structure()
+
+ # Copy documents
+ if doc_files:
+ copied_files = initializer.copy_documents(doc_files)
+ logger.info(f"\nCopied {len(copied_files)} file(s) to raw directory")
+
+ # Process documents
+ if not args.skip_processing:
+ await initializer.process_documents()
+ else:
+ logger.info("\nSkipping document processing (--skip-processing specified)")
+
+ # Extract numbered items (automatically after processing)
+ if not args.skip_processing and not args.skip_extract:
+ initializer.extract_numbered_items(batch_size=args.batch_size)
+ elif args.skip_extract:
+ logger.info("\nSkipping numbered items extraction (--skip-extract specified)")
+
+ logger.info(f"\n{'=' * 60}")
+ logger.info(f"✓ Knowledge base '{args.name}' initialized successfully!")
+ logger.info(f"Location: {initializer.kb_dir}")
+ logger.info(f"{'=' * 60}\n")
+
+
+if __name__ == "__main__":
+ # Logging configuration already completed during module import, no need to configure again here
+ asyncio.run(main())
diff --git a/src/knowledge/kb.py b/src/knowledge/kb.py
new file mode 100644
index 000000000..eea6aff82
--- /dev/null
+++ b/src/knowledge/kb.py
@@ -0,0 +1,19 @@
+#!/usr/bin/env python
+"""
+Knowledge Base Management Tool - Standalone Entry Script
+Can be run directly: python knowledge_init/kb.py [command]
+"""
+
+from pathlib import Path
+import sys
+
+# Ensure project root is in sys.path
+project_root = Path(__file__).parent.parent.parent
+if str(project_root) not in sys.path:
+ sys.path.insert(0, str(project_root))
+
+# Import main function from startup script
+from src.knowledge.start_kb import main
+
+if __name__ == "__main__":
+ main()
diff --git a/src/knowledge/manager.py b/src/knowledge/manager.py
new file mode 100644
index 000000000..c3b49b423
--- /dev/null
+++ b/src/knowledge/manager.py
@@ -0,0 +1,457 @@
+#!/usr/bin/env python
+"""
+Knowledge Base Manager
+
+Manages multiple knowledge bases and provides utilities for accessing them.
+"""
+
+import json
+from pathlib import Path
+
+
+class KnowledgeBaseManager:
+ """Manager for knowledge bases"""
+
+ def __init__(self, base_dir="./data/knowledge_bases"):
+ self.base_dir = Path(base_dir)
+ self.base_dir.mkdir(parents=True, exist_ok=True)
+
+ # Config file to track knowledge bases
+ self.config_file = self.base_dir / "kb_config.json"
+ self.config = self._load_config()
+
+ def _load_config(self) -> dict:
+ """Load knowledge base configuration"""
+ if self.config_file.exists():
+ with open(self.config_file, encoding="utf-8") as f:
+ return json.load(f)
+ return {"knowledge_bases": {}, "default": None}
+
+ def _save_config(self):
+ """Save knowledge base configuration"""
+ with open(self.config_file, "w", encoding="utf-8") as f:
+ json.dump(self.config, f, indent=2, ensure_ascii=False)
+
+ def list_knowledge_bases(self) -> list[str]:
+ """List all available knowledge bases from kb_config.json"""
+ kb_list = []
+
+ # Read knowledge base list from config file (this is the authoritative source)
+ config_kbs = self.config.get("knowledge_bases", {})
+
+ for kb_name in config_kbs.keys():
+ # Verify knowledge base directory exists
+ kb_dir = self.base_dir / kb_name
+ if kb_dir.exists() and kb_dir.is_dir():
+ kb_list.append(kb_name)
+ else:
+ # If in config but directory doesn't exist, log warning but don't add
+ print(
+ f"Warning: Knowledge base '{kb_name}' is in config but directory does not exist: {kb_dir}"
+ )
+
+ # If no config file or config is empty, fallback to scanning directory (backward compatibility)
+ if not kb_list and self.base_dir.exists():
+ for item in self.base_dir.iterdir():
+ if item.is_dir() and item.name != "__pycache__":
+ metadata_file = item / "metadata.json"
+ if metadata_file.exists():
+ kb_list.append(item.name)
+
+ return sorted(kb_list)
+
+ def register_knowledge_base(self, name: str, description: str = "", set_default: bool = False):
+ """Register a knowledge base"""
+ kb_dir = self.base_dir / name
+ if not kb_dir.exists():
+ raise ValueError(f"Knowledge base directory does not exist: {kb_dir}")
+
+ if "knowledge_bases" not in self.config:
+ self.config["knowledge_bases"] = {}
+
+ self.config["knowledge_bases"][name] = {"path": name, "description": description}
+
+ if set_default or not self.config.get("default"):
+ self.config["default"] = name
+
+ self._save_config()
+
+ def get_knowledge_base_path(self, name: str | None = None) -> Path:
+ """Get path to a knowledge base"""
+ if name is None:
+ name = self.config.get("default")
+ if name is None:
+ raise ValueError("No default knowledge base set")
+
+ kb_dir = self.base_dir / name
+ if not kb_dir.exists():
+ raise ValueError(f"Knowledge base not found: {name}")
+
+ return kb_dir
+
+ def get_rag_storage_path(self, name: str | None = None) -> Path:
+ """Get RAG storage path for a knowledge base"""
+ kb_dir = self.get_knowledge_base_path(name)
+ rag_storage = kb_dir / "rag_storage"
+ if not rag_storage.exists():
+ raise ValueError(f"RAG storage not found for knowledge base: {name or 'default'}")
+ return rag_storage
+
+ def get_images_path(self, name: str | None = None) -> Path:
+ """Get images path for a knowledge base"""
+ kb_dir = self.get_knowledge_base_path(name)
+ return kb_dir / "images"
+
+ def get_content_list_path(self, name: str | None = None) -> Path:
+ """Get content list path for a knowledge base"""
+ kb_dir = self.get_knowledge_base_path(name)
+ return kb_dir / "content_list"
+
+ def get_raw_path(self, name: str | None = None) -> Path:
+ """Get raw documents path for a knowledge base"""
+ kb_dir = self.get_knowledge_base_path(name)
+ return kb_dir / "raw"
+
+ def set_default(self, name: str):
+ """Set default knowledge base"""
+ if name not in self.list_knowledge_bases():
+ raise ValueError(f"Knowledge base not found: {name}")
+
+ self.config["default"] = name
+ self._save_config()
+
+ def get_default(self) -> str | None:
+ """Get default knowledge base name"""
+ return self.config.get("default")
+
+ def get_metadata(self, name: str | None = None) -> dict:
+ """Get knowledge base metadata"""
+ kb_dir = self.get_knowledge_base_path(name)
+ metadata_file = kb_dir / "metadata.json"
+
+ if metadata_file.exists():
+ with open(metadata_file, encoding="utf-8") as f:
+ return json.load(f)
+
+ return {}
+
+ def get_info(self, name: str | None = None) -> dict:
+ """Get detailed information about a knowledge base.
+
+ This method:
+ 1. Gets the KB name (from parameter or default)
+ 2. Reads metadata.json from the KB directory
+ 3. Collects statistics about files and RAG status
+ """
+ kb_name = name or self.get_default()
+ if kb_name is None:
+ raise ValueError("No knowledge base name provided and no default set")
+
+ # Get knowledge base path
+ kb_dir = self.base_dir / kb_name
+ if not kb_dir.exists():
+ raise ValueError(f"Knowledge base directory does not exist: {kb_dir}")
+
+ # Verify knowledge base is in config (if not, give warning but don't block)
+ if kb_name not in self.config.get("knowledge_bases", {}):
+ print(
+ f"Warning: Knowledge base '{kb_name}' is not in kb_config.json, but directory exists"
+ )
+
+ info = {
+ "name": kb_name,
+ "path": str(kb_dir),
+ "is_default": kb_name == self.get_default(),
+ "metadata": {},
+ }
+
+ # Read metadata.json (if exists)
+ metadata_file = kb_dir / "metadata.json"
+ if metadata_file.exists():
+ try:
+ with open(metadata_file, encoding="utf-8") as f:
+ info["metadata"] = json.load(f)
+ except Exception as e:
+ print(f"Warning: Failed to read metadata.json for KB '{kb_name}': {e}")
+ info["metadata"] = {}
+ else:
+ # metadata.json doesn't exist, use empty dict
+ info["metadata"] = {}
+
+ # Count files - handle errors gracefully
+ raw_dir = kb_dir / "raw"
+ images_dir = kb_dir / "images"
+ content_list_dir = kb_dir / "content_list"
+ rag_storage_dir = kb_dir / "rag_storage"
+
+ try:
+ raw_count = (
+ len([f for f in raw_dir.iterdir() if f.is_file()]) if raw_dir.exists() else 0
+ )
+ except Exception:
+ raw_count = 0
+
+ try:
+ images_count = (
+ len([f for f in images_dir.iterdir() if f.is_file()]) if images_dir.exists() else 0
+ )
+ except Exception:
+ images_count = 0
+
+ try:
+ content_lists_count = (
+ len(list(content_list_dir.glob("*.json"))) if content_list_dir.exists() else 0
+ )
+ except Exception:
+ content_lists_count = 0
+
+ info["statistics"] = {
+ "raw_documents": raw_count,
+ "images": images_count,
+ "content_lists": content_lists_count,
+ "rag_initialized": rag_storage_dir.exists() and rag_storage_dir.is_dir(),
+ }
+
+ # Try to get RAG statistics
+ if rag_storage_dir.exists() and rag_storage_dir.is_dir():
+ try:
+ entities_file = rag_storage_dir / "kv_store_full_entities.json"
+ relations_file = rag_storage_dir / "kv_store_full_relations.json"
+ chunks_file = rag_storage_dir / "kv_store_text_chunks.json"
+
+ rag_stats = {}
+ if entities_file.exists():
+ try:
+ with open(entities_file, encoding="utf-8") as f:
+ entities_data = json.load(f)
+ rag_stats["entities"] = (
+ len(entities_data) if isinstance(entities_data, (list, dict)) else 0
+ )
+ except Exception:
+ pass
+
+ if relations_file.exists():
+ try:
+ with open(relations_file, encoding="utf-8") as f:
+ relations_data = json.load(f)
+ rag_stats["relations"] = (
+ len(relations_data)
+ if isinstance(relations_data, (list, dict))
+ else 0
+ )
+ except Exception:
+ pass
+
+ if chunks_file.exists():
+ try:
+ with open(chunks_file, encoding="utf-8") as f:
+ chunks_data = json.load(f)
+ rag_stats["chunks"] = (
+ len(chunks_data) if isinstance(chunks_data, (list, dict)) else 0
+ )
+ except Exception:
+ pass
+
+ if rag_stats:
+ info["statistics"]["rag"] = rag_stats
+ except Exception:
+ pass
+
+ return info
+
+ def delete_knowledge_base(self, name: str, confirm: bool = False) -> bool:
+ """
+ Delete a knowledge base
+
+ Args:
+ name: Knowledge base name
+ confirm: If True, skip confirmation (use with caution!)
+
+ Returns:
+ True if deleted successfully
+ """
+ import shutil
+
+ if name not in self.list_knowledge_bases():
+ raise ValueError(f"Knowledge base not found: {name}")
+
+ kb_dir = self.get_knowledge_base_path(name)
+
+ if not confirm:
+ # Ask for confirmation in CLI
+ print(f"⚠️ Warning: This will permanently delete the knowledge base '{name}'")
+ print(f" Path: {kb_dir}")
+ response = input("Are you sure? Type 'yes' to confirm: ")
+ if response.lower() != "yes":
+ print("Deletion cancelled.")
+ return False
+
+ # Delete the directory
+ shutil.rmtree(kb_dir)
+
+ # Remove from config
+ if name in self.config.get("knowledge_bases", {}):
+ del self.config["knowledge_bases"][name]
+
+ # Update default if this was the default
+ if self.config.get("default") == name:
+ remaining = self.list_knowledge_bases()
+ self.config["default"] = remaining[0] if remaining else None
+
+ self._save_config()
+ return True
+
+ def clean_rag_storage(self, name: str | None = None, backup: bool = True) -> bool:
+ """
+ Clean (delete) RAG storage for a knowledge base
+ Useful when RAG data is corrupted
+
+ Args:
+ name: Knowledge base name (default if not specified)
+ backup: If True, backup the RAG storage before deleting
+
+ Returns:
+ True if cleaned successfully
+ """
+ from datetime import datetime
+ import shutil
+
+ kb_name = name or self.get_default()
+ kb_dir = self.get_knowledge_base_path(kb_name)
+ rag_storage_dir = kb_dir / "rag_storage"
+
+ if not rag_storage_dir.exists():
+ print(f"RAG storage does not exist for '{kb_name}'")
+ return False
+
+ # Backup if requested
+ if backup:
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
+ backup_dir = kb_dir / f"rag_storage_backup_{timestamp}"
+ shutil.copytree(rag_storage_dir, backup_dir)
+ print(f"✓ Backed up to: {backup_dir}")
+
+ # Delete RAG storage
+ shutil.rmtree(rag_storage_dir)
+ rag_storage_dir.mkdir(parents=True, exist_ok=True)
+
+ print(f"✓ RAG storage cleaned for '{kb_name}'")
+ return True
+
+
+def main():
+ """Command-line interface for knowledge base manager"""
+ import argparse
+
+ parser = argparse.ArgumentParser(description="Knowledge Base Manager")
+ parser.add_argument(
+ "--base-dir", default="./knowledge_bases", help="Base directory for knowledge bases"
+ )
+
+ subparsers = parser.add_subparsers(dest="command", help="Commands")
+
+ # List command
+ subparsers.add_parser("list", help="List all knowledge bases")
+
+ # Info command
+ info_parser = subparsers.add_parser("info", help="Show knowledge base information")
+ info_parser.add_argument(
+ "name", nargs="?", help="Knowledge base name (default if not specified)"
+ )
+
+ # Set default command
+ default_parser = subparsers.add_parser("set-default", help="Set default knowledge base")
+ default_parser.add_argument("name", help="Knowledge base name")
+
+ # Delete command
+ delete_parser = subparsers.add_parser("delete", help="Delete a knowledge base")
+ delete_parser.add_argument("name", help="Knowledge base name")
+ delete_parser.add_argument("--force", action="store_true", help="Skip confirmation")
+
+ # Clean RAG command
+ clean_parser = subparsers.add_parser(
+ "clean-rag", help="Clean RAG storage (useful for corrupted data)"
+ )
+ clean_parser.add_argument(
+ "name", nargs="?", help="Knowledge base name (default if not specified)"
+ )
+ clean_parser.add_argument(
+ "--no-backup", action="store_true", help="Don't backup before cleaning"
+ )
+
+ args = parser.parse_args()
+
+ manager = KnowledgeBaseManager(args.base_dir)
+
+ if args.command == "list":
+ kb_list = manager.list_knowledge_bases()
+ default_kb = manager.get_default()
+
+ print("\nAvailable Knowledge Bases:")
+ print("=" * 60)
+ if not kb_list:
+ print("No knowledge bases found")
+ else:
+ for kb_name in kb_list:
+ default_marker = " (default)" if kb_name == default_kb else ""
+ print(f" • {kb_name}{default_marker}")
+ print()
+
+ elif args.command == "info":
+ try:
+ info = manager.get_info(args.name)
+
+ print("\nKnowledge Base Information:")
+ print("=" * 60)
+ print(f"Name: {info['name']}")
+ print(f"Path: {info['path']}")
+ print(f"Default: {'Yes' if info['is_default'] else 'No'}")
+
+ if info.get("metadata"):
+ print("\nMetadata:")
+ for key, value in info["metadata"].items():
+ print(f" {key}: {value}")
+
+ print("\nStatistics:")
+ stats = info["statistics"]
+ print(f" Raw documents: {stats['raw_documents']}")
+ print(f" Images: {stats['images']}")
+ print(f" Content lists: {stats['content_lists']}")
+ print(f" RAG initialized: {'Yes' if stats['rag_initialized'] else 'No'}")
+
+ if "rag" in stats:
+ print("\n RAG Statistics:")
+ for key, value in stats["rag"].items():
+ print(f" {key}: {value}")
+
+ print()
+ except Exception as e:
+ print(f"Error: {e!s}")
+
+ elif args.command == "set-default":
+ try:
+ manager.set_default(args.name)
+ print(f"✓ Set '{args.name}' as default knowledge base")
+ except Exception as e:
+ print(f"Error: {e!s}")
+
+ elif args.command == "delete":
+ try:
+ success = manager.delete_knowledge_base(args.name, confirm=args.force)
+ if success:
+ print(f"✓ Deleted knowledge base '{args.name}'")
+ except Exception as e:
+ print(f"Error: {e!s}")
+
+ elif args.command == "clean-rag":
+ try:
+ manager.clean_rag_storage(args.name, backup=not args.no_backup)
+ except Exception as e:
+ print(f"Error: {e!s}")
+
+ else:
+ parser.print_help()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/src/knowledge/progress_tracker.py b/src/knowledge/progress_tracker.py
new file mode 100644
index 000000000..449538edb
--- /dev/null
+++ b/src/knowledge/progress_tracker.py
@@ -0,0 +1,191 @@
+"""
+Progress Tracker - Tracks knowledge base initialization progress
+"""
+
+import asyncio
+from collections.abc import Callable
+from datetime import datetime
+from enum import Enum
+import json
+from pathlib import Path
+import sys
+
+# Add project root to path
+project_root = Path(__file__).parent.parent.parent
+sys.path.insert(0, str(project_root))
+
+# Use unified logging system
+from src.core.logging import get_logger
+
+_logger = get_logger("KnowledgeInit")
+
+
+def _get_logger():
+ return _logger
+
+
+class ProgressStage(Enum):
+ """Initialization stage"""
+
+ INITIALIZING = "initializing" # Initializing
+ PROCESSING_DOCUMENTS = "processing_documents" # Processing documents
+ PROCESSING_FILE = "processing_file" # Processing single file
+ EXTRACTING_ITEMS = "extracting_items" # Extracting numbered items
+ COMPLETED = "completed" # Completed
+ ERROR = "error" # Error
+
+
+class ProgressTracker:
+ """Progress tracker"""
+
+ def __init__(self, kb_name: str, base_dir: Path):
+ self.kb_name = kb_name
+ self.base_dir = base_dir
+ self.kb_dir = base_dir / kb_name
+ self.progress_file = self.kb_dir / ".progress.json"
+ self._callbacks: list = [] # Support multiple callbacks
+ self.task_id: str | None = None # Task ID (for log identification)
+
+ def set_callback(self, callback: Callable[[dict], None]):
+ """Set progress callback function (can be called multiple times to add multiple callbacks)"""
+ if callback not in self._callbacks:
+ self._callbacks.append(callback)
+
+ def remove_callback(self, callback: Callable[[dict], None]):
+ """Remove progress callback function"""
+ if callback in self._callbacks:
+ self._callbacks.remove(callback)
+
+ def _notify(self, progress: dict):
+ """Notify progress update (call all callbacks)"""
+ # Try to send via broadcaster (if available)
+ try:
+ from src.api.utils.progress_broadcaster import ProgressBroadcaster
+
+ broadcaster = ProgressBroadcaster.get_instance()
+
+ # Try to get current event loop and broadcast
+ try:
+ loop = asyncio.get_running_loop()
+ # If event loop is running, use create_task (non-blocking)
+ asyncio.create_task(broadcaster.broadcast(self.kb_name, progress))
+ except RuntimeError:
+ # No running event loop, try to get main event loop
+ try:
+ # Try to get main event loop (FastAPI main loop)
+ loop = asyncio.get_event_loop()
+ if loop.is_running():
+ # If loop is running, create task
+ asyncio.create_task(broadcaster.broadcast(self.kb_name, progress))
+ else:
+ # If loop exists but not running, try to run (may fail, but doesn't affect main flow)
+ try:
+ loop.run_until_complete(broadcaster.broadcast(self.kb_name, progress))
+ except RuntimeError:
+ # Cannot run, ignore
+ pass
+ except RuntimeError:
+ # Completely unable to get event loop, use thread-safe method
+ # Try to send via call_soon_threadsafe (if possible)
+ try:
+ # Get main event loop (if exists)
+ import threading
+
+ # If we're in background thread, need to find main event loop
+ # Here we use a simple strategy: save progress to file, WebSocket will poll
+ except:
+ pass
+ except (ImportError, Exception):
+ # Broadcaster unavailable or error, continue using callbacks
+ # Don't print error to avoid interfering with normal flow
+ pass
+
+ # Call all registered callbacks
+ for callback in self._callbacks:
+ try:
+ callback(progress)
+ except Exception as e:
+ print(f"[ProgressTracker] Callback error: {e}")
+
+ def _save_progress(self, progress: dict):
+ """Save progress to file"""
+ try:
+ self.kb_dir.mkdir(parents=True, exist_ok=True)
+ with open(self.progress_file, "w", encoding="utf-8") as f:
+ json.dump(progress, f, indent=2, ensure_ascii=False)
+ except Exception as e:
+ print(f"[ProgressTracker] Failed to save progress: {e}")
+
+ def update(
+ self,
+ stage: ProgressStage,
+ message: str = "",
+ current: int = 0,
+ total: int = 0,
+ file_name: str = "",
+ error: str | None = None,
+ ):
+ """Update progress"""
+ progress = {
+ "kb_name": self.kb_name,
+ "stage": stage.value,
+ "message": message,
+ "current": current,
+ "total": total,
+ "file_name": file_name,
+ "progress_percent": int(current / total * 100) if total > 0 else 0,
+ "timestamp": datetime.now().isoformat(),
+ }
+
+ if error:
+ progress["error"] = error
+ progress["stage"] = ProgressStage.ERROR.value
+
+ # Output to logger (terminal and log file)
+ try:
+ logger = _get_logger()
+ prefix = f"[{self.task_id}]" if self.task_id else ""
+
+ if total > 0:
+ percent = progress["progress_percent"]
+ progress_msg = f"{prefix} {message} ({current}/{total}, {percent}%)"
+ if file_name:
+ progress_msg += f" - File: {file_name}"
+ else:
+ progress_msg = f"{prefix} {message}"
+ if file_name:
+ progress_msg += f" - File: {file_name}"
+
+ if error:
+ logger.error(f"{progress_msg} - Error: {error}")
+ else:
+ logger.progress(progress_msg)
+ except Exception:
+ # If logging fails, print to console
+ prefix = f"[{self.task_id}]" if self.task_id else ""
+ print(f"{prefix} [ProgressTracker] {message} ({current}/{total if total > 0 else '?'})")
+ if error:
+ print(f"{prefix} [ProgressTracker] Error: {error}")
+
+ self._save_progress(progress)
+ self._notify(progress)
+
+ def get_progress(self) -> dict | None:
+ """Get current progress"""
+ if not self.progress_file.exists():
+ return None
+
+ try:
+ with open(self.progress_file, encoding="utf-8") as f:
+ return json.load(f)
+ except Exception as e:
+ print(f"[ProgressTracker] Failed to read progress: {e}")
+ return None
+
+ def clear(self):
+ """Clear progress file"""
+ if self.progress_file.exists():
+ try:
+ self.progress_file.unlink()
+ except Exception as e:
+ print(f"[ProgressTracker] Failed to clear progress: {e}")
diff --git a/src/knowledge/start_kb.py b/src/knowledge/start_kb.py
new file mode 100644
index 000000000..6d2541719
--- /dev/null
+++ b/src/knowledge/start_kb.py
@@ -0,0 +1,534 @@
+#!/usr/bin/env python
+"""
+Knowledge Base Management Startup Script - Unified Entry Point
+Provides knowledge base initialization, management, querying, and other functions
+"""
+
+import argparse
+import asyncio
+from pathlib import Path
+import sys
+
+# Set paths - compatible with both direct execution and module import
+try:
+ from .config import KNOWLEDGE_BASES_DIR, get_env_config, setup_paths
+
+ setup_paths()
+ from .extract_numbered_items import process_content_list
+ from .initializer import KnowledgeBaseInitializer
+ from .manager import KnowledgeBaseManager
+except ImportError:
+ # If relative import fails, means this file is run directly
+ # Add parent directory to path
+ sys.path.insert(0, str(Path(__file__).parent.parent.parent))
+ from src.knowledge.config import KNOWLEDGE_BASES_DIR, get_env_config, setup_paths
+
+ setup_paths()
+ from src.knowledge.extract_numbered_items import process_content_list
+ from src.knowledge.initializer import KnowledgeBaseInitializer
+ from src.knowledge.manager import KnowledgeBaseManager
+
+
+def list_knowledge_bases():
+ """List all knowledge bases"""
+ manager = KnowledgeBaseManager(str(KNOWLEDGE_BASES_DIR))
+ kb_list = manager.list_knowledge_bases()
+ default_kb = manager.get_default()
+
+ print("\n" + "=" * 60)
+ print("📚 Available Knowledge Bases")
+ print("=" * 60)
+
+ if not kb_list:
+ print(" ⚠️ No knowledge bases yet")
+ print("\nTip: Use 'init' command to create a new knowledge base")
+ else:
+ for kb_name in kb_list:
+ default_marker = " ⭐ (default)" if kb_name == default_kb else ""
+ print(f" • {kb_name}{default_marker}")
+
+ # Display statistics
+ try:
+ info = manager.get_info(kb_name)
+ stats = info.get("statistics", {})
+ print(f" - Documents: {stats.get('raw_documents', 0)} files")
+ print(f" - Images: {stats.get('images', 0)} files")
+ print(
+ f" - RAG: {'Initialized' if stats.get('rag_initialized') else 'Not initialized'}"
+ )
+ except:
+ pass
+
+ print("=" * 60 + "\n")
+
+
+def show_kb_info(kb_name=None):
+ """Display detailed knowledge base information"""
+ manager = KnowledgeBaseManager(str(KNOWLEDGE_BASES_DIR))
+
+ try:
+ info = manager.get_info(kb_name)
+
+ print("\n" + "=" * 60)
+ print(f"📖 Knowledge Base Info: {info['name']}")
+ print("=" * 60)
+ print(f"Path: {info['path']}")
+ print(f"Default: {'Yes' if info['is_default'] else 'No'}")
+
+ if info.get("metadata"):
+ print("\n[Metadata]")
+ for key, value in info["metadata"].items():
+ print(f" {key}: {value}")
+
+ print("\n[Statistics]")
+ stats = info["statistics"]
+ print(f" Raw Documents: {stats['raw_documents']} files")
+ print(f" Extracted Images: {stats['images']} files")
+ print(f" Content Lists: {stats['content_lists']} files")
+ print(f" RAG Status: {'Initialized' if stats['rag_initialized'] else 'Not initialized'}")
+
+ if "rag" in stats:
+ print("\n[RAG Statistics]")
+ for key, value in stats["rag"].items():
+ print(f" {key}: {value}")
+
+ print("=" * 60 + "\n")
+
+ except Exception as e:
+ print(f"❌ Error: {e!s}\n")
+
+
+def set_default_kb(kb_name):
+ """Set default knowledge base"""
+ manager = KnowledgeBaseManager(str(KNOWLEDGE_BASES_DIR))
+
+ try:
+ manager.set_default(kb_name)
+ print(f"✅ Set '{kb_name}' as default knowledge base\n")
+ except Exception as e:
+ print(f"❌ Error: {e!s}\n")
+
+
+async def init_knowledge_base(args):
+ """Initialize new knowledge base"""
+ # Get API configuration
+ env_config = get_env_config()
+ api_key = args.api_key or env_config["api_key"]
+ base_url = args.base_url or env_config["base_url"]
+
+ if not api_key and not args.skip_processing:
+ print("❌ Error: API Key not set")
+ print("Please set environment variable LLM_BINDING_API_KEY or use --api-key parameter\n")
+ return
+
+ # Collect document files
+ doc_files = []
+ if args.docs:
+ doc_files.extend(args.docs)
+
+ if args.docs_dir:
+ docs_dir = Path(args.docs_dir)
+ if docs_dir.exists() and docs_dir.is_dir():
+ for ext in ["*.pdf", "*.docx", "*.doc", "*.txt", "*.md"]:
+ doc_files.extend([str(f) for f in docs_dir.glob(ext)])
+ else:
+ print(f"❌ Error: Document directory does not exist: {args.docs_dir}\n")
+ return
+
+ if not args.skip_processing and not doc_files:
+ print("❌ Error: No documents specified")
+ print("Use --docs or --docs-dir to specify documents\n")
+ return
+
+ # Initialize knowledge base
+ print("\n" + "=" * 60)
+ print(f"🚀 Initializing knowledge base: {args.name}")
+ print("=" * 60 + "\n")
+
+ initializer = KnowledgeBaseInitializer(
+ kb_name=args.name, base_dir=str(KNOWLEDGE_BASES_DIR), api_key=api_key, base_url=base_url
+ )
+
+ # Create directory structure
+ initializer.create_directory_structure()
+
+ # Copy documents
+ if doc_files:
+ copied_files = initializer.copy_documents(doc_files)
+ print(f"✅ Copied {len(copied_files)} files\n")
+
+ # Process documents
+ if not args.skip_processing:
+ await initializer.process_documents()
+ else:
+ print("⏭️ Skipping document processing\n")
+
+ # Extract numbered items
+ if not args.skip_processing and not args.skip_extract:
+ initializer.extract_numbered_items(batch_size=args.batch_size)
+ elif args.skip_extract:
+ print("⏭️ Skipping numbered items extraction\n")
+
+ print("\n" + "=" * 60)
+ print(f"✅ Knowledge base '{args.name}' initialization complete!")
+ print(f"Location: {initializer.kb_dir}")
+ print("=" * 60 + "\n")
+
+
+def extract_items(args):
+ """Extract numbered items"""
+ # Get API configuration
+ env_config = get_env_config()
+ api_key = args.api_key or env_config["api_key"]
+ base_url = args.base_url or env_config["base_url"]
+
+ if not api_key:
+ print("❌ Error: API Key not set")
+ print("Please set environment variable LLM_BINDING_API_KEY or use --api-key parameter\n")
+ return
+
+ # Build paths
+ kb_dir = KNOWLEDGE_BASES_DIR / args.kb
+ content_list_dir = kb_dir / "content_list"
+
+ if not content_list_dir.exists():
+ print(f"❌ Error: content_list directory does not exist: {content_list_dir}\n")
+ return
+
+ # Get files to process
+ if args.content_file:
+ content_list_files = [content_list_dir / args.content_file]
+ if not content_list_files[0].exists():
+ print(f"❌ Error: content_list file does not exist: {content_list_files[0]}\n")
+ return
+ else:
+ content_list_files = sorted(content_list_dir.glob("*.json"))
+ if not content_list_files:
+ print(f"❌ Error: No JSON files found in {content_list_dir}\n")
+ return
+
+ if args.debug:
+ print("⚠️ Debug mode: Only processing first file\n")
+ content_list_files = content_list_files[:1]
+
+ output_file = kb_dir / "numbered_items.json"
+
+ print("\n" + "=" * 60)
+ print(f"🔍 Extracting numbered items: {args.kb}")
+ print("=" * 60)
+ print(f"File count: {len(content_list_files)}")
+ print(f"Batch size: {args.batch_size}")
+ print(f"Max concurrent: {args.max_concurrent}")
+ print("=" * 60 + "\n")
+
+ try:
+ for idx, content_list_file in enumerate(content_list_files, 1):
+ print(f"\nProcessing file [{idx}/{len(content_list_files)}]: {content_list_file.name}")
+
+ process_content_list(
+ content_list_file,
+ output_file,
+ api_key,
+ base_url,
+ args.batch_size,
+ merge=(idx > 1), # Auto-merge after first file
+ )
+
+ print("\n" + "=" * 60)
+ print("✅ Extraction complete!")
+ print(f"Output file: {output_file}")
+ print("=" * 60 + "\n")
+
+ except Exception as e:
+ print(f"\n❌ Extraction failed: {e}\n")
+
+
+def delete_knowledge_base(args):
+ """Delete knowledge base"""
+ manager = KnowledgeBaseManager(str(KNOWLEDGE_BASES_DIR))
+
+ try:
+ success = manager.delete_knowledge_base(args.name, confirm=args.force)
+ if success:
+ print(f"\n✅ Deleted knowledge base '{args.name}'\n")
+ except Exception as e:
+ print(f"\n❌ Error: {e}\n")
+
+
+def clean_rag_storage(args):
+ """Clean RAG storage"""
+ manager = KnowledgeBaseManager(str(KNOWLEDGE_BASES_DIR))
+
+ print("\n" + "=" * 60)
+ print("🧹 Cleaning RAG storage")
+ print("=" * 60 + "\n")
+
+ try:
+ manager.clean_rag_storage(args.name, backup=not args.no_backup)
+ print("\n" + "=" * 60)
+ print("✅ RAG storage cleaned!")
+ print("💡 Tip: Use 'add_documents.py' to reprocess documents to rebuild RAG")
+ print("=" * 60 + "\n")
+ except Exception as e:
+ print(f"\n❌ Error: {e}\n")
+
+
+async def refresh_knowledge_base(args):
+ """Refresh knowledge base (reprocess all documents)"""
+ manager = KnowledgeBaseManager(str(KNOWLEDGE_BASES_DIR))
+
+ # Get API configuration
+ env_config = get_env_config()
+ api_key = args.api_key or env_config["api_key"]
+ base_url = args.base_url or env_config["base_url"]
+
+ if not api_key:
+ print("❌ Error: API Key not set")
+ print("Please set environment variable LLM_BINDING_API_KEY or use --api-key parameter\n")
+ return
+
+ try:
+ kb_name = args.name
+ kb_dir = manager.get_knowledge_base_path(kb_name)
+ raw_dir = kb_dir / "raw"
+
+ if not raw_dir.exists() or not list(raw_dir.glob("*")):
+ print(f"❌ Error: No raw documents found in knowledge base '{kb_name}'\n")
+ return
+
+ print("\n" + "=" * 60)
+ print(f"🔄 Refreshing knowledge base: {kb_name}")
+ print("=" * 60)
+ print(f"Path: {kb_dir}")
+ print("=" * 60 + "\n")
+
+ # Step 1: Clean RAG storage
+ print("Step 1/3: Cleaning RAG storage...")
+ manager.clean_rag_storage(kb_name, backup=not args.no_backup)
+
+ # Step 2: Clean content_list and images (optional)
+ if args.full:
+ print("\nStep 2/3: Cleaning extracted content and images...")
+ content_list_dir = kb_dir / "content_list"
+ images_dir = kb_dir / "images"
+
+ if content_list_dir.exists():
+ import shutil
+
+ shutil.rmtree(content_list_dir)
+ content_list_dir.mkdir(parents=True, exist_ok=True)
+ print(" ✓ Cleaned content_list")
+
+ if images_dir.exists():
+ import shutil
+
+ shutil.rmtree(images_dir)
+ images_dir.mkdir(parents=True, exist_ok=True)
+ print(" ✓ Cleaned images")
+ else:
+ print("\nStep 2/3: Skipping content cleanup (use --full for complete refresh)")
+
+ # Step 3: Reprocess all documents
+ print("\nStep 3/3: Reprocessing documents...")
+
+ from src.knowledge.initializer import KnowledgeBaseInitializer
+
+ initializer = KnowledgeBaseInitializer(
+ kb_name=kb_name, base_dir=str(KNOWLEDGE_BASES_DIR), api_key=api_key, base_url=base_url
+ )
+
+ # Reprocess documents
+ await initializer.process_documents()
+
+ # Extract numbered items
+ if not args.skip_extract:
+ print("\nExtracting numbered items...")
+ initializer.extract_numbered_items(batch_size=args.batch_size)
+
+ print("\n" + "=" * 60)
+ print(f"✅ Knowledge base '{kb_name}' refresh complete!")
+ print("=" * 60 + "\n")
+
+ except Exception as e:
+ print(f"\n❌ Refresh failed: {e}\n")
+ raise
+
+
+def main():
+ """Main function"""
+ parser = argparse.ArgumentParser(
+ description="Knowledge Base Management Tool",
+ formatter_class=argparse.RawDescriptionHelpFormatter,
+ epilog="""
+Usage Examples:
+
+ [Recommended: Directly run kb.py]
+ python knowledge_init/kb.py list
+ python knowledge_init/kb.py info ai_textbook
+ python knowledge_init/kb.py set-default math2211
+ python knowledge_init/kb.py init my_kb --docs document.pdf
+ python knowledge_init/kb.py init my_course --docs-dir ./materials/
+ python knowledge_init/kb.py extract --kb ai_textbook
+ python knowledge_init/kb.py extract --kb ai_textbook --debug
+
+ [New: Delete and Refresh Features]
+ python knowledge_init/kb.py delete old_kb # Delete knowledge base (requires confirmation)
+ python knowledge_init/kb.py delete old_kb --force # Force delete (skip confirmation)
+ python knowledge_init/kb.py clean-rag C2-test # Clean RAG storage (fix corrupted graph data)
+ python knowledge_init/kb.py refresh ai_textbook # Refresh knowledge base (reprocess all documents)
+ python knowledge_init/kb.py refresh ai_textbook --full # Full refresh
+
+ [Method 2: Run as module]
+ python -m knowledge_init.start_kb list
+ python -m knowledge_init.start_kb init my_kb --docs document.pdf
+ python -m knowledge_init.start_kb clean-rag C2-test
+
+ [Important] All commands must be run from project root directory (OpenTutor/)!
+ """,
+ )
+
+ subparsers = parser.add_subparsers(dest="command", help="Command")
+
+ # list command
+ subparsers.add_parser("list", help="List all knowledge bases")
+
+ # info command
+ info_parser = subparsers.add_parser("info", help="Show knowledge base information")
+ info_parser.add_argument(
+ "name",
+ nargs="?",
+ help="Knowledge base name (optional, default shows default knowledge base)",
+ )
+
+ # set-default command
+ default_parser = subparsers.add_parser("set-default", help="Set default knowledge base")
+ default_parser.add_argument("name", help="Knowledge base name")
+
+ # init command
+ init_parser = subparsers.add_parser("init", help="Initialize new knowledge base")
+ init_parser.add_argument("name", help="Knowledge base name")
+ init_parser.add_argument("--docs", nargs="+", help="Document file list")
+ init_parser.add_argument("--docs-dir", help="Document directory")
+ init_parser.add_argument("--api-key", help="OpenAI API Key")
+ init_parser.add_argument("--base-url", help="API Base URL")
+ init_parser.add_argument(
+ "--skip-processing", action="store_true", help="Skip document processing"
+ )
+ init_parser.add_argument(
+ "--skip-extract", action="store_true", help="Skip numbered items extraction"
+ )
+ init_parser.add_argument("--batch-size", type=int, default=20, help="Batch size (default 20)")
+
+ # extract command
+ extract_parser = subparsers.add_parser("extract", help="Extract numbered items")
+ extract_parser.add_argument("--kb", required=True, help="Knowledge base name")
+ extract_parser.add_argument("--content-file", help="Specify content_list file (optional)")
+ extract_parser.add_argument(
+ "--batch-size", type=int, default=20, help="Batch size (default 20)"
+ )
+ extract_parser.add_argument(
+ "--max-concurrent", type=int, default=5, help="Max concurrent tasks (default 5)"
+ )
+ extract_parser.add_argument(
+ "--debug", action="store_true", help="Debug mode (only process first file)"
+ )
+ extract_parser.add_argument("--api-key", help="OpenAI API Key")
+ extract_parser.add_argument("--base-url", help="API Base URL")
+
+ # delete command
+ delete_parser = subparsers.add_parser("delete", help="Delete knowledge base")
+ delete_parser.add_argument("name", help="Knowledge base name")
+ delete_parser.add_argument("--force", action="store_true", help="Skip confirmation (dangerous)")
+
+ # clean-rag command
+ clean_parser = subparsers.add_parser(
+ "clean-rag", help="Clean RAG storage (fix corrupted graph data)"
+ )
+ clean_parser.add_argument(
+ "name",
+ nargs="?",
+ help="Knowledge base name (optional, default uses default knowledge base)",
+ )
+ clean_parser.add_argument(
+ "--no-backup", action="store_true", help="No backup (not recommended)"
+ )
+
+ # refresh command
+ refresh_parser = subparsers.add_parser(
+ "refresh", help="Refresh knowledge base (reprocess all documents)"
+ )
+ refresh_parser.add_argument("name", help="Knowledge base name")
+ refresh_parser.add_argument(
+ "--full", action="store_true", help="Full refresh (clean all extracted content)"
+ )
+ refresh_parser.add_argument(
+ "--no-backup", action="store_true", help="No backup for RAG storage"
+ )
+ refresh_parser.add_argument(
+ "--skip-extract", action="store_true", help="Skip numbered items extraction"
+ )
+ refresh_parser.add_argument(
+ "--batch-size", type=int, default=20, help="Batch size (default 20)"
+ )
+ refresh_parser.add_argument("--api-key", help="OpenAI API Key")
+ refresh_parser.add_argument("--base-url", help="API Base URL")
+
+ args = parser.parse_args()
+
+ # Windows console UTF-8 support
+ if sys.platform == "win32":
+ import io
+
+ sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8")
+
+ # Execute command
+ if args.command == "list":
+ list_knowledge_bases()
+
+ elif args.command == "info":
+ show_kb_info(args.name)
+
+ elif args.command == "set-default":
+ set_default_kb(args.name)
+
+ elif args.command == "init":
+ try:
+ asyncio.run(init_knowledge_base(args))
+ except (KeyboardInterrupt, SystemExit):
+ print("\n\n⚠️ Operation cancelled")
+ except IndexError as e:
+ # Ignore IndexError during asyncio cleanup (doesn't affect functionality)
+ if "pop from an empty deque" not in str(e):
+ raise
+ except Exception as e:
+ print(f"\n❌ Error: {e}")
+ raise
+
+ elif args.command == "extract":
+ extract_items(args)
+
+ elif args.command == "delete":
+ delete_knowledge_base(args)
+
+ elif args.command == "clean-rag":
+ clean_rag_storage(args)
+
+ elif args.command == "refresh":
+ try:
+ asyncio.run(refresh_knowledge_base(args))
+ except (KeyboardInterrupt, SystemExit):
+ print("\n\n⚠️ Operation cancelled")
+ except IndexError as e:
+ # Ignore IndexError during asyncio cleanup
+ if "pop from an empty deque" not in str(e):
+ raise
+ except Exception as e:
+ print(f"\n❌ Error: {e}")
+ raise
+
+ else:
+ parser.print_help()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/src/tools/README.md b/src/tools/README.md
new file mode 100644
index 000000000..59949f536
--- /dev/null
+++ b/src/tools/README.md
@@ -0,0 +1,563 @@
+# Tools Module
+
+This module provides a collection of various tools used in the OpenTutor 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 ⭐
+├── query_item_tool.py # Numbered item query 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
+ query_numbered_item, # Query numbered items
+ 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 `solve_config.yaml` or `question_config.yaml`
+- Environment variables:
+ - `RUN_CODE_WORKSPACE`: Workspace directory
+ - `RUN_CODE_ALLOWED_ROOTS`: List of allowed root directories
+
+---
+
+### 2. Numbered Item Query Tool (`query_item_tool.py`)
+
+Query numbered items in the knowledge base, such as definitions, theorems, formulas, figures, etc.
+
+**Key Features:**
+- Support for multiple numbered item types: definitions, theorems, formulas, figures, examples, remarks, etc.
+- Support for fuzzy and exact matching
+- Returns multiple matching results
+- Backward compatible with single result format
+
+**Usage Example:**
+
+```python
+from src.tools import query_numbered_item
+
+# Query definition
+result = query_numbered_item(
+ identifier="Definition 1.1",
+ kb_name="ai_textbook"
+)
+
+# Query formula
+result = query_numbered_item(
+ identifier="(1.2.1)",
+ kb_name="ai_textbook"
+)
+
+# Query figure
+result = query_numbered_item(
+ identifier="Figure 2.5",
+ kb_name="ai_textbook",
+ max_results=3
+)
+
+# Result format
+# {
+# "identifier": str, # Original query identifier
+# "type": str, # Type: formula/definition/theorem/lemma/figure/example/remark
+# "status": str, # success/failed
+# "count": int, # Number of matched items
+# "items": [ # List of all matched items
+# {
+# "identifier": str,
+# "type": str,
+# "content": str
+# }
+# ],
+# "content": str, # Backward compatible: single item content or merged content
+# "error": str # Error message (only when failed)
+# }
+```
+
+**Supported Identifier Formats:**
+- Definition/Theorem: `"Definition 1.1"`, `"Theorem 2.3"`
+- Formula: `"(1.2.1)"`, `"(2.3.5)"`
+- Figure: `"Figure 1.1"`, `"Figure 2.5"`
+- Example/Remark: `"Example 1.1"`, `"Remark 2.1"`
+
+---
+
+### 3. 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/solve_config.yaml`: Solver configuration (includes `tools.run_code`)
+- `config/question_config.yaml`: Question 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 query_numbered_item, rag_search
+
+# Query specific definition
+definition = query_numbered_item("Definition 3.1", kb_name="ai_textbook")
+
+# 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__.py
new file mode 100644
index 000000000..8ad379a13
--- /dev/null
+++ b/src/tools/__init__.py
@@ -0,0 +1,86 @@
+#!/usr/bin/env python
+"""
+Tools Package - Unified tool collection
+
+Includes:
+- rag_tool: RAG retrieval tool
+- web_search: Web search tool
+- query_item_tool: Query item tool
+- paper_search_tool: Paper search tool
+- tex_downloader: LaTeX source download tool
+- tex_chunker: LaTeX text chunking tool
+"""
+
+# Patch lightrag.utils BEFORE any imports that use lightrag
+import importlib.util
+import sys
+
+try:
+ # Directly load lightrag.utils module without triggering lightrag/__init__.py
+ _spec = importlib.util.find_spec("lightrag.utils")
+ if _spec and _spec.origin:
+ _utils = importlib.util.module_from_spec(_spec)
+ sys.modules["lightrag.utils"] = _utils
+ _spec.loader.exec_module(_utils)
+
+ # Apply patches
+ for _k, _v in {
+ "verbose_debug": lambda *args, **kwargs: None,
+ "VERBOSE_DEBUG": False,
+ "get_env_value": lambda key, default=None: default,
+ "safe_unicode_decode": lambda t: (
+ t.decode("utf-8", errors="ignore") if isinstance(t, bytes) else t
+ ),
+ }.items():
+ if not hasattr(_utils, _k):
+ setattr(_utils, _k, _v)
+
+ if not hasattr(_utils, "wrap_embedding_func_with_attrs"):
+
+ def _wrap(**attrs):
+ def dec(f):
+ for k, v in attrs.items():
+ setattr(f, k, v)
+ return f
+
+ return dec
+
+ _utils.wrap_embedding_func_with_attrs = _wrap
+except Exception as e:
+ import traceback
+
+ print(f"Warning: Failed to patch lightrag.utils: {e}")
+ traceback.print_exc()
+
+from .code_executor import run_code, run_code_sync
+from .query_item_tool import query_numbered_item
+from .rag_tool import rag_search
+from .web_search import web_search
+
+# Paper research related tools
+try:
+ from .paper_search_tool import PaperSearchTool
+ from .tex_chunker import TexChunker
+ from .tex_downloader import TexDownloader, read_tex_file
+
+ __all__ = [
+ "PaperSearchTool",
+ "TexChunker",
+ "TexDownloader",
+ "query_numbered_item",
+ "rag_search",
+ "read_tex_file",
+ "run_code",
+ "run_code_sync",
+ "web_search",
+ ]
+except ImportError as e:
+ # If import fails (e.g., missing tiktoken), only export basic tools
+ print(f"⚠️ Some paper tools import failed: {e}")
+ __all__ = [
+ "query_numbered_item",
+ "rag_search",
+ "run_code",
+ "run_code_sync",
+ "web_search",
+ ]
diff --git a/src/tools/code_executor.py b/src/tools/code_executor.py
new file mode 100644
index 000000000..240eac6c9
--- /dev/null
+++ b/src/tools/code_executor.py
@@ -0,0 +1,536 @@
+#!/usr/bin/env python
+"""
+Run Code Tool - Code execution tool
+Execute Python code in isolated workspace, preserving original input/output structure.
+"""
+
+import ast
+import asyncio
+from contextlib import contextmanager
+from dataclasses import dataclass, field
+from datetime import datetime
+import os
+from pathlib import Path
+import subprocess
+import sys
+import tempfile
+import time
+from typing import Any
+
+RUN_CODE_WORKSPACE_ENV = "RUN_CODE_WORKSPACE"
+RUN_CODE_ALLOWED_ROOTS_ENV = "RUN_CODE_ALLOWED_ROOTS"
+DEFAULT_WORKSPACE_NAME = "run_code_workspace"
+PROJECT_ROOT = Path(__file__).resolve().parents[2]
+
+from src.core.logging import get_logger
+
+logger = get_logger("CodeExecutor")
+
+
+def _load_config() -> dict[str, Any]:
+ """Load run_code configuration from main.yaml and module configs"""
+ try:
+ from src.core.core import load_config_with_main
+
+ # Try loading from solve_config (most common use case)
+ try:
+ config = load_config_with_main("solve_config.yaml", PROJECT_ROOT)
+ run_code_config = config.get("tools", {}).get("run_code", {})
+ if run_code_config:
+ logger.debug("Loaded run_code config from solve_config.yaml (with main.yaml)")
+ return run_code_config
+ except Exception as e:
+ logger.debug(f"Failed to load from solve_config: {e}")
+
+ # Fallback to question_config
+ try:
+ config = load_config_with_main("question_config.yaml", PROJECT_ROOT)
+ run_code_config = config.get("tools", {}).get("run_code", {})
+ if run_code_config:
+ logger.debug("Loaded run_code config from question_config.yaml (with main.yaml)")
+ return run_code_config
+ except Exception as e:
+ logger.debug(f"Failed to load from question_config: {e}")
+
+ # Fallback to main.yaml only
+ try:
+ config = load_config_with_main("solve_config.yaml", PROJECT_ROOT)
+ run_code_config = config.get("tools", {}).get("run_code", {})
+ if run_code_config:
+ return run_code_config
+ except Exception:
+ pass
+
+ except ImportError:
+ logger.debug("config_loader not available, using fallback")
+
+ # Fallback: try loading main.yaml directly
+ try:
+ import yaml
+
+ main_config_path = PROJECT_ROOT / "config" / "main.yaml"
+ if main_config_path.exists():
+ with open(main_config_path, encoding="utf-8") as f:
+ config = yaml.safe_load(f) or {}
+ run_code_config = config.get("tools", {}).get("run_code", {})
+ if run_code_config:
+ logger.debug("Loaded run_code config from main.yaml")
+ return run_code_config
+ except Exception as e:
+ logger.debug(f"Failed to load from main.yaml: {e}")
+
+ return {}
+
+
+class CodeExecutionError(Exception):
+ """Code execution error"""
+
+
+@dataclass
+class OperationEntry:
+ action: str
+ details: dict[str, Any]
+ timestamp: str = field(default_factory=lambda: datetime.now().isoformat())
+
+
+class OperationLogger:
+ """Simple operation history logger, inspired by code_implementation_server recording method"""
+
+ def __init__(self, max_entries: int = 200):
+ self._history: list[OperationEntry] = []
+ self._max_entries = max_entries
+
+ def log(self, action: str, details: dict[str, Any]):
+ entry = OperationEntry(action=action, details=details)
+ self._history.append(entry)
+ if len(self._history) > self._max_entries:
+ self._history.pop(0)
+ logger.debug(f"Operation logged: {action} | details={details.get('status')}")
+
+ @property
+ def history(self) -> list[OperationEntry]:
+ return list(self._history)
+
+
+class WorkspaceManager:
+ """Manages isolated workspace, similar to code_implementation_server workspace logic"""
+
+ def __init__(self):
+ # Load configuration (priority: environment variable > config file > default)
+ config = _load_config()
+
+ # Determine workspace directory (priority: environment variable > config file > default)
+ env_path = os.getenv(RUN_CODE_WORKSPACE_ENV)
+ if env_path:
+ self.base_dir = Path(env_path).expanduser().resolve()
+ else:
+ config_workspace = config.get("workspace")
+ if config_workspace:
+ # Support relative paths (relative to project root) and absolute paths
+ workspace_path = Path(config_workspace).expanduser()
+ if workspace_path.is_absolute():
+ self.base_dir = workspace_path.resolve()
+ else:
+ self.base_dir = (PROJECT_ROOT / workspace_path).resolve()
+ else:
+ # Default workspace is set under user directory
+ self.base_dir = (PROJECT_ROOT / "data" / "user" / DEFAULT_WORKSPACE_NAME).resolve()
+
+ # Determine allowed root paths list
+ # Default includes project root and user directory
+ self.allowed_roots: list[Path] = [
+ PROJECT_ROOT.resolve(),
+ (PROJECT_ROOT / "data" / "user").resolve(),
+ ]
+
+ # Read allowed root paths from config file
+ config_allowed_roots = config.get("allowed_roots", [])
+ if isinstance(config_allowed_roots, str):
+ config_allowed_roots = [config_allowed_roots]
+ for root_path in config_allowed_roots:
+ root = Path(root_path).expanduser()
+ if root.is_absolute():
+ resolved_root = root.resolve()
+ else:
+ resolved_root = (PROJECT_ROOT / root).resolve()
+ # Avoid duplicate addition
+ if resolved_root not in self.allowed_roots:
+ self.allowed_roots.append(resolved_root)
+
+ # Read additional allowed root paths from environment variables
+ extra_roots = os.getenv(RUN_CODE_ALLOWED_ROOTS_ENV)
+ if extra_roots:
+ for raw_path in extra_roots.split(os.pathsep):
+ raw_path = raw_path.strip()
+ if raw_path:
+ path = Path(raw_path).expanduser()
+ if path.is_absolute():
+ resolved_path = path.resolve()
+ else:
+ resolved_path = (PROJECT_ROOT / path).resolve()
+ # Avoid duplicate addition
+ if resolved_path not in self.allowed_roots:
+ self.allowed_roots.append(resolved_path)
+
+ # Ensure workspace directory itself can also be a valid root path
+ if self.base_dir not in self.allowed_roots:
+ self.allowed_roots.append(self.base_dir)
+
+ self._initialized = False
+
+ def initialize(self):
+ if not self._initialized:
+ self.base_dir.mkdir(parents=True, exist_ok=True)
+ self._initialized = True
+ logger.info(f"Run-code workspace initialized at {self.base_dir}")
+
+ def ensure_initialized(self):
+ if not self._initialized:
+ self.initialize()
+
+ @contextmanager
+ def create_temp_dir(self) -> Path:
+ self.ensure_initialized()
+ with tempfile.TemporaryDirectory(dir=self.base_dir) as temp_dir:
+ yield Path(temp_dir)
+
+ def resolve_assets_dir(self, assets_dir: str | None) -> Path | None:
+ if not assets_dir:
+ return None
+ path = Path(assets_dir).expanduser()
+ if not path.is_absolute():
+ path = (self.base_dir / path).resolve()
+ self._ensure_within_allowed_roots(path)
+ path.mkdir(parents=True, exist_ok=True)
+ return path
+
+ def collect_artifacts(self, assets_dir: Path | None) -> tuple[list[str], list[str]]:
+ artifacts: list[str] = []
+ artifact_paths: list[str] = []
+ if not assets_dir or not assets_dir.exists():
+ return artifacts, artifact_paths
+
+ for file_path in assets_dir.iterdir():
+ if file_path.is_file() and file_path.name != ".gitkeep":
+ artifacts.append(str(file_path.relative_to(assets_dir)))
+ artifact_paths.append(str(file_path.resolve()))
+ return artifacts, artifact_paths
+
+ def _ensure_within_allowed_roots(self, path: Path):
+ resolved_path = path.resolve()
+ for root in self.allowed_roots:
+ # Use Path object methods for path comparison, avoiding Windows path separator and case issues
+ try:
+ # Python 3.9+ use is_relative_to
+ if hasattr(resolved_path, "is_relative_to"):
+ if resolved_path.is_relative_to(root):
+ return
+ else:
+ # Python < 3.9 use path comparison after resolve()
+ # Convert to lowercase and normalize path separators for comparison (Windows compatible)
+ resolved_str = str(resolved_path).lower().replace("\\", "/")
+ root_str = str(root.resolve()).lower().replace("\\", "/")
+ if resolved_str.startswith(root_str):
+ return
+ except (ValueError, AttributeError):
+ # If is_relative_to fails, fallback to string comparison
+ resolved_str = str(resolved_path).lower().replace("\\", "/")
+ root_str = str(root.resolve()).lower().replace("\\", "/")
+ if resolved_str.startswith(root_str):
+ return
+ allowed = "\n".join(str(root) for root in self.allowed_roots)
+ raise ValueError(
+ f"Assets directory {resolved_path} must be located under one of the following allowed paths:\n{allowed}"
+ )
+
+
+class ImportGuard:
+ """Parse AST, restrict import modules, ensure consistency with allowed_imports logic"""
+
+ @staticmethod
+ def validate(code: str, allowed_imports: list[str] | None):
+ if not allowed_imports:
+ return
+
+ allowed = set(allowed_imports)
+ try:
+ tree = ast.parse(code)
+ except SyntaxError as exc:
+ raise CodeExecutionError(f"Code syntax error: {exc}") from exc
+
+ imported: list[str] = []
+ for node in ast.walk(tree):
+ if isinstance(node, ast.Import):
+ for alias in node.names:
+ imported.append(alias.name.split(".")[0])
+ elif isinstance(node, ast.ImportFrom):
+ if node.module:
+ imported.append(node.module.split(".")[0])
+
+ unauthorized = sorted({name for name in imported if name not in allowed})
+ if unauthorized:
+ raise CodeExecutionError(
+ f"The following modules are not in the allowed list: {', '.join(unauthorized)}"
+ )
+
+
+class CodeExecutionEnvironment:
+ """Encapsulates actual code execution logic, maintaining consistency with DeepCode server flow"""
+
+ def __init__(self, workspace: WorkspaceManager):
+ self.workspace = workspace
+
+ def run_python(
+ self,
+ code: str,
+ timeout: int,
+ assets_dir: Path | None,
+ ) -> tuple[str, str, int, float]:
+ env = os.environ.copy()
+ env["PYTHONIOENCODING"] = "utf-8"
+
+ with self.workspace.create_temp_dir() as temp_dir:
+ code_file = temp_dir / "code.py"
+ code_file.write_text(code, encoding="utf-8")
+
+ work_dir = assets_dir if assets_dir else temp_dir
+ start_time = time.time()
+
+ result = subprocess.run(
+ [sys.executable, str(code_file)],
+ check=False,
+ capture_output=True,
+ text=True,
+ encoding="utf-8",
+ errors="replace",
+ timeout=timeout,
+ cwd=str(work_dir),
+ env=env,
+ )
+
+ elapsed_ms = (time.time() - start_time) * 1000
+ return result.stdout, result.stderr, result.returncode, elapsed_ms
+
+
+WORKSPACE_MANAGER = WorkspaceManager()
+OPERATION_LOGGER = OperationLogger()
+EXECUTION_ENV = CodeExecutionEnvironment(WORKSPACE_MANAGER)
+
+
+async def run_code(
+ language: str,
+ code: str,
+ timeout: int = 10,
+ assets_dir: str | None = None,
+ allowed_imports: list[str] | None = None,
+) -> dict[str, Any]:
+ """
+ Execute code in isolated environment, return result structure consistent with previous version.
+ """
+ if language.lower() != "python":
+ raise ValueError(f"Unsupported language: {language}, currently only Python is supported")
+
+ WORKSPACE_MANAGER.ensure_initialized()
+ ImportGuard.validate(code, allowed_imports)
+
+ assets_path = WORKSPACE_MANAGER.resolve_assets_dir(assets_dir)
+ loop = asyncio.get_running_loop()
+
+ def _execute():
+ return EXECUTION_ENV.run_python(code, timeout, assets_path)
+
+ try:
+ stdout, stderr, exit_code, elapsed_ms = await loop.run_in_executor(None, _execute)
+ artifacts, artifact_paths = WORKSPACE_MANAGER.collect_artifacts(assets_path)
+
+ result = {
+ "stdout": stdout,
+ "stderr": stderr,
+ "artifacts": artifacts,
+ "artifact_paths": artifact_paths,
+ "exit_code": exit_code,
+ "elapsed_ms": elapsed_ms,
+ }
+
+ OPERATION_LOGGER.log(
+ "execute_python",
+ {
+ "status": "success",
+ "language": language,
+ "timeout": timeout,
+ "assets_dir": str(assets_path) if assets_path else None,
+ "exit_code": exit_code,
+ "elapsed_ms": elapsed_ms,
+ "code_size": len(code),
+ },
+ )
+
+ return result
+
+ except subprocess.TimeoutExpired as timeout_exc:
+ # Code execution timeout
+ artifacts, artifact_paths = WORKSPACE_MANAGER.collect_artifacts(assets_path)
+ elapsed_ms = timeout * 1000
+ message = f"Code execution timeout ({timeout} seconds)"
+
+ logger.warning(f"Code execution timeout after {timeout}s: {timeout_exc}")
+
+ OPERATION_LOGGER.log(
+ "execute_python",
+ {
+ "status": "timeout",
+ "language": language,
+ "timeout": timeout,
+ "assets_dir": str(assets_path) if assets_path else None,
+ },
+ )
+
+ return {
+ "stdout": "",
+ "stderr": message,
+ "artifacts": artifacts,
+ "artifact_paths": artifact_paths,
+ "exit_code": -1,
+ "elapsed_ms": elapsed_ms,
+ }
+
+ except Exception as exc: # pylint: disable=broad-except
+ # Catch all other exceptions to ensure main flow is not interrupted
+ artifacts, artifact_paths = WORKSPACE_MANAGER.collect_artifacts(assets_path)
+ elapsed_ms = 0.0
+
+ if isinstance(exc, CodeExecutionError):
+ stderr_message = str(exc)
+ else:
+ stderr_message = f"Code execution failed: {exc}"
+
+ # Log detailed error information
+ logger.error(f"Code execution error: {exc}", exc_info=True)
+
+ OPERATION_LOGGER.log(
+ "execute_python",
+ {
+ "status": "error",
+ "language": language,
+ "timeout": timeout,
+ "assets_dir": str(assets_path) if assets_path else None,
+ "error": stderr_message,
+ },
+ )
+
+ return {
+ "stdout": "",
+ "stderr": stderr_message,
+ "artifacts": artifacts,
+ "artifact_paths": artifact_paths,
+ "exit_code": -1,
+ "elapsed_ms": elapsed_ms,
+ }
+
+
+def run_code_sync(
+ language: str,
+ code: str,
+ timeout: int = 10,
+ assets_dir: str | None = None,
+) -> dict[str, Any]:
+ """
+ Synchronous version of code execution (for non-async environments)
+ """
+
+ return asyncio.run(run_code(language, code, timeout, assets_dir))
+
+
+if __name__ == "__main__":
+ import textwrap
+
+ async def _demo():
+ print("==== 1. Test normal output ====")
+ sample1 = "print('Hello from run_code workspace!')"
+ result1 = await run_code("python", sample1, timeout=5)
+ print("stdout:", result1["stdout"])
+ print("stderr:", result1["stderr"])
+ print("artifacts:", result1.get("artifacts", {}))
+ print("artifact_paths:", result1.get("artifact_paths", []))
+ print("exit_code:", result1["exit_code"])
+ print("-" * 40)
+
+ print("==== 2. Test exception case ====")
+ sample2 = "raise ValueError('Test error from run_code!')"
+ result2 = await run_code("python", sample2, timeout=5)
+ print("stdout:", result2["stdout"])
+ print("stderr:", result2["stderr"])
+ print("exit_code:", result2["exit_code"])
+ print("-" * 40)
+
+ print("==== 3. Test code timeout ====")
+ sample3 = textwrap.dedent(
+ """
+ import time
+ time.sleep(10)
+ print("Timeout should occur before this prints.")
+ """
+ )
+ result3 = await run_code("python", sample3, timeout=2)
+ print("stdout:", result3["stdout"])
+ print("stderr:", result3["stderr"])
+ print("exit_code:", result3["exit_code"])
+ print("-" * 40)
+
+ print("==== 4. Test plotting functionality (matplotlib) ====")
+ sample4 = textwrap.dedent(
+ """
+ import matplotlib.pyplot as plt
+ plt.figure()
+ plt.plot([1, 2, 3], [4, 2, 5])
+ plt.title('Simple Plot')
+ plt.savefig('test_plot.png')
+ print('Plot created!')
+ """
+ )
+ result4 = await run_code("python", sample4, timeout=5)
+ print("stdout:", result4["stdout"])
+ print("stderr:", result4["stderr"])
+ print("artifacts:", result4.get("artifacts", {}))
+ print("artifact_paths:", result4.get("artifact_paths", []))
+ print("exit_code:", result4["exit_code"])
+ # Check generated images
+ if result4.get("artifact_paths"):
+ print("Generated image files:", result4["artifact_paths"])
+ else:
+ print("No image files found.")
+ print("-" * 40)
+
+ print("==== 5. Test standard input ====")
+ sample5 = textwrap.dedent(
+ """
+ text = input("Please enter content: ")
+ print("You entered: ", text)
+ """
+ )
+ # Standard run_code does not provide stdin, this example tests output behavior
+ result5 = await run_code("python", sample5, timeout=5)
+ print("stdout:", result5["stdout"])
+ print("stderr:", result5["stderr"])
+ print("exit_code:", result5["exit_code"])
+ print("-" * 40)
+
+ print("==== 6. Test multi-file and resource read/write ====")
+ sample6 = textwrap.dedent(
+ """
+ with open('test_file.txt', 'w', encoding='utf-8') as f:
+ f.write('Fake data for test!\\nAnother line.')
+ with open('test_file.txt', 'r', encoding='utf-8') as f:
+ content = f.read()
+ print('File content:', content)
+ """
+ )
+ result6 = await run_code("python", sample6, timeout=5)
+ print("stdout:", result6["stdout"])
+ print("stderr:", result6["stderr"])
+ print("artifacts:", result6.get("artifacts", {}))
+ print("artifact_paths:", result6.get("artifact_paths", []))
+ print("exit_code:", result6["exit_code"])
+ print("-" * 40)
+
+ asyncio.run(_demo())
diff --git a/src/tools/paper_search_tool.py b/src/tools/paper_search_tool.py
new file mode 100644
index 000000000..f4831a8c5
--- /dev/null
+++ b/src/tools/paper_search_tool.py
@@ -0,0 +1,171 @@
+"""
+Paper Search Tool - ArXiv paper search tool
+
+Features:
+1. Search ArXiv papers
+2. Parse paper metadata
+3. Format paper information
+
+Author: OpenTutor Team
+Version: v1.0
+Based on: TODO.md specification
+"""
+
+import asyncio
+from datetime import datetime
+import re
+
+import arxiv
+
+
+class PaperSearchTool:
+ """ArXiv paper search tool"""
+
+ def __init__(self):
+ """Initialize search tool"""
+ self.client = arxiv.Client()
+
+ async def search_papers(
+ self,
+ query: str,
+ max_results: int = 3,
+ years_limit: int | None = 3,
+ sort_by: str = "relevance",
+ ) -> list[dict]:
+ """
+ Search ArXiv papers
+
+ Args:
+ query: Search query keywords
+ max_results: Number of papers to return
+ years_limit: Paper year limit (last N years), None means no limit
+ sort_by: Sort method - "relevance" or "date"
+
+ Returns:
+ List of papers, each paper contains:
+ - title: Title
+ - authors: Author list
+ - year: Publication year
+ - abstract: Abstract
+ - url: Paper URL
+ - arxiv_id: ArXiv ID
+ - published: Publication date (ISO format)
+ """
+ # Determine sort method
+ if sort_by == "date":
+ sort_criterion = arxiv.SortCriterion.SubmittedDate
+ else:
+ sort_criterion = arxiv.SortCriterion.Relevance
+
+ # Build search object
+ search = arxiv.Search(
+ query=query,
+ max_results=max_results * 3, # Search more for filtering
+ sort_by=sort_criterion,
+ sort_order=arxiv.SortOrder.Descending,
+ )
+
+ papers = []
+ current_year = datetime.now().year
+
+ # Execute search asynchronously (arxiv library is synchronous, but we can run in executor)
+ results = list(self.client.results(search))
+
+ for result in results:
+ # Extract year
+ published_date = result.published
+ paper_year = published_date.year
+
+ # Year filtering
+ if years_limit and (current_year - paper_year) > years_limit:
+ continue
+
+ # Extract ArXiv ID
+ arxiv_id = result.entry_id.split("/")[-1]
+ if "v" in arxiv_id:
+ arxiv_id = arxiv_id.split("v")[0] # Remove version number
+
+ # Extract authors
+ authors = [author.name for author in result.authors]
+
+ # Build paper information
+ paper_info = {
+ "title": result.title,
+ "authors": authors,
+ "year": paper_year,
+ "abstract": result.summary,
+ "url": result.entry_id,
+ "arxiv_id": arxiv_id,
+ "published": published_date.isoformat(),
+ }
+
+ papers.append(paper_info)
+
+ # If enough collected, stop
+ if len(papers) >= max_results:
+ break
+
+ return papers
+
+ def format_paper_citation(self, paper: dict) -> str:
+ """
+ Format paper citation
+
+ Args:
+ paper: Paper information dictionary
+
+ Returns:
+ Citation string: (FirstAuthor et al., Year)
+ """
+ if not paper["authors"]:
+ return f"(Unknown, {paper['year']})"
+
+ first_author = paper["authors"][0].split()[-1] # Extract surname
+
+ if len(paper["authors"]) > 1:
+ return f"({first_author} et al., {paper['year']})"
+ return f"({first_author}, {paper['year']})"
+
+ def extract_arxiv_id_from_url(self, url: str) -> str | None:
+ """
+ Extract ArXiv ID from URL
+
+ Args:
+ url: ArXiv URL
+
+ Returns:
+ ArXiv ID or None
+ """
+ match = re.search(r"arxiv\.org/(?:abs|pdf)/(\d+\.\d+)", url)
+ if match:
+ return match.group(1)
+ return None
+
+
+# ========== Usage Example ==========
+
+
+async def main():
+ """Test function"""
+ tool = PaperSearchTool()
+
+ # Test search
+ print("Search: transformer attention mechanism")
+ papers = await tool.search_papers(
+ query="transformer attention mechanism", max_results=3, years_limit=3, sort_by="relevance"
+ )
+
+ print(f"\nFound {len(papers)} papers:\n")
+
+ for i, paper in enumerate(papers, 1):
+ print(f"{i}. {paper['title']}")
+ print(f" Authors: {', '.join(paper['authors'][:3])}")
+ print(f" Year: {paper['year']}")
+ print(f" Citation: {tool.format_paper_citation(paper)}")
+ print(f" URL: {paper['url']}")
+ print(f" ArXiv ID: {paper['arxiv_id']}")
+ print()
+
+
+if __name__ == "__main__":
+ asyncio.run(main())
diff --git a/src/tools/query_item_tool.py b/src/tools/query_item_tool.py
new file mode 100644
index 000000000..8be41b294
--- /dev/null
+++ b/src/tools/query_item_tool.py
@@ -0,0 +1,309 @@
+#!/usr/bin/env python
+"""
+Query Numbered Item Tool - Query definitions, theorems, formulas, figures, etc.
+"""
+
+import json
+from pathlib import Path
+import sys
+
+# Add parent directory to path (insert at front to prioritize project modules)
+project_root = Path(__file__).parent.parent.parent
+sys.path.insert(0, str(project_root))
+
+
+def query_numbered_item(
+ identifier: str,
+ kb_name: str | None = None,
+ kb_base_dir: str | None = None,
+ max_results: int | None = None,
+) -> dict:
+ """
+ Query numbered item - Supports returning multiple matching results
+
+ Args:
+ identifier: Identifier of the numbered item
+ - Definition/Theorem: e.g., "Definition 1.1", "Theorem 2.3"
+ - Formula: e.g., "(1.2.1)", "(2.3.5)"
+ - Figure: e.g., "Figure 1.1", "Figure 2.5"
+ - Example: e.g., "Example 1.1", "Remark 2.1"
+ kb_name: Knowledge base name (optional, defaults to default knowledge base)
+ kb_base_dir: Knowledge base base directory (optional, defaults to knowledge_bases under project root)
+ max_results: Maximum number of items to return (optional, defaults to config value or 5)
+
+ Returns:
+ dict: Dictionary containing query results
+ {
+ "identifier": str, # Original query identifier
+ "type": str, # formula/definition/theorem/lemma/figure/example/remark
+ "status": str, # success/failed
+ "count": int, # Number of matched items
+ "items": [ # List of all matched items (sorted by priority)
+ {
+ "identifier": str, # Actual matched identifier
+ "type": str,
+ "content": str
+ },
+ ...
+ ],
+ "content": str, # Backward compatible: single item content or merged content for multiple items
+ "error": str (only when failed)
+ }
+ """
+ # Load configuration for max_results if not specified
+ if max_results is None:
+ try:
+ from src.core.core import load_config_with_main
+
+ project_root = Path(__file__).parent.parent.parent
+ config = load_config_with_main("main.yaml", project_root)
+ max_results = config.get("tools", {}).get("query_item", {}).get("max_results", 5)
+ except Exception:
+ max_results = 5 # Default value
+
+ # If path not specified, use absolute path relative to this file
+ if kb_base_dir is None:
+ # __file__ = OpenTutor/tools/query_item_tool.py
+ # .parent = OpenTutor/tools
+ # .parent = OpenTutor
+ kb_base_dir = Path(__file__).parent.parent.parent / "data/knowledge_bases"
+ else:
+ kb_base_dir = Path(kb_base_dir)
+
+ base_dir = kb_base_dir
+
+ # Get knowledge base
+ if not kb_name:
+ config_file = base_dir / "kb_config.json"
+ if config_file.exists():
+ try:
+ with open(config_file, encoding="utf-8") as f:
+ config = json.load(f)
+ kb_name = config.get("default")
+ except Exception:
+ pass
+
+ if not kb_name:
+ return {
+ "identifier": identifier,
+ "type": "unknown",
+ "content": "",
+ "status": "failed",
+ "error": "Error: Knowledge base not specified and no default knowledge base",
+ }
+
+ # Load items
+ kb_dir = base_dir / kb_name
+ if not kb_dir.exists():
+ return {
+ "identifier": identifier,
+ "type": "unknown",
+ "content": "",
+ "status": "failed",
+ "error": f"Error: Knowledge base '{kb_name}' does not exist",
+ }
+
+ items_file = kb_dir / "numbered_items.json"
+ if not items_file.exists():
+ return {
+ "identifier": identifier,
+ "type": "unknown",
+ "content": "",
+ "status": "failed",
+ "error": f"Error: numbered_items.json not found in knowledge base '{kb_name}'",
+ }
+
+ try:
+ with open(items_file, encoding="utf-8") as f:
+ raw_items = json.load(f)
+ except Exception as e:
+ return {
+ "identifier": identifier,
+ "type": "unknown",
+ "content": "",
+ "status": "failed",
+ "error": f"Error: Unable to read file - {e}",
+ }
+
+ # Extract text content
+ items = {}
+ for key, value in raw_items.items():
+ if isinstance(value, dict):
+ items[key] = value.get("text", str(value))
+ else:
+ items[key] = value
+
+ # Validate identifier parameter
+ if not identifier:
+ return {
+ "identifier": identifier or "",
+ "type": "unknown",
+ "content": "",
+ "status": "failed",
+ "error": "Error: identifier parameter is empty or None",
+ }
+
+ # Ensure identifier is a string
+ if not isinstance(identifier, str):
+ identifier = str(identifier)
+
+ # Determine type
+ item_type = "unknown"
+ identifier_lower = identifier.lower()
+ if "figure" in identifier_lower:
+ item_type = "figure"
+ elif "definition" in identifier_lower:
+ item_type = "definition"
+ elif "theorem" in identifier_lower:
+ item_type = "theorem"
+ elif "lemma" in identifier_lower:
+ item_type = "lemma"
+ elif "example" in identifier_lower:
+ item_type = "example"
+ elif "remark" in identifier_lower:
+ item_type = "remark"
+ elif identifier.strip().startswith("(") and identifier.strip().endswith(")"):
+ item_type = "formula"
+
+ # 1. Exact match (highest priority)
+ if identifier in items:
+ matched_item = {"identifier": identifier, "type": item_type, "content": items[identifier]}
+ return {
+ "identifier": identifier,
+ "type": item_type,
+ "status": "success",
+ "count": 1,
+ "items": [matched_item],
+ "content": items[identifier], # Backward compatible
+ }
+
+ # 2. Case-insensitive exact match
+ exact_matches = []
+ for key, value in items.items():
+ if key.lower() == identifier_lower:
+ exact_matches.append({"identifier": key, "type": item_type, "content": value})
+
+ if exact_matches:
+ # Limit results
+ if max_results and len(exact_matches) > max_results:
+ exact_matches = exact_matches[:max_results]
+
+ # Build content (backward compatible)
+ content = (
+ exact_matches[0]["content"]
+ if len(exact_matches) == 1
+ else "\n\n".join(
+ [f"[{item['identifier']}]\n{item['content']}" for item in exact_matches]
+ )
+ )
+
+ return {
+ "identifier": identifier,
+ "type": item_type,
+ "status": "success",
+ "count": len(exact_matches),
+ "items": exact_matches,
+ "content": content,
+ }
+
+ # 3. Prefix match (e.g., "2.1" matches "(2.1.1)", "(2.1.2)", etc.)
+ prefix_matches = []
+ identifier_clean = identifier.strip().strip("()") # Remove parentheses, extract pure numbers
+
+ for key, value in items.items():
+ key_clean = key.strip().strip("()")
+ # Prefix match: key starts with identifier (after removing parentheses)
+ if (
+ key_clean.startswith(identifier_clean + ".")
+ or key_clean == identifier_clean
+ or key.lower().startswith(identifier_lower)
+ ):
+ prefix_matches.append({"identifier": key, "type": item_type, "content": value})
+
+ # Limit results
+ if max_results and len(prefix_matches) > max_results:
+ prefix_matches = prefix_matches[:max_results]
+
+ if prefix_matches:
+ # Build content
+ content = (
+ prefix_matches[0]["content"]
+ if len(prefix_matches) == 1
+ else "\n\n".join(
+ [f"[{item['identifier']}]\n{item['content']}" for item in prefix_matches]
+ )
+ )
+
+ return {
+ "identifier": identifier,
+ "type": item_type,
+ "status": "success",
+ "count": len(prefix_matches),
+ "items": prefix_matches,
+ "content": content,
+ }
+
+ # 4. Partial match (contains query string)
+ partial_matches = []
+ for key, value in items.items():
+ if identifier_lower in key.lower():
+ partial_matches.append({"identifier": key, "type": item_type, "content": value})
+
+ # Limit results
+ if max_results and len(partial_matches) > max_results:
+ partial_matches = partial_matches[:max_results]
+
+ if partial_matches:
+ content = (
+ partial_matches[0]["content"]
+ if len(partial_matches) == 1
+ else "\n\n".join(
+ [f"[{item['identifier']}]\n{item['content']}" for item in partial_matches]
+ )
+ )
+
+ return {
+ "identifier": identifier,
+ "type": item_type,
+ "status": "success",
+ "count": len(partial_matches),
+ "items": partial_matches,
+ "content": content,
+ }
+
+ # 5. Not found - provide suggestions
+ suggestions = [k for k in items if identifier_lower in k.lower()][:5]
+ error_msg = f"Numbered item '{identifier}' not found"
+ if suggestions:
+ error_msg += "\n\nSimilar items:\n" + "\n".join(f" • {s}" for s in suggestions)
+
+ return {
+ "identifier": identifier,
+ "type": item_type,
+ "status": "failed",
+ "count": 0,
+ "items": [],
+ "content": "",
+ "error": error_msg,
+ }
+
+
+if __name__ == "__main__":
+ import sys
+
+ if sys.platform == "win32":
+ import io
+
+ sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8")
+
+ # Test
+ print("Testing query_numbered_item\n" + "=" * 60)
+
+ # Test 1
+ print("\n[Test 1] Query formula (1.2.1):")
+ result = query_numbered_item("(1.2.1)", kb_name="ai_textbook")
+ print(f"Status: {result['status']}")
+ print(f"Type: {result['type']}")
+ print(f"Content: {result.get('content', result.get('error'))[:200]}...")
+
+ print("\n" + "=" * 60)
diff --git a/src/tools/rag_tool.py b/src/tools/rag_tool.py
new file mode 100644
index 000000000..be8e54bb5
--- /dev/null
+++ b/src/tools/rag_tool.py
@@ -0,0 +1,262 @@
+#!/usr/bin/env python
+"""
+RAG Query Tool - Wrapper for RAG query functionality
+"""
+
+import asyncio
+from pathlib import Path
+import sys
+
+# Add parent directory to path (insert at front to prioritize project modules)
+project_root = Path(__file__).parent.parent.parent
+# Add raganything module path
+raganything_path = project_root.parent / "raganything" / "RAG-Anything"
+if raganything_path.exists():
+ sys.path.insert(0, str(raganything_path))
+
+from dotenv import load_dotenv
+from lightrag.llm.openai import openai_complete_if_cache, openai_embed
+from lightrag.utils import EmbeddingFunc
+from raganything import RAGAnything, RAGAnythingConfig
+
+from src.core.core import get_embedding_config, get_llm_config
+from src.core.logging import LightRAGLogContext
+from src.knowledge.manager import KnowledgeBaseManager
+
+# Load environment variables
+load_dotenv(project_root / "OpenTutor.env", override=False)
+load_dotenv(project_root / ".env", override=False)
+
+
+async def rag_search(
+ query: str,
+ kb_name: str | None = None,
+ mode: str = "hybrid",
+ api_key: str | None = None,
+ base_url: str | None = None,
+ kb_base_dir: str | None = None,
+ **kwargs,
+) -> dict:
+ """
+ Query knowledge base using RAG
+
+ Args:
+ query: Query question
+ kb_name: Knowledge base name (optional, defaults to default knowledge base)
+ mode: Query mode, options: "local", "global", "hybrid", "naive" (default: "hybrid")
+ api_key: LLM API key (optional, defaults to reading from environment variables)
+ base_url: LLM API Base URL (optional, defaults to reading from environment variables)
+ kb_base_dir: Knowledge base base directory (default: "./knowledge_bases")
+ **kwargs: Other query parameters (e.g., only_need_context, only_need_prompt, etc.)
+
+ Returns:
+ dict: Dictionary containing query results
+ {
+ "query": str,
+ "answer": str,
+ "mode": str
+ }
+ """
+ # Get LLM configuration
+ try:
+ llm_config = get_llm_config()
+ except ValueError as e:
+ raise ValueError(f"LLM configuration error: {e!s}")
+
+ # Get Embedding configuration
+ try:
+ embedding_config = get_embedding_config()
+ except ValueError as e:
+ raise ValueError(f"Embedding configuration error: {e!s}")
+
+ # Override configuration with provided parameters (if provided)
+ llm_api_key = api_key or llm_config["api_key"]
+ llm_base_url = base_url or llm_config["base_url"]
+ llm_model = llm_config["model"]
+
+ embedding_api_key = embedding_config["api_key"]
+ embedding_base_url = embedding_config["base_url"]
+ embedding_model = embedding_config["model"]
+ embedding_dim = embedding_config["dim"]
+ embedding_max_tokens = embedding_config["max_tokens"]
+
+ # If knowledge base path not specified, try to get from config
+ if kb_base_dir is None:
+ try:
+ from src.core.core import get_path_from_config, load_config_with_main
+
+ project_root = Path(__file__).parent.parent.parent
+ # Try loading from solve_config (most common)
+ config = load_config_with_main("solve_config.yaml", project_root)
+ kb_base_dir = get_path_from_config(config, "knowledge_bases_dir") or config.get(
+ "tools", {}
+ ).get("rag_tool", {}).get("kb_base_dir")
+ if kb_base_dir:
+ kb_base_dir = str(kb_base_dir)
+ except Exception:
+ pass
+
+ # Fallback to default path
+ if kb_base_dir is None:
+ project_root = Path(__file__).parent.parent.parent
+ kb_base_dir = str(project_root / "data" / "knowledge_bases")
+
+ # Use KnowledgeBaseManager to get RAG storage path
+ try:
+ kb_manager = KnowledgeBaseManager(kb_base_dir)
+ working_dir = str(kb_manager.get_rag_storage_path(kb_name))
+ except ValueError as e:
+ # If rag_storage doesn't exist, try using traditional path
+ if "RAG storage not found" in str(e):
+ if kb_name:
+ kb_dir = Path(kb_base_dir) / kb_name
+ else:
+ kb_dir = Path(kb_base_dir) / kb_manager.get_default()
+ working_dir = str(kb_dir / "rag_storage")
+ # If still doesn't exist, provide friendly message
+ if not Path(working_dir).exists():
+ raise ValueError(
+ "Error: Knowledge base RAG storage not initialized\nHint: Please run init_knowledge_base.py to initialize the knowledge base"
+ )
+ else:
+ raise ValueError(f"Error: {e!s}")
+ except Exception as e:
+ raise Exception(f"Error: Unable to access knowledge base - {e!s}")
+
+ # Define LLM function
+ def llm_model_func(prompt, system_prompt=None, history_messages=[], **kwargs):
+ return openai_complete_if_cache(
+ llm_model,
+ prompt,
+ system_prompt=system_prompt,
+ history_messages=history_messages,
+ api_key=llm_api_key,
+ base_url=llm_base_url,
+ **kwargs,
+ )
+
+ def vision_model_func(
+ prompt,
+ system_prompt=None,
+ history_messages=[],
+ image_data=None,
+ messages=None,
+ **kwargs,
+ ):
+ # If messages format is provided (for multimodal VLM enhanced query), use it directly
+ if messages:
+ # Remove 'messages' and other message-related params from kwargs to avoid duplicate parameter
+ clean_kwargs = {
+ k: v
+ for k, v in kwargs.items()
+ if k not in ["messages", "prompt", "system_prompt", "history_messages"]
+ }
+ return openai_complete_if_cache(
+ llm_model,
+ prompt="", # Empty prompt when using messages
+ system_prompt=None,
+ history_messages=[],
+ messages=messages,
+ api_key=llm_api_key,
+ base_url=llm_base_url,
+ **clean_kwargs,
+ )
+ # Traditional single image format
+ if image_data:
+ # Remove message-related params from kwargs to avoid duplicate parameter
+ clean_kwargs = {
+ k: v
+ for k, v in kwargs.items()
+ if k not in ["messages", "prompt", "system_prompt", "history_messages"]
+ }
+ return openai_complete_if_cache(
+ llm_model,
+ prompt="", # Empty prompt when using messages
+ system_prompt=None,
+ history_messages=[],
+ messages=[
+ {"role": "system", "content": system_prompt} if system_prompt else None,
+ (
+ {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": prompt},
+ {
+ "type": "image_url",
+ "image_url": {"url": f"data:image/jpeg;base64,{image_data}"},
+ },
+ ],
+ }
+ if image_data
+ else {"role": "user", "content": prompt}
+ ),
+ ],
+ api_key=llm_api_key,
+ base_url=llm_base_url,
+ **clean_kwargs,
+ )
+ # Pure text format
+ return llm_model_func(prompt, system_prompt, history_messages, **kwargs)
+
+ # Define embedding function
+ embedding_func = EmbeddingFunc(
+ embedding_dim=embedding_dim,
+ max_token_size=embedding_max_tokens,
+ func=lambda texts: openai_embed(
+ texts,
+ model=embedding_model,
+ api_key=embedding_api_key,
+ base_url=embedding_base_url,
+ ),
+ )
+
+ # Create RAG instance
+ config = RAGAnythingConfig(
+ working_dir=working_dir,
+ enable_image_processing=True,
+ enable_table_processing=True,
+ enable_equation_processing=True,
+ )
+
+ # Use log forwarding context manager
+ with LightRAGLogContext(scene="rag_tool"):
+ rag = RAGAnything(
+ config=config,
+ llm_model_func=llm_model_func,
+ # vision_model_func=vision_model_func,
+ embedding_func=embedding_func,
+ )
+
+ # Ensure initialization
+ await rag._ensure_lightrag_initialized()
+
+ # Execute query
+ try:
+ answer = await rag.aquery(query, mode=mode, **kwargs)
+ answer_str = answer if isinstance(answer, str) else str(answer)
+
+ return {"query": query, "answer": answer_str, "mode": mode}
+ except Exception as e:
+ raise Exception(f"Query failed: {e!s}")
+
+
+if __name__ == "__main__":
+ import sys
+
+ if sys.platform == "win32":
+ import io
+
+ sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8")
+
+ # Test
+ result = asyncio.run(
+ rag_search(
+ "What is the lookup table (LUT) in FPGA?",
+ kb_name="DE-all",
+ mode="naive",
+ only_need_context=False,
+ )
+ )
+
+ print(f"Query: {result['query']}")
+ print(f"Answer: {result['answer']}")
diff --git a/src/tools/tex_chunker.py b/src/tools/tex_chunker.py
new file mode 100644
index 000000000..e820b2aef
--- /dev/null
+++ b/src/tools/tex_chunker.py
@@ -0,0 +1,334 @@
+"""
+TeX Chunker - LaTeX text chunking tool
+
+Features:
+1. Intelligent chunking of LaTeX content (by section or token count)
+2. Token estimation (based on GPT tokenizer)
+3. Maintain context coherence (overlap between chunks)
+
+Author: OpenTutor Team
+Version: v1.0
+Based on: TODO.md specification
+"""
+
+import os
+import re
+
+import tiktoken
+
+
+class TexChunker:
+ """LaTeX text chunking tool"""
+
+ def __init__(self, model: str | None = None):
+ """
+ Initialize chunking tool
+
+ Args:
+ model: Model name (for token estimation). If not provided, read from LLM_MODEL environment variable
+ """
+ # Read model configuration from environment variables
+ if model is None:
+ model = os.getenv("LLM_MODEL", "gpt-4o")
+
+ try:
+ self.encoder = tiktoken.encoding_for_model(model)
+ except:
+ # If model not supported, use cl100k_base (GPT-4 encoding)
+ self.encoder = tiktoken.get_encoding("cl100k_base")
+
+ def estimate_tokens(self, text: str) -> int:
+ """
+ Estimate token count of text
+
+ Args:
+ text: Input text
+
+ Returns:
+ Token count
+ """
+ try:
+ # Clean text: remove overly long repeated characters (may cause token explosion)
+ cleaned_text = self._clean_text(text)
+ tokens = self.encoder.encode(cleaned_text)
+ return len(tokens)
+ except Exception as e:
+ # If encoding fails, use rough estimate: 1 token ≈ 4 chars
+ print(f" ⚠️ Token estimation failed, using rough estimate: {e!s}")
+ return len(text) // 4
+
+ def _clean_text(self, text: str) -> str:
+ """
+ Clean text to prevent token estimation anomalies
+
+ - Remove overly long repeated character sequences
+ - Limit single line length
+ """
+ import re
+
+ # Remove overly long repeated characters (e.g., consecutive spaces, newlines, etc.)
+ text = re.sub(r"(\s)\1{100,}", r"\1" * 10, text)
+
+ # Remove overly long single lines (may be erroneous data)
+ lines = text.split("\n")
+ cleaned_lines = []
+ for line in lines:
+ if len(line) > 10000: # Single line over 10k characters, may be problematic
+ print(f" ⚠️ Detected overly long line ({len(line)} characters), truncating")
+ line = line[:10000] + "...[truncated]"
+ cleaned_lines.append(line)
+
+ return "\n".join(cleaned_lines)
+
+ def split_tex_into_chunks(
+ self, tex_content: str, max_tokens: int = 8000, overlap: int = 500
+ ) -> list[str]:
+ r"""
+ Split LaTeX content into chunks
+
+ Strategy:
+ 1. Prioritize splitting by sections (\section, \subsection)
+ 2. If single section is too long, split by paragraphs
+ 3. Maintain overlap tokens to avoid context loss
+
+ Args:
+ tex_content: LaTeX source code
+ max_tokens: Maximum tokens per chunk (default: 8000)
+ overlap: Overlap tokens between chunks (default: 500)
+
+ Returns:
+ List of chunks
+ """
+ total_tokens = self.estimate_tokens(tex_content)
+
+ # If total length doesn't exceed max_tokens, return directly
+ if total_tokens <= max_tokens:
+ return [tex_content]
+
+ print(f" LaTeX content needs chunking: {total_tokens:,} tokens > {max_tokens:,} tokens")
+ print(
+ f" File character count: {len(tex_content):,}, line count: {len(tex_content.splitlines()):,}"
+ )
+
+ # 1. Try splitting by sections
+ sections = self._split_by_sections(tex_content)
+
+ # 2. Merge sections into chunks
+ chunks = []
+ current_chunk = ""
+ current_tokens = 0
+
+ for section in sections:
+ section_tokens = self.estimate_tokens(section)
+
+ if section_tokens > max_tokens:
+ # Single section too long, need further splitting
+ if current_chunk:
+ chunks.append(current_chunk)
+ current_chunk = ""
+ current_tokens = 0
+
+ # Split overly long section by paragraphs
+ sub_chunks = self._split_by_paragraphs(section, max_tokens, overlap)
+ chunks.extend(sub_chunks)
+ # Check if can merge into current chunk
+ elif current_tokens + section_tokens <= max_tokens:
+ current_chunk += section
+ current_tokens += section_tokens
+ else:
+ # Save current chunk, start new chunk
+ if current_chunk:
+ chunks.append(current_chunk)
+
+ # Add overlap (take part from end of current chunk)
+ if chunks and overlap > 0:
+ overlap_text = self._get_overlap_text(chunks[-1], overlap)
+ current_chunk = overlap_text + section
+ current_tokens = self.estimate_tokens(current_chunk)
+ else:
+ current_chunk = section
+ current_tokens = section_tokens
+
+ # Save last chunk
+ if current_chunk:
+ chunks.append(current_chunk)
+
+ print(f" Chunking completed: {len(chunks)} chunks")
+ return chunks
+
+ def _split_by_sections(self, tex_content: str) -> list[str]:
+ """
+ Split LaTeX content by sections
+
+ Recognizes:
+ - \\section{...}
+ - \\subsection{...}
+ - \\subsubsection{...}
+
+ Returns:
+ List of sections
+ """
+ # Regex match section markers
+ pattern = r"(\\(?:sub)*section\{[^}]*\})"
+
+ # Split text
+ parts = re.split(pattern, tex_content)
+
+ if len(parts) <= 1:
+ # No section markers found, split by paragraphs
+ return self._split_by_paragraphs(tex_content, max_tokens=10000, overlap=0)
+
+ # Recombine: merge section markers and content
+ sections = []
+ for i in range(1, len(parts), 2):
+ if i < len(parts):
+ section = parts[i] # Section marker
+ if i + 1 < len(parts):
+ section += parts[i + 1] # Section content
+ sections.append(section)
+
+ # Add preamble part (first element)
+ if parts[0].strip():
+ sections.insert(0, parts[0])
+
+ return sections
+
+ def _split_by_paragraphs(self, text: str, max_tokens: int, overlap: int) -> list[str]:
+ """
+ Split text by paragraphs (for overly long sections)
+
+ Args:
+ text: Input text
+ max_tokens: Maximum tokens per chunk
+ overlap: Overlap tokens
+
+ Returns:
+ List of paragraph chunks
+ """
+ # Split paragraphs by double newlines
+ paragraphs = re.split(r"\n\n+", text)
+
+ chunks = []
+ current_chunk = ""
+ current_tokens = 0
+
+ for para in paragraphs:
+ para_tokens = self.estimate_tokens(para)
+
+ if para_tokens > max_tokens:
+ # Single paragraph too long, split by sentences
+ if current_chunk:
+ chunks.append(current_chunk)
+ current_chunk = ""
+ current_tokens = 0
+
+ # Split by sentences (simple method: split by periods)
+ sentences = re.split(r"(?<=[.!?])\s+", para)
+ for sentence in sentences:
+ sentence_tokens = self.estimate_tokens(sentence)
+ if current_tokens + sentence_tokens <= max_tokens:
+ current_chunk += sentence + " "
+ current_tokens += sentence_tokens
+ else:
+ if current_chunk:
+ chunks.append(current_chunk)
+ current_chunk = sentence + " "
+ current_tokens = sentence_tokens
+ # Check if can merge
+ elif current_tokens + para_tokens <= max_tokens:
+ current_chunk += para + "\n\n"
+ current_tokens += para_tokens
+ else:
+ # Save current chunk
+ if current_chunk:
+ chunks.append(current_chunk)
+
+ # Add overlap
+ if chunks and overlap > 0:
+ overlap_text = self._get_overlap_text(chunks[-1], overlap)
+ current_chunk = overlap_text + para + "\n\n"
+ current_tokens = self.estimate_tokens(current_chunk)
+ else:
+ current_chunk = para + "\n\n"
+ current_tokens = para_tokens
+
+ # Save last chunk
+ if current_chunk:
+ chunks.append(current_chunk)
+
+ return chunks
+
+ def _get_overlap_text(self, previous_chunk: str, overlap_tokens: int) -> str:
+ """
+ Extract overlap portion from end of previous chunk
+
+ Args:
+ previous_chunk: Previous chunk
+ overlap_tokens: Number of overlap tokens
+
+ Returns:
+ Overlap text
+ """
+ # Encode entire chunk
+ tokens = self.encoder.encode(previous_chunk)
+
+ # Take last overlap_tokens tokens
+ if len(tokens) <= overlap_tokens:
+ return previous_chunk
+
+ overlap_token_ids = tokens[-overlap_tokens:]
+ overlap_text = self.encoder.decode(overlap_token_ids)
+
+ return overlap_text
+
+
+# ========== Usage Example ==========
+
+if __name__ == "__main__":
+ # Create chunking tool
+ chunker = TexChunker(model="gpt-4o")
+
+ # Test text
+ test_tex = r"""
+\section{Introduction}
+This is the introduction section with some content that is moderately long.
+It contains multiple paragraphs and discusses the background of the research.
+
+The problem we are addressing is important and has wide applications.
+
+\section{Related Work}
+Previous work has explored various approaches to this problem.
+Some researchers have used method A, while others prefer method B.
+
+Recent advances in deep learning have opened new possibilities.
+
+\subsection{Deep Learning Approaches}
+Neural networks have shown promising results in many tasks.
+Convolutional networks are particularly effective for image processing.
+
+\section{Methodology}
+Our approach combines the best aspects of previous methods.
+We propose a novel architecture that addresses the key limitations.
+
+\subsection{Model Architecture}
+The model consists of three main components: encoder, processor, and decoder.
+Each component is carefully designed to handle specific aspects of the task.
+
+\section{Experiments}
+We conducted extensive experiments on multiple datasets.
+The results demonstrate the effectiveness of our approach.
+ """
+
+ # Estimate tokens
+ total_tokens = chunker.estimate_tokens(test_tex)
+ print(f"Total tokens: {total_tokens}")
+
+ # Chunk (set smaller max_tokens for demonstration)
+ chunks = chunker.split_tex_into_chunks(tex_content=test_tex, max_tokens=200, overlap=50)
+
+ print(f"\nChunking result: {len(chunks)} chunks\n")
+
+ for i, chunk in enumerate(chunks, 1):
+ chunk_tokens = chunker.estimate_tokens(chunk)
+ print(f"Chunk {i} ({chunk_tokens} tokens):")
+ print(chunk[:200] + "...\n")
diff --git a/src/tools/tex_downloader.py b/src/tools/tex_downloader.py
new file mode 100644
index 000000000..3e8c2179b
--- /dev/null
+++ b/src/tools/tex_downloader.py
@@ -0,0 +1,236 @@
+"""
+TeX Downloader - LaTeX source code download tool
+
+Features:
+1. Download LaTeX source from ArXiv
+2. Extract and locate main tex file
+3. Read tex content
+
+Author: OpenTutor Team
+Version: v1.0
+Based on: TODO.md specification
+"""
+
+from pathlib import Path
+import re
+import shutil
+import tarfile
+import tempfile
+import zipfile
+
+import requests
+
+
+class TexDownloadResult:
+ """LaTeX download result"""
+
+ def __init__(
+ self,
+ success: bool,
+ tex_path: str | None = None,
+ tex_content: str | None = None,
+ error: str | None = None,
+ ):
+ self.success = success
+ self.tex_path = tex_path
+ self.tex_content = tex_content
+ self.error = error
+
+
+class TexDownloader:
+ """LaTeX source code download tool"""
+
+ def __init__(self, workspace_dir: str):
+ """
+ Initialize downloader
+
+ Args:
+ workspace_dir: Workspace directory (for saving downloaded files)
+ """
+ self.workspace_dir = Path(workspace_dir)
+ self.workspace_dir.mkdir(parents=True, exist_ok=True)
+
+ def download_arxiv_source(
+ self, arxiv_url: str, arxiv_id: str | None = None
+ ) -> TexDownloadResult:
+ """
+ Download LaTeX source from ArXiv
+
+ Args:
+ arxiv_url: ArXiv paper URL
+ arxiv_id: ArXiv ID (optional, if not in URL)
+
+ Returns:
+ TexDownloadResult object
+ """
+ # Extract ArXiv ID
+ if not arxiv_id:
+ arxiv_id = self._extract_arxiv_id(arxiv_url)
+
+ if not arxiv_id:
+ return TexDownloadResult(success=False, error="Unable to extract ArXiv ID")
+
+ try:
+ # Build source download URL
+ source_url = f"https://arxiv.org/e-print/{arxiv_id}"
+
+ # Download source package
+ print(f" Downloading source: {source_url}")
+ response = requests.get(source_url, timeout=30)
+ response.raise_for_status()
+
+ # Create temporary directory
+ temp_dir = tempfile.mkdtemp(dir=self.workspace_dir)
+
+ # Save source package
+ source_file = Path(temp_dir) / f"{arxiv_id}_source"
+ with open(source_file, "wb") as f:
+ f.write(response.content)
+
+ # Extract source package
+ extract_dir = Path(temp_dir) / "extracted"
+ extract_dir.mkdir(exist_ok=True)
+
+ if self._is_tar_file(source_file):
+ self._extract_tar(source_file, extract_dir)
+ elif self._is_zip_file(source_file):
+ self._extract_zip(source_file, extract_dir)
+ else:
+ # Might be a single tex file
+ shutil.copy(source_file, extract_dir / f"{arxiv_id}.tex")
+
+ # Find main tex file
+ main_tex = self._find_main_tex(extract_dir)
+
+ if not main_tex:
+ return TexDownloadResult(success=False, error="Main tex file not found")
+
+ # Read tex content
+ tex_content = self._read_tex_file(main_tex)
+
+ # Move to permanent location
+ paper_dir = self.workspace_dir / f"paper_{arxiv_id}"
+ paper_dir.mkdir(exist_ok=True)
+
+ final_tex_path = paper_dir / "main.tex"
+ shutil.copy(main_tex, final_tex_path)
+
+ # Clean up temporary directory
+ shutil.rmtree(temp_dir, ignore_errors=True)
+
+ return TexDownloadResult(
+ success=True, tex_path=str(final_tex_path), tex_content=tex_content
+ )
+
+ except requests.exceptions.RequestException as e:
+ return TexDownloadResult(success=False, error=f"Download failed: {e!s}")
+ except Exception as e:
+ return TexDownloadResult(success=False, error=f"Processing failed: {e!s}")
+
+ def _extract_arxiv_id(self, url: str) -> str | None:
+ """Extract ArXiv ID from URL"""
+ match = re.search(r"arxiv\.org/(?:abs|pdf)/(\d+\.\d+)", url)
+ if match:
+ return match.group(1)
+ return None
+
+ def _is_tar_file(self, file_path: Path) -> bool:
+ """Check if file is a tar file"""
+ try:
+ with tarfile.open(file_path, "r:*") as tar:
+ return True
+ except:
+ return False
+
+ def _is_zip_file(self, file_path: Path) -> bool:
+ """Check if file is a zip file"""
+ try:
+ with zipfile.ZipFile(file_path, "r") as zip_file:
+ return True
+ except:
+ return False
+
+ def _extract_tar(self, tar_path: Path, extract_dir: Path):
+ """Extract tar file"""
+ with tarfile.open(tar_path, "r:*") as tar:
+ tar.extractall(extract_dir)
+
+ def _extract_zip(self, zip_path: Path, extract_dir: Path):
+ """Extract zip file"""
+ with zipfile.ZipFile(zip_path, "r") as zip_file:
+ zip_file.extractall(extract_dir)
+
+ def _find_main_tex(self, directory: Path) -> Path | None:
+ """
+ Find main tex file
+
+ Priority:
+ 1. main.tex
+ 2. paper.tex
+ 3. Tex file containing \\documentclass
+ 4. Largest tex file
+ """
+ tex_files = list(directory.rglob("*.tex"))
+
+ if not tex_files:
+ return None
+
+ # 1. Find main.tex or paper.tex
+ for name in ["main.tex", "paper.tex", "manuscript.tex"]:
+ for tex_file in tex_files:
+ if tex_file.name.lower() == name:
+ return tex_file
+
+ # 2. Find file containing \documentclass
+ for tex_file in tex_files:
+ try:
+ content = tex_file.read_text(encoding="utf-8", errors="ignore")
+ if r"\documentclass" in content:
+ return tex_file
+ except:
+ continue
+
+ # 3. Return largest tex file
+ largest_tex = max(tex_files, key=lambda f: f.stat().st_size)
+ return largest_tex
+
+ def _read_tex_file(self, tex_path: Path) -> str:
+ """Read tex file content"""
+ try:
+ return tex_path.read_text(encoding="utf-8", errors="ignore")
+ except Exception as e:
+ raise Exception(f"Failed to read tex file: {e!s}")
+
+
+def read_tex_file(tex_path: str) -> str:
+ """
+ Read tex file content (convenience function)
+
+ Args:
+ tex_path: tex file path
+
+ Returns:
+ tex content
+ """
+ return Path(tex_path).read_text(encoding="utf-8", errors="ignore")
+
+
+# ========== Usage Example ==========
+
+if __name__ == "__main__":
+ # Test download
+ downloader = TexDownloader(workspace_dir="./test_workspace")
+
+ # Test an ArXiv paper
+ result = downloader.download_arxiv_source(
+ arxiv_url="https://arxiv.org/abs/1706.03762", # Attention is All You Need
+ arxiv_id="1706.03762",
+ )
+
+ if result.success:
+ print("✓ Download successful!")
+ print(f" File path: {result.tex_path}")
+ print(f" Content length: {len(result.tex_content)} characters")
+ print(f" Content preview: {result.tex_content[:500]}...")
+ else:
+ print(f"✗ Download failed: {result.error}")
diff --git a/src/tools/web_search.py b/src/tools/web_search.py
new file mode 100644
index 000000000..c0d5a710e
--- /dev/null
+++ b/src/tools/web_search.py
@@ -0,0 +1,172 @@
+#!/usr/bin/env python
+"""
+Web Search Tool - Network search using Perplexity API
+"""
+
+from datetime import datetime
+import json
+import os
+
+try:
+ from perplexity import Perplexity
+
+ PERPLEXITY_AVAILABLE = True
+except ImportError:
+ PERPLEXITY_AVAILABLE = False
+ Perplexity = None
+
+
+def web_search(query: str, output_dir: str | None = None, verbose: bool = False) -> dict:
+ """
+ Perform network search using Perplexity API and return results
+
+ Args:
+ query: Search query
+ output_dir: Output directory (optional, if provided will save results)
+ verbose: Whether to print detailed information
+
+ Returns:
+ dict: Dictionary containing search results
+ {
+ "query": str,
+ "answer": str,
+ "result_file": str (if file was saved)
+ }
+
+ Raises:
+ ImportError: If perplexity module is not installed
+ ValueError: If PERPLEXITY_API_KEY environment variable is not set
+ Exception: If API call fails
+ """
+ # Check if perplexity module is available
+ if not PERPLEXITY_AVAILABLE:
+ raise ImportError(
+ "perplexity module is not installed. To use web search functionality, please install the corresponding package.\n"
+ "Note: This is an optional feature and does not affect the use of other modules."
+ )
+
+ # Check API key
+ api_key = os.environ.get("PERPLEXITY_API_KEY")
+ if not api_key:
+ raise ValueError("PERPLEXITY_API_KEY environment variable is not set")
+
+ # Initialize client
+ client = Perplexity(api_key=api_key)
+
+ try:
+ # Call API
+ completion = client.chat.completions.create(
+ model="sonar",
+ messages=[
+ {
+ "role": "system",
+ "content": "You are a helpful AI assistant. Provide detailed and accurate answers based on web search results.",
+ },
+ {"role": "user", "content": query},
+ ],
+ )
+
+ # Extract response content
+ answer = completion.choices[0].message.content
+
+ # Build result dictionary
+ result = {
+ "timestamp": datetime.now().isoformat(),
+ "query": query,
+ "model": completion.model,
+ "answer": answer,
+ "response": {
+ "content": answer,
+ "role": completion.choices[0].message.role,
+ "finish_reason": completion.choices[0].finish_reason,
+ },
+ "usage": {
+ "prompt_tokens": completion.usage.prompt_tokens,
+ "completion_tokens": completion.usage.completion_tokens,
+ "total_tokens": completion.usage.total_tokens,
+ "cost": {
+ "total_cost": completion.usage.cost.total_cost,
+ "input_tokens_cost": completion.usage.cost.input_tokens_cost,
+ "output_tokens_cost": completion.usage.cost.output_tokens_cost,
+ },
+ },
+ "citations": [],
+ "search_results": [],
+ }
+
+ # Extract citation links (improved: includes complete metadata)
+ if hasattr(completion, "citations") and completion.citations:
+ for i, citation_url in enumerate(completion.citations, 1):
+ citation_data = {
+ "id": i,
+ "reference": f"[{i}]",
+ "url": citation_url,
+ "title": "",
+ "snippet": "",
+ }
+
+ # Try to match from search_results
+ for search_item in result.get("search_results", []):
+ if search_item.get("url") == citation_url:
+ citation_data["title"] = search_item.get("title", "")
+ citation_data["snippet"] = search_item.get("snippet", "")
+ break
+
+ result["citations"].append(citation_data)
+
+ # Extract search result details
+ if hasattr(completion, "search_results") and completion.search_results:
+ for search_item in completion.search_results:
+ search_result = {
+ "title": search_item.title,
+ "url": search_item.url,
+ "date": search_item.date,
+ "last_updated": search_item.last_updated,
+ "snippet": search_item.snippet,
+ "source": search_item.source,
+ }
+ result["search_results"].append(search_result)
+
+ # If output directory provided, save results
+ result_file = None
+ if output_dir:
+ os.makedirs(output_dir, exist_ok=True)
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
+ output_filename = f"search_{timestamp}.json"
+ output_path = os.path.join(output_dir, output_filename)
+
+ with open(output_path, "w", encoding="utf-8") as f:
+ json.dump(result, f, ensure_ascii=False, indent=2)
+
+ result_file = output_path
+
+ if verbose:
+ print(f"Search results saved to: {output_path}")
+
+ # Add file path to result
+ if result_file:
+ result["result_file"] = result_file
+
+ if verbose:
+ print(f"Query: {query}")
+ print(f"Answer: {answer[:200]}..." if len(answer) > 200 else answer)
+
+ return result
+
+ except Exception as e:
+ raise Exception(f"Perplexity API call failed: {e!s}")
+
+
+if __name__ == "__main__":
+ import sys
+
+ if sys.platform == "win32":
+ import io
+
+ sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8")
+
+ # Test
+ result = web_search("What is a diffusion model?", output_dir="./test_output", verbose=True)
+ print("\nSearch completed!")
+ print(f"Query: {result['query']}")
+ print(f"Answer: {result['answer'][:300]}...")
diff --git a/src/utils/config_manager.py b/src/utils/config_manager.py
new file mode 100644
index 000000000..053a39943
--- /dev/null
+++ b/src/utils/config_manager.py
@@ -0,0 +1,137 @@
+import os
+from pathlib import Path
+from threading import Lock
+from typing import Any, Dict
+
+import yaml
+
+
+class ConfigManager:
+ """
+ Thread-safe manager for reading and writing configuration files.
+ Primarily manages config/main.yaml and reads .env.
+ """
+
+ _instance = None
+ _lock = Lock()
+
+ def __new__(cls):
+ 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):
+ if self._initialized:
+ return
+
+ self.project_root = Path(__file__).parent.parent.parent
+ self.config_path = self.project_root / "config" / "main.yaml"
+ self._config_cache = None
+ self._last_mtime = 0
+ self._initialized = True
+
+ def load_config(self, force_reload: bool = False) -> Dict[str, Any]:
+ """
+ Load configuration from main.yaml.
+ Uses caching based on file modification time.
+ """
+ if not self.config_path.exists():
+ return {}
+
+ current_mtime = self.config_path.stat().st_mtime
+
+ if self._config_cache is None or force_reload or current_mtime > self._last_mtime:
+ with self._lock:
+ try:
+ with open(self.config_path, "r", encoding="utf-8") as f:
+ self._config_cache = yaml.safe_load(f) or {}
+ self._last_mtime = current_mtime
+ except Exception as e:
+ print(f"Error loading config: {e}")
+ return {}
+
+ return self._config_cache.copy() # Return copy to prevent direct mutation
+
+ def save_config(self, config: Dict[str, Any]) -> bool:
+ """
+ Save configuration to main.yaml.
+ Merges provided config with existing one to ensure partial updates work if needed,
+ though usually we expect full section replacements.
+ """
+ try:
+ # First, load current to ensure we have latest structure
+ current_config = self.load_config(force_reload=True)
+
+ # recursive update strategy could be implemented here if granular updates are needed,
+ # but for now we expect the caller to provide structurally correct data or we just save what's given.
+ # To be safe against partial updates killing unrelated sections, we should assume 'config'
+ # might just contain the sections to update.
+
+ # Simple recursive update helper
+ def deep_update(target, source):
+ for key, value in source.items():
+ if isinstance(value, dict) and key in target and isinstance(target[key], dict):
+ deep_update(target[key], value)
+ else:
+ target[key] = value
+
+ deep_update(current_config, config)
+
+ # Ensure directory exists
+ self.config_path.parent.mkdir(parents=True, exist_ok=True)
+
+ with self._lock:
+ with open(self.config_path, "w", encoding="utf-8") as f:
+ yaml.safe_dump(
+ current_config,
+ f,
+ default_flow_style=False,
+ allow_unicode=True,
+ sort_keys=False,
+ )
+
+ # Update cache
+ self._config_cache = current_config
+ self._last_mtime = self.config_path.stat().st_mtime
+
+ return True
+ except Exception as e:
+ print(f"Error saving config: {e}")
+ return False
+
+ def get_env_info(self) -> Dict[str, str]:
+ """
+ Read relevant environment variables.
+ """
+ # Reload env vars from file could be done here using python-dotenv if needed,
+ # but usually os.environ is populated at startup.
+ # For dynamic .env reading, we might want to read the file directly.
+
+ env_vars = {}
+ env_path = self.project_root / ".env"
+
+ if env_path.exists():
+ try:
+ with open(env_path, "r", encoding="utf-8") as f:
+ for line in f:
+ line = line.strip()
+ if not line or line.startswith("#"):
+ continue
+ if "=" in line:
+ key, val = line.split("=", 1)
+ env_vars[key.strip()] = val.strip().strip('"').strip("'")
+ except Exception:
+ pass
+
+ # Fallback to os.environ for values not in .env file but set in environment
+ # Specific keys we care about
+ keys_of_interest = ["LLM_MODEL", "OPENAI_API_KEY", "GOOGLE_API_KEY"] # Add others as needed
+
+ # We might want to mask keys, but returning model name is safe.
+ return {
+ "model": env_vars.get("LLM_MODEL", os.environ.get("LLM_MODEL", "Pro/Flash")),
+ # Add other non-sensitive info if needed
+ }
diff --git a/web/.env.local b/web/.env.local
new file mode 100644
index 000000000..6ff5dfa0e
--- /dev/null
+++ b/web/.env.local
@@ -0,0 +1,9 @@
+# ============================================
+# Auto-generated by start_web.py
+# ============================================
+# This file is automatically updated based on config/main.yaml
+# Do not manually edit this file - it will be overwritten on startup
+# To change the backend port, edit config/main.yaml instead
+# ============================================
+
+NEXT_PUBLIC_API_BASE=http://localhost:8001
diff --git a/web/.prettierignore b/web/.prettierignore
new file mode 100644
index 000000000..d6b85186f
--- /dev/null
+++ b/web/.prettierignore
@@ -0,0 +1,40 @@
+# Dependencies
+node_modules/
+package-lock.json
+bun.lock
+
+# Build outputs
+.next/
+out/
+dist/
+build/
+.vercel/
+
+# Cache
+.cache/
+.parcel-cache/
+
+# Environment files
+.env
+.env.local
+.env*.local
+
+# Logs
+*.log
+npm-debug.log*
+yarn-debug.log*
+yarn-error.log*
+
+# OS files
+.DS_Store
+Thumbs.db
+
+# IDE
+.vscode/
+.idea/
+
+# Generated files
+next-env.d.ts
+
+# Public assets (usually don't need formatting)
+public/
diff --git a/web/.prettierrc.json b/web/.prettierrc.json
new file mode 100644
index 000000000..21dfddb02
--- /dev/null
+++ b/web/.prettierrc.json
@@ -0,0 +1,13 @@
+{
+ "semi": false,
+ "singleQuote": true,
+ "tabWidth": 2,
+ "useTabs": false,
+ "trailingComma": "es5",
+ "printWidth": 100,
+ "arrowParens": "avoid",
+ "endOfLine": "lf",
+ "bracketSpacing": true,
+ "jsxSingleQuote": false,
+ "plugins": []
+}
diff --git a/web/README.md b/web/README.md
new file mode 100644
index 000000000..e7cc7cc9b
--- /dev/null
+++ b/web/README.md
@@ -0,0 +1,322 @@
+# Web Frontend
+
+The Web frontend is a Next.js 14 application that provides the user interface for the OpenTutor system.
+
+## 📋 Overview
+
+The frontend provides:
+
+- Dashboard with activity tracking
+- Knowledge base management
+- Problem solving interface
+- Question generation interface
+- Research interface
+- Guided learning interface
+- Co-Writer interface
+- Notebook management
+- Idea generation interface
+
+## 🏗️ Architecture
+
+```
+web/
+├── app/ # Next.js app directory
+│ ├── page.tsx # Dashboard (home page)
+│ ├── layout.tsx # Root layout
+│ ├── globals.css # Global styles
+│ ├── knowledge/ # Knowledge base pages
+│ ├── solver/ # Problem solving pages
+│ ├── question/ # Question generation pages
+│ ├── research/ # Research pages
+│ ├── guide/ # Guided learning pages
+│ ├── co_writer/ # Co-Writer pages
+│ ├── notebook/ # Notebook pages
+│ ├── ideagen/ # Idea generation pages
+│ └── settings/ # Settings pages
+├── components/ # React components
+│ ├── Sidebar.tsx # Navigation sidebar
+│ ├── SystemStatus.tsx # System status indicator
+│ ├── ActivityDetail.tsx # Activity detail view
+│ ├── CoWriterEditor.tsx # Co-Writer editor
+│ ├── AddToNotebookModal.tsx # Add to notebook modal
+│ └── ui/ # UI components
+│ ├── Button.tsx
+│ └── Modal.tsx
+├── context/ # React context
+│ └── GlobalContext.tsx # Global state management
+├── lib/ # Utilities
+│ └── api.ts # API client
+├── package.json # Dependencies
+├── tsconfig.json # TypeScript configuration
+├── tailwind.config.js # Tailwind CSS configuration
+└── postcss.config.js # PostCSS configuration
+```
+
+## 🛠️ Technology Stack
+
+- **Framework**: Next.js 14 (App Router)
+- **Language**: TypeScript
+- **Styling**: Tailwind CSS
+- **UI Components**: Custom components with Lucide React icons
+- **Markdown**: react-markdown with KaTeX for math
+- **PDF Export**: jsPDF + html2canvas
+- **Animations**: Framer Motion
+
+## 📦 Dependencies
+
+### Core Dependencies
+
+```json
+{
+ "next": "14.0.3",
+ "react": "^18",
+ "react-dom": "^18",
+ "react-markdown": "^9.0.1",
+ "rehype-katex": "^7.0.0",
+ "remark-math": "^6.0.0",
+ "lucide-react": "^0.294.0",
+ "framer-motion": "^10.16.4",
+ "jspdf": "^2.5.1",
+ "html2canvas": "^1.4.1"
+}
+```
+
+## 🚀 Getting Started
+
+### Installation
+
+```bash
+cd web
+npm install
+```
+
+### Development
+
+```bash
+npm run dev
+```
+
+The frontend will be available at `http://localhost:3782` (or port configured in `config/main.yaml`).
+
+### Build
+
+```bash
+npm run build
+npm start
+```
+
+## 📁 Key Components
+
+### Dashboard (app/page.tsx)
+
+Main dashboard showing:
+
+- Recent activities
+- Knowledge base overview
+- Notebook statistics
+- Quick access to modules
+
+### API Client (lib/api.ts)
+
+Centralized API client for backend communication:
+
+```typescript
+import { apiUrl } from "@/lib/api";
+
+// REST API
+const response = await fetch(`${apiUrl}/knowledge/list`);
+
+// WebSocket
+const ws = new WebSocket(`${wsUrl}/api/v1/solve`);
+```
+
+### Global Context (context/GlobalContext.tsx)
+
+Manages global state:
+
+- System status
+- User preferences
+- Active sessions
+
+### Sidebar (components/Sidebar.tsx)
+
+Navigation sidebar with links to all modules.
+
+## 🔌 API Integration
+
+### REST API
+
+```typescript
+const response = await fetch(`${apiUrl}/api/v1/knowledge/list`, {
+ method: "GET",
+ headers: {
+ "Content-Type": "application/json",
+ },
+});
+const data = await response.json();
+```
+
+### WebSocket
+
+```typescript
+const ws = new WebSocket(`${wsUrl}/api/v1/solve`);
+
+ws.onopen = () => {
+ ws.send(
+ JSON.stringify({
+ question: "Your question",
+ kb_name: "ai_textbook",
+ }),
+ );
+};
+
+ws.onmessage = (event) => {
+ const data = JSON.parse(event.data);
+ // Handle streaming data
+};
+
+ws.onerror = (error) => {
+ console.error("WebSocket error:", error);
+};
+
+ws.onclose = () => {
+ console.log("WebSocket closed");
+};
+```
+
+## 🎨 Styling
+
+### Tailwind CSS
+
+The project uses Tailwind CSS for styling. Configuration in `tailwind.config.js`.
+
+### Global Styles
+
+Global styles in `app/globals.css` including:
+
+- Base styles
+- Custom CSS variables
+- Utility classes
+
+## 📱 Pages
+
+### Knowledge Base (`/knowledge`)
+
+- List knowledge bases
+- Create new knowledge base
+- Upload documents
+- View knowledge base details
+
+### Problem Solving (`/solver`)
+
+- Input problem
+- Select knowledge base
+- Real-time solving with streaming
+- View solution
+
+### Question Generation (`/question`)
+
+- Configure question requirements
+- Generate questions
+- View generated questions
+
+### Research (`/research`)
+
+- Input research topic
+- Select research mode
+- Real-time research progress
+- View research report
+
+### Guided Learning (`/guide`)
+
+- Select notebook
+- Generate learning plan
+- Interactive learning pages
+- Q&A during learning
+
+### Co-Writer (`/co_writer`)
+
+- Markdown editor
+- AI text editing
+- Automatic annotation
+- TTS narration
+
+### Notebook (`/notebook`)
+
+- List notebooks
+- Create/edit notebooks
+- View notebook records
+- Organize records
+
+### Idea Generation (`/ideagen`)
+
+- Select notebook
+- Generate research ideas
+- View generated ideas
+
+## ⚙️ Configuration
+
+### API Base URL
+
+Configured in `lib/api.ts`:
+
+```typescript
+export const apiUrl =
+ process.env.NEXT_PUBLIC_API_BASE || "http://localhost:8001";
+export const wsUrl = process.env.NEXT_PUBLIC_WS_BASE || "ws://localhost:8001";
+```
+
+Set in `.env.local`:
+
+```bash
+NEXT_PUBLIC_API_BASE=http://localhost:8001
+NEXT_PUBLIC_WS_BASE=ws://localhost:8001
+```
+
+## 🔗 Related Modules
+
+- **Backend API**: `src/api/` - FastAPI backend
+- **Agents**: `src/agents/` - Agent implementations
+- **Config**: `config/` - Configuration files
+
+## 🛠️ Development
+
+### Adding a New Page
+
+1. Create page in `app/`:
+
+ ```typescript
+ // app/my-page/page.tsx
+ export default function MyPage() {
+ return <div>My Page</div>
+ }
+ ```
+
+2. Add navigation link in `components/Sidebar.tsx`
+
+### Adding a New Component
+
+1. Create component in `components/`:
+
+ ```typescript
+ // components/MyComponent.tsx
+ export default function MyComponent() {
+ return <div>My Component</div>
+ }
+ ```
+
+2. Export from `components/index.ts` if needed
+
+### Styling Guidelines
+
+- Use Tailwind CSS utility classes
+- Follow existing component patterns
+- Use Lucide React for icons
+- Maintain responsive design
+
+## ⚠️ Notes
+
+1. **API URL**: Ensure API base URL matches backend configuration
+2. **WebSocket**: WebSocket URL must use `ws://` or `wss://` protocol
+3. **CORS**: Backend must allow frontend origin in CORS settings
+4. **Environment Variables**: Use `NEXT_PUBLIC_` prefix for client-side variables
diff --git a/web/app/co_writer/page.tsx b/web/app/co_writer/page.tsx
new file mode 100644
index 000000000..1d5ce194f
--- /dev/null
+++ b/web/app/co_writer/page.tsx
@@ -0,0 +1,26 @@
+"use client";
+
+import CoWriterEditor from "@/components/CoWriterEditor";
+import { Edit3 } from "lucide-react";
+
+export default function CoWriterPage() {
+ return (
+ <div className="h-[calc(100vh-4rem)] animate-fade-in flex flex-col">
+ {/* Header */}
+ <div className="mb-4 shrink-0">
+ <h1 className="text-2xl font-bold text-slate-900 dark:text-slate-100 tracking-tight flex items-center gap-2">
+ <Edit3 className="w-6 h-6 text-purple-600 dark:text-purple-400" />
+ Co-Writer
+ </h1>
+ <p className="text-slate-500 dark:text-slate-400 text-sm mt-1">
+ Intelligent markdown editor with AI-powered writing assistance.
+ </p>
+ </div>
+
+ {/* Editor Container */}
+ <div className="flex-1 min-h-0">
+ <CoWriterEditor />
+ </div>
+ </div>
+ );
+}
diff --git a/web/app/globals.css b/web/app/globals.css
new file mode 100644
index 000000000..6d5e3b5cd
--- /dev/null
+++ b/web/app/globals.css
@@ -0,0 +1,437 @@
+@tailwind base;
+@tailwind components;
+@tailwind utilities;
+
+@layer base {
+ :root {
+ --background: 0 0% 100%;
+ --foreground: 222.2 84% 4.9%;
+
+ --card: 0 0% 100%;
+ --card-foreground: 222.2 84% 4.9%;
+
+ --popover: 0 0% 100%;
+ --popover-foreground: 222.2 84% 4.9%;
+
+ --primary: 221.2 83.2% 53.3%;
+ --primary-foreground: 210 40% 98%;
+
+ --secondary: 210 40% 96.1%;
+ --secondary-foreground: 222.2 47.4% 11.2%;
+
+ --muted: 210 40% 96.1%;
+ --muted-foreground: 215.4 16.3% 46.9%;
+
+ --accent: 210 40% 96.1%;
+ --accent-foreground: 222.2 47.4% 11.2%;
+
+ --destructive: 0 84.2% 60.2%;
+ --destructive-foreground: 210 40% 98%;
+
+ --border: 214.3 31.8% 91.4%;
+ --input: 214.3 31.8% 91.4%;
+ --ring: 221.2 83.2% 53.3%;
+
+ --radius: 0.5rem;
+ }
+
+ .dark {
+ --background: 222.2 84% 4.9%;
+ --foreground: 210 40% 98%;
+
+ --card: 222.2 84% 4.9%;
+ --card-foreground: 210 40% 98%;
+
+ --popover: 222.2 84% 4.9%;
+ --popover-foreground: 210 40% 98%;
+
+ --primary: 210 40% 98%;
+ --primary-foreground: 222.2 47.4% 11.2%;
+
+ --secondary: 217.2 32.6% 17.5%;
+ --secondary-foreground: 210 40% 98%;
+
+ --muted: 217.2 32.6% 17.5%;
+ --muted-foreground: 215 20.2% 65.1%;
+
+ --accent: 217.2 32.6% 17.5%;
+ --accent-foreground: 210 40% 98%;
+
+ --destructive: 0 62.8% 30.6%;
+ --destructive-foreground: 210 40% 98%;
+
+ --border: 217.2 32.6% 17.5%;
+ --input: 217.2 32.6% 17.5%;
+ --ring: 212.7 26.8% 83.9%;
+ }
+}
+
+@layer base {
+ * {
+ @apply border-border;
+ }
+ body {
+ @apply bg-background text-foreground;
+ font-feature-settings:
+ "rlig" 1,
+ "calt" 1;
+ }
+}
+
+/* Markdown Styles */
+.prose pre {
+ @apply bg-slate-950 text-slate-50 rounded-lg p-4 overflow-x-auto my-4;
+}
+
+.prose code {
+ @apply bg-slate-100 text-slate-900 px-1.5 py-0.5 rounded text-sm font-mono;
+}
+
+.dark .prose code {
+ @apply bg-slate-700 text-slate-200;
+}
+
+.prose pre code {
+ @apply bg-transparent text-inherit p-0;
+}
+
+.prose h1,
+.prose h2,
+.prose h3 {
+ @apply font-semibold tracking-tight text-slate-900 mt-8 mb-4;
+}
+
+.dark .prose h1,
+.dark .prose h2,
+.dark .prose h3 {
+ @apply text-slate-100;
+}
+
+.prose p {
+ @apply leading-7 mb-4 text-slate-700;
+}
+
+.dark .prose p {
+ @apply text-slate-300;
+}
+
+.prose ul {
+ @apply list-disc list-outside ml-6 mb-4 text-slate-700;
+}
+
+.dark .prose ul {
+ @apply text-slate-300;
+}
+
+.prose ol {
+ @apply list-decimal list-outside ml-6 mb-4 text-slate-700;
+}
+
+.dark .prose ol {
+ @apply text-slate-300;
+}
+
+.prose blockquote {
+ @apply border-l-4 border-blue-500 pl-4 italic my-4 text-slate-600;
+}
+
+.dark .prose blockquote {
+ @apply text-slate-400 border-blue-400;
+}
+
+.prose a {
+ @apply text-blue-600 hover:text-blue-700 underline;
+}
+
+.dark .prose a {
+ @apply text-blue-400 hover:text-blue-300;
+}
+
+/* Prose strong/bold */
+.prose strong {
+ @apply text-slate-900 font-semibold;
+}
+
+.dark .prose strong {
+ @apply text-slate-100;
+}
+
+/* KaTeX Styles for Dark Mode */
+.dark .katex {
+ color: #e2e8f0;
+}
+
+.dark .katex .mord,
+.dark .katex .mbin,
+.dark .katex .mrel,
+.dark .katex .mopen,
+.dark .katex .mclose,
+.dark .katex .mpunct,
+.dark .katex .minner,
+.dark .katex .mop {
+ color: #e2e8f0;
+}
+
+/* Tables in dark mode */
+.prose table {
+ @apply border-collapse;
+}
+
+.prose th {
+ @apply bg-slate-100 text-slate-900 font-semibold px-4 py-2 border border-slate-200;
+}
+
+.dark .prose th {
+ @apply bg-slate-700 text-slate-100 border-slate-600;
+}
+
+.prose td {
+ @apply px-4 py-2 border border-slate-200 text-slate-700;
+}
+
+.dark .prose td {
+ @apply border-slate-600 text-slate-300;
+}
+
+/* Custom Animations */
+@keyframes fade-in {
+ from {
+ opacity: 0;
+ transform: translateY(10px);
+ }
+ to {
+ opacity: 1;
+ transform: translateY(0);
+ }
+}
+
+.animate-fade-in {
+ animation: fade-in 0.3s ease-out forwards;
+}
+
+/* Rough Notation - Handwritten style annotations */
+.rough-notation-container {
+ /* Ensure SVG filters are available */
+}
+
+.rough-notation {
+ display: inline;
+ position: relative;
+}
+
+/* Circle annotation - handwritten style */
+.rough-circle {
+ position: relative;
+ display: inline-block;
+ padding: 0 6px;
+}
+
+.rough-circle::before {
+ content: "";
+ position: absolute;
+ top: -4px;
+ left: -4px;
+ right: -4px;
+ bottom: -4px;
+ border: 2.5px solid #ef4444;
+ border-radius: 50%;
+ transform: rotate(-2deg);
+ filter: url(#rough-filter);
+ animation: rough-draw 0.5s ease-out forwards;
+}
+
+.rough-circle::after {
+ content: "";
+ position: absolute;
+ top: -3px;
+ left: -2px;
+ right: -6px;
+ bottom: -5px;
+ border: 1.5px solid rgba(239, 68, 68, 0.4);
+ border-radius: 45% 55% 50% 50%;
+ transform: rotate(1deg);
+}
+
+/* Highlight annotation - handwritten highlighter effect */
+.rough-highlight {
+ background:
+ linear-gradient(
+ 104deg,
+ rgba(254, 240, 138, 0) 0.9%,
+ rgba(254, 240, 138, 1) 2.4%,
+ rgba(254, 240, 138, 0.5) 5.8%,
+ rgba(254, 240, 138, 0.3) 93%,
+ rgba(254, 240, 138, 0.8) 96%,
+ rgba(254, 240, 138, 0) 98%
+ ),
+ linear-gradient(
+ 183deg,
+ rgba(254, 240, 138, 0) 0%,
+ rgba(254, 240, 138, 0.4) 7.9%,
+ rgba(254, 240, 138, 0) 15%
+ );
+ padding: 0.1em 0.2em;
+ margin: 0 -0.2em;
+ border-radius: 0.2em;
+ box-decoration-break: clone;
+ -webkit-box-decoration-break: clone;
+}
+
+/* Box annotation - handwritten border effect */
+.rough-box {
+ position: relative;
+ display: inline-block;
+ padding: 2px 6px;
+}
+
+.rough-box::before {
+ content: "";
+ position: absolute;
+ top: -2px;
+ left: -3px;
+ right: -3px;
+ bottom: -2px;
+ border: 2px solid #3b82f6;
+ border-radius: 2px;
+ transform: rotate(-0.5deg) skewX(-0.5deg);
+}
+
+.rough-box::after {
+ content: "";
+ position: absolute;
+ top: 0px;
+ left: -1px;
+ right: -5px;
+ bottom: -4px;
+ border: 1.5px solid rgba(59, 130, 246, 0.3);
+ border-radius: 1px;
+ transform: rotate(0.5deg);
+}
+
+/* Underline annotation - handwritten wavy line effect */
+.rough-underline {
+ position: relative;
+ text-decoration: none;
+}
+
+.rough-underline::after {
+ content: "";
+ position: absolute;
+ left: 0;
+ right: 0;
+ bottom: -2px;
+ height: 4px;
+ background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 20 4'%3E%3Cpath d='M0 3 Q5 0 10 3 T20 3' stroke='%231e293b' stroke-width='1.5' fill='none' stroke-linecap='round'/%3E%3C/svg%3E")
+ repeat-x;
+ background-size: 12px 4px;
+}
+
+.dark .rough-underline::after {
+ background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 20 4'%3E%3Cpath d='M0 3 Q5 0 10 3 T20 3' stroke='%23e2e8f0' stroke-width='1.5' fill='none' stroke-linecap='round'/%3E%3C/svg%3E")
+ repeat-x;
+ background-size: 12px 4px;
+}
+
+/* Dark mode for rough highlight */
+.dark .rough-highlight {
+ background:
+ linear-gradient(
+ 104deg,
+ rgba(251, 191, 36, 0) 0.9%,
+ rgba(251, 191, 36, 0.4) 2.4%,
+ rgba(251, 191, 36, 0.2) 5.8%,
+ rgba(251, 191, 36, 0.15) 93%,
+ rgba(251, 191, 36, 0.35) 96%,
+ rgba(251, 191, 36, 0) 98%
+ ),
+ linear-gradient(
+ 183deg,
+ rgba(251, 191, 36, 0) 0%,
+ rgba(251, 191, 36, 0.2) 7.9%,
+ rgba(251, 191, 36, 0) 15%
+ );
+}
+
+/* Bracket annotation - handwritten bracket effect */
+.rough-bracket {
+ display: inline;
+}
+
+.rough-bracket-container {
+ position: relative;
+ padding-left: 16px;
+ margin-left: 4px;
+}
+
+.rough-bracket-container::before {
+ content: "";
+ position: absolute;
+ left: 0;
+ top: -4px;
+ bottom: -4px;
+ width: 10px;
+ border-left: 3px solid #8b5cf6;
+ border-top: 3px solid #8b5cf6;
+ border-bottom: 3px solid #8b5cf6;
+ border-radius: 4px 0 0 4px;
+ transform: scaleX(0.6);
+ transform-origin: left center;
+}
+
+/* Bracket style when used directly as inline element */
+span.rough-bracket {
+ border-left: 3px solid #8b5cf6;
+ padding-left: 8px;
+ margin-left: 4px;
+ display: inline;
+ position: relative;
+}
+
+span.rough-bracket::before {
+ content: "";
+ position: absolute;
+ left: -3px;
+ top: -2px;
+ width: 8px;
+ height: 3px;
+ border-left: 3px solid #8b5cf6;
+ border-top: 3px solid #8b5cf6;
+ border-radius: 3px 0 0 0;
+}
+
+span.rough-bracket::after {
+ content: "";
+ position: absolute;
+ left: -3px;
+ bottom: -2px;
+ width: 8px;
+ height: 3px;
+ border-left: 3px solid #8b5cf6;
+ border-bottom: 3px solid #8b5cf6;
+ border-radius: 0 0 0 3px;
+}
+
+/* Hand-drawn effect animation */
+@keyframes rough-draw {
+ from {
+ stroke-dashoffset: 100;
+ opacity: 0;
+ }
+ to {
+ stroke-dashoffset: 0;
+ opacity: 1;
+ }
+}
+
+/* Simplified styles for PDF export */
+@media print {
+ .rough-circle::before,
+ .rough-circle::after,
+ .rough-box::before,
+ .rough-box::after,
+ .rough-underline::after,
+ .rough-bracket-container::before {
+ filter: none;
+ animation: none;
+ }
+}
diff --git a/web/app/guide/page.tsx b/web/app/guide/page.tsx
new file mode 100644
index 000000000..94350291f
--- /dev/null
+++ b/web/app/guide/page.tsx
@@ -0,0 +1,1443 @@
+"use client";
+
+import { useState, useEffect, useRef } from "react";
+import {
+ BookOpen,
+ MessageSquare,
+ Send,
+ Loader2,
+ ChevronRight,
+ ChevronDown,
+ Bug,
+ CheckCircle2,
+ GraduationCap,
+ Sparkles,
+ ArrowRight,
+ Play,
+ FileText,
+ ChevronLeft,
+ X,
+ Check,
+ Circle,
+} from "lucide-react";
+import ReactMarkdown from "react-markdown";
+import remarkGfm from "remark-gfm";
+import remarkMath from "remark-math";
+import rehypeKatex from "rehype-katex";
+import "katex/dist/katex.min.css";
+import { apiUrl } from "@/lib/api";
+import { processLatexContent } from "@/lib/latex";
+
+interface Notebook {
+ id: string;
+ name: string;
+ description: string;
+ record_count: number;
+ color: string;
+}
+
+interface NotebookRecord {
+ id: string;
+ title: string;
+ user_query: string;
+ output: string;
+ type: string;
+}
+
+interface SelectedRecord extends NotebookRecord {
+ notebookId: string;
+ notebookName: string;
+}
+
+interface KnowledgePoint {
+ knowledge_title: string;
+ knowledge_summary: string;
+ user_difficulty: string;
+}
+
+interface ChatMessage {
+ id: string;
+ role: "user" | "assistant" | "system";
+ content: string;
+ timestamp?: number;
+}
+
+interface SessionState {
+ session_id: string | null;
+ notebook_id: string | null;
+ notebook_name: string;
+ knowledge_points: KnowledgePoint[];
+ current_index: number;
+ current_html: string;
+ status: "idle" | "initialized" | "learning" | "completed";
+ progress: number;
+ summary: string;
+}
+
+export default function GuidePage() {
+ // Multi-notebook selection (same as ideagen)
+ const [notebooks, setNotebooks] = useState<Notebook[]>([]);
+ const [expandedNotebooks, setExpandedNotebooks] = useState<Set<string>>(
+ new Set(),
+ );
+ const [notebookRecordsMap, setNotebookRecordsMap] = useState<
+ Map<string, NotebookRecord[]>
+ >(new Map());
+ const [selectedRecords, setSelectedRecords] = useState<
+ Map<string, SelectedRecord>
+ >(new Map()); // recordId -> record with notebook info
+ const [loadingNotebooks, setLoadingNotebooks] = useState(true);
+ const [loadingRecordsFor, setLoadingRecordsFor] = useState<Set<string>>(
+ new Set(),
+ );
+
+ // Session state
+ const [sessionState, setSessionState] = useState<SessionState>({
+ session_id: null,
+ notebook_id: null,
+ notebook_name: "",
+ knowledge_points: [],
+ current_index: -1,
+ current_html: "",
+ status: "idle",
+ progress: 0,
+ summary: "",
+ });
+
+ // Chat state
+ const [chatMessages, setChatMessages] = useState<ChatMessage[]>([]);
+ const [inputMessage, setInputMessage] = useState("");
+ const [sendingMessage, setSendingMessage] = useState(false);
+
+ // UI state
+ const [showDebugModal, setShowDebugModal] = useState(false);
+ const [debugDescription, setDebugDescription] = useState("");
+ const [fixingHtml, setFixingHtml] = useState(false);
+
+ // Sidebar state
+ const [sidebarCollapsed, setSidebarCollapsed] = useState(false);
+ const [sidebarWide, setSidebarWide] = useState(false); // false: 1:3, true: 3:1
+ const [isLoading, setIsLoading] = useState(false);
+ const [loadingMessage, setLoadingMessage] = useState("");
+
+ const chatContainerRef = useRef<HTMLDivElement>(null);
+ const htmlFrameRef = useRef<HTMLIFrameElement>(null);
+
+ // Load notebooks
+ useEffect(() => {
+ fetchNotebooks();
+ }, []);
+
+ // Auto-scroll chat
+ useEffect(() => {
+ if (chatContainerRef.current) {
+ chatContainerRef.current.scrollTo({
+ top: chatContainerRef.current.scrollHeight,
+ behavior: "smooth",
+ });
+ }
+ }, [chatMessages]);
+
+ // Helper function to inject KaTeX into HTML if needed
+ const injectKaTeX = (html: string): string => {
+ // Check if KaTeX is already included (case-insensitive)
+ const htmlLower = html.toLowerCase();
+ const hasKaTeX =
+ htmlLower.includes("katex.min.css") ||
+ htmlLower.includes("katex.min.js") ||
+ htmlLower.includes("katex@") ||
+ htmlLower.includes("cdn.jsdelivr.net/npm/katex") ||
+ htmlLower.includes("unpkg.com/katex");
+
+ if (hasKaTeX) {
+ console.log("KaTeX already included in HTML, skipping injection");
+ return html;
+ }
+
+ // KaTeX CDN links (using version 0.16.9 for compatibility)
+ const katexCSS =
+ '<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.css" integrity="sha384-n8MVd4RsNIU0tAv4ct0nTaAbDJwPJzDEaqSD1odI+WdtXRGWt2kTvGFasHpSy3SV" crossorigin="anonymous">';
+ const katexJS =
+ '<script defer src="https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.js" integrity="sha384-XjKyOOlGwcjNTAIQHIpgOno0Hl1YQqzUOEleOLALmuqehneUG+vnGctmUb0ZY0l8" crossorigin="anonymous"></script>';
+ const katexAutoRender =
+ '<script defer src="https://cdn.jsdelivr.net/npm/[email protected]/dist/contrib/auto-render.min.js" integrity="sha384-+VBxd3r6XgURycqtZ117n7w6ODWgRrA7TlVzRsFtwW3ZxUo8h4w20Z5J3d3xjfcw" crossorigin="anonymous" onload="renderMathInElement(document.body);"></script>';
+
+ const katexInjection = ` ${katexCSS}\n ${katexJS}\n ${katexAutoRender}`;
+
+ // Try to inject into </head> section (most common case)
+ if (html.includes("</head>")) {
+ console.log("Injecting KaTeX before </head> tag");
+ return html.replace("</head>", `${katexInjection}\n</head>`);
+ }
+
+ // If no </head> tag, try to inject after <head> tag
+ if (html.includes("<head>")) {
+ console.log("Injecting KaTeX after <head> tag");
+ // Use regex to handle <head> with attributes
+ return html.replace(/<head([^>]*)>/i, `<head$1>\n${katexInjection}`);
+ }
+
+ // If HTML structure exists but no <head>, add it
+ if (html.includes("<html")) {
+ console.log("Adding <head> section with KaTeX");
+ return html.replace(
+ /(<html[^>]*>)/i,
+ `$1\n<head>\n <meta charset="UTF-8">\n <meta name="viewport" content="width=device-width, initial-scale=1.0">\n${katexInjection}\n</head>`,
+ );
+ }
+
+ // If no HTML structure, wrap it with full HTML document
+ console.log("Wrapping content with full HTML document including KaTeX");
+ return `<!DOCTYPE html>
+<html lang="zh">
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+${katexInjection}
+</head>
+<body>
+${html}
+</body>
+</html>`;
+ };
+
+ // Update HTML iframe
+ useEffect(() => {
+ if (!sessionState.current_html) {
+ return;
+ }
+
+ // Use setTimeout to ensure DOM is updated
+ const timer = setTimeout(() => {
+ if (htmlFrameRef.current) {
+ const iframe = htmlFrameRef.current;
+ console.log(
+ "Updating iframe with HTML, length:",
+ sessionState.current_html.length,
+ );
+
+ // Inject KaTeX support if needed
+ const htmlWithKaTeX = injectKaTeX(sessionState.current_html);
+
+ // Use srcdoc attribute (most reliable method)
+ try {
+ iframe.srcdoc = htmlWithKaTeX;
+ console.log("Iframe srcdoc set successfully with KaTeX support");
+ } catch (e) {
+ console.warn("srcdoc not supported, using contentDocument:", e);
+ // Fallback to contentDocument if srcdoc not supported
+ const handleLoad = () => {
+ try {
+ const doc =
+ iframe.contentDocument || iframe.contentWindow?.document;
+ if (doc) {
+ doc.open();
+ doc.write(htmlWithKaTeX);
+ doc.close();
+ console.log(
+ "Iframe content written via contentDocument with KaTeX support",
+ );
+ }
+ } catch (err) {
+ console.error("Failed to write to iframe:", err);
+ }
+ };
+
+ if (
+ iframe.contentDocument &&
+ iframe.contentDocument.readyState === "complete"
+ ) {
+ handleLoad();
+ } else {
+ iframe.onload = handleLoad;
+ }
+ }
+ } else {
+ console.warn("htmlFrameRef.current is null");
+ }
+ }, 100);
+
+ return () => clearTimeout(timer);
+ }, [sessionState.current_html, sessionState.current_index]);
+
+ const addLoadingMessage = (message: string) => {
+ const loadingMsg: ChatMessage = {
+ id: `loading-${Date.now()}`,
+ role: "system",
+ content: `⏳ ${message}`,
+ timestamp: Date.now(),
+ };
+ setChatMessages((prev) => [...prev, loadingMsg]);
+ return loadingMsg.id;
+ };
+
+ const removeLoadingMessage = (id: string) => {
+ setChatMessages((prev) => prev.filter((msg) => msg.id !== id));
+ };
+
+ const fetchNotebooks = 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,
+ );
+ setNotebooks(notebooksWithRecords);
+ setLoadingNotebooks(false);
+ } catch (err) {
+ console.error("Failed to fetch notebooks:", err);
+ setLoadingNotebooks(false);
+ }
+ };
+
+ const fetchNotebookRecords = async (notebookId: string) => {
+ if (notebookRecordsMap.has(notebookId)) return; // Already fetched
+
+ setLoadingRecordsFor((prev) => {
+ const newSet = new Set(prev);
+ newSet.add(notebookId);
+ return newSet;
+ });
+ try {
+ const res = await fetch(apiUrl(`/api/v1/notebook/${notebookId}`));
+ const data = await res.json();
+ setNotebookRecordsMap((prev) =>
+ new Map(prev).set(notebookId, data.records || []),
+ );
+ } catch (err) {
+ console.error("Failed to fetch notebook records:", err);
+ } finally {
+ setLoadingRecordsFor((prev) => {
+ const newSet = new Set(prev);
+ newSet.delete(notebookId);
+ return newSet;
+ });
+ }
+ };
+
+ const toggleNotebookExpanded = (notebookId: string) => {
+ const notebook = notebooks.find((nb) => nb.id === notebookId);
+ if (!notebook) return;
+
+ setExpandedNotebooks((prev) => {
+ const newSet = new Set(prev);
+ if (newSet.has(notebookId)) {
+ newSet.delete(notebookId);
+ } else {
+ newSet.add(notebookId);
+ // Fetch records when expanding
+ fetchNotebookRecords(notebookId);
+ }
+ return newSet;
+ });
+ };
+
+ const toggleRecordSelection = (
+ record: NotebookRecord,
+ notebookId: string,
+ notebookName: string,
+ ) => {
+ setSelectedRecords((prev) => {
+ const newMap = new Map(prev);
+ if (newMap.has(record.id)) {
+ newMap.delete(record.id);
+ } else {
+ newMap.set(record.id, { ...record, notebookId, notebookName });
+ }
+ return newMap;
+ });
+ };
+
+ const selectAllFromNotebook = (notebookId: string, notebookName: string) => {
+ const records = notebookRecordsMap.get(notebookId) || [];
+ setSelectedRecords((prev) => {
+ const newMap = new Map(prev);
+ records.forEach((r) =>
+ newMap.set(r.id, { ...r, notebookId, notebookName }),
+ );
+ return newMap;
+ });
+ };
+
+ const deselectAllFromNotebook = (notebookId: string) => {
+ const records = notebookRecordsMap.get(notebookId) || [];
+ const recordIds = new Set(records.map((r) => r.id));
+ setSelectedRecords((prev) => {
+ const newMap = new Map(prev);
+ recordIds.forEach((id) => newMap.delete(id));
+ return newMap;
+ });
+ };
+
+ const clearAllSelections = () => {
+ setSelectedRecords(new Map());
+ };
+
+ const getTypeColor = (type: string) => {
+ switch (type) {
+ case "solve":
+ return "bg-blue-100 text-blue-700 border-blue-200";
+ case "question":
+ return "bg-purple-100 text-purple-700 border-purple-200";
+ case "research":
+ return "bg-emerald-100 text-emerald-700 border-emerald-200";
+ case "co_writer":
+ return "bg-amber-100 text-amber-700 border-amber-200";
+ default:
+ return "bg-slate-100 text-slate-700 border-slate-200";
+ }
+ };
+
+ const handleCreateSession = async () => {
+ if (selectedRecords.size === 0) return;
+
+ setIsLoading(true);
+ setLoadingMessage("Analyzing notes and generating learning plan...");
+ const loadingId = addLoadingMessage(
+ "Analyzing notes and generating learning plan...",
+ );
+
+ try {
+ // Send records directly for cross-notebook support
+ const recordsArray = Array.from(selectedRecords.values()).map((r) => ({
+ id: r.id,
+ title: r.title,
+ user_query: r.user_query,
+ output: r.output,
+ type: r.type,
+ }));
+
+ const res = await fetch(apiUrl("/api/v1/guide/create_session"), {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ records: recordsArray }),
+ });
+ const data = await res.json();
+
+ removeLoadingMessage(loadingId);
+ setIsLoading(false);
+ setLoadingMessage("");
+
+ if (data.success) {
+ // Get notebook names from selected records
+ const notebookNames = Array.from(
+ new Set(
+ Array.from(selectedRecords.values()).map((r) => r.notebookName),
+ ),
+ );
+ const notebookName =
+ notebookNames.length === 1
+ ? notebookNames[0]
+ : `Cross-Notebook (${notebookNames.length} notebooks, ${selectedRecords.size} records)`;
+
+ setSessionState({
+ session_id: data.session_id,
+ notebook_id: "cross_notebook",
+ notebook_name: notebookName,
+ knowledge_points: data.knowledge_points || [],
+ current_index: -1,
+ current_html: "",
+ status: "initialized",
+ progress: 0,
+ summary: "",
+ });
+
+ // Add system message: show learning plan
+ const planMessage = `📚 Learning plan generated with **${data.total_points}** knowledge points:\n\n${data.knowledge_points.map((kp: KnowledgePoint, idx: number) => `${idx + 1}. ${kp.knowledge_title}`).join("\n")}\n\nClick "Start Learning" button above to begin!`;
+ setChatMessages([
+ {
+ id: "plan",
+ role: "system",
+ content: planMessage,
+ timestamp: Date.now(),
+ },
+ ]);
+ } else {
+ setChatMessages((prev) => [
+ ...prev,
+ {
+ id: `error-${Date.now()}`,
+ role: "system",
+ content: `❌ Failed to create session: ${data.error}`,
+ timestamp: Date.now(),
+ },
+ ]);
+ }
+ } catch (err) {
+ removeLoadingMessage(loadingId);
+ setIsLoading(false);
+ setLoadingMessage("");
+ console.error("Failed to create session:", err);
+ setChatMessages((prev) => [
+ ...prev,
+ {
+ id: `error-${Date.now()}`,
+ role: "system",
+ content: "❌ Failed to create session, please try again later",
+ timestamp: Date.now(),
+ },
+ ]);
+ }
+ };
+
+ const handleStartLearning = async () => {
+ if (!sessionState.session_id) return;
+
+ setIsLoading(true);
+ setLoadingMessage("Generating interactive learning page...");
+ const loadingId = addLoadingMessage(
+ "Generating interactive learning page...",
+ );
+
+ try {
+ const res = await fetch(apiUrl("/api/v1/guide/start"), {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ session_id: sessionState.session_id }),
+ });
+ const data = await res.json();
+
+ removeLoadingMessage(loadingId);
+ setIsLoading(false);
+ setLoadingMessage("");
+
+ if (data.success) {
+ // Ensure HTML exists
+ const htmlContent = data.html || "";
+ console.log("Start learning - HTML length:", htmlContent.length);
+
+ setSessionState((prev) => ({
+ ...prev,
+ current_index: data.current_index,
+ current_html: htmlContent,
+ status: "learning",
+ progress: data.progress || 0,
+ }));
+
+ // Add system message
+ setChatMessages((prev) => [
+ ...prev,
+ {
+ id: `start-${Date.now()}`,
+ role: "system",
+ content: data.message || "Starting the first knowledge point",
+ timestamp: Date.now(),
+ },
+ ]);
+ } else {
+ setChatMessages((prev) => [
+ ...prev,
+ {
+ id: `error-${Date.now()}`,
+ role: "system",
+ content: `❌ Failed to start learning: ${data.error || "Unknown error"}`,
+ timestamp: Date.now(),
+ },
+ ]);
+ }
+ } catch (err) {
+ removeLoadingMessage(loadingId);
+ setIsLoading(false);
+ setLoadingMessage("");
+ console.error("Failed to start learning:", err);
+ setChatMessages((prev) => [
+ ...prev,
+ {
+ id: `error-${Date.now()}`,
+ role: "system",
+ content: "❌ Failed to start learning, please try again later",
+ timestamp: Date.now(),
+ },
+ ]);
+ }
+ };
+
+ const handleNextKnowledge = async () => {
+ if (!sessionState.session_id) return;
+
+ setIsLoading(true);
+ setLoadingMessage("Generating next knowledge point...");
+ const loadingId = addLoadingMessage("Generating next knowledge point...");
+
+ try {
+ const res = await fetch(apiUrl("/api/v1/guide/next"), {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ session_id: sessionState.session_id }),
+ });
+ const data = await res.json();
+
+ removeLoadingMessage(loadingId);
+ setIsLoading(false);
+ setLoadingMessage("");
+
+ if (data.success) {
+ if (data.status === "completed") {
+ // Learning completed
+ setSessionState((prev) => ({
+ ...prev,
+ status: "completed",
+ summary: data.summary || "",
+ progress: 100,
+ }));
+
+ setChatMessages((prev) => [
+ ...prev,
+ {
+ id: `complete-${Date.now()}`,
+ role: "system",
+ content:
+ data.message ||
+ "🎉 Congratulations on completing all knowledge points!",
+ timestamp: Date.now(),
+ },
+ ]);
+ } else {
+ // Move to next knowledge point
+ setSessionState((prev) => ({
+ ...prev,
+ current_index: data.current_index,
+ current_html: data.html || "",
+ progress: data.progress || 0,
+ }));
+
+ setChatMessages((prev) => [
+ ...prev,
+ {
+ id: `next-${Date.now()}`,
+ role: "system",
+ content: data.message || "Moving to next knowledge point",
+ timestamp: Date.now(),
+ },
+ ]);
+ }
+ } else {
+ setChatMessages((prev) => [
+ ...prev,
+ {
+ id: `error-${Date.now()}`,
+ role: "system",
+ content: `❌ Failed to move to next: ${data.error || "Unknown error"}`,
+ timestamp: Date.now(),
+ },
+ ]);
+ }
+ } catch (err) {
+ removeLoadingMessage(loadingId);
+ setIsLoading(false);
+ setLoadingMessage("");
+ console.error("Failed to move to next:", err);
+ setChatMessages((prev) => [
+ ...prev,
+ {
+ id: `error-${Date.now()}`,
+ role: "system",
+ content: "❌ Failed to move to next, please try again later",
+ timestamp: Date.now(),
+ },
+ ]);
+ }
+ };
+
+ const handleSendMessage = async () => {
+ if (!inputMessage.trim() || !sessionState.session_id || sendingMessage)
+ return;
+
+ const userMsg: ChatMessage = {
+ id: `user-${Date.now()}`,
+ role: "user",
+ content: inputMessage,
+ timestamp: Date.now(),
+ };
+
+ setChatMessages((prev) => [...prev, userMsg]);
+ const userInput = inputMessage;
+ setInputMessage("");
+ setSendingMessage(true);
+
+ // Add thinking indicator
+ const thinkingId = addLoadingMessage("Thinking...");
+
+ try {
+ const res = await fetch(apiUrl("/api/v1/guide/chat"), {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ session_id: sessionState.session_id,
+ message: userInput,
+ }),
+ });
+ const data = await res.json();
+
+ removeLoadingMessage(thinkingId);
+
+ if (data.success) {
+ setChatMessages((prev) => [
+ ...prev,
+ {
+ id: `assistant-${Date.now()}`,
+ role: "assistant",
+ content: data.answer || "",
+ timestamp: Date.now(),
+ },
+ ]);
+ } else {
+ setChatMessages((prev) => [
+ ...prev,
+ {
+ id: `error-${Date.now()}`,
+ role: "assistant",
+ content: `❌ Error: ${data.error || "Failed to respond"}`,
+ timestamp: Date.now(),
+ },
+ ]);
+ }
+ } catch (err) {
+ removeLoadingMessage(thinkingId);
+ console.error("Failed to send message:", err);
+ setChatMessages((prev) => [
+ ...prev,
+ {
+ id: `error-${Date.now()}`,
+ role: "assistant",
+ content: "❌ Failed to send message, please try again later",
+ timestamp: Date.now(),
+ },
+ ]);
+ } finally {
+ setSendingMessage(false);
+ }
+ };
+
+ const handleFixHtml = async () => {
+ if (!sessionState.session_id || !debugDescription.trim() || fixingHtml)
+ return;
+
+ setFixingHtml(true);
+ const loadingId = addLoadingMessage("Fixing HTML page...");
+
+ try {
+ const res = await fetch(apiUrl("/api/v1/guide/fix_html"), {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ session_id: sessionState.session_id,
+ bug_description: debugDescription,
+ }),
+ });
+ const data = await res.json();
+
+ removeLoadingMessage(loadingId);
+
+ if (data.success) {
+ setSessionState((prev) => ({
+ ...prev,
+ current_html: data.html || prev.current_html,
+ }));
+ setShowDebugModal(false);
+ setDebugDescription("");
+ setChatMessages((prev) => [
+ ...prev,
+ {
+ id: `fix-${Date.now()}`,
+ role: "system",
+ content: "✅ HTML page has been fixed!",
+ timestamp: Date.now(),
+ },
+ ]);
+ } else {
+ setChatMessages((prev) => [
+ ...prev,
+ {
+ id: `error-${Date.now()}`,
+ role: "system",
+ content: `❌ Fix failed: ${data.error || "Unknown error"}`,
+ timestamp: Date.now(),
+ },
+ ]);
+ }
+ } catch (err) {
+ removeLoadingMessage(loadingId);
+ console.error("Failed to fix HTML:", err);
+ setChatMessages((prev) => [
+ ...prev,
+ {
+ id: `error-${Date.now()}`,
+ role: "system",
+ content: "❌ Fix failed, please try again later",
+ timestamp: Date.now(),
+ },
+ ]);
+ } finally {
+ setFixingHtml(false);
+ }
+ };
+
+ const canStart =
+ sessionState.status === "initialized" &&
+ sessionState.knowledge_points.length > 0;
+ const canNext =
+ sessionState.status === "learning" &&
+ sessionState.current_index < sessionState.knowledge_points.length - 1;
+ const isCompleted = sessionState.status === "completed";
+ const isLastKnowledge =
+ sessionState.status === "learning" &&
+ sessionState.current_index === sessionState.knowledge_points.length - 1;
+
+ // Calculate widths based on ratio
+ const leftWidthPercent = sidebarCollapsed ? 0 : sidebarWide ? 75 : 25; // 3:1 or 1:3
+ const rightWidthPercent = sidebarCollapsed ? 100 : sidebarWide ? 25 : 75;
+
+ return (
+ <div className="h-[calc(100vh-8rem)] flex gap-4 animate-fade-in relative">
+ {/* LEFT PANEL: Chat & Control */}
+ <div
+ className={`flex flex-col gap-4 h-full transition-all duration-300 flex-shrink-0 ${sidebarCollapsed ? "overflow-hidden" : ""}`}
+ style={{
+ width: sidebarCollapsed ? 0 : `${leftWidthPercent}%`,
+ minWidth: sidebarCollapsed
+ ? 0
+ : `${Math.max(leftWidthPercent * 0.01 * 1200, 300)}px`,
+ maxWidth: sidebarCollapsed ? 0 : `${leftWidthPercent}%`,
+ }}
+ >
+ {/* Multi-Notebook Selection (same as ideagen) */}
+ {sessionState.status === "idle" && (
+ <div className="bg-white dark:bg-slate-800 rounded-2xl shadow-sm border border-slate-200 dark:border-slate-700 flex flex-col overflow-hidden">
+ <div className="p-3 border-b border-slate-100 dark:border-slate-700 bg-slate-50/50 dark:bg-slate-800/50 flex justify-between items-center">
+ <h2 className="font-bold text-slate-900 dark:text-slate-100 flex items-center gap-2">
+ <BookOpen className="w-5 h-5 text-indigo-600 dark:text-indigo-400" />
+ Select Source (Cross-Notebook)
+ </h2>
+ {selectedRecords.size > 0 && (
+ <button
+ onClick={clearAllSelections}
+ className="text-xs text-slate-500 dark:text-slate-400 hover:text-red-600 dark:hover:text-red-400"
+ >
+ Clear ({selectedRecords.size})
+ </button>
+ )}
+ </div>
+
+ <div className="flex-1 overflow-y-auto max-h-[400px]">
+ {loadingNotebooks ? (
+ <div className="flex items-center justify-center py-8">
+ <Loader2 className="w-5 h-5 animate-spin text-indigo-600 dark:text-indigo-400" />
+ </div>
+ ) : notebooks.length === 0 ? (
+ <div className="p-4 text-center text-sm text-slate-400 dark:text-slate-500">
+ No notebooks with records found
+ </div>
+ ) : (
+ <div className="divide-y divide-slate-100 dark:divide-slate-700">
+ {notebooks.map((notebook) => {
+ const isExpanded = expandedNotebooks.has(notebook.id);
+ const records = notebookRecordsMap.get(notebook.id) || [];
+ const isLoading = loadingRecordsFor.has(notebook.id);
+ const selectedFromThis = records.filter((r) =>
+ selectedRecords.has(r.id),
+ ).length;
+
+ return (
+ <div key={notebook.id}>
+ {/* Notebook Header */}
+ <div
+ className="p-3 flex items-center gap-2 cursor-pointer hover:bg-slate-50 dark:hover:bg-slate-700/50 transition-colors"
+ onClick={() => toggleNotebookExpanded(notebook.id)}
+ >
+ {isExpanded ? (
+ <ChevronDown className="w-4 h-4 text-slate-400 dark:text-slate-500" />
+ ) : (
+ <ChevronRight className="w-4 h-4 text-slate-400 dark:text-slate-500" />
+ )}
+ <div
+ className="w-3 h-3 rounded-full"
+ style={{
+ backgroundColor: notebook.color || "#94a3b8",
+ }}
+ />
+ <span className="flex-1 text-sm font-medium text-slate-700 dark:text-slate-200 truncate">
+ {notebook.name}
+ </span>
+ <span className="text-xs text-slate-400 dark:text-slate-500">
+ {selectedFromThis > 0 && (
+ <span className="text-indigo-600 dark:text-indigo-400 font-medium">
+ {selectedFromThis}/
+ </span>
+ )}
+ {notebook.record_count}
+ </span>
+ </div>
+
+ {/* Records List */}
+ {isExpanded && (
+ <div className="pl-6 pr-2 pb-2 bg-slate-50/50 dark:bg-slate-800/50">
+ {isLoading ? (
+ <div className="flex items-center justify-center py-4">
+ <Loader2 className="w-4 h-4 animate-spin text-indigo-600 dark:text-indigo-400" />
+ </div>
+ ) : records.length === 0 ? (
+ <div className="py-2 text-xs text-slate-400 dark:text-slate-500 text-center">
+ No records
+ </div>
+ ) : (
+ <>
+ <div className="flex gap-2 mb-2">
+ <button
+ onClick={(e) => {
+ e.stopPropagation();
+ selectAllFromNotebook(
+ notebook.id,
+ notebook.name,
+ );
+ }}
+ className="text-xs text-indigo-600 dark:text-indigo-400 hover:text-indigo-700 dark:hover:text-indigo-300"
+ >
+ Select All
+ </button>
+ <button
+ onClick={(e) => {
+ e.stopPropagation();
+ deselectAllFromNotebook(notebook.id);
+ }}
+ className="text-xs text-slate-500 dark:text-slate-400 hover:text-slate-700 dark:hover:text-slate-300"
+ >
+ Deselect
+ </button>
+ </div>
+ <div className="space-y-1">
+ {records.map((record) => (
+ <div
+ key={record.id}
+ onClick={(e) => {
+ e.stopPropagation();
+ toggleRecordSelection(
+ record,
+ notebook.id,
+ notebook.name,
+ );
+ }}
+ className={`p-2 rounded-lg cursor-pointer transition-all border ${
+ selectedRecords.has(record.id)
+ ? "bg-indigo-50 dark:bg-indigo-900/30 border-indigo-200 dark:border-indigo-700"
+ : "hover:bg-white dark:hover:bg-slate-700 border-transparent hover:border-slate-200 dark:hover:border-slate-600"
+ }`}
+ >
+ <div className="flex items-center gap-2">
+ <div
+ className={`w-4 h-4 rounded border flex items-center justify-center shrink-0 ${
+ selectedRecords.has(record.id)
+ ? "bg-indigo-500 border-indigo-500 text-white"
+ : "border-slate-300 dark:border-slate-500"
+ }`}
+ >
+ {selectedRecords.has(record.id) && (
+ <Check className="w-2.5 h-2.5" />
+ )}
+ </div>
+ <div className="flex-1 min-w-0">
+ <span
+ className={`text-[10px] font-bold uppercase px-1 py-0.5 rounded ${getTypeColor(record.type)}`}
+ >
+ {record.type}
+ </span>
+ <span className="text-xs text-slate-700 dark:text-slate-200 ml-2 truncate">
+ {record.title}
+ </span>
+ </div>
+ </div>
+ </div>
+ ))}
+ </div>
+ </>
+ )}
+ </div>
+ )}
+ </div>
+ );
+ })}
+ </div>
+ )}
+ </div>
+
+ {/* Generate Button */}
+ <div className="p-3 border-t border-slate-100 dark:border-slate-700">
+ <button
+ onClick={handleCreateSession}
+ disabled={isLoading || selectedRecords.size === 0}
+ className="w-full px-4 py-2.5 bg-gradient-to-r from-indigo-500 to-purple-500 text-white rounded-xl hover:from-indigo-600 hover:to-purple-600 transition-all disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2 font-medium shadow-md shadow-indigo-500/20"
+ >
+ {isLoading ? (
+ <>
+ <Loader2 className="w-4 h-4 animate-spin" />
+ Generating...
+ </>
+ ) : (
+ <>
+ <Sparkles className="w-4 h-4" />
+ Generate Learning Plan ({selectedRecords.size} items)
+ </>
+ )}
+ </button>
+ </div>
+ </div>
+ )}
+
+ {/* Progress Bar with Action Buttons */}
+ {sessionState.status !== "idle" && (
+ <div className="bg-white dark:bg-slate-800 p-4 rounded-2xl shadow-sm border border-slate-200 dark:border-slate-700">
+ <div className="flex items-center justify-between mb-2">
+ <span className="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wider">
+ Learning Progress
+ </span>
+ <span className="text-xs text-slate-400 dark:text-slate-500">
+ {sessionState.progress}%
+ </span>
+ </div>
+ <div className="h-2 bg-slate-100 dark:bg-slate-700 rounded-full overflow-hidden mb-4">
+ <div
+ className="h-full bg-gradient-to-r from-indigo-500 to-purple-500 rounded-full transition-all duration-500"
+ style={{ width: `${sessionState.progress}%` }}
+ />
+ </div>
+ {sessionState.knowledge_points.length > 0 && (
+ <p className="text-xs text-slate-400 dark:text-slate-500 mb-4">
+ Knowledge Point {sessionState.current_index + 1} /{" "}
+ {sessionState.knowledge_points.length}
+ </p>
+ )}
+
+ {/* Action Buttons */}
+ <div className="flex gap-2">
+ {canStart && (
+ <button
+ onClick={handleStartLearning}
+ disabled={isLoading}
+ className="flex-1 px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2 text-sm font-medium"
+ >
+ {isLoading ? (
+ <>
+ <Loader2 className="w-4 h-4 animate-spin" />
+ Generating...
+ </>
+ ) : (
+ <>
+ <Play className="w-4 h-4" />
+ Start Learning
+ </>
+ )}
+ </button>
+ )}
+
+ {canNext && (
+ <button
+ onClick={handleNextKnowledge}
+ disabled={isLoading}
+ className="flex-1 px-4 py-2 bg-emerald-600 text-white rounded-lg hover:bg-emerald-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2 text-sm font-medium"
+ >
+ {isLoading ? (
+ <>
+ <Loader2 className="w-4 h-4 animate-spin" />
+ Loading...
+ </>
+ ) : (
+ <>
+ <ChevronRight className="w-4 h-4" />
+ Next
+ </>
+ )}
+ </button>
+ )}
+
+ {isLastKnowledge && (
+ <button
+ onClick={handleNextKnowledge}
+ disabled={isLoading}
+ className="flex-1 px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2 text-sm font-medium"
+ >
+ {isLoading ? (
+ <>
+ <Loader2 className="w-4 h-4 animate-spin" />
+ Generating Summary...
+ </>
+ ) : (
+ <>
+ <CheckCircle2 className="w-4 h-4" />
+ Complete Learning
+ </>
+ )}
+ </button>
+ )}
+ </div>
+ </div>
+ )}
+
+ {/* Chat Interface */}
+ <div className="flex-1 bg-white dark:bg-slate-800 rounded-2xl shadow-sm border border-slate-200 dark:border-slate-700 flex flex-col overflow-hidden">
+ <div className="p-3 border-b border-slate-100 dark:border-slate-700 bg-slate-50/50 dark:bg-slate-800/50 text-xs font-bold text-slate-500 dark:text-slate-400 uppercase tracking-wider flex items-center gap-2">
+ <MessageSquare className="w-4 h-4" />
+ Learning Assistant
+ </div>
+
+ <div
+ ref={chatContainerRef}
+ className="flex-1 overflow-y-auto p-4 space-y-4 bg-slate-50/30 dark:bg-slate-800/30"
+ >
+ {chatMessages.map((msg) => (
+ <div
+ key={msg.id}
+ className={`flex flex-col ${msg.role === "user" ? "items-end" : "items-start"}`}
+ >
+ <div
+ className={`max-w-[90%] rounded-2xl px-4 py-3 text-sm ${
+ msg.role === "user"
+ ? "bg-indigo-600 text-white rounded-tr-none shadow-md shadow-indigo-500/20"
+ : msg.role === "system" && msg.content.includes("⏳")
+ ? "bg-amber-50 border border-amber-200 text-amber-900 rounded-tl-none"
+ : msg.role === "system"
+ ? "bg-blue-50 border border-blue-200 text-blue-900 rounded-tl-none"
+ : "bg-white border border-slate-200 text-slate-700 rounded-tl-none shadow-sm"
+ }`}
+ >
+ {msg.role === "system" ? (
+ <div className="prose prose-sm max-w-none">
+ <ReactMarkdown
+ remarkPlugins={[remarkGfm, remarkMath]}
+ rehypePlugins={[rehypeKatex]}
+ components={{
+ table: ({ node, ...props }) => (
+ <div className="overflow-x-auto my-4 rounded-lg border border-slate-200 shadow-sm">
+ <table
+ className="min-w-full divide-y divide-slate-200 text-sm"
+ {...props}
+ />
+ </div>
+ ),
+ thead: ({ node, ...props }) => (
+ <thead className="bg-slate-50" {...props} />
+ ),
+ th: ({ node, ...props }) => (
+ <th
+ className="px-3 py-2 text-left font-semibold text-slate-700 whitespace-nowrap border-b border-slate-200"
+ {...props}
+ />
+ ),
+ tbody: ({ node, ...props }) => (
+ <tbody
+ className="divide-y divide-slate-100 bg-white"
+ {...props}
+ />
+ ),
+ td: ({ node, ...props }) => (
+ <td
+ className="px-3 py-2 text-slate-600 border-b border-slate-100"
+ {...props}
+ />
+ ),
+ tr: ({ node, ...props }) => (
+ <tr
+ className="hover:bg-slate-50/50 transition-colors"
+ {...props}
+ />
+ ),
+ }}
+ >
+ {processLatexContent(msg.content)}
+ </ReactMarkdown>
+ </div>
+ ) : msg.role === "assistant" ? (
+ <div className="prose prose-sm max-w-none prose-slate">
+ <ReactMarkdown
+ remarkPlugins={[remarkGfm, remarkMath]}
+ rehypePlugins={[rehypeKatex]}
+ components={{
+ table: ({ node, ...props }) => (
+ <div className="overflow-x-auto my-4 rounded-lg border border-slate-200 shadow-sm">
+ <table
+ className="min-w-full divide-y divide-slate-200 text-sm"
+ {...props}
+ />
+ </div>
+ ),
+ thead: ({ node, ...props }) => (
+ <thead className="bg-slate-50" {...props} />
+ ),
+ th: ({ node, ...props }) => (
+ <th
+ className="px-3 py-2 text-left font-semibold text-slate-700 whitespace-nowrap border-b border-slate-200"
+ {...props}
+ />
+ ),
+ tbody: ({ node, ...props }) => (
+ <tbody
+ className="divide-y divide-slate-100 bg-white"
+ {...props}
+ />
+ ),
+ td: ({ node, ...props }) => (
+ <td
+ className="px-3 py-2 text-slate-600 border-b border-slate-100"
+ {...props}
+ />
+ ),
+ tr: ({ node, ...props }) => (
+ <tr
+ className="hover:bg-slate-50/50 transition-colors"
+ {...props}
+ />
+ ),
+ }}
+ >
+ {processLatexContent(msg.content)}
+ </ReactMarkdown>
+ </div>
+ ) : (
+ <p>{msg.content}</p>
+ )}
+ </div>
+ </div>
+ ))}
+ </div>
+
+ {/* Input Area */}
+ {sessionState.status === "learning" && (
+ <div className="p-3 bg-white dark:bg-slate-800 border-t border-slate-100 dark:border-slate-700">
+ <div className="relative flex items-center gap-2">
+ <input
+ type="text"
+ value={inputMessage}
+ onChange={(e) => setInputMessage(e.target.value)}
+ onKeyDown={(e) =>
+ e.key === "Enter" && !e.shiftKey && handleSendMessage()
+ }
+ placeholder="Have any questions? Feel free to ask..."
+ disabled={sendingMessage}
+ className="flex-1 pl-4 pr-10 py-2.5 bg-slate-100 dark:bg-slate-700 border-transparent focus:bg-white dark:focus:bg-slate-600 focus:border-indigo-500 focus:ring-2 focus:ring-indigo-500/20 rounded-xl text-sm text-slate-900 dark:text-slate-100 placeholder:text-slate-400 dark:placeholder:text-slate-500 transition-all outline-none disabled:opacity-50 disabled:cursor-not-allowed"
+ />
+ <button
+ onClick={handleSendMessage}
+ disabled={!inputMessage.trim() || sendingMessage}
+ className="p-2.5 bg-indigo-600 text-white rounded-xl hover:bg-indigo-700 active:scale-95 transition-all disabled:opacity-50 disabled:cursor-not-allowed shadow-lg shadow-indigo-500/20"
+ >
+ {sendingMessage ? (
+ <Loader2 className="w-4 h-4 animate-spin" />
+ ) : (
+ <Send className="w-4 h-4" />
+ )}
+ </button>
+ </div>
+ </div>
+ )}
+ </div>
+ </div>
+
+ {/* RIGHT PANEL: Interactive Content */}
+ <div
+ className="flex flex-col h-full overflow-hidden transition-all duration-300 flex-1 relative"
+ style={{ width: `${rightWidthPercent}%` }}
+ >
+ {/* Collapse/Expand and Width Toggle Button - positioned relative to right panel */}
+ <div className="absolute top-4 left-4 z-20 flex gap-2">
+ <button
+ onClick={() => setSidebarCollapsed(!sidebarCollapsed)}
+ className="p-2 bg-white dark:bg-slate-800 border border-slate-200 dark:border-slate-600 rounded-lg shadow-sm hover:bg-slate-50 dark:hover:bg-slate-700 transition-all"
+ title={sidebarCollapsed ? "Expand sidebar" : "Collapse sidebar"}
+ >
+ {sidebarCollapsed ? (
+ <ChevronRight className="w-4 h-4 text-slate-600 dark:text-slate-300" />
+ ) : (
+ <ChevronLeft className="w-4 h-4 text-slate-600 dark:text-slate-300" />
+ )}
+ </button>
+ {!sidebarCollapsed && (
+ <button
+ onClick={() => setSidebarWide(!sidebarWide)}
+ className="p-2 bg-white dark:bg-slate-800 border border-slate-200 dark:border-slate-600 rounded-lg shadow-sm hover:bg-slate-50 dark:hover:bg-slate-700 transition-all"
+ title={
+ sidebarWide
+ ? "Switch to narrow sidebar (1:3)"
+ : "Switch to wide sidebar (3:1)"
+ }
+ >
+ <ArrowRight
+ className={`w-4 h-4 text-slate-600 dark:text-slate-300 transition-transform ${sidebarWide ? "rotate-180" : ""}`}
+ />
+ </button>
+ )}
+ </div>
+ {sessionState.status === "idle" ? (
+ <div className="flex-1 bg-white dark:bg-slate-800 rounded-2xl shadow-sm border border-slate-200 dark:border-slate-700 flex flex-col items-center justify-center text-slate-300 dark:text-slate-600 p-8">
+ <GraduationCap className="w-24 h-24 text-slate-200 dark:text-slate-600 mb-6" />
+ <h3 className="text-lg font-medium text-slate-600 dark:text-slate-300 mb-2">
+ Guided Learning
+ </h3>
+ <p className="text-sm text-slate-400 dark:text-slate-500 max-w-md text-center leading-relaxed">
+ Select a notebook, and the system will generate a personalized
+ learning plan. Through interactive pages and intelligent Q&A,
+ you'll gradually master all the content.
+ </p>
+ </div>
+ ) : isCompleted ? (
+ <div className="flex-1 bg-white dark:bg-slate-800 rounded-2xl shadow-sm border border-slate-200 dark:border-slate-700 flex flex-col overflow-hidden relative">
+ {/* Summary Header */}
+ <div className="p-4 border-b border-slate-100 dark:border-slate-700 bg-gradient-to-r from-emerald-50 to-indigo-50 dark:from-emerald-900/20 dark:to-indigo-900/20 flex items-center justify-between shrink-0">
+ <h2 className="font-bold text-slate-800 dark:text-slate-100 flex items-center gap-2">
+ <CheckCircle2 className="w-5 h-5 text-emerald-600 dark:text-emerald-400" />
+ Learning Summary
+ </h2>
+ </div>
+ {/* Summary Content */}
+ <div className="flex-1 overflow-y-auto p-8 bg-white dark:bg-slate-800">
+ <div className="prose prose-slate dark:prose-invert prose-headings:font-bold prose-h1:text-2xl prose-h2:text-xl max-w-none">
+ <ReactMarkdown
+ remarkPlugins={[remarkGfm, remarkMath]}
+ rehypePlugins={[rehypeKatex]}
+ components={{
+ table: ({ node, ...props }) => (
+ <div className="overflow-x-auto my-6 rounded-lg border border-slate-200 shadow-sm">
+ <table
+ className="min-w-full divide-y divide-slate-200 text-sm"
+ {...props}
+ />
+ </div>
+ ),
+ thead: ({ node, ...props }) => (
+ <thead className="bg-slate-50" {...props} />
+ ),
+ th: ({ node, ...props }) => (
+ <th
+ className="px-4 py-3 text-left font-semibold text-slate-700 whitespace-nowrap border-b border-slate-200"
+ {...props}
+ />
+ ),
+ tbody: ({ node, ...props }) => (
+ <tbody
+ className="divide-y divide-slate-100 bg-white"
+ {...props}
+ />
+ ),
+ td: ({ node, ...props }) => (
+ <td
+ className="px-4 py-3 text-slate-600 border-b border-slate-100"
+ {...props}
+ />
+ ),
+ tr: ({ node, ...props }) => (
+ <tr
+ className="hover:bg-slate-50/50 transition-colors"
+ {...props}
+ />
+ ),
+ }}
+ >
+ {processLatexContent(sessionState.summary || "")}
+ </ReactMarkdown>
+ </div>
+ </div>
+ </div>
+ ) : sessionState.status === "learning" ? (
+ <div className="flex-1 bg-white dark:bg-slate-800 rounded-2xl shadow-sm border border-slate-200 dark:border-slate-700 flex flex-col overflow-hidden relative">
+ {/* Debug Button */}
+ <button
+ onClick={() => setShowDebugModal(true)}
+ className="absolute top-4 right-4 z-10 p-2 bg-slate-100 dark:bg-slate-700 hover:bg-slate-200 dark:hover:bg-slate-600 rounded-lg transition-colors shadow-sm"
+ title="Fix HTML"
+ >
+ <Bug className="w-4 h-4 text-slate-600 dark:text-slate-300" />
+ </button>
+
+ {/* HTML Content */}
+ {sessionState.current_html ? (
+ <iframe
+ ref={htmlFrameRef}
+ className="w-full h-full border-0"
+ title="Interactive Learning Content"
+ sandbox="allow-scripts allow-same-origin"
+ key={`html-${sessionState.current_index}-${sessionState.current_html.length}`}
+ />
+ ) : (
+ <div className="flex-1 flex items-center justify-center">
+ <Loader2 className="w-12 h-12 text-indigo-400 dark:text-indigo-500 animate-spin mb-4" />
+ <p className="text-slate-500 dark:text-slate-400">
+ {loadingMessage || "Loading learning content..."}
+ </p>
+ </div>
+ )}
+ </div>
+ ) : (
+ <div className="flex-1 bg-white dark:bg-slate-800 rounded-2xl shadow-sm border border-slate-200 dark:border-slate-700 flex flex-col items-center justify-center text-slate-300 dark:text-slate-600 p-8">
+ <Loader2 className="w-12 h-12 text-indigo-400 dark:text-indigo-500 animate-spin mb-4" />
+ <p className="text-slate-500 dark:text-slate-400">
+ {loadingMessage || "Loading learning content..."}
+ </p>
+ </div>
+ )}
+ </div>
+
+ {/* Debug Modal */}
+ {showDebugModal && (
+ <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 animate-in fade-in">
+ <div className="bg-white dark:bg-slate-800 rounded-2xl shadow-2xl w-[500px] animate-in zoom-in-95">
+ <div className="p-4 border-b border-slate-100 dark:border-slate-700 flex items-center justify-between">
+ <h3 className="font-bold text-slate-900 dark:text-slate-100 flex items-center gap-2">
+ <Bug className="w-5 h-5 text-amber-600 dark:text-amber-400" />
+ Fix HTML Issue
+ </h3>
+ <button
+ onClick={() => {
+ setShowDebugModal(false);
+ setDebugDescription("");
+ }}
+ className="p-1 hover:bg-slate-100 dark:hover:bg-slate-700 rounded-lg"
+ >
+ <X className="w-5 h-5 text-slate-500 dark:text-slate-400" />
+ </button>
+ </div>
+ <div className="p-6 space-y-4">
+ <div>
+ <label className="block text-xs font-bold text-slate-500 dark:text-slate-400 uppercase tracking-wider mb-2">
+ Issue Description
+ </label>
+ <textarea
+ value={debugDescription}
+ onChange={(e) => setDebugDescription(e.target.value)}
+ placeholder="Describe the HTML issue, e.g.: button not clickable, style display error, interaction not working..."
+ rows={6}
+ className="w-full px-4 py-2 border border-slate-200 dark:border-slate-600 bg-white dark:bg-slate-700 text-slate-900 dark:text-slate-100 rounded-xl focus:ring-2 focus:ring-amber-500/20 focus:border-amber-500 outline-none resize-none"
+ />
+ </div>
+ </div>
+ <div className="p-4 border-t border-slate-100 dark:border-slate-700 flex justify-end gap-2">
+ <button
+ onClick={() => {
+ setShowDebugModal(false);
+ setDebugDescription("");
+ }}
+ className="px-4 py-2 text-slate-600 dark:text-slate-300 hover:bg-slate-100 dark:hover:bg-slate-700 rounded-lg transition-colors"
+ >
+ Cancel
+ </button>
+ <button
+ onClick={handleFixHtml}
+ disabled={!debugDescription.trim() || fixingHtml}
+ className="px-4 py-2 bg-amber-600 text-white rounded-lg hover:bg-amber-700 transition-colors disabled:opacity-50 flex items-center gap-2"
+ >
+ {fixingHtml ? (
+ <>
+ <Loader2 className="w-4 h-4 animate-spin" />
+ Fixing...
+ </>
+ ) : (
+ <>
+ <Bug className="w-4 h-4" />
+ Fix
+ </>
+ )}
+ </button>
+ </div>
+ </div>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/web/app/ideagen/page.tsx b/web/app/ideagen/page.tsx
new file mode 100644
index 000000000..9ab7ed3eb
--- /dev/null
+++ b/web/app/ideagen/page.tsx
@@ -0,0 +1,753 @@
+"use client";
+
+import { useState, useEffect, useRef } from "react";
+import {
+ Lightbulb,
+ BookOpen,
+ ChevronDown,
+ ChevronRight,
+ Loader2,
+ Check,
+ Save,
+ RefreshCw,
+ Sparkles,
+ Brain,
+ FileText,
+ CheckCircle2,
+ Circle,
+ AlertCircle,
+ Zap,
+} from "lucide-react";
+import ReactMarkdown from "react-markdown";
+import remarkGfm from "remark-gfm";
+import remarkMath from "remark-math";
+import rehypeKatex from "rehype-katex";
+import "katex/dist/katex.min.css";
+import { apiUrl, wsUrl } from "@/lib/api";
+import { processLatexContent } from "@/lib/latex";
+import AddToNotebookModal from "@/components/AddToNotebookModal";
+import { useGlobal } from "@/context/GlobalContext";
+
+interface Notebook {
+ id: string;
+ name: string;
+ description: string;
+ record_count: number;
+ color: string;
+}
+
+interface NotebookRecord {
+ id: string;
+ title: string;
+ user_query: string;
+ output: string;
+ type: string;
+}
+
+interface ResearchIdea {
+ id: string;
+ knowledge_point: string;
+ description: string;
+ research_ideas: string[];
+ statement: string;
+ expanded: boolean;
+ selected: boolean;
+}
+
+// Extended interface to include notebook info
+interface SelectedRecord extends NotebookRecord {
+ notebookId: string;
+ notebookName: string;
+}
+
+export default function IdeaGenPage() {
+ // Global state for persistence across page navigation
+ const { ideaGenState, setIdeaGenState } = useGlobal();
+
+ // Notebook selection - now supports multiple notebooks
+ const [notebooks, setNotebooks] = useState<Notebook[]>([]);
+ const [expandedNotebooks, setExpandedNotebooks] = useState<Set<string>>(
+ new Set(),
+ );
+ const [notebookRecordsMap, setNotebookRecordsMap] = useState<
+ Map<string, NotebookRecord[]>
+ >(new Map());
+ const [selectedRecords, setSelectedRecords] = useState<
+ Map<string, SelectedRecord>
+ >(new Map()); // recordId -> record with notebook info
+ const [loadingNotebooks, setLoadingNotebooks] = useState(true);
+ const [loadingRecordsFor, setLoadingRecordsFor] = useState<Set<string>>(
+ new Set(),
+ );
+
+ // User thoughts input
+ const [userThoughts, setUserThoughts] = useState("");
+
+ // Use global state for generation (persists across navigation)
+ const isGenerating = ideaGenState.isGenerating;
+ const generationStatus = ideaGenState.generationStatus;
+ const generatedIdeas = ideaGenState.generatedIdeas;
+ const progress = ideaGenState.progress;
+
+ const setIsGenerating = (val: boolean) =>
+ setIdeaGenState((prev) => ({ ...prev, isGenerating: val }));
+ const setGenerationStatus = (val: string) =>
+ setIdeaGenState((prev) => ({ ...prev, generationStatus: val }));
+ const setGeneratedIdeas = (
+ updater: ResearchIdea[] | ((prev: ResearchIdea[]) => ResearchIdea[]),
+ ) => {
+ setIdeaGenState((prev) => ({
+ ...prev,
+ generatedIdeas:
+ typeof updater === "function" ? updater(prev.generatedIdeas) : updater,
+ }));
+ };
+ const setProgress = (val: { current: number; total: number } | null) =>
+ setIdeaGenState((prev) => ({ ...prev, progress: val }));
+
+ // Save modal
+ const [showSaveModal, setShowSaveModal] = useState(false);
+ const [ideaToSave, setIdeaToSave] = useState<ResearchIdea | null>(null);
+
+ const wsRef = useRef<WebSocket | null>(null);
+
+ // Load notebooks
+ useEffect(() => {
+ fetchNotebooks();
+ return () => {
+ if (wsRef.current) {
+ wsRef.current.close();
+ }
+ };
+ }, []);
+
+ const fetchNotebooks = 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,
+ );
+ setNotebooks(notebooksWithRecords);
+ setLoadingNotebooks(false);
+ } catch (err) {
+ console.error("Failed to fetch notebooks:", err);
+ setLoadingNotebooks(false);
+ }
+ };
+
+ const fetchNotebookRecords = async (notebookId: string) => {
+ if (notebookRecordsMap.has(notebookId)) return; // Already fetched
+
+ setLoadingRecordsFor((prev) => new Set([...prev, notebookId]));
+ try {
+ const res = await fetch(apiUrl(`/api/v1/notebook/${notebookId}`));
+ const data = await res.json();
+ setNotebookRecordsMap((prev) =>
+ new Map(prev).set(notebookId, data.records || []),
+ );
+ } catch (err) {
+ console.error("Failed to fetch notebook records:", err);
+ } finally {
+ setLoadingRecordsFor((prev) => {
+ const newSet = new Set(prev);
+ newSet.delete(notebookId);
+ return newSet;
+ });
+ }
+ };
+
+ const toggleNotebookExpanded = (notebookId: string) => {
+ const notebook = notebooks.find((nb) => nb.id === notebookId);
+ if (!notebook) return;
+
+ setExpandedNotebooks((prev) => {
+ const newSet = new Set(prev);
+ if (newSet.has(notebookId)) {
+ newSet.delete(notebookId);
+ } else {
+ newSet.add(notebookId);
+ // Fetch records when expanding
+ fetchNotebookRecords(notebookId);
+ }
+ return newSet;
+ });
+ };
+
+ const toggleRecordSelection = (
+ record: NotebookRecord,
+ notebookId: string,
+ notebookName: string,
+ ) => {
+ setSelectedRecords((prev) => {
+ const newMap = new Map(prev);
+ if (newMap.has(record.id)) {
+ newMap.delete(record.id);
+ } else {
+ newMap.set(record.id, { ...record, notebookId, notebookName });
+ }
+ return newMap;
+ });
+ };
+
+ const selectAllFromNotebook = (notebookId: string, notebookName: string) => {
+ const records = notebookRecordsMap.get(notebookId) || [];
+ setSelectedRecords((prev) => {
+ const newMap = new Map(prev);
+ records.forEach((r) =>
+ newMap.set(r.id, { ...r, notebookId, notebookName }),
+ );
+ return newMap;
+ });
+ };
+
+ const deselectAllFromNotebook = (notebookId: string) => {
+ const records = notebookRecordsMap.get(notebookId) || [];
+ const recordIds = new Set(records.map((r) => r.id));
+ setSelectedRecords((prev) => {
+ const newMap = new Map(prev);
+ recordIds.forEach((id) => newMap.delete(id));
+ return newMap;
+ });
+ };
+
+ const clearAllSelections = () => {
+ setSelectedRecords(new Map());
+ };
+
+ const startGeneration = () => {
+ if (selectedRecords.size === 0) return;
+
+ setIsGenerating(true);
+ setGenerationStatus("Connecting...");
+ setGeneratedIdeas([]);
+ setProgress(null);
+
+ const ws = new WebSocket(wsUrl("/api/v1/ideagen/generate"));
+ wsRef.current = ws;
+
+ ws.onopen = () => {
+ setGenerationStatus("Initializing...");
+ // Send records directly for cross-notebook support
+ const recordsArray = Array.from(selectedRecords.values()).map((r) => ({
+ id: r.id,
+ title: r.title,
+ user_query: r.user_query,
+ output: r.output,
+ type: r.type,
+ }));
+ ws.send(
+ JSON.stringify({
+ records: recordsArray,
+ user_thoughts: userThoughts.trim() || undefined,
+ }),
+ );
+ };
+
+ ws.onmessage = (event) => {
+ const data = JSON.parse(event.data);
+
+ switch (data.type) {
+ case "status":
+ setGenerationStatus(data.message);
+ // Check if this is the "complete" stage from backend
+ if (data.stage === "complete") {
+ setIsGenerating(false);
+ }
+ // Update progress from status data if available
+ if (data.data?.index && data.data?.total) {
+ setProgress({ current: data.data.index, total: data.data.total });
+ }
+ break;
+ case "progress":
+ if (data.data?.index && data.data?.total) {
+ setProgress({ current: data.data.index, total: data.data.total });
+ }
+ break;
+ case "idea":
+ setGeneratedIdeas((prev) => [
+ ...prev,
+ { ...data.data, selected: false },
+ ]);
+ break;
+ case "complete":
+ setGenerationStatus("Completed!");
+ setIsGenerating(false);
+ break;
+ case "error":
+ setGenerationStatus(
+ `Error: ${data.message || data.content || "Unknown error"}`,
+ );
+ setIsGenerating(false);
+ break;
+ }
+ };
+
+ ws.onerror = () => {
+ setGenerationStatus("Connection Error");
+ setIsGenerating(false);
+ };
+
+ ws.onclose = () => {
+ wsRef.current = null;
+ };
+ };
+
+ const toggleIdeaExpanded = (ideaId: string) => {
+ setGeneratedIdeas((prev) =>
+ prev.map((idea) =>
+ idea.id === ideaId ? { ...idea, expanded: !idea.expanded } : idea,
+ ),
+ );
+ };
+
+ const toggleIdeaSelected = (ideaId: string) => {
+ setGeneratedIdeas((prev) =>
+ prev.map((idea) =>
+ idea.id === ideaId ? { ...idea, selected: !idea.selected } : idea,
+ ),
+ );
+ };
+
+ const selectAllIdeas = () => {
+ setGeneratedIdeas((prev) =>
+ prev.map((idea) => ({ ...idea, selected: true })),
+ );
+ };
+
+ const deselectAllIdeas = () => {
+ setGeneratedIdeas((prev) =>
+ prev.map((idea) => ({ ...idea, selected: false })),
+ );
+ };
+
+ const saveIdea = (idea: ResearchIdea) => {
+ setIdeaToSave(idea);
+ setShowSaveModal(true);
+ };
+
+ const saveSelectedIdeas = () => {
+ const selected = generatedIdeas.filter((i) => i.selected);
+ if (selected.length > 0) {
+ // Merge all selected ideas
+ const combinedIdea: ResearchIdea = {
+ id: "combined",
+ knowledge_point: "Collection of Research Ideas",
+ description: `Research ideas containing ${selected.length} knowledge points`,
+ research_ideas: selected.flatMap((i) => i.research_ideas),
+ statement: selected.map((i) => i.statement).join("\n\n---\n\n"),
+ expanded: false,
+ selected: false,
+ };
+ setIdeaToSave(combinedIdea);
+ setShowSaveModal(true);
+ }
+ };
+
+ const getTypeColor = (type: string) => {
+ switch (type) {
+ case "solve":
+ return "bg-blue-100 text-blue-700 border-blue-200";
+ case "question":
+ return "bg-purple-100 text-purple-700 border-purple-200";
+ case "research":
+ return "bg-emerald-100 text-emerald-700 border-emerald-200";
+ case "co_writer":
+ return "bg-amber-100 text-amber-700 border-amber-200";
+ default:
+ return "bg-slate-100 text-slate-700 border-slate-200";
+ }
+ };
+
+ return (
+ <div className="h-[calc(100vh-4rem)] flex gap-4 animate-fade-in">
+ {/* Left Panel: Source Selection */}
+ <div className="flex-[1_1_33%] min-w-[350px] max-w-[500px] flex flex-col gap-4">
+ {/* Multi-Notebook Selection */}
+ <div className="flex-1 bg-white dark:bg-slate-800 rounded-2xl shadow-sm border border-slate-200 dark:border-slate-700 flex flex-col overflow-hidden">
+ <div className="p-3 border-b border-slate-100 dark:border-slate-700 bg-slate-50/50 dark:bg-slate-800/50 flex justify-between items-center">
+ <h2 className="font-bold text-slate-900 dark:text-slate-100 flex items-center gap-2">
+ <BookOpen className="w-5 h-5 text-amber-600 dark:text-amber-400" />
+ Select Source (Cross-Notebook)
+ </h2>
+ {selectedRecords.size > 0 && (
+ <button
+ onClick={clearAllSelections}
+ className="text-xs text-slate-500 dark:text-slate-400 hover:text-red-600 dark:hover:text-red-400"
+ >
+ Clear ({selectedRecords.size})
+ </button>
+ )}
+ </div>
+
+ <div className="flex-1 overflow-y-auto">
+ {loadingNotebooks ? (
+ <div className="flex items-center justify-center py-8">
+ <Loader2 className="w-5 h-5 animate-spin text-amber-600 dark:text-amber-400" />
+ </div>
+ ) : notebooks.length === 0 ? (
+ <div className="p-4 text-center text-sm text-slate-400 dark:text-slate-500">
+ No notebooks with records found
+ </div>
+ ) : (
+ <div className="divide-y divide-slate-100 dark:divide-slate-700">
+ {notebooks.map((notebook) => {
+ const isExpanded = expandedNotebooks.has(notebook.id);
+ const records = notebookRecordsMap.get(notebook.id) || [];
+ const isLoading = loadingRecordsFor.has(notebook.id);
+ const selectedFromThis = records.filter((r) =>
+ selectedRecords.has(r.id),
+ ).length;
+
+ return (
+ <div key={notebook.id}>
+ {/* Notebook Header */}
+ <div
+ className="p-3 flex items-center gap-2 cursor-pointer hover:bg-slate-50 dark:hover:bg-slate-700/50 transition-colors"
+ onClick={() => toggleNotebookExpanded(notebook.id)}
+ >
+ {isExpanded ? (
+ <ChevronDown className="w-4 h-4 text-slate-400 dark:text-slate-500" />
+ ) : (
+ <ChevronRight className="w-4 h-4 text-slate-400 dark:text-slate-500" />
+ )}
+ <div
+ className="w-3 h-3 rounded-full"
+ style={{
+ backgroundColor: notebook.color || "#94a3b8",
+ }}
+ />
+ <span className="flex-1 text-sm font-medium text-slate-700 dark:text-slate-200 truncate">
+ {notebook.name}
+ </span>
+ <span className="text-xs text-slate-400 dark:text-slate-500">
+ {selectedFromThis > 0 && (
+ <span className="text-amber-600 dark:text-amber-400 font-medium">
+ {selectedFromThis}/
+ </span>
+ )}
+ {notebook.record_count}
+ </span>
+ </div>
+
+ {/* Records List */}
+ {isExpanded && (
+ <div className="pl-6 pr-2 pb-2 bg-slate-50/50 dark:bg-slate-800/50">
+ {isLoading ? (
+ <div className="flex items-center justify-center py-4">
+ <Loader2 className="w-4 h-4 animate-spin text-amber-600 dark:text-amber-400" />
+ </div>
+ ) : records.length === 0 ? (
+ <div className="py-2 text-xs text-slate-400 dark:text-slate-500 text-center">
+ No records
+ </div>
+ ) : (
+ <>
+ <div className="flex gap-2 mb-2">
+ <button
+ onClick={(e) => {
+ e.stopPropagation();
+ selectAllFromNotebook(
+ notebook.id,
+ notebook.name,
+ );
+ }}
+ className="text-xs text-amber-600 dark:text-amber-400 hover:text-amber-700 dark:hover:text-amber-300"
+ >
+ Select All
+ </button>
+ <button
+ onClick={(e) => {
+ e.stopPropagation();
+ deselectAllFromNotebook(notebook.id);
+ }}
+ className="text-xs text-slate-500 dark:text-slate-400 hover:text-slate-700 dark:hover:text-slate-300"
+ >
+ Cancel
+ </button>
+ </div>
+ <div className="space-y-1">
+ {records.map((record) => (
+ <div
+ key={record.id}
+ onClick={(e) => {
+ e.stopPropagation();
+ toggleRecordSelection(
+ record,
+ notebook.id,
+ notebook.name,
+ );
+ }}
+ className={`p-2 rounded-lg cursor-pointer transition-all border ${
+ selectedRecords.has(record.id)
+ ? "bg-amber-50 dark:bg-amber-900/30 border-amber-200 dark:border-amber-700"
+ : "hover:bg-white dark:hover:bg-slate-700 border-transparent hover:border-slate-200 dark:hover:border-slate-600"
+ }`}
+ >
+ <div className="flex items-center gap-2">
+ <div
+ className={`w-4 h-4 rounded border flex items-center justify-center shrink-0 ${
+ selectedRecords.has(record.id)
+ ? "bg-amber-500 border-amber-500 text-white"
+ : "border-slate-300 dark:border-slate-500"
+ }`}
+ >
+ {selectedRecords.has(record.id) && (
+ <Check className="w-2.5 h-2.5" />
+ )}
+ </div>
+ <div className="flex-1 min-w-0">
+ <span
+ className={`text-[10px] font-bold uppercase px-1 py-0.5 rounded ${getTypeColor(record.type)}`}
+ >
+ {record.type}
+ </span>
+ <span className="text-xs text-slate-700 dark:text-slate-200 ml-2 truncate">
+ {record.title}
+ </span>
+ </div>
+ </div>
+ </div>
+ ))}
+ </div>
+ </>
+ )}
+ </div>
+ )}
+ </div>
+ );
+ })}
+ </div>
+ )}
+ </div>
+
+ {/* User Thoughts Input */}
+ <div className="p-3 border-t border-slate-100 dark:border-slate-700 bg-slate-50/50 dark:bg-slate-800/50">
+ <label className="text-xs font-bold text-slate-500 dark:text-slate-400 uppercase tracking-wider block mb-2">
+ Your Thoughts (Optional)
+ </label>
+ <textarea
+ value={userThoughts}
+ onChange={(e) => setUserThoughts(e.target.value)}
+ placeholder="Describe your thoughts or research direction based on these materials..."
+ className="w-full px-3 py-2 bg-white dark:bg-slate-700 border border-slate-200 dark:border-slate-600 rounded-lg text-sm text-slate-900 dark:text-slate-100 placeholder:text-slate-400 dark:placeholder:text-slate-500 resize-none focus:ring-2 focus:ring-amber-500/20 focus:border-amber-500 outline-none"
+ rows={2}
+ />
+ </div>
+
+ {/* Generate Button */}
+ <div className="p-3 border-t border-slate-100 dark:border-slate-700">
+ <button
+ onClick={startGeneration}
+ disabled={isGenerating || selectedRecords.size === 0}
+ className="w-full px-4 py-2.5 bg-gradient-to-r from-amber-500 to-orange-500 text-white rounded-xl hover:from-amber-600 hover:to-orange-600 transition-all disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2 font-medium shadow-md shadow-amber-500/20"
+ >
+ {isGenerating ? (
+ <>
+ <Loader2 className="w-4 h-4 animate-spin" />
+ Generating...
+ </>
+ ) : (
+ <>
+ <Sparkles className="w-4 h-4" />
+ Generate Ideas ({selectedRecords.size} items)
+ </>
+ )}
+ </button>
+ </div>
+ </div>
+ </div>
+
+ {/* Right Panel: Generated Ideas */}
+ <div className="flex-[2_1_67%] min-w-0 flex flex-col bg-white dark:bg-slate-800 rounded-2xl shadow-sm border border-slate-200 dark:border-slate-700 overflow-hidden">
+ {/* Header */}
+ <div className="p-4 border-b border-slate-100 dark:border-slate-700 bg-gradient-to-r from-amber-50 to-orange-50 dark:from-amber-900/20 dark:to-orange-900/20 flex justify-between items-center">
+ <div className="flex items-center gap-3">
+ <div className="p-2 bg-amber-100 dark:bg-amber-900/40 rounded-xl">
+ <Lightbulb className="w-5 h-5 text-amber-600 dark:text-amber-400" />
+ </div>
+ <div>
+ <h1 className="font-bold text-slate-900 dark:text-slate-100">
+ IdeaGen
+ </h1>
+ <p className="text-xs text-slate-500 dark:text-slate-400">
+ Discover research ideas from your notes
+ </p>
+ </div>
+ </div>
+
+ {generatedIdeas.length > 0 && (
+ <div className="flex items-center gap-2">
+ <button
+ onClick={selectAllIdeas}
+ className="px-3 py-1.5 text-xs text-amber-600 dark:text-amber-400 hover:bg-amber-50 dark:hover:bg-amber-900/40 rounded-lg transition-colors"
+ >
+ Select All
+ </button>
+ <button
+ onClick={saveSelectedIdeas}
+ disabled={!generatedIdeas.some((i) => i.selected)}
+ className="px-3 py-1.5 text-xs bg-amber-600 text-white rounded-lg hover:bg-amber-700 transition-colors disabled:opacity-50 flex items-center gap-1"
+ >
+ <Save className="w-3 h-3" />
+ Save Selected
+ </button>
+ </div>
+ )}
+ </div>
+
+ {/* Status Bar */}
+ {(isGenerating || generationStatus) && (
+ <div className="px-4 py-2 bg-amber-50 dark:bg-amber-900/30 border-b border-amber-100 dark:border-amber-800 flex items-center justify-between">
+ <div className="flex items-center gap-2">
+ {isGenerating && (
+ <Loader2 className="w-4 h-4 animate-spin text-amber-600 dark:text-amber-400" />
+ )}
+ <span className="text-sm text-amber-700 dark:text-amber-300">
+ {generationStatus}
+ </span>
+ </div>
+ {progress && (
+ <span className="text-xs text-amber-600 dark:text-amber-400">
+ {progress.current} / {progress.total}
+ </span>
+ )}
+ </div>
+ )}
+
+ {/* Ideas List */}
+ <div className="flex-1 overflow-y-auto p-4">
+ {generatedIdeas.length === 0 && !isGenerating ? (
+ <div className="h-full flex flex-col items-center justify-center text-slate-400 dark:text-slate-500">
+ <Brain className="w-16 h-16 text-slate-200 dark:text-slate-600 mb-4" />
+ <p className="text-slate-500 dark:text-slate-400 text-center max-w-md">
+ Select notebook records and click "Generate Ideas"
+ <br />
+ <span className="text-xs text-slate-400 dark:text-slate-500 mt-2 block">
+ System will analyze content, extract knowledge points, and
+ generate research ideas
+ </span>
+ </p>
+ </div>
+ ) : (
+ <div className="space-y-4">
+ {generatedIdeas.map((idea) => (
+ <div
+ key={idea.id}
+ className={`rounded-2xl border transition-all ${
+ idea.selected
+ ? "bg-amber-50 dark:bg-amber-900/30 border-amber-200 dark:border-amber-700 shadow-md shadow-amber-100 dark:shadow-amber-900/20"
+ : "bg-white dark:bg-slate-700 border-slate-200 dark:border-slate-600 hover:border-slate-300 dark:hover:border-slate-500"
+ }`}
+ >
+ {/* Idea Header */}
+ <div className="p-4 flex items-start gap-3">
+ {/* Selection Checkbox */}
+ <button
+ onClick={() => toggleIdeaSelected(idea.id)}
+ className={`w-6 h-6 rounded-full border-2 flex items-center justify-center shrink-0 transition-all ${
+ idea.selected
+ ? "bg-amber-500 border-amber-500 text-white"
+ : "border-slate-300 dark:border-slate-500 hover:border-amber-400 dark:hover:border-amber-500"
+ }`}
+ >
+ {idea.selected && <Check className="w-4 h-4" />}
+ </button>
+
+ {/* Main Content */}
+ <div className="flex-1 min-w-0">
+ <div className="flex items-center justify-between">
+ <h3 className="font-semibold text-slate-900 dark:text-slate-100 flex items-center gap-2">
+ <Zap className="w-4 h-4 text-amber-500 dark:text-amber-400" />
+ {idea.knowledge_point}
+ </h3>
+ <div className="flex items-center gap-2">
+ <span className="text-xs text-slate-400 dark:text-slate-500 bg-slate-100 dark:bg-slate-600 px-2 py-0.5 rounded-full">
+ {idea.research_ideas.length} ideas
+ </span>
+ <button
+ onClick={() => saveIdea(idea)}
+ className="p-1.5 text-slate-400 dark:text-slate-500 hover:text-amber-600 dark:hover:text-amber-400 hover:bg-amber-50 dark:hover:bg-amber-900/40 rounded-lg transition-colors"
+ title="Save to Notebook"
+ >
+ <Save className="w-4 h-4" />
+ </button>
+ </div>
+ </div>
+
+ <p className="text-sm text-slate-500 dark:text-slate-400 mt-1 line-clamp-2">
+ {idea.description}
+ </p>
+
+ {/* Research Ideas Preview */}
+ <div className="flex flex-wrap gap-2 mt-3">
+ {idea.research_ideas.slice(0, 3).map((ri, idx) => (
+ <span
+ key={idx}
+ className="text-xs bg-slate-100 dark:bg-slate-600 text-slate-600 dark:text-slate-300 px-2 py-1 rounded-lg line-clamp-1 max-w-[200px]"
+ >
+ {ri.substring(0, 50)}...
+ </span>
+ ))}
+ {idea.research_ideas.length > 3 && (
+ <span className="text-xs text-slate-400 dark:text-slate-500">
+ +{idea.research_ideas.length - 3} more
+ </span>
+ )}
+ </div>
+ </div>
+
+ {/* Expand Button */}
+ <button
+ onClick={() => toggleIdeaExpanded(idea.id)}
+ className="p-1.5 text-slate-400 dark:text-slate-500 hover:text-slate-600 dark:hover:text-slate-300 hover:bg-slate-100 dark:hover:bg-slate-600 rounded-lg transition-colors"
+ >
+ {idea.expanded ? (
+ <ChevronDown className="w-5 h-5" />
+ ) : (
+ <ChevronRight className="w-5 h-5" />
+ )}
+ </button>
+ </div>
+
+ {/* Expanded Content */}
+ {idea.expanded && (
+ <div className="px-4 pb-4 pt-0 border-t border-slate-100 dark:border-slate-600 mt-0">
+ <div className="mt-4 prose prose-sm prose-slate dark:prose-invert max-w-none">
+ <ReactMarkdown
+ remarkPlugins={[remarkGfm, remarkMath]}
+ rehypePlugins={[rehypeKatex]}
+ >
+ {processLatexContent(idea.statement)}
+ </ReactMarkdown>
+ </div>
+ </div>
+ )}
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ </div>
+
+ {/* Save Modal */}
+ {ideaToSave && (
+ <AddToNotebookModal
+ isOpen={showSaveModal}
+ onClose={() => {
+ setShowSaveModal(false);
+ setIdeaToSave(null);
+ }}
+ recordType="research"
+ title={`Research Idea: ${ideaToSave.knowledge_point}`}
+ userQuery={ideaToSave.description}
+ output={ideaToSave.statement}
+ metadata={{
+ ideas_count: ideaToSave.research_ideas.length,
+ source: "ideagen",
+ }}
+ />
+ )}
+ </div>
+ );
+}
diff --git a/web/app/knowledge/page.tsx b/web/app/knowledge/page.tsx
new file mode 100644
index 000000000..87cee82c2
--- /dev/null
+++ b/web/app/knowledge/page.tsx
@@ -0,0 +1,1018 @@
+"use client";
+
+import { useState, useEffect, useCallback, useRef } from "react";
+import {
+ BookOpen,
+ Database,
+ FileText,
+ Image as ImageIcon,
+ Layers,
+ MoreVertical,
+ Plus,
+ Search,
+ Upload,
+ Trash2,
+ Loader2,
+ X,
+ RefreshCw,
+} from "lucide-react";
+import { apiUrl, wsUrl } from "@/lib/api";
+
+interface KnowledgeBase {
+ name: string;
+ is_default: boolean;
+ statistics: {
+ raw_documents: number;
+ images: number;
+ content_lists: number;
+ rag_initialized: boolean;
+ rag?: {
+ chunks?: number;
+ entities?: number;
+ relations?: number;
+ };
+ };
+}
+
+interface ProgressInfo {
+ stage: string;
+ message: string;
+ current: number;
+ total: number;
+ file_name?: string;
+ progress_percent: number;
+ error?: string;
+}
+
+export default function KnowledgePage() {
+ const [kbs, setKbs] = useState<KnowledgeBase[]>([]);
+ const [loading, setLoading] = useState(true);
+ const [error, setError] = useState<string | null>(null);
+ const [uploadModalOpen, setUploadModalOpen] = useState(false);
+ const [createModalOpen, setCreateModalOpen] = useState(false);
+ const [targetKb, setTargetKb] = useState<string>("");
+ const [uploading, setUploading] = useState(false);
+ const [files, setFiles] = useState<FileList | null>(null);
+ const [newKbName, setNewKbName] = useState("");
+ const [dragActive, setDragActive] = useState(false);
+ const [progressMap, setProgressMap] = useState<Record<string, ProgressInfo>>(
+ {},
+ );
+ // Use ref only for WebSocket connections (no need for state as it's not used in render)
+ const wsConnectionsRef = useRef<Record<string, WebSocket>>({});
+ const kbsNamesRef = useRef<string[]>([]);
+
+ // Restore progress state from localStorage (with cleanup of stuck states)
+ useEffect(() => {
+ try {
+ const saved = localStorage.getItem("kb_progress_map");
+ if (saved) {
+ const parsed = JSON.parse(saved);
+
+ // Clean up stuck progress states (older than 30 minutes and not completed/error)
+ const now = new Date().getTime();
+ const thirtyMinutes = 30 * 60 * 1000;
+ const cleaned: Record<string, ProgressInfo> = {};
+
+ Object.entries(parsed).forEach(([kbName, progress]: [string, any]) => {
+ if (progress.timestamp) {
+ const progressTime = new Date(progress.timestamp).getTime();
+ const age = now - progressTime;
+
+ // Keep if: completed, error, or recent (< 30 min)
+ if (
+ progress.stage === "completed" ||
+ progress.stage === "error" ||
+ age < thirtyMinutes
+ ) {
+ cleaned[kbName] = progress;
+ } else {
+ console.log(
+ `[KB Progress] Clearing stuck progress for ${kbName} (age: ${Math.round(age / 60000)} min)`,
+ );
+ }
+ } else {
+ // No timestamp, keep completed/error, clear others
+ if (progress.stage === "completed" || progress.stage === "error") {
+ cleaned[kbName] = progress;
+ }
+ }
+ });
+
+ setProgressMap(cleaned);
+ localStorage.setItem("kb_progress_map", JSON.stringify(cleaned));
+ }
+ } catch (e) {
+ console.error("Failed to load progress from localStorage:", e);
+ }
+ }, []);
+
+ // Persist progress state to localStorage
+ useEffect(() => {
+ try {
+ localStorage.setItem("kb_progress_map", JSON.stringify(progressMap));
+ } catch (e) {
+ console.error("Failed to save progress to localStorage:", e);
+ }
+ }, [progressMap]);
+
+ // Define fetchKnowledgeBases using useCallback to ensure it's available
+ const fetchKnowledgeBases = useCallback(async () => {
+ try {
+ setLoading(true);
+ setError(null);
+
+ const baseUrl = apiUrl("");
+ const listUrl = apiUrl("/api/v1/knowledge/list");
+ const healthUrl = apiUrl("/api/v1/knowledge/health");
+
+ console.log("🔍 Fetching knowledge bases...");
+ console.log(" Base URL:", baseUrl);
+ console.log(" List URL:", listUrl);
+ console.log(" Health URL:", healthUrl);
+
+ // Test health check endpoint first
+ try {
+ const healthRes = await fetch(healthUrl);
+ const healthData = await healthRes.json();
+ console.log("✅ Health check response:", healthData);
+ } catch (healthErr) {
+ console.warn("⚠️ Health check failed:", healthErr);
+ }
+
+ // Fetch knowledge base list
+ const res = await fetch(listUrl, {
+ method: "GET",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ });
+
+ console.log("📡 Response status:", res.status, res.statusText);
+ console.log(
+ "📡 Response headers:",
+ Object.fromEntries(res.headers.entries()),
+ );
+
+ if (!res.ok) {
+ let errorMessage = `HTTP ${res.status}: Failed to fetch knowledge bases`;
+ let errorDetail = "";
+ try {
+ const errorData = await res.json();
+ errorDetail = errorData.detail || errorData.message || "";
+ errorMessage = errorDetail || errorMessage;
+ console.error("❌ Error response:", errorData);
+ } catch (parseErr) {
+ const text = await res.text();
+ console.error("❌ Error response (text):", text);
+ errorMessage = `${errorMessage}. Response: ${text.substring(0, 200)}`;
+ }
+ throw new Error(errorMessage);
+ }
+
+ const data = await res.json();
+ console.log("✅ Received knowledge bases:", data);
+ console.log("✅ Data type:", Array.isArray(data) ? "array" : typeof data);
+ console.log("✅ Data length:", Array.isArray(data) ? data.length : "N/A");
+
+ if (!Array.isArray(data)) {
+ throw new Error(
+ `Invalid response format: expected array, got ${typeof data}`,
+ );
+ }
+
+ setKbs(data);
+ setError(null); // Clear previous error - empty list is not an error, it's just empty state
+ } catch (err: any) {
+ console.error("❌ Error fetching knowledge bases:", err);
+ console.error("❌ Error stack:", err.stack);
+
+ let errorMessage =
+ err.message ||
+ "Failed to load knowledge bases. Please ensure the backend is running.";
+
+ // Provide more detailed message for network errors
+ if (err.name === "TypeError" && err.message.includes("fetch")) {
+ errorMessage = `Network error: Cannot connect to backend at ${apiUrl("")}. Please ensure the backend is running.`;
+ }
+
+ setError(errorMessage);
+ } finally {
+ setLoading(false);
+ }
+ }, []);
+
+ useEffect(() => {
+ fetchKnowledgeBases();
+ }, [fetchKnowledgeBases]);
+
+ // Establish WebSocket connections for all KBs to receive progress updates (only when KB names change)
+ useEffect(() => {
+ // Skip if still loading or kbs is not yet loaded
+ if (loading || !kbs) {
+ return;
+ }
+
+ // Only re-establish connections if KB names actually changed
+ const currentKbNames = [...kbs.map((kb) => kb.name)].sort();
+ const currentKbNamesStr = currentKbNames.join(",");
+ const prevKbNames = [...(kbsNamesRef.current || [])].sort();
+ const prevKbNamesStr = prevKbNames.join(",");
+
+ // If KB names haven't changed, don't re-establish connections
+ if (
+ currentKbNamesStr === prevKbNamesStr &&
+ currentKbNamesStr !== "" &&
+ Object.keys(wsConnectionsRef.current).length > 0
+ ) {
+ // Update statistics in existing connections context, but don't reconnect
+ return;
+ }
+
+ // If kbs is empty and we have connections, close them all
+ if (kbs.length === 0) {
+ if (Object.keys(wsConnectionsRef.current).length > 0) {
+ Object.values(wsConnectionsRef.current).forEach((ws) => {
+ if (
+ ws &&
+ (ws.readyState === WebSocket.OPEN ||
+ ws.readyState === WebSocket.CONNECTING)
+ ) {
+ ws.close();
+ }
+ });
+ wsConnectionsRef.current = {};
+ }
+ kbsNamesRef.current = [];
+ return;
+ }
+
+ // Close old connections that are no longer needed
+ Object.entries(wsConnectionsRef.current).forEach(([kbName, ws]) => {
+ if (!kbs.find((kb) => kb.name === kbName)) {
+ if (
+ ws &&
+ (ws.readyState === WebSocket.OPEN ||
+ ws.readyState === WebSocket.CONNECTING)
+ ) {
+ ws.close();
+ }
+ delete wsConnectionsRef.current[kbName];
+ }
+ });
+
+ const connections: Record<string, WebSocket> = {
+ ...wsConnectionsRef.current,
+ };
+
+ kbs.forEach((kb) => {
+ // Only create new connection if one doesn't exist
+ if (
+ connections[kb.name] &&
+ connections[kb.name].readyState !== WebSocket.CLOSED
+ ) {
+ return;
+ }
+ // Connect to all KBs (not just uninitialized ones)
+ // This allows receiving progress updates when adding documents
+ const ws = new WebSocket(
+ wsUrl(`/api/v1/knowledge/${kb.name}/progress/ws`),
+ );
+
+ ws.onopen = () => {
+ console.log(`[Progress WS] Connected for KB: ${kb.name}`);
+ };
+
+ ws.onmessage = (event) => {
+ try {
+ const data = JSON.parse(event.data);
+ if (data.type === "progress" && data.data) {
+ // If KB is already initialized (ready), ignore stale in-progress updates
+ // Only accept 'completed' or 'error' or recent updates (within 5 minutes)
+ if (kb.statistics.rag_initialized) {
+ const progressStage = data.data.stage;
+ const progressTime = data.data.timestamp
+ ? new Date(data.data.timestamp).getTime()
+ : 0;
+ const now = new Date().getTime();
+ const fiveMinutes = 5 * 60 * 1000;
+
+ // Skip stale in-progress updates for already-ready KBs
+ if (progressStage !== "completed" && progressStage !== "error") {
+ if (!progressTime || now - progressTime > fiveMinutes) {
+ console.log(
+ `[Progress WS] Ignoring stale progress for ready KB: ${kb.name}`,
+ );
+ return;
+ }
+ }
+ }
+
+ setProgressMap((prev) => {
+ const updated = {
+ ...prev,
+ [kb.name]: data.data,
+ };
+ // Auto-persist to localStorage
+ try {
+ localStorage.setItem(
+ "kb_progress_map",
+ JSON.stringify(updated),
+ );
+ } catch (e) {
+ console.error("Failed to save progress to localStorage:", e);
+ }
+ return updated;
+ });
+
+ // Don't auto-refresh KB list when completed or error
+ // User can manually refresh using the refresh button
+ } else if (data.type === "error") {
+ console.error(
+ `[Progress WS] Error for KB ${kb.name}:`,
+ data.message,
+ );
+ }
+ } catch (e) {
+ console.error(
+ `[Progress WS] Error parsing message for ${kb.name}:`,
+ e,
+ );
+ }
+ };
+
+ ws.onerror = (error) => {
+ console.error(`[Progress WS] Error for ${kb.name}:`, error);
+ };
+
+ ws.onclose = () => {
+ console.log(`[Progress WS] Closed for KB: ${kb.name}`);
+ };
+
+ connections[kb.name] = ws;
+ wsConnectionsRef.current[kb.name] = ws;
+ });
+
+ kbsNamesRef.current = kbs.map((kb) => kb.name);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [kbs, loading]);
+
+ // Cleanup all connections on component unmount
+ useEffect(() => {
+ return () => {
+ Object.values(wsConnectionsRef.current).forEach((ws) => {
+ if (
+ ws &&
+ (ws.readyState === WebSocket.OPEN ||
+ ws.readyState === WebSocket.CONNECTING)
+ ) {
+ ws.close();
+ }
+ });
+ wsConnectionsRef.current = {};
+ };
+ }, []);
+
+ const handleDelete = async (name: string) => {
+ if (
+ !confirm(
+ `Are you sure you want to delete knowledge base "${name}"? This cannot be undone.`,
+ )
+ )
+ return;
+
+ try {
+ const res = await fetch(apiUrl(`/api/v1/knowledge/${name}`), {
+ method: "DELETE",
+ });
+ if (!res.ok) throw new Error("Failed to delete knowledge base");
+
+ // Also clear progress state for this KB
+ clearProgress(name);
+
+ fetchKnowledgeBases();
+ } catch (err) {
+ console.error(err);
+ alert("Failed to delete knowledge base");
+ }
+ };
+
+ // Clear progress state for a specific KB (frontend + backend)
+ const clearProgress = async (kbName: string) => {
+ // Clear frontend state
+ setProgressMap((prev) => {
+ const updated = { ...prev };
+ delete updated[kbName];
+ try {
+ localStorage.setItem("kb_progress_map", JSON.stringify(updated));
+ } catch (e) {
+ console.error("Failed to save progress to localStorage:", e);
+ }
+ return updated;
+ });
+
+ // Clear backend progress file
+ try {
+ await fetch(apiUrl(`/api/v1/knowledge/${kbName}/progress/clear`), {
+ method: "POST",
+ });
+ console.log(`[Progress] Cleared backend progress for KB: ${kbName}`);
+ } catch (e) {
+ console.error("Failed to clear backend progress:", e);
+ }
+ };
+
+ // Clear all stuck progress states
+ const clearAllStuckProgress = () => {
+ setProgressMap((prev) => {
+ const cleaned: Record<string, ProgressInfo> = {};
+ Object.entries(prev).forEach(([kbName, progress]) => {
+ // Only keep completed and error states
+ if (progress.stage === "completed" || progress.stage === "error") {
+ cleaned[kbName] = progress;
+ }
+ });
+ try {
+ localStorage.setItem("kb_progress_map", JSON.stringify(cleaned));
+ } catch (e) {
+ console.error("Failed to save progress to localStorage:", e);
+ }
+ return cleaned;
+ });
+ };
+
+ const handleUpload = async (e: React.FormEvent) => {
+ e.preventDefault();
+ if (!files || files.length === 0 || !targetKb) return;
+
+ setUploading(true);
+ const formData = new FormData();
+ Array.from(files).forEach((file) => {
+ formData.append("files", file);
+ });
+
+ try {
+ const res = await fetch(apiUrl(`/api/v1/knowledge/${targetKb}/upload`), {
+ method: "POST",
+ body: formData,
+ });
+ if (!res.ok) throw new Error("Upload failed");
+
+ setUploadModalOpen(false);
+ setFiles(null);
+ // Refresh immediately to establish WebSocket connection
+ await fetchKnowledgeBases();
+ alert("Files uploaded successfully! Processing started in background.");
+ } catch (err) {
+ console.error(err);
+ alert("Failed to upload files");
+ } finally {
+ setUploading(false);
+ }
+ };
+
+ const handleCreate = async (e: React.FormEvent) => {
+ e.preventDefault();
+ if (!newKbName || !files || files.length === 0) return;
+
+ setUploading(true);
+ const formData = new FormData();
+ formData.append("name", newKbName);
+ Array.from(files).forEach((file) => {
+ formData.append("files", file);
+ });
+
+ try {
+ const res = await fetch(apiUrl("/api/v1/knowledge/create"), {
+ method: "POST",
+ body: formData,
+ });
+ if (!res.ok) {
+ const errorData = await res.json();
+ throw new Error(errorData.detail || "Creation failed");
+ }
+
+ const result = await res.json();
+
+ // Immediately display new KB in frontend (optimistic update)
+ const newKb: KnowledgeBase = {
+ name: result.name,
+ is_default: false,
+ statistics: {
+ raw_documents: result.files?.length || 0,
+ images: 0,
+ content_lists: 0,
+ rag_initialized: false,
+ },
+ };
+
+ // Add to list (if not exists)
+ setKbs((prev) => {
+ const exists = prev.some((kb) => kb.name === newKb.name);
+ if (exists) {
+ return prev;
+ }
+ return [newKb, ...prev];
+ });
+
+ // Initialize progress state
+ setProgressMap((prev) => ({
+ ...prev,
+ [newKb.name]: {
+ stage: "initializing",
+ message: "Initializing knowledge base...",
+ current: 0,
+ total: 0,
+ file_name: "",
+ progress_percent: 0,
+ timestamp: new Date().toISOString(),
+ },
+ }));
+
+ setCreateModalOpen(false);
+ setFiles(null);
+ setNewKbName("");
+
+ // Delay refresh to get full info (but user can already see the new KB)
+ setTimeout(async () => {
+ await fetchKnowledgeBases();
+ }, 1000);
+
+ alert(
+ "Knowledge base created successfully! Initialization started in background.",
+ );
+ } catch (err: any) {
+ console.error(err);
+ alert(`Failed to create knowledge base: ${err.message}`);
+ } finally {
+ setUploading(false);
+ }
+ };
+
+ const handleDrag = useCallback((e: React.DragEvent) => {
+ e.preventDefault();
+ e.stopPropagation();
+ if (e.type === "dragenter" || e.type === "dragover") {
+ setDragActive(true);
+ } else if (e.type === "dragleave") {
+ setDragActive(false);
+ }
+ }, []);
+
+ const handleDrop = useCallback((e: React.DragEvent) => {
+ e.preventDefault();
+ e.stopPropagation();
+ setDragActive(false);
+ if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
+ setFiles(e.dataTransfer.files);
+ }
+ }, []);
+
+ return (
+ <div className="animate-fade-in">
+ {/* Header */}
+ <div className="flex justify-between items-end mb-8">
+ <div>
+ <h1 className="text-3xl font-bold text-slate-900 dark:text-slate-100 tracking-tight flex items-center gap-3">
+ <BookOpen className="w-8 h-8 text-blue-600 dark:text-blue-400" />
+ Knowledge Bases
+ </h1>
+ <p className="text-slate-500 dark:text-slate-400 mt-2">
+ Manage and explore your educational content repositories.
+ </p>
+ </div>
+ <div className="flex gap-3">
+ <button
+ onClick={async () => {
+ setLoading(true);
+ await fetchKnowledgeBases();
+ }}
+ className="bg-white dark:bg-slate-800 text-slate-700 dark:text-slate-300 px-4 py-2 rounded-lg text-sm font-medium hover:bg-slate-50 dark:hover:bg-slate-700 transition-colors flex items-center gap-2 border border-slate-200 dark:border-slate-600 shadow-sm hover:shadow"
+ title="Refresh knowledge bases"
+ >
+ <RefreshCw className="w-4 h-4" />
+ Refresh
+ </button>
+ <button
+ onClick={() => {
+ setFiles(null);
+ setNewKbName("");
+ setCreateModalOpen(true);
+ }}
+ className="bg-slate-900 dark:bg-slate-100 text-white dark:text-slate-900 px-4 py-2 rounded-lg text-sm font-medium hover:bg-slate-800 dark:hover:bg-slate-200 transition-colors flex items-center gap-2 shadow-lg shadow-slate-900/20"
+ >
+ <Plus className="w-4 h-4" />
+ New Knowledge Base
+ </button>
+ </div>
+ </div>
+
+ {/* Error State */}
+ {error && (
+ <div className="bg-red-50 dark:bg-red-900/30 text-red-600 dark:text-red-400 p-4 rounded-xl border border-red-100 dark:border-red-800 mb-6 flex items-center gap-3">
+ <div className="w-2 h-2 rounded-full bg-red-500" />
+ {error}
+ </div>
+ )}
+
+ {/* Loading State */}
+ {loading && (
+ <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
+ {[1, 2, 3].map((i) => (
+ <div
+ key={i}
+ className="bg-white dark:bg-slate-800 h-48 rounded-2xl shadow-sm border border-slate-200 dark:border-slate-700 animate-pulse"
+ />
+ ))}
+ </div>
+ )}
+
+ {/* KB Grid */}
+ {!loading && (
+ <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
+ {kbs.map((kb) => (
+ <div
+ key={kb.name}
+ className="group bg-white dark:bg-slate-800 rounded-2xl shadow-sm border border-slate-200 dark:border-slate-700 hover:shadow-md transition-all duration-300 hover:-translate-y-1 overflow-hidden flex flex-col"
+ >
+ {/* Card Header */}
+ <div className="p-6 border-b border-slate-100 dark:border-slate-700 bg-slate-50/50 dark:bg-slate-800/50 flex justify-between items-start">
+ <div className="flex items-center gap-3">
+ <div className="w-10 h-10 bg-white dark:bg-slate-700 rounded-xl border border-slate-200 dark:border-slate-600 flex items-center justify-center shadow-sm">
+ <Database className="w-5 h-5 text-blue-500 dark:text-blue-400" />
+ </div>
+ <div>
+ <h3 className="font-bold text-slate-900 dark:text-slate-100">
+ {kb.name}
+ </h3>
+ {kb.is_default && (
+ <span className="inline-flex items-center px-2 py-0.5 rounded-full bg-blue-50 dark:bg-blue-900/40 text-blue-600 dark:text-blue-400 text-[10px] font-bold uppercase tracking-wide border border-blue-100 dark:border-blue-800 mt-1">
+ Default
+ </span>
+ )}
+ </div>
+ </div>
+ <div className="flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
+ <button
+ onClick={() => {
+ setTargetKb(kb.name);
+ setFiles(null);
+ setUploadModalOpen(true);
+ }}
+ className="p-2 hover:bg-slate-200 dark:hover:bg-slate-600 rounded-lg text-slate-500 dark:text-slate-400 hover:text-blue-600 dark:hover:text-blue-400 transition-colors"
+ title="Upload Documents"
+ >
+ <Upload className="w-4 h-4" />
+ </button>
+ <button
+ onClick={() => handleDelete(kb.name)}
+ className="p-2 hover:bg-red-100 dark:hover:bg-red-900/40 rounded-lg text-slate-500 dark:text-slate-400 hover:text-red-600 dark:hover:text-red-400 transition-colors"
+ title="Delete Knowledge Base"
+ >
+ <Trash2 className="w-4 h-4" />
+ </button>
+ </div>
+ </div>
+
+ {/* Stats */}
+ <div className="p-6 space-y-4 flex-1">
+ <div className="grid grid-cols-2 gap-4">
+ <div className="bg-slate-50 dark:bg-slate-700/50 p-3 rounded-lg">
+ <p className="text-xs text-slate-500 dark:text-slate-400 font-medium mb-1 flex items-center gap-1.5">
+ <FileText className="w-3 h-3" /> Documents
+ </p>
+ <p className="text-lg font-bold text-slate-700 dark:text-slate-200">
+ {kb.statistics.raw_documents}
+ </p>
+ </div>
+ <div className="bg-slate-50 dark:bg-slate-700/50 p-3 rounded-lg">
+ <p className="text-xs text-slate-500 dark:text-slate-400 font-medium mb-1 flex items-center gap-1.5">
+ <ImageIcon className="w-3 h-3" /> Images
+ </p>
+ <p className="text-lg font-bold text-slate-700 dark:text-slate-200">
+ {kb.statistics.images}
+ </p>
+ </div>
+ </div>
+
+ <div className="pt-2">
+ <div className="flex items-center justify-between text-xs mb-2">
+ <span className="text-slate-500 dark:text-slate-400 font-medium flex items-center gap-1.5">
+ <Layers className="w-3 h-3" /> Status
+ </span>
+ {(() => {
+ const progress = progressMap[kb.name];
+ if (progress) {
+ if (progress.stage === "completed") {
+ return (
+ <span className="text-emerald-600 dark:text-emerald-400 font-bold">
+ Ready
+ </span>
+ );
+ } else if (progress.stage === "error") {
+ return (
+ <span className="text-red-600 dark:text-red-400 font-bold">
+ Error
+ </span>
+ );
+ } else {
+ // Display current stage and progress
+ const stageLabels: Record<string, string> = {
+ initializing: "Initializing",
+ processing_documents: "Processing",
+ processing_file: "Processing File",
+ extracting_items: "Extracting Items",
+ };
+ const stageLabel =
+ stageLabels[progress.stage] || progress.stage;
+ return (
+ <span className="text-blue-600 dark:text-blue-400 font-bold flex items-center gap-1">
+ <Loader2 className="w-3 h-3 animate-spin" />
+ {stageLabel} {progress.progress_percent}%
+ </span>
+ );
+ }
+ }
+ return (
+ <span
+ className={
+ kb.statistics.rag_initialized
+ ? "text-emerald-600 dark:text-emerald-400 font-bold"
+ : "text-slate-400 dark:text-slate-500"
+ }
+ >
+ {kb.statistics.rag_initialized
+ ? "Ready"
+ : "Not Indexed"}
+ </span>
+ );
+ })()}
+ </div>
+ <div className="w-full bg-slate-100 dark:bg-slate-700 rounded-full h-1.5 overflow-hidden">
+ {(() => {
+ const progress = progressMap[kb.name];
+ if (progress) {
+ const percent = progress.progress_percent;
+ let bgColor = "bg-blue-500";
+ if (progress.stage === "completed") {
+ bgColor = "bg-emerald-500";
+ } else if (progress.stage === "error") {
+ bgColor = "bg-red-500";
+ }
+ return (
+ <div
+ className={`h-full rounded-full ${bgColor} transition-all duration-300`}
+ style={{ width: `${percent}%` }}
+ />
+ );
+ }
+ return (
+ <div
+ className={`h-full rounded-full ${kb.statistics.rag_initialized ? "bg-emerald-500 w-full" : "bg-slate-300 w-0"}`}
+ />
+ );
+ })()}
+ </div>
+ {(() => {
+ const progress = progressMap[kb.name];
+ if (progress && progress.message) {
+ return (
+ <div className="mt-2 space-y-1">
+ <div className="text-[10px] text-slate-600 dark:text-slate-400 font-medium flex items-center justify-between">
+ <span>{progress.message}</span>
+ {/* Clear button for stuck states */}
+ {progress.stage !== "completed" && (
+ <button
+ onClick={async (e) => {
+ e.stopPropagation();
+ await clearProgress(kb.name);
+ // Refresh KB list to show correct status
+ fetchKnowledgeBases();
+ }}
+ className="text-slate-400 dark:text-slate-500 hover:text-red-500 dark:hover:text-red-400 transition-colors"
+ title="Clear progress status"
+ >
+ <X className="w-3 h-3" />
+ </button>
+ )}
+ </div>
+ {progress.file_name && (
+ <div className="text-[10px] text-slate-500 dark:text-slate-400 flex items-center gap-1">
+ <FileText className="w-3 h-3" />
+ <span className="truncate">
+ {progress.file_name}
+ </span>
+ </div>
+ )}
+ {progress.current > 0 && progress.total > 0 && (
+ <div className="text-[10px] text-slate-400 dark:text-slate-500">
+ File {progress.current} of {progress.total}
+ </div>
+ )}
+ {progress.error && (
+ <div className="text-[10px] text-red-600 dark:text-red-400 mt-1">
+ Error: {progress.error}
+ </div>
+ )}
+ </div>
+ );
+ }
+ if (kb.statistics.rag) {
+ return (
+ <div className="mt-2 flex gap-3 text-[10px] text-slate-400 dark:text-slate-500">
+ <span>{kb.statistics.rag.chunks} chunks</span>
+ <span>•</span>
+ <span>{kb.statistics.rag.entities} entities</span>
+ </div>
+ );
+ }
+ return null;
+ })()}
+ </div>
+ </div>
+ </div>
+ ))}
+
+ {/* Empty State */}
+ {kbs.length === 0 && (
+ <div className="col-span-full text-center py-12 text-slate-400 dark:text-slate-500">
+ <Database className="w-12 h-12 mx-auto mb-4 opacity-20" />
+ <p>No knowledge bases found. Create one to get started.</p>
+ </div>
+ )}
+ </div>
+ )}
+
+ {/* Create KB Modal */}
+ {createModalOpen && (
+ <div className="fixed inset-0 bg-black/50 backdrop-blur-sm z-50 flex items-center justify-center p-4">
+ <div className="bg-white dark:bg-slate-800 rounded-2xl shadow-2xl w-full max-w-md p-6 animate-in zoom-in-95">
+ <div className="flex justify-between items-center mb-4">
+ <h3 className="text-lg font-bold text-slate-900 dark:text-slate-100">
+ Create Knowledge Base
+ </h3>
+ <button
+ onClick={() => setCreateModalOpen(false)}
+ className="text-slate-400 dark:text-slate-500 hover:text-slate-600 dark:hover:text-slate-300"
+ >
+ <X className="w-5 h-5" />
+ </button>
+ </div>
+
+ <form onSubmit={handleCreate} className="space-y-4">
+ <div>
+ <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">
+ Knowledge Base Name
+ </label>
+ <input
+ type="text"
+ required
+ value={newKbName}
+ onChange={(e) => setNewKbName(e.target.value)}
+ placeholder="e.g., Math101"
+ className="w-full px-3 py-2 rounded-lg border border-slate-200 dark:border-slate-600 bg-white dark:bg-slate-700 text-slate-900 dark:text-slate-100 focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 transition-all"
+ />
+ </div>
+
+ <div>
+ <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">
+ Upload Documents
+ </label>
+ <div
+ className={`border-2 border-dashed rounded-xl p-8 text-center transition-colors ${
+ dragActive
+ ? "border-blue-500 bg-blue-50 dark:bg-blue-900/30"
+ : "border-slate-200 dark:border-slate-600 hover:border-blue-400 dark:hover:border-blue-500 bg-slate-50 dark:bg-slate-700/50"
+ }`}
+ onDragEnter={handleDrag}
+ onDragLeave={handleDrag}
+ onDragOver={handleDrag}
+ onDrop={handleDrop}
+ >
+ <input
+ type="file"
+ multiple
+ className="hidden"
+ id="kb-file-upload"
+ onChange={(e) => setFiles(e.target.files)}
+ accept=".pdf,.txt,.md"
+ />
+ <label
+ htmlFor="kb-file-upload"
+ className="cursor-pointer flex flex-col items-center gap-2"
+ >
+ <Upload
+ className={`w-8 h-8 ${dragActive ? "text-blue-500 dark:text-blue-400" : "text-slate-400 dark:text-slate-500"}`}
+ />
+ <span className="text-sm font-medium text-slate-600 dark:text-slate-300">
+ {files && files.length > 0
+ ? `${files.length} files selected`
+ : "Drag & drop files here or click to browse"}
+ </span>
+ <span className="text-xs text-slate-400 dark:text-slate-500">
+ Supports PDF, TXT, MD
+ </span>
+ </label>
+ </div>
+ </div>
+
+ <div className="flex gap-3 pt-2">
+ <button
+ type="button"
+ onClick={() => setCreateModalOpen(false)}
+ className="flex-1 py-2.5 rounded-xl border border-slate-200 dark:border-slate-600 text-slate-600 dark:text-slate-300 font-medium hover:bg-slate-50 dark:hover:bg-slate-700"
+ >
+ Cancel
+ </button>
+ <button
+ type="submit"
+ disabled={
+ !newKbName || !files || files.length === 0 || uploading
+ }
+ className="flex-1 py-2.5 rounded-xl bg-slate-900 dark:bg-slate-100 text-white dark:text-slate-900 font-medium hover:bg-slate-800 dark:hover:bg-slate-200 disabled:opacity-50 flex items-center justify-center gap-2"
+ >
+ {uploading ? (
+ <Loader2 className="w-4 h-4 animate-spin" />
+ ) : (
+ "Create & Initialize"
+ )}
+ </button>
+ </div>
+ </form>
+ </div>
+ </div>
+ )}
+
+ {/* Upload Modal (Existing) */}
+ {uploadModalOpen && (
+ <div className="fixed inset-0 bg-black/50 backdrop-blur-sm z-50 flex items-center justify-center p-4">
+ <div className="bg-white dark:bg-slate-800 rounded-2xl shadow-2xl w-full max-w-md p-6 animate-in zoom-in-95">
+ <div className="flex justify-between items-center mb-4">
+ <h3 className="text-lg font-bold text-slate-900 dark:text-slate-100">
+ Upload Documents
+ </h3>
+ <button
+ onClick={() => setUploadModalOpen(false)}
+ className="text-slate-400 dark:text-slate-500 hover:text-slate-600 dark:hover:text-slate-300"
+ >
+ <X className="w-5 h-5" />
+ </button>
+ </div>
+ <p className="text-sm text-slate-500 dark:text-slate-400 mb-4">
+ Upload PDF, TXT, or MD files to{" "}
+ <strong className="text-slate-700 dark:text-slate-200">
+ {targetKb}
+ </strong>
+ .
+ </p>
+
+ <form onSubmit={handleUpload} className="space-y-4">
+ <div className="border-2 border-dashed border-slate-200 dark:border-slate-600 rounded-xl p-8 text-center hover:border-blue-400 dark:hover:border-blue-500 transition-colors bg-slate-50 dark:bg-slate-700/50">
+ <input
+ type="file"
+ multiple
+ className="hidden"
+ id="file-upload"
+ onChange={(e) => setFiles(e.target.files)}
+ accept=".pdf,.txt,.md"
+ />
+ <label
+ htmlFor="file-upload"
+ className="cursor-pointer flex flex-col items-center gap-2"
+ >
+ <Upload className="w-8 h-8 text-slate-400 dark:text-slate-500" />
+ <span className="text-sm font-medium text-slate-600 dark:text-slate-300">
+ {files && files.length > 0
+ ? `${files.length} files selected`
+ : "Click to browse files"}
+ </span>
+ </label>
+ </div>
+
+ <div className="flex gap-3">
+ <button
+ type="button"
+ onClick={() => setUploadModalOpen(false)}
+ className="flex-1 py-2.5 rounded-xl border border-slate-200 dark:border-slate-600 text-slate-600 dark:text-slate-300 font-medium hover:bg-slate-50 dark:hover:bg-slate-700"
+ >
+ Cancel
+ </button>
+ <button
+ type="submit"
+ disabled={!files || uploading}
+ className="flex-1 py-2.5 rounded-xl bg-blue-600 text-white font-medium hover:bg-blue-700 disabled:opacity-50 flex items-center justify-center gap-2"
+ >
+ {uploading ? (
+ <Loader2 className="w-4 h-4 animate-spin" />
+ ) : (
+ "Upload"
+ )}
+ </button>
+ </div>
+ </form>
+ </div>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/web/app/layout.tsx b/web/app/layout.tsx
new file mode 100644
index 000000000..3937e98c9
--- /dev/null
+++ b/web/app/layout.tsx
@@ -0,0 +1,34 @@
+import type { Metadata } from "next";
+import { Plus_Jakarta_Sans } from "next/font/google";
+import "./globals.css";
+import Sidebar from "@/components/Sidebar";
+import { GlobalProvider } from "@/context/GlobalContext";
+
+// Use more modern, geometric fonts
+const font = Plus_Jakarta_Sans({ subsets: ["latin"] });
+
+export const metadata: Metadata = {
+ title: "OpenTutor Platform",
+ description: "Multi-Agent Teaching & Research Copilot",
+};
+
+export default function RootLayout({
+ children,
+}: {
+ children: React.ReactNode;
+}) {
+ return (
+ <html lang="en" suppressHydrationWarning>
+ <body className={font.className}>
+ <GlobalProvider>
+ <div className="flex h-screen bg-slate-50 dark:bg-slate-900 overflow-hidden transition-colors duration-200">
+ <Sidebar />
+ <main className="flex-1 overflow-y-auto bg-slate-50 dark:bg-slate-900">
+ <div className="w-full p-8">{children}</div>
+ </main>
+ </div>
+ </GlobalProvider>
+ </body>
+ </html>
+ );
+}
diff --git a/web/app/notebook/page.tsx b/web/app/notebook/page.tsx
new file mode 100644
index 000000000..c867fdba1
--- /dev/null
+++ b/web/app/notebook/page.tsx
@@ -0,0 +1,1290 @@
+"use client";
+
+import { useState, useEffect } from "react";
+import {
+ BookOpen,
+ Plus,
+ Trash2,
+ Edit3,
+ Search,
+ Clock,
+ FileText,
+ Calculator,
+ Microscope,
+ PenTool,
+ ChevronRight,
+ ChevronLeft,
+ ArrowRight,
+ X,
+ Check,
+ Palette,
+ MoreVertical,
+ FolderOpen,
+ Database,
+ Maximize2,
+ Minimize2,
+ Download,
+ History,
+ Import,
+ Upload,
+} from "lucide-react";
+import ReactMarkdown from "react-markdown";
+import remarkMath from "remark-math";
+import rehypeKatex from "rehype-katex";
+import "katex/dist/katex.min.css";
+import { apiUrl } from "@/lib/api";
+import { processLatexContent } from "@/lib/latex";
+
+interface NotebookRecord {
+ id: string;
+ type: "solve" | "question" | "research" | "co_writer";
+ title: string;
+ user_query: string;
+ output: string;
+ metadata: Record<string, any>;
+ created_at: number;
+ kb_name?: string;
+}
+
+interface Notebook {
+ id: string;
+ name: string;
+ description: string;
+ created_at: number;
+ updated_at: number;
+ records: NotebookRecord[];
+ color: string;
+ icon: string;
+}
+
+interface NotebookSummary {
+ id: string;
+ name: string;
+ description: string;
+ created_at: number;
+ updated_at: number;
+ record_count: number;
+ color: string;
+ icon: string;
+}
+
+const COLORS = [
+ "#3B82F6", // blue
+ "#8B5CF6", // purple
+ "#EC4899", // pink
+ "#EF4444", // red
+ "#F97316", // orange
+ "#EAB308", // yellow
+ "#22C55E", // green
+ "#14B8A6", // teal
+ "#06B6D4", // cyan
+ "#6366F1", // indigo
+];
+
+const getRecordIcon = (type: string) => {
+ switch (type) {
+ case "solve":
+ return <Calculator className="w-4 h-4" />;
+ case "question":
+ return <FileText className="w-4 h-4" />;
+ case "research":
+ return <Microscope className="w-4 h-4" />;
+ case "co_writer":
+ return <PenTool className="w-4 h-4" />;
+ default:
+ return <FileText className="w-4 h-4" />;
+ }
+};
+
+const getRecordLabel = (type: string) => {
+ switch (type) {
+ case "solve":
+ return "Solver";
+ case "question":
+ return "Question";
+ case "research":
+ return "Research";
+ case "co_writer":
+ return "Co-Writer";
+ default:
+ return "Record";
+ }
+};
+
+const getRecordColor = (type: string) => {
+ switch (type) {
+ case "solve":
+ return "text-blue-500 bg-blue-50 border-blue-200";
+ case "question":
+ return "text-purple-500 bg-purple-50 border-purple-200";
+ case "research":
+ return "text-emerald-500 bg-emerald-50 border-emerald-200";
+ case "co_writer":
+ return "text-amber-500 bg-amber-50 border-amber-200";
+ default:
+ return "text-slate-500 bg-slate-50 border-slate-200";
+ }
+};
+
+export default function NotebookPage() {
+ const [notebooks, setNotebooks] = useState<NotebookSummary[]>([]);
+ const [selectedNotebook, setSelectedNotebook] = useState<Notebook | null>(
+ null,
+ );
+ const [selectedRecord, setSelectedRecord] = useState<NotebookRecord | null>(
+ null,
+ );
+ const [loading, setLoading] = useState(true);
+ const [searchTerm, setSearchTerm] = useState("");
+
+ // Collapse states
+ const [leftCollapsed, setLeftCollapsed] = useState(false);
+ const [middleCollapsed, setMiddleCollapsed] = useState(false);
+ const [rightCollapsed, setRightCollapsed] = useState(false);
+
+ // Modal states
+ const [showCreateModal, setShowCreateModal] = useState(false);
+ const [showEditModal, setShowEditModal] = useState(false);
+ const [showDeleteConfirm, setShowDeleteConfirm] = useState<string | null>(
+ null,
+ );
+
+ // Form states
+ const [newNotebook, setNewNotebook] = useState({
+ name: "",
+ description: "",
+ color: "#3B82F6",
+ });
+ const [editingNotebook, setEditingNotebook] = useState<{
+ id: string;
+ name: string;
+ description: string;
+ color: string;
+ } | null>(null);
+
+ // Layout state for expandable detail panel (deprecated, using rightCollapsed instead)
+ const [detailExpanded, setDetailExpanded] = useState(false);
+
+ // Import modal state
+ const [showImportModal, setShowImportModal] = useState(false);
+ const [availableNotebooks, setAvailableNotebooks] = useState<
+ NotebookSummary[]
+ >([]);
+ const [importSourceNotebook, setImportSourceNotebook] = useState<string>("");
+ const [importSourceRecords, setImportSourceRecords] = useState<
+ NotebookRecord[]
+ >([]);
+ const [selectedImportRecords, setSelectedImportRecords] = useState<
+ Set<string>
+ >(new Set());
+ const [loadingImport, setLoadingImport] = useState(false);
+
+ // Fetch notebooks
+ useEffect(() => {
+ fetchNotebooks();
+ }, []);
+
+ const fetchNotebooks = async () => {
+ try {
+ const res = await fetch(apiUrl("/api/v1/notebook/list"));
+ const data = await res.json();
+ setNotebooks(data.notebooks || []);
+ } catch (err) {
+ console.error("Failed to fetch notebooks:", err);
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ const fetchNotebookDetail = async (notebookId: string) => {
+ try {
+ const res = await fetch(apiUrl(`/api/v1/notebook/${notebookId}`));
+ const data = await res.json();
+ setSelectedNotebook(data);
+ setSelectedRecord(null);
+ } catch (err) {
+ console.error("Failed to fetch notebook detail:", err);
+ }
+ };
+
+ const handleCreateNotebook = async () => {
+ if (!newNotebook.name.trim()) return;
+
+ try {
+ const res = await fetch(apiUrl("/api/v1/notebook/create"), {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(newNotebook),
+ });
+ const data = await res.json();
+ if (data.success) {
+ fetchNotebooks();
+ setShowCreateModal(false);
+ setNewNotebook({ name: "", description: "", color: "#3B82F6" });
+ }
+ } catch (err) {
+ console.error("Failed to create notebook:", err);
+ }
+ };
+
+ const handleUpdateNotebook = async () => {
+ if (!editingNotebook || !editingNotebook.name.trim()) return;
+
+ try {
+ const res = await fetch(
+ apiUrl(`/api/v1/notebook/${editingNotebook.id}`),
+ {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ name: editingNotebook.name,
+ description: editingNotebook.description,
+ color: editingNotebook.color,
+ }),
+ },
+ );
+ const data = await res.json();
+ if (data.success) {
+ fetchNotebooks();
+ if (selectedNotebook?.id === editingNotebook.id) {
+ fetchNotebookDetail(editingNotebook.id);
+ }
+ setShowEditModal(false);
+ setEditingNotebook(null);
+ }
+ } catch (err) {
+ console.error("Failed to update notebook:", err);
+ }
+ };
+
+ const handleDeleteNotebook = async (notebookId: string) => {
+ try {
+ const res = await fetch(apiUrl(`/api/v1/notebook/${notebookId}`), {
+ method: "DELETE",
+ });
+ const data = await res.json();
+ if (data.success) {
+ fetchNotebooks();
+ if (selectedNotebook?.id === notebookId) {
+ setSelectedNotebook(null);
+ }
+ setShowDeleteConfirm(null);
+ }
+ } catch (err) {
+ console.error("Failed to delete notebook:", err);
+ }
+ };
+
+ const handleDeleteRecord = async (recordId: string) => {
+ if (!selectedNotebook) return;
+
+ try {
+ const res = await fetch(
+ apiUrl(`/api/v1/notebook/${selectedNotebook.id}/records/${recordId}`),
+ {
+ method: "DELETE",
+ },
+ );
+ const data = await res.json();
+ if (data.success) {
+ fetchNotebookDetail(selectedNotebook.id);
+ if (selectedRecord?.id === recordId) {
+ setSelectedRecord(null);
+ }
+ }
+ } catch (err) {
+ console.error("Failed to delete record:", err);
+ }
+ };
+
+ // Export functions
+ const exportAsMarkdown = () => {
+ if (!selectedRecord) return;
+
+ const content = `# ${selectedRecord.title}\n\n**Type:** ${selectedRecord.type}\n**Created:** ${new Date(selectedRecord.created_at * 1000).toLocaleString()}\n\n## User Query\n\n${selectedRecord.user_query}\n\n## Output\n\n${selectedRecord.output}`;
+
+ const blob = new Blob([content], { type: "text/markdown" });
+ const url = URL.createObjectURL(blob);
+ const a = document.createElement("a");
+ a.href = url;
+ a.download = `${selectedRecord.title.replace(/[^a-zA-Z0-9]/g, "_")}.md`;
+ a.click();
+ URL.revokeObjectURL(url);
+ };
+
+ const exportAsPDF = async () => {
+ if (!selectedRecord) return;
+
+ // Use browser print for simple PDF export
+ const printContent = `
+ <html>
+ <head>
+ <title>${selectedRecord.title}</title>
+ <style>
+ body { font-family: system-ui, -apple-system, sans-serif; padding: 40px; max-width: 800px; margin: 0 auto; }
+ h1 { color: #1e293b; }
+ .meta { color: #64748b; font-size: 14px; margin-bottom: 20px; }
+ .section { margin: 20px 0; }
+ .section-title { font-size: 12px; text-transform: uppercase; color: #94a3b8; font-weight: 600; margin-bottom: 8px; }
+ .query { background: #eff6ff; padding: 16px; border-radius: 8px; }
+ .output { background: #f8fafc; padding: 16px; border-radius: 8px; white-space: pre-wrap; }
+ </style>
+ </head>
+ <body>
+ <h1>${selectedRecord.title}</h1>
+ <div class="meta">${selectedRecord.type.toUpperCase()} • ${new Date(selectedRecord.created_at * 1000).toLocaleString()}</div>
+ <div class="section">
+ <div class="section-title">User Query</div>
+ <div class="query">${selectedRecord.user_query}</div>
+ </div>
+ <div class="section">
+ <div class="section-title">Output</div>
+ <div class="output">${selectedRecord.output}</div>
+ </div>
+ </body>
+ </html>
+ `;
+
+ const printWindow = window.open("", "_blank");
+ if (printWindow) {
+ printWindow.document.write(printContent);
+ printWindow.document.close();
+ printWindow.print();
+ }
+ };
+
+ // Import functions
+ const openImportModal = async () => {
+ if (!selectedNotebook) return;
+
+ setShowImportModal(true);
+ setLoadingImport(true);
+
+ try {
+ const res = await fetch(apiUrl("/api/v1/notebook/list"));
+ const data = await res.json();
+ // Filter out current notebook
+ const others = (data.notebooks || []).filter(
+ (nb: NotebookSummary) =>
+ nb.id !== selectedNotebook.id && nb.record_count > 0,
+ );
+ setAvailableNotebooks(others);
+ } catch (err) {
+ console.error("Failed to fetch notebooks for import:", err);
+ } finally {
+ setLoadingImport(false);
+ }
+ };
+
+ const loadImportSourceRecords = async (notebookId: string) => {
+ setImportSourceNotebook(notebookId);
+ setLoadingImport(true);
+
+ try {
+ const res = await fetch(apiUrl(`/api/v1/notebook/${notebookId}`));
+ const data = await res.json();
+ setImportSourceRecords(data.records || []);
+ setSelectedImportRecords(new Set());
+ } catch (err) {
+ console.error("Failed to fetch records for import:", err);
+ } finally {
+ setLoadingImport(false);
+ }
+ };
+
+ const toggleImportRecord = (recordId: string) => {
+ setSelectedImportRecords((prev) => {
+ const newSet = new Set(prev);
+ if (newSet.has(recordId)) {
+ newSet.delete(recordId);
+ } else {
+ newSet.add(recordId);
+ }
+ return newSet;
+ });
+ };
+
+ const handleImportRecords = async () => {
+ if (!selectedNotebook || selectedImportRecords.size === 0) return;
+
+ setLoadingImport(true);
+
+ try {
+ // Get selected records
+ const recordsToImport = importSourceRecords.filter((r) =>
+ selectedImportRecords.has(r.id),
+ );
+
+ // Add each record to current notebook
+ for (const record of recordsToImport) {
+ await fetch(apiUrl(`/api/v1/notebook/${selectedNotebook.id}/records`), {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ type: record.type,
+ title: `[Imported] ${record.title}`,
+ user_query: record.user_query,
+ output: record.output,
+ metadata: {
+ ...record.metadata,
+ imported_from: importSourceNotebook,
+ },
+ }),
+ });
+ }
+
+ // Refresh notebook
+ fetchNotebookDetail(selectedNotebook.id);
+ setShowImportModal(false);
+ setImportSourceNotebook("");
+ setImportSourceRecords([]);
+ setSelectedImportRecords(new Set());
+ } catch (err) {
+ console.error("Failed to import records:", err);
+ } finally {
+ setLoadingImport(false);
+ }
+ };
+
+ const filteredNotebooks = notebooks.filter(
+ (nb) =>
+ nb.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
+ nb.description.toLowerCase().includes(searchTerm.toLowerCase()),
+ );
+
+ return (
+ <div
+ className="h-[calc(100vh-4rem)] flex gap-4 animate-fade-in"
+ style={{ justifyContent: "flex-start" }}
+ >
+ {/* Left Panel: Notebook List */}
+ <div
+ className={`flex flex-col bg-white dark:bg-slate-800 rounded-2xl shadow-sm border border-slate-200 dark:border-slate-700 overflow-hidden transition-all duration-300 flex-shrink-0 ${leftCollapsed ? "overflow-hidden" : ""}`}
+ style={{
+ width: leftCollapsed ? 0 : "288px",
+ minWidth: leftCollapsed ? 0 : "288px",
+ maxWidth: leftCollapsed ? 0 : "288px",
+ opacity: leftCollapsed ? 0 : 1,
+ }}
+ >
+ {/* Header */}
+ <div className="p-4 border-b border-slate-100 dark:border-slate-700 bg-gradient-to-r from-indigo-50 to-purple-50 dark:from-indigo-900/30 dark:to-purple-900/30">
+ <div className="flex items-center justify-between mb-4">
+ <h1 className="text-lg font-bold text-slate-900 dark:text-slate-100 flex items-center gap-2">
+ <BookOpen className="w-5 h-5 text-indigo-600 dark:text-indigo-400" />
+ Notebooks
+ </h1>
+ <div className="flex items-center gap-2">
+ <button
+ onClick={() => setShowCreateModal(true)}
+ className="p-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 transition-all shadow-md shadow-indigo-500/20"
+ >
+ <Plus className="w-4 h-4" />
+ </button>
+ <button
+ onClick={() => setLeftCollapsed(true)}
+ className="p-2 bg-white dark:bg-slate-700 border border-slate-200 dark:border-slate-600 rounded-lg shadow-sm hover:bg-slate-50 dark:hover:bg-slate-600 transition-all"
+ title="Collapse left panel"
+ >
+ <ChevronLeft className="w-4 h-4 text-slate-600 dark:text-slate-300" />
+ </button>
+ </div>
+ </div>
+
+ {/* Search */}
+ <div className="relative">
+ <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400 dark:text-slate-500" />
+ <input
+ type="text"
+ placeholder="Search notebooks..."
+ value={searchTerm}
+ onChange={(e) => setSearchTerm(e.target.value)}
+ className="w-full pl-9 pr-4 py-2 bg-white dark:bg-slate-700 border border-slate-200 dark:border-slate-600 rounded-lg text-sm text-slate-900 dark:text-slate-100 placeholder:text-slate-400 dark:placeholder:text-slate-500 focus:ring-2 focus:ring-indigo-500/20 focus:border-indigo-500 outline-none"
+ />
+ </div>
+ </div>
+
+ {/* Notebook List */}
+ <div className="flex-1 overflow-y-auto p-2">
+ {loading ? (
+ <div className="p-8 text-center text-slate-400 dark:text-slate-500">
+ Loading...
+ </div>
+ ) : filteredNotebooks.length === 0 ? (
+ <div className="p-8 text-center">
+ <FolderOpen className="w-12 h-12 text-slate-200 dark:text-slate-600 mx-auto mb-3" />
+ <p className="text-slate-500 dark:text-slate-400 text-sm">
+ No notebooks yet
+ </p>
+ <p className="text-slate-400 dark:text-slate-500 text-xs mt-1">
+ Create your first notebook to get started
+ </p>
+ </div>
+ ) : (
+ <div className="space-y-2">
+ {filteredNotebooks.map((nb) => (
+ <div
+ key={nb.id}
+ onClick={() => fetchNotebookDetail(nb.id)}
+ className={`p-3 rounded-xl cursor-pointer transition-all group ${
+ selectedNotebook?.id === nb.id
+ ? "bg-indigo-50 dark:bg-indigo-900/30 border-2 border-indigo-200 dark:border-indigo-700"
+ : "hover:bg-slate-50 dark:hover:bg-slate-700/50 border-2 border-transparent"
+ }`}
+ >
+ <div className="flex items-start gap-3">
+ <div
+ className="w-10 h-10 rounded-lg flex items-center justify-center shrink-0"
+ style={{
+ backgroundColor: `${nb.color}20`,
+ color: nb.color,
+ }}
+ >
+ <BookOpen className="w-5 h-5" />
+ </div>
+ <div className="flex-1 min-w-0">
+ <div className="flex items-center justify-between">
+ <h3 className="font-semibold text-slate-900 dark:text-slate-100 truncate text-sm">
+ {nb.name}
+ </h3>
+ <div className="opacity-0 group-hover:opacity-100 transition-opacity flex gap-1">
+ <button
+ onClick={(e) => {
+ e.stopPropagation();
+ setEditingNotebook({
+ id: nb.id,
+ name: nb.name,
+ description: nb.description,
+ color: nb.color,
+ });
+ setShowEditModal(true);
+ }}
+ className="p-1 hover:bg-slate-200 dark:hover:bg-slate-600 rounded"
+ >
+ <Edit3 className="w-3 h-3 text-slate-500 dark:text-slate-400" />
+ </button>
+ <button
+ onClick={(e) => {
+ e.stopPropagation();
+ setShowDeleteConfirm(nb.id);
+ }}
+ className="p-1 hover:bg-red-100 dark:hover:bg-red-900/40 rounded"
+ >
+ <Trash2 className="w-3 h-3 text-red-500 dark:text-red-400" />
+ </button>
+ </div>
+ </div>
+ {nb.description && (
+ <p className="text-xs text-slate-500 dark:text-slate-400 truncate mt-0.5">
+ {nb.description}
+ </p>
+ )}
+ <div className="flex items-center gap-3 mt-2 text-[10px] text-slate-400 dark:text-slate-500">
+ <span className="flex items-center gap-1">
+ <FileText className="w-3 h-3" />
+ {nb.record_count} records
+ </span>
+ <span className="flex items-center gap-1">
+ <Clock className="w-3 h-3" />
+ {new Date(nb.updated_at * 1000).toLocaleDateString()}
+ </span>
+ </div>
+ </div>
+ </div>
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ </div>
+ {leftCollapsed && (
+ <button
+ onClick={() => setLeftCollapsed(false)}
+ className="p-2 bg-white dark:bg-slate-800 border border-slate-200 dark:border-slate-600 rounded-lg shadow-sm hover:bg-slate-50 dark:hover:bg-slate-700 transition-all self-start mt-4 shrink-0"
+ title="Expand left panel"
+ >
+ <ChevronRight className="w-4 h-4 text-slate-600 dark:text-slate-300" />
+ </button>
+ )}
+
+ {/* Middle Panel: Records List */}
+ <div
+ className={`flex flex-col bg-white dark:bg-slate-800 rounded-2xl shadow-sm border border-slate-200 dark:border-slate-700 overflow-hidden transition-all duration-300 flex-shrink-0 ${middleCollapsed ? "overflow-hidden" : ""}`}
+ style={{
+ width: middleCollapsed ? 0 : "320px",
+ minWidth: middleCollapsed ? 0 : "320px",
+ maxWidth: middleCollapsed ? 0 : "320px",
+ opacity: middleCollapsed ? 0 : 1,
+ }}
+ >
+ {/* Notebook Header */}
+ <div
+ className="p-4 border-b border-slate-100 dark:border-slate-700 shrink-0"
+ style={{
+ backgroundColor: selectedNotebook
+ ? `${selectedNotebook.color}10`
+ : "transparent",
+ }}
+ >
+ <div className="flex items-center justify-between gap-3">
+ {selectedNotebook ? (
+ <>
+ <div className="flex items-center gap-3 flex-1 min-w-0">
+ <div
+ className="w-12 h-12 rounded-xl flex items-center justify-center shrink-0"
+ style={{
+ backgroundColor: `${selectedNotebook.color}20`,
+ color: selectedNotebook.color,
+ }}
+ >
+ <BookOpen className="w-6 h-6" />
+ </div>
+ <div className="flex-1 min-w-0">
+ <h2 className="font-bold text-slate-900 dark:text-slate-100 truncate">
+ {selectedNotebook.name}
+ </h2>
+ {selectedNotebook.description && (
+ <p className="text-xs text-slate-500 dark:text-slate-400 mt-0.5 truncate">
+ {selectedNotebook.description}
+ </p>
+ )}
+ </div>
+ </div>
+ </>
+ ) : (
+ <div className="flex-1" />
+ )}
+ <button
+ onClick={() => setMiddleCollapsed(true)}
+ className="p-2 bg-white dark:bg-slate-700 border border-slate-200 dark:border-slate-600 rounded-lg shadow-sm hover:bg-slate-50 dark:hover:bg-slate-600 transition-all shrink-0"
+ title="Collapse middle panel"
+ >
+ <ChevronLeft className="w-4 h-4 text-slate-600 dark:text-slate-300" />
+ </button>
+ </div>
+ </div>
+
+ {selectedNotebook ? (
+ <>
+ {/* Records List */}
+ <div className="flex-1 overflow-y-auto p-3">
+ {selectedNotebook.records.length === 0 ? (
+ <div className="p-8 text-center">
+ <FileText className="w-12 h-12 text-slate-200 dark:text-slate-600 mx-auto mb-3" />
+ <p className="text-slate-500 dark:text-slate-400 text-sm">
+ No records yet
+ </p>
+ <p className="text-slate-400 dark:text-slate-500 text-xs mt-1">
+ Add records from Solver, Question, Research, or Co-Writer
+ </p>
+ </div>
+ ) : (
+ <div className="space-y-2">
+ {selectedNotebook.records.map((record) => (
+ <div
+ key={record.id}
+ onClick={() => setSelectedRecord(record)}
+ className={`p-3 rounded-xl cursor-pointer transition-all group border ${
+ selectedRecord?.id === record.id
+ ? "bg-slate-50 dark:bg-slate-700/50 border-slate-300 dark:border-slate-600"
+ : "hover:bg-slate-50 dark:hover:bg-slate-700/50 border-transparent hover:border-slate-200 dark:hover:border-slate-600"
+ }`}
+ >
+ <div className="flex items-start gap-3">
+ <div
+ className={`p-2 rounded-lg border ${getRecordColor(record.type)}`}
+ >
+ {getRecordIcon(record.type)}
+ </div>
+ <div className="flex-1 min-w-0">
+ <div className="flex items-center gap-2 mb-1">
+ <span
+ className={`text-[10px] font-bold uppercase px-1.5 py-0.5 rounded ${getRecordColor(record.type)}`}
+ >
+ {getRecordLabel(record.type)}
+ </span>
+ {record.kb_name && (
+ <span className="text-[10px] text-slate-400 dark:text-slate-500 flex items-center gap-0.5">
+ <Database className="w-3 h-3" />
+ {record.kb_name}
+ </span>
+ )}
+ </div>
+ <h4 className="text-sm font-medium text-slate-900 dark:text-slate-100 line-clamp-1">
+ {record.title}
+ </h4>
+ <p className="text-xs text-slate-500 dark:text-slate-400 line-clamp-2 mt-1">
+ {record.user_query}
+ </p>
+ <div className="flex items-center justify-between mt-2">
+ <span className="text-[10px] text-slate-400 dark:text-slate-500">
+ {new Date(
+ record.created_at * 1000,
+ ).toLocaleString()}
+ </span>
+ <button
+ onClick={(e) => {
+ e.stopPropagation();
+ handleDeleteRecord(record.id);
+ }}
+ className="opacity-0 group-hover:opacity-100 p-1 hover:bg-red-100 dark:hover:bg-red-900/40 rounded transition-all"
+ >
+ <Trash2 className="w-3 h-3 text-red-500 dark:text-red-400" />
+ </button>
+ </div>
+ </div>
+ </div>
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ </>
+ ) : (
+ <div className="flex-1 flex flex-col items-center justify-center text-slate-400 dark:text-slate-500 p-8">
+ <BookOpen className="w-16 h-16 text-slate-200 dark:text-slate-600 mb-4" />
+ <p className="text-slate-500 dark:text-slate-400">
+ Select a notebook to view records
+ </p>
+ </div>
+ )}
+ </div>
+ {middleCollapsed && (
+ <button
+ onClick={() => setMiddleCollapsed(false)}
+ className="p-2 bg-white dark:bg-slate-800 border border-slate-200 dark:border-slate-600 rounded-lg shadow-sm hover:bg-slate-50 dark:hover:bg-slate-700 transition-all self-start mt-4 shrink-0"
+ title="Expand middle panel"
+ >
+ <ChevronRight className="w-4 h-4 text-slate-600 dark:text-slate-300" />
+ </button>
+ )}
+
+ {/* Right Panel: Record Detail */}
+ <div
+ className={`flex flex-col bg-white dark:bg-slate-800 rounded-2xl shadow-sm border border-slate-200 dark:border-slate-700 overflow-hidden transition-all duration-300 ${rightCollapsed ? "flex-shrink-0 overflow-hidden" : "flex-1"}`}
+ style={{
+ width: rightCollapsed ? 0 : undefined,
+ minWidth: rightCollapsed ? 0 : undefined,
+ maxWidth: rightCollapsed ? 0 : undefined,
+ opacity: rightCollapsed ? 0 : 1,
+ marginLeft: "auto",
+ order: 3,
+ }}
+ >
+ {/* Record Header with Action Buttons */}
+ <div className="p-4 border-b border-slate-100 dark:border-slate-700 bg-slate-50/50 dark:bg-slate-800/50 shrink-0">
+ <div className="flex items-center justify-between gap-3">
+ <div className="flex items-center gap-3 flex-1 min-w-0">
+ <button
+ onClick={() => setRightCollapsed(true)}
+ className="p-2 bg-white dark:bg-slate-700 border border-slate-200 dark:border-slate-600 rounded-lg shadow-sm hover:bg-slate-50 dark:hover:bg-slate-600 transition-all shrink-0"
+ title="Collapse right panel"
+ >
+ <ChevronRight className="w-4 h-4 text-slate-600 dark:text-slate-300" />
+ </button>
+ {selectedRecord ? (
+ <>
+ <div
+ className={`p-2 rounded-lg border ${getRecordColor(selectedRecord.type)} shrink-0`}
+ >
+ {getRecordIcon(selectedRecord.type)}
+ </div>
+ <div className="flex-1 min-w-0">
+ <h2 className="font-bold text-slate-900 dark:text-slate-100 truncate">
+ {selectedRecord.title}
+ </h2>
+ <div className="flex items-center gap-2 mt-1">
+ <span
+ className={`text-[10px] font-bold uppercase px-1.5 py-0.5 rounded ${getRecordColor(selectedRecord.type)}`}
+ >
+ {getRecordLabel(selectedRecord.type)}
+ </span>
+ <span className="text-xs text-slate-400 dark:text-slate-500">
+ {new Date(
+ selectedRecord.created_at * 1000,
+ ).toLocaleString()}
+ </span>
+ </div>
+ </div>
+ </>
+ ) : (
+ <div className="flex-1" />
+ )}
+ </div>
+
+ {/* Action Buttons - Export and History */}
+ {selectedRecord && (
+ <div className="flex items-center gap-2 shrink-0">
+ <button
+ onClick={exportAsMarkdown}
+ className="flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium text-slate-600 dark:text-slate-300 hover:text-slate-900 dark:hover:text-slate-100 hover:bg-slate-100 dark:hover:bg-slate-700 rounded-lg transition-colors"
+ title="Export as Markdown"
+ >
+ <Download className="w-3.5 h-3.5" />
+ .md
+ </button>
+ <button
+ onClick={exportAsPDF}
+ className="flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium text-slate-600 dark:text-slate-300 hover:text-slate-900 dark:hover:text-slate-100 hover:bg-slate-100 dark:hover:bg-slate-700 rounded-lg transition-colors"
+ title="Export as PDF"
+ >
+ <Download className="w-3.5 h-3.5" />
+ .pdf
+ </button>
+ <button
+ onClick={openImportModal}
+ className="flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium text-indigo-600 dark:text-indigo-400 hover:text-indigo-700 dark:hover:text-indigo-300 hover:bg-indigo-50 dark:hover:bg-indigo-900/40 rounded-lg transition-colors"
+ title="Import records from other notebooks"
+ >
+ <Upload className="w-3.5 h-3.5" />
+ Import
+ </button>
+ </div>
+ )}
+ </div>
+ </div>
+
+ {selectedRecord ? (
+ <>
+ {/* Record Content */}
+ <div className="flex-1 overflow-y-auto p-6">
+ {/* User Query */}
+ <div className="mb-6">
+ <h3 className="text-xs font-bold text-slate-500 dark:text-slate-400 uppercase tracking-wider mb-2">
+ User Query
+ </h3>
+ <div className="p-4 bg-blue-50 dark:bg-blue-900/30 rounded-xl border border-blue-100 dark:border-blue-800">
+ <p className="text-slate-700 dark:text-slate-200">
+ {selectedRecord.user_query}
+ </p>
+ </div>
+ </div>
+
+ {/* Output */}
+ <div>
+ <h3 className="text-xs font-bold text-slate-500 dark:text-slate-400 uppercase tracking-wider mb-2">
+ Output
+ </h3>
+ <div className="p-4 bg-slate-50 dark:bg-slate-700/50 rounded-xl border border-slate-100 dark:border-slate-600">
+ <div className="prose prose-slate dark:prose-invert max-w-none prose-sm">
+ <ReactMarkdown
+ remarkPlugins={[remarkMath]}
+ rehypePlugins={[rehypeKatex]}
+ >
+ {processLatexContent(selectedRecord.output)}
+ </ReactMarkdown>
+ </div>
+ </div>
+ </div>
+
+ {/* Metadata */}
+ {Object.keys(selectedRecord.metadata).length > 0 && (
+ <div className="mt-6">
+ <h3 className="text-xs font-bold text-slate-500 dark:text-slate-400 uppercase tracking-wider mb-2">
+ Metadata
+ </h3>
+ <div className="p-4 bg-slate-50 dark:bg-slate-700/50 rounded-xl border border-slate-100 dark:border-slate-600">
+ <pre className="text-xs text-slate-600 dark:text-slate-300 overflow-x-auto">
+ {JSON.stringify(selectedRecord.metadata, null, 2)}
+ </pre>
+ </div>
+ </div>
+ )}
+ </div>
+ </>
+ ) : (
+ <div className="flex-1 flex flex-col items-center justify-center text-slate-400 dark:text-slate-500 p-8">
+ <FileText className="w-16 h-16 text-slate-200 dark:text-slate-600 mb-4" />
+ <p className="text-slate-500 dark:text-slate-400">
+ Select a record to view details
+ </p>
+ </div>
+ )}
+ </div>
+ {rightCollapsed && (
+ <button
+ onClick={() => setRightCollapsed(false)}
+ className="p-2 bg-white dark:bg-slate-800 border border-slate-200 dark:border-slate-600 rounded-lg shadow-sm hover:bg-slate-50 dark:hover:bg-slate-700 transition-all self-start mt-4 shrink-0"
+ title="Expand right panel"
+ >
+ <ChevronLeft className="w-4 h-4 text-slate-600 dark:text-slate-300" />
+ </button>
+ )}
+
+ {/* Create Notebook Modal */}
+ {showCreateModal && (
+ <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 animate-in fade-in">
+ <div className="bg-white dark:bg-slate-800 rounded-2xl shadow-2xl w-[400px] animate-in zoom-in-95">
+ <div className="p-4 border-b border-slate-100 dark:border-slate-700 flex items-center justify-between">
+ <h3 className="font-bold text-slate-900 dark:text-slate-100">
+ Create New Notebook
+ </h3>
+ <button
+ onClick={() => setShowCreateModal(false)}
+ className="p-1 hover:bg-slate-100 dark:hover:bg-slate-700 rounded-lg"
+ >
+ <X className="w-5 h-5 text-slate-500 dark:text-slate-400" />
+ </button>
+ </div>
+ <div className="p-6 space-y-4">
+ <div>
+ <label className="block text-xs font-bold text-slate-500 dark:text-slate-400 uppercase tracking-wider mb-2">
+ Name
+ </label>
+ <input
+ type="text"
+ value={newNotebook.name}
+ onChange={(e) =>
+ setNewNotebook((prev) => ({
+ ...prev,
+ name: e.target.value,
+ }))
+ }
+ placeholder="My Notebook"
+ className="w-full px-4 py-2 border border-slate-200 dark:border-slate-600 bg-white dark:bg-slate-700 text-slate-900 dark:text-slate-100 rounded-xl focus:ring-2 focus:ring-indigo-500/20 focus:border-indigo-500 outline-none"
+ />
+ </div>
+ <div>
+ <label className="block text-xs font-bold text-slate-500 dark:text-slate-400 uppercase tracking-wider mb-2">
+ Description (Optional)
+ </label>
+ <textarea
+ value={newNotebook.description}
+ onChange={(e) =>
+ setNewNotebook((prev) => ({
+ ...prev,
+ description: e.target.value,
+ }))
+ }
+ placeholder="Notes about machine learning..."
+ rows={3}
+ className="w-full px-4 py-2 border border-slate-200 dark:border-slate-600 bg-white dark:bg-slate-700 text-slate-900 dark:text-slate-100 rounded-xl focus:ring-2 focus:ring-indigo-500/20 focus:border-indigo-500 outline-none resize-none"
+ />
+ </div>
+ <div>
+ <label className="block text-xs font-bold text-slate-500 dark:text-slate-400 uppercase tracking-wider mb-2">
+ Color
+ </label>
+ <div className="flex gap-2 flex-wrap">
+ {COLORS.map((color) => (
+ <button
+ key={color}
+ onClick={() =>
+ setNewNotebook((prev) => ({ ...prev, color }))
+ }
+ className={`w-8 h-8 rounded-lg transition-all ${
+ newNotebook.color === color
+ ? "ring-2 ring-offset-2 ring-slate-400 dark:ring-slate-500 dark:ring-offset-slate-800 scale-110"
+ : ""
+ }`}
+ style={{ backgroundColor: color }}
+ />
+ ))}
+ </div>
+ </div>
+ </div>
+ <div className="p-4 border-t border-slate-100 dark:border-slate-700 flex justify-end gap-2">
+ <button
+ onClick={() => setShowCreateModal(false)}
+ className="px-4 py-2 text-slate-600 dark:text-slate-300 hover:bg-slate-100 dark:hover:bg-slate-700 rounded-lg transition-colors"
+ >
+ Cancel
+ </button>
+ <button
+ onClick={handleCreateNotebook}
+ disabled={!newNotebook.name.trim()}
+ className="px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 transition-colors disabled:opacity-50 flex items-center gap-2"
+ >
+ <Plus className="w-4 h-4" />
+ Create
+ </button>
+ </div>
+ </div>
+ </div>
+ )}
+
+ {/* Edit Notebook Modal */}
+ {showEditModal && editingNotebook && (
+ <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 animate-in fade-in">
+ <div className="bg-white dark:bg-slate-800 rounded-2xl shadow-2xl w-[400px] animate-in zoom-in-95">
+ <div className="p-4 border-b border-slate-100 dark:border-slate-700 flex items-center justify-between">
+ <h3 className="font-bold text-slate-900 dark:text-slate-100">
+ Edit Notebook
+ </h3>
+ <button
+ onClick={() => {
+ setShowEditModal(false);
+ setEditingNotebook(null);
+ }}
+ className="p-1 hover:bg-slate-100 dark:hover:bg-slate-700 rounded-lg"
+ >
+ <X className="w-5 h-5 text-slate-500 dark:text-slate-400" />
+ </button>
+ </div>
+ <div className="p-6 space-y-4">
+ <div>
+ <label className="block text-xs font-bold text-slate-500 dark:text-slate-400 uppercase tracking-wider mb-2">
+ Name
+ </label>
+ <input
+ type="text"
+ value={editingNotebook.name}
+ onChange={(e) =>
+ setEditingNotebook((prev) =>
+ prev ? { ...prev, name: e.target.value } : null,
+ )
+ }
+ className="w-full px-4 py-2 border border-slate-200 dark:border-slate-600 bg-white dark:bg-slate-700 text-slate-900 dark:text-slate-100 rounded-xl focus:ring-2 focus:ring-indigo-500/20 focus:border-indigo-500 outline-none"
+ />
+ </div>
+ <div>
+ <label className="block text-xs font-bold text-slate-500 dark:text-slate-400 uppercase tracking-wider mb-2">
+ Description
+ </label>
+ <textarea
+ value={editingNotebook.description}
+ onChange={(e) =>
+ setEditingNotebook((prev) =>
+ prev ? { ...prev, description: e.target.value } : null,
+ )
+ }
+ rows={3}
+ className="w-full px-4 py-2 border border-slate-200 dark:border-slate-600 bg-white dark:bg-slate-700 text-slate-900 dark:text-slate-100 rounded-xl focus:ring-2 focus:ring-indigo-500/20 focus:border-indigo-500 outline-none resize-none"
+ />
+ </div>
+ <div>
+ <label className="block text-xs font-bold text-slate-500 dark:text-slate-400 uppercase tracking-wider mb-2">
+ Color
+ </label>
+ <div className="flex gap-2 flex-wrap">
+ {COLORS.map((color) => (
+ <button
+ key={color}
+ onClick={() =>
+ setEditingNotebook((prev) =>
+ prev ? { ...prev, color } : null,
+ )
+ }
+ className={`w-8 h-8 rounded-lg transition-all ${
+ editingNotebook.color === color
+ ? "ring-2 ring-offset-2 ring-slate-400 dark:ring-slate-500 dark:ring-offset-slate-800 scale-110"
+ : ""
+ }`}
+ style={{ backgroundColor: color }}
+ />
+ ))}
+ </div>
+ </div>
+ </div>
+ <div className="p-4 border-t border-slate-100 dark:border-slate-700 flex justify-end gap-2">
+ <button
+ onClick={() => {
+ setShowEditModal(false);
+ setEditingNotebook(null);
+ }}
+ className="px-4 py-2 text-slate-600 dark:text-slate-300 hover:bg-slate-100 dark:hover:bg-slate-700 rounded-lg transition-colors"
+ >
+ Cancel
+ </button>
+ <button
+ onClick={handleUpdateNotebook}
+ disabled={!editingNotebook.name.trim()}
+ className="px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 transition-colors disabled:opacity-50 flex items-center gap-2"
+ >
+ <Check className="w-4 h-4" />
+ Save Changes
+ </button>
+ </div>
+ </div>
+ </div>
+ )}
+
+ {/* Delete Confirmation Modal */}
+ {showDeleteConfirm && (
+ <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 animate-in fade-in">
+ <div className="bg-white dark:bg-slate-800 rounded-2xl shadow-2xl w-[360px] animate-in zoom-in-95">
+ <div className="p-6 text-center">
+ <div className="w-12 h-12 bg-red-100 dark:bg-red-900/40 rounded-full flex items-center justify-center mx-auto mb-4">
+ <Trash2 className="w-6 h-6 text-red-600 dark:text-red-400" />
+ </div>
+ <h3 className="font-bold text-slate-900 dark:text-slate-100 mb-2">
+ Delete Notebook?
+ </h3>
+ <p className="text-sm text-slate-500 dark:text-slate-400">
+ This action cannot be undone. All records in this notebook will
+ be permanently deleted.
+ </p>
+ </div>
+ <div className="p-4 border-t border-slate-100 dark:border-slate-700 flex justify-center gap-2">
+ <button
+ onClick={() => setShowDeleteConfirm(null)}
+ className="px-4 py-2 text-slate-600 dark:text-slate-300 hover:bg-slate-100 dark:hover:bg-slate-700 rounded-lg transition-colors"
+ >
+ Cancel
+ </button>
+ <button
+ onClick={() => handleDeleteNotebook(showDeleteConfirm)}
+ className="px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 transition-colors flex items-center gap-2"
+ >
+ <Trash2 className="w-4 h-4" />
+ Delete
+ </button>
+ </div>
+ </div>
+ </div>
+ )}
+
+ {/* Import Records Modal */}
+ {showImportModal && (
+ <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 animate-in fade-in">
+ <div className="bg-white dark:bg-slate-800 rounded-2xl shadow-2xl w-[500px] max-h-[80vh] flex flex-col animate-in zoom-in-95">
+ <div className="p-4 border-b border-slate-100 dark:border-slate-700 flex items-center justify-between shrink-0">
+ <h3 className="font-bold text-slate-900 dark:text-slate-100 flex items-center gap-2">
+ <Upload className="w-5 h-5 text-indigo-600 dark:text-indigo-400" />
+ Import Records
+ </h3>
+ <button
+ onClick={() => {
+ setShowImportModal(false);
+ setImportSourceNotebook("");
+ setImportSourceRecords([]);
+ setSelectedImportRecords(new Set());
+ }}
+ className="p-1 hover:bg-slate-100 dark:hover:bg-slate-700 rounded-lg"
+ >
+ <X className="w-5 h-5 text-slate-500 dark:text-slate-400" />
+ </button>
+ </div>
+
+ <div className="flex-1 overflow-y-auto p-4 space-y-4">
+ {/* Source Notebook Selection */}
+ <div>
+ <label className="block text-xs font-bold text-slate-500 dark:text-slate-400 uppercase tracking-wider mb-2">
+ Source Notebook
+ </label>
+ <select
+ value={importSourceNotebook}
+ onChange={(e) => loadImportSourceRecords(e.target.value)}
+ className="w-full px-4 py-2 border border-slate-200 dark:border-slate-600 bg-white dark:bg-slate-700 text-slate-900 dark:text-slate-100 rounded-xl focus:ring-2 focus:ring-indigo-500/20 focus:border-indigo-500 outline-none"
+ >
+ <option value="">Select a notebook...</option>
+ {availableNotebooks.map((nb) => (
+ <option key={nb.id} value={nb.id}>
+ {nb.name} ({nb.record_count} records)
+ </option>
+ ))}
+ </select>
+ </div>
+
+ {/* Records Selection */}
+ {importSourceNotebook && (
+ <div>
+ <div className="flex items-center justify-between mb-2">
+ <label className="text-xs font-bold text-slate-500 dark:text-slate-400 uppercase tracking-wider">
+ Select Records ({selectedImportRecords.size} selected)
+ </label>
+ <div className="flex gap-2">
+ <button
+ onClick={() =>
+ setSelectedImportRecords(
+ new Set(importSourceRecords.map((r) => r.id)),
+ )
+ }
+ className="text-xs text-indigo-600 dark:text-indigo-400 hover:text-indigo-700 dark:hover:text-indigo-300"
+ >
+ Select All
+ </button>
+ <button
+ onClick={() => setSelectedImportRecords(new Set())}
+ className="text-xs text-slate-500 dark:text-slate-400 hover:text-slate-700 dark:hover:text-slate-300"
+ >
+ Clear
+ </button>
+ </div>
+ </div>
+
+ {loadingImport ? (
+ <div className="py-8 text-center text-slate-400 dark:text-slate-500">
+ Loading records...
+ </div>
+ ) : importSourceRecords.length === 0 ? (
+ <div className="py-8 text-center text-slate-400 dark:text-slate-500">
+ No records in this notebook
+ </div>
+ ) : (
+ <div className="space-y-2 max-h-64 overflow-y-auto">
+ {importSourceRecords.map((record) => (
+ <div
+ key={record.id}
+ onClick={() => toggleImportRecord(record.id)}
+ className={`p-3 rounded-xl cursor-pointer transition-all border ${
+ selectedImportRecords.has(record.id)
+ ? "bg-indigo-50 dark:bg-indigo-900/30 border-indigo-200 dark:border-indigo-700"
+ : "hover:bg-slate-50 dark:hover:bg-slate-700/50 border-slate-200 dark:border-slate-600"
+ }`}
+ >
+ <div className="flex items-center gap-3">
+ <div
+ className={`w-5 h-5 rounded border-2 flex items-center justify-center shrink-0 ${
+ selectedImportRecords.has(record.id)
+ ? "bg-indigo-500 border-indigo-500 text-white"
+ : "border-slate-300 dark:border-slate-500"
+ }`}
+ >
+ {selectedImportRecords.has(record.id) && (
+ <Check className="w-3 h-3" />
+ )}
+ </div>
+ <div className="flex-1 min-w-0">
+ <div className="flex items-center gap-2">
+ <span
+ className={`text-[10px] font-bold uppercase px-1.5 py-0.5 rounded ${getRecordColor(record.type)}`}
+ >
+ {record.type}
+ </span>
+ <span className="text-sm font-medium text-slate-900 dark:text-slate-100 truncate">
+ {record.title}
+ </span>
+ </div>
+ <p className="text-xs text-slate-500 dark:text-slate-400 truncate mt-1">
+ {record.user_query}
+ </p>
+ </div>
+ </div>
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+
+ <div className="p-4 border-t border-slate-100 dark:border-slate-700 flex justify-end gap-2 shrink-0">
+ <button
+ onClick={() => {
+ setShowImportModal(false);
+ setImportSourceNotebook("");
+ setImportSourceRecords([]);
+ setSelectedImportRecords(new Set());
+ }}
+ className="px-4 py-2 text-slate-600 dark:text-slate-300 hover:bg-slate-100 dark:hover:bg-slate-700 rounded-lg transition-colors"
+ >
+ Cancel
+ </button>
+ <button
+ onClick={handleImportRecords}
+ disabled={selectedImportRecords.size === 0 || loadingImport}
+ className="px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 transition-colors flex items-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed"
+ >
+ <Upload className="w-4 h-4" />
+ Import{" "}
+ {selectedImportRecords.size > 0 &&
+ `(${selectedImportRecords.size})`}
+ </button>
+ </div>
+ </div>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/web/app/page.tsx b/web/app/page.tsx
new file mode 100644
index 000000000..f9f9de9bb
--- /dev/null
+++ b/web/app/page.tsx
@@ -0,0 +1,381 @@
+"use client";
+
+import { useState, useEffect } from "react";
+import {
+ LayoutDashboard,
+ History,
+ ArrowRight,
+ FileText,
+ HelpCircle,
+ Search,
+ Clock,
+ ChevronRight,
+ Database,
+ BookOpen,
+ Book,
+ Calculator,
+ Microscope,
+ PenTool,
+ Plus,
+} from "lucide-react";
+import Link from "next/link";
+import ActivityDetail from "@/components/ActivityDetail";
+import SystemStatus from "@/components/SystemStatus";
+import { apiUrl } from "@/lib/api";
+import { getTranslation } from "@/lib/i18n";
+import { useGlobal } from "@/context/GlobalContext";
+
+interface Activity {
+ id: string;
+ type: "solve" | "question" | "research";
+ title: string;
+ summary: string;
+ timestamp: number;
+ content: any;
+}
+
+interface NotebookSummary {
+ id: string;
+ name: string;
+ description: string;
+ record_count: number;
+ updated_at: number;
+ color: string;
+}
+
+interface NotebookStats {
+ total_notebooks: number;
+ total_records: number;
+ records_by_type: {
+ solve: number;
+ question: number;
+ research: number;
+ co_writer: number;
+ };
+ recent_notebooks: NotebookSummary[];
+}
+
+export default function DashboardPage() {
+ const { uiSettings } = useGlobal();
+ const t = (key: string) => getTranslation(uiSettings.language, key);
+ const [activities, setActivities] = useState<Activity[]>([]);
+ const [loading, setLoading] = useState(true);
+ const [selectedActivity, setSelectedActivity] = useState<Activity | null>(
+ null,
+ );
+ const [notebookStats, setNotebookStats] = useState<NotebookStats | null>(
+ null,
+ );
+
+ useEffect(() => {
+ // Fetch activities
+ fetch(apiUrl("/api/v1/dashboard/recent?limit=10"))
+ .then((res) => res.json())
+ .then((data) => setActivities(data))
+ .catch((err) => {
+ console.error(err);
+ })
+ .finally(() => setLoading(false));
+
+ // Fetch notebook statistics
+ fetch(apiUrl("/api/v1/notebook/statistics"))
+ .then((res) => res.json())
+ .then((data) => setNotebookStats(data))
+ .catch((err) => {
+ console.error("Failed to fetch notebook stats:", err);
+ });
+ }, []);
+
+ const getIcon = (type: string) => {
+ switch (type) {
+ case "solve":
+ return <HelpCircle className="w-5 h-5 text-blue-500" />;
+ case "question":
+ return <FileText className="w-5 h-5 text-purple-500" />;
+ case "research":
+ return <Search className="w-5 h-5 text-emerald-500" />;
+ default:
+ return <LayoutDashboard className="w-5 h-5 text-slate-500" />;
+ }
+ };
+
+ const getLabel = (type: string) => {
+ switch (type) {
+ case "solve":
+ return t("Problem Solved");
+ case "question":
+ return t("Question Generated");
+ case "research":
+ return t("Research Report");
+ default:
+ return t("Activity");
+ }
+ };
+
+ return (
+ <div className="animate-fade-in space-y-8">
+ {/* Header */}
+ <div>
+ <h1 className="text-3xl font-bold text-slate-900 dark:text-slate-100 tracking-tight flex items-center gap-3">
+ <LayoutDashboard className="w-8 h-8 text-blue-600 dark:text-blue-400" />
+ {t("Dashboard")}
+ </h1>
+ <p className="text-slate-500 dark:text-slate-400 mt-2">
+ {t("Overview of your recent learning activities")}
+ </p>
+ </div>
+
+ <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
+ {/* Left: Recent Activity Feed */}
+ <div className="lg:col-span-2 space-y-6">
+ <div className="flex items-center justify-between">
+ <h2 className="text-lg font-bold text-slate-900 dark:text-slate-100 flex items-center gap-2">
+ <History className="w-5 h-5 text-slate-400 dark:text-slate-500" />
+ {t("Recent Activity")}
+ </h2>
+ <Link
+ href="#"
+ className="text-sm text-blue-600 dark:text-blue-400 font-medium hover:underline flex items-center gap-1"
+ >
+ {t("View All")} <ChevronRight className="w-4 h-4" />
+ </Link>
+ </div>
+
+ <div className="bg-white dark:bg-slate-800 rounded-2xl shadow-sm border border-slate-200 dark:border-slate-700 divide-y divide-slate-100 dark:divide-slate-700 overflow-hidden">
+ {loading ? (
+ <div className="p-8 text-center text-slate-400 dark:text-slate-500">
+ {t("Loading activities...")}
+ </div>
+ ) : activities.length === 0 ? (
+ <div className="p-12 text-center">
+ <div className="w-16 h-16 bg-slate-50 dark:bg-slate-700 rounded-full flex items-center justify-center mx-auto mb-4">
+ <History className="w-8 h-8 text-slate-300 dark:text-slate-500" />
+ </div>
+ <p className="text-slate-500 dark:text-slate-400">
+ {t("No recent activity found")}
+ </p>
+ <p className="text-sm text-slate-400 dark:text-slate-500 mt-1">
+ {t("Start solving problems or generating questions!")}
+ </p>
+ </div>
+ ) : (
+ activities.map((activity) => (
+ <div
+ key={activity.id}
+ onClick={() => setSelectedActivity(activity)}
+ className="p-5 hover:bg-slate-50 dark:hover:bg-slate-700/50 transition-colors group cursor-pointer"
+ >
+ <div className="flex gap-4">
+ <div className="mt-1">
+ <div className="w-10 h-10 rounded-xl bg-slate-50 dark:bg-slate-700 border border-slate-100 dark:border-slate-600 flex items-center justify-center group-hover:scale-110 transition-transform duration-300">
+ {getIcon(activity.type)}
+ </div>
+ </div>
+ <div className="flex-1 min-w-0">
+ <div className="flex justify-between items-start">
+ <p className="text-xs font-bold uppercase tracking-wider text-slate-500 dark:text-slate-400 mb-1">
+ {getLabel(activity.type)}
+ </p>
+ <span className="text-xs text-slate-400 dark:text-slate-500 flex items-center gap-1">
+ <Clock className="w-3 h-3" />
+ {new Date(
+ activity.timestamp * 1000,
+ ).toLocaleDateString()}
+ </span>
+ </div>
+ <h3 className="text-base font-semibold text-slate-900 dark:text-slate-100 truncate pr-4">
+ {activity.title}
+ </h3>
+ {activity.summary && (
+ <p className="text-sm text-slate-500 dark:text-slate-400 mt-1 line-clamp-2">
+ {activity.summary}
+ </p>
+ )}
+ {activity.content?.kb_name && (
+ <div className="mt-3 flex items-center gap-2">
+ <span className="inline-flex items-center px-2 py-0.5 rounded text-[10px] font-medium bg-slate-100 dark:bg-slate-700 text-slate-600 dark:text-slate-300 border border-slate-200 dark:border-slate-600">
+ <Database className="w-3 h-3 mr-1" />
+ {activity.content.kb_name}
+ </span>
+ </div>
+ )}
+ </div>
+ <div className="self-center opacity-0 group-hover:opacity-100 transition-opacity">
+ <ArrowRight className="w-5 h-5 text-slate-400 dark:text-slate-500" />
+ </div>
+ </div>
+ </div>
+ ))
+ )}
+ </div>
+ </div>
+
+ {/* Right: Quick Actions / Stats */}
+ <div className="space-y-6">
+ {/* Notebooks Overview */}
+ <div className="bg-gradient-to-br from-indigo-600 to-purple-600 rounded-2xl p-6 text-white shadow-lg">
+ <div className="flex items-center justify-between mb-4">
+ <h3 className="font-bold text-lg flex items-center gap-2">
+ <Book className="w-5 h-5" />
+ {t("My Notebooks")}
+ </h3>
+ <Link
+ href="/notebook"
+ className="text-xs text-white/80 hover:text-white flex items-center gap-1"
+ >
+ {t("View All")} <ChevronRight className="w-3 h-3" />
+ </Link>
+ </div>
+
+ {notebookStats ? (
+ <>
+ <div className="grid grid-cols-2 gap-3 mb-4">
+ <div className="bg-white/10 rounded-xl p-3">
+ <div className="text-2xl font-bold">
+ {notebookStats.total_notebooks}
+ </div>
+ <div className="text-xs text-white/70">{t("Notebooks")}</div>
+ </div>
+ <div className="bg-white/10 rounded-xl p-3">
+ <div className="text-2xl font-bold">
+ {notebookStats.total_records}
+ </div>
+ <div className="text-xs text-white/70">{t("records")}</div>
+ </div>
+ </div>
+
+ {/* Records by type */}
+ <div className="space-y-2">
+ <div className="flex items-center justify-between text-xs">
+ <span className="flex items-center gap-1.5 text-white/80">
+ <Calculator className="w-3 h-3" /> {t("Solve")}
+ </span>
+ <span className="font-medium">
+ {notebookStats.records_by_type.solve}
+ </span>
+ </div>
+ <div className="flex items-center justify-between text-xs">
+ <span className="flex items-center gap-1.5 text-white/80">
+ <FileText className="w-3 h-3" /> {t("Question")}
+ </span>
+ <span className="font-medium">
+ {notebookStats.records_by_type.question}
+ </span>
+ </div>
+ <div className="flex items-center justify-between text-xs">
+ <span className="flex items-center gap-1.5 text-white/80">
+ <Microscope className="w-3 h-3" /> {t("Research")}
+ </span>
+ <span className="font-medium">
+ {notebookStats.records_by_type.research}
+ </span>
+ </div>
+ <div className="flex items-center justify-between text-xs">
+ <span className="flex items-center gap-1.5 text-white/80">
+ <PenTool className="w-3 h-3" /> {t("Co-Writer")}
+ </span>
+ <span className="font-medium">
+ {notebookStats.records_by_type.co_writer}
+ </span>
+ </div>
+ </div>
+
+ {/* Recent notebooks */}
+ {notebookStats.recent_notebooks.length > 0 && (
+ <div className="mt-4 pt-4 border-t border-white/20">
+ <div className="text-xs text-white/60 mb-2">Recent</div>
+ <div className="space-y-2">
+ {notebookStats.recent_notebooks.slice(0, 3).map((nb) => (
+ <Link
+ key={nb.id}
+ href="/notebook"
+ className="flex items-center gap-2 p-2 bg-white/10 rounded-lg hover:bg-white/20 transition-colors"
+ >
+ <div
+ className="w-6 h-6 rounded flex items-center justify-center"
+ style={{ backgroundColor: nb.color }}
+ >
+ <BookOpen className="w-3 h-3 text-white" />
+ </div>
+ <div className="flex-1 min-w-0">
+ <div className="text-sm font-medium truncate">
+ {nb.name}
+ </div>
+ <div className="text-[10px] text-white/60">
+ {nb.record_count} records
+ </div>
+ </div>
+ </Link>
+ ))}
+ </div>
+ </div>
+ )}
+ </>
+ ) : (
+ <div className="text-center py-4">
+ <BookOpen className="w-8 h-8 mx-auto mb-2 text-white/40" />
+ <p className="text-sm text-white/60">{t("No notebooks yet")}</p>
+ <Link
+ href="/notebook"
+ className="mt-2 inline-flex items-center gap-1 text-xs text-white/80 hover:text-white"
+ >
+ <Plus className="w-3 h-3" /> {t("Create your first notebook")}
+ </Link>
+ </div>
+ )}
+ </div>
+
+ {/* System Status */}
+ <div className="bg-white dark:bg-slate-800 rounded-2xl shadow-sm border border-slate-200 dark:border-slate-700 p-6">
+ <h3 className="font-bold text-slate-900 dark:text-slate-100 mb-4">
+ {t("System Status")}
+ </h3>
+ <SystemStatus />
+ </div>
+
+ <div className="bg-white dark:bg-slate-800 rounded-2xl shadow-sm border border-slate-200 dark:border-slate-700 p-6">
+ <h3 className="font-bold text-slate-900 dark:text-slate-100 mb-4">
+ {t("Quick Actions")}
+ </h3>
+ <div className="space-y-3">
+ <Link
+ href="/solver"
+ className="block w-full p-3 rounded-xl bg-blue-50 dark:bg-blue-900/30 text-blue-700 dark:text-blue-300 font-medium hover:bg-blue-100 dark:hover:bg-blue-900/50 transition-colors text-sm flex items-center gap-3"
+ >
+ <div className="p-1.5 bg-white dark:bg-slate-700 rounded-lg shadow-sm">
+ <HelpCircle className="w-4 h-4 text-blue-600 dark:text-blue-400" />
+ </div>
+ {t("Ask a Question")}
+ </Link>
+ <Link
+ href="/question"
+ className="block w-full p-3 rounded-xl bg-purple-50 dark:bg-purple-900/30 text-purple-700 dark:text-purple-300 font-medium hover:bg-purple-100 dark:hover:bg-purple-900/50 transition-colors text-sm flex items-center gap-3"
+ >
+ <div className="p-1.5 bg-white dark:bg-slate-700 rounded-lg shadow-sm">
+ <FileText className="w-4 h-4 text-purple-600 dark:text-purple-400" />
+ </div>
+ {t("Generate Quiz")}
+ </Link>
+ <Link
+ href="/research"
+ className="block w-full p-3 rounded-xl bg-emerald-50 dark:bg-emerald-900/30 text-emerald-700 dark:text-emerald-300 font-medium hover:bg-emerald-100 dark:hover:bg-emerald-900/50 transition-colors text-sm flex items-center gap-3"
+ >
+ <div className="p-1.5 bg-white dark:bg-slate-700 rounded-lg shadow-sm">
+ <Search className="w-4 h-4 text-emerald-600 dark:text-emerald-400" />
+ </div>
+ {t("Start Research")}
+ </Link>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ {selectedActivity && (
+ <ActivityDetail
+ activity={selectedActivity}
+ onClose={() => setSelectedActivity(null)}
+ />
+ )}
+ </div>
+ );
+}
diff --git a/web/app/question/page.tsx b/web/app/question/page.tsx
new file mode 100644
index 000000000..9afbdaa8a
--- /dev/null
+++ b/web/app/question/page.tsx
@@ -0,0 +1,1094 @@
+"use client";
+
+import { useState, useEffect } from "react";
+import {
+ PenTool,
+ CheckCircle2,
+ AlertCircle,
+ Loader2,
+ BookOpen,
+ BrainCircuit,
+ Sparkles,
+ RefreshCw,
+ FileText,
+ Book,
+ Upload,
+ Database,
+ FileQuestion,
+ Activity,
+ Zap,
+ ChevronDown,
+ ChevronRight,
+} from "lucide-react";
+import { useGlobal } from "@/context/GlobalContext";
+import ReactMarkdown from "react-markdown";
+import remarkMath from "remark-math";
+import rehypeKatex from "rehype-katex";
+import "katex/dist/katex.min.css";
+import { apiUrl } from "@/lib/api";
+import { processLatexContent } from "@/lib/latex";
+import AddToNotebookModal from "@/components/AddToNotebookModal";
+import { QuestionDashboard } from "@/components/question";
+import { useQuestionReducer } from "@/hooks/useQuestionReducer";
+
+export default function QuestionPage() {
+ const {
+ questionState,
+ setQuestionState,
+ startQuestionGen,
+ startMimicQuestionGen,
+ resetQuestionGen,
+ } = useGlobal();
+
+ // Dashboard state for parallel generation
+ const [dashboardState, dispatchDashboard] = useQuestionReducer();
+ const [selectedTaskId, setSelectedTaskId] = useState<string | null>(null);
+
+ // Tab state: "questions" shows the quiz, "process" shows the dashboard
+ const [activeTab, setActiveTab] = useState<"questions" | "process">(
+ "questions",
+ );
+
+ // Local interaction state
+ const [kbs, setKbs] = useState<string[]>([]);
+
+ // Answering state
+ const [activeIdx, setActiveIdx] = useState(0);
+ const [userAnswers, setUserAnswers] = useState<Record<number, string>>({});
+ const [submittedMap, setSubmittedMap] = useState<Record<number, boolean>>({});
+ const [showValidation, setShowValidation] = useState(false);
+
+ // Notebook modal state
+ const [showNotebookModal, setShowNotebookModal] = useState(false);
+
+ // Check if generation is in progress
+ const isGenerating =
+ questionState.step === "generating" || questionState.step === "result";
+ const isConfigMode = questionState.step === "config";
+
+ // Fetch KBs on mount only
+ useEffect(() => {
+ fetch(apiUrl("/api/v1/knowledge/list"))
+ .then((res) => res.json())
+ .then((data) => {
+ const names = data.map((kb: any) => kb.name);
+ setKbs(names);
+ if (!questionState.selectedKb && names.length > 0) {
+ setQuestionState((prev) => ({ ...prev, selectedKb: names[0] }));
+ }
+ })
+ .catch((err) => console.error("Failed to fetch KBs:", err));
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
+
+ const handleStart = () => {
+ if (questionState.mode === "knowledge") {
+ startQuestionGen(
+ questionState.topic,
+ questionState.difficulty,
+ questionState.type,
+ questionState.count,
+ questionState.selectedKb,
+ );
+ } else {
+ // Mimic mode - use PDF file or pre-parsed directory
+ startMimicQuestionGen(
+ questionState.uploadedFile,
+ questionState.paperPath,
+ questionState.selectedKb,
+ questionState.count > 0 ? questionState.count : undefined,
+ );
+ }
+ // Reset interaction state
+ setUserAnswers({});
+ setSubmittedMap({});
+ setActiveIdx(0);
+ setShowValidation(false);
+ // Switch to process tab when generating
+ setActiveTab("process");
+ };
+
+ const handleAnswer = (val: string) => {
+ if (submittedMap[activeIdx]) return;
+ setUserAnswers((prev) => ({ ...prev, [activeIdx]: val }));
+ };
+
+ const handleSubmit = () => {
+ setSubmittedMap((prev) => ({ ...prev, [activeIdx]: true }));
+ };
+
+ const handleFileUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
+ const file = e.target.files?.[0] || null;
+ if (file && file.type !== "application/pdf") {
+ alert("Please upload a PDF exam paper");
+ return;
+ }
+ setQuestionState((prev) => ({
+ ...prev,
+ uploadedFile: file,
+ paperPath: file ? "" : prev.paperPath,
+ }));
+ };
+
+ const currentQuestion = questionState.results[activeIdx];
+ const totalQuestions = questionState.results.length;
+ const extendedCount = questionState.results.filter(
+ (r: any) => r.extended,
+ ).length;
+
+ // Auto-switch to questions tab when generation completes
+ useEffect(() => {
+ if (questionState.step === "result" && totalQuestions > 0) {
+ setActiveTab("questions");
+ }
+ }, [questionState.step, totalQuestions]);
+
+ return (
+ <div className="h-[calc(100vh-4rem)] flex flex-col animate-fade-in overflow-hidden p-4">
+ {/* Main Panel */}
+ <div className="flex-1 flex flex-col bg-white dark:bg-slate-800 rounded-2xl shadow-sm border border-slate-200 dark:border-slate-700 overflow-hidden min-h-0">
+ {/* Header Row */}
+ <div className="p-4 border-b border-slate-100 dark:border-slate-700 bg-slate-50/50 dark:bg-slate-800/50 flex justify-between items-center backdrop-blur-sm shrink-0">
+ <div className="flex items-center gap-4">
+ <div className="flex items-center gap-2 text-slate-700 dark:text-slate-200 font-semibold">
+ <PenTool className="w-5 h-5 text-purple-600 dark:text-purple-400" />
+ Question Generator
+ </div>
+
+ {/* Mode Switching - disabled when generating */}
+ <div
+ className={`flex bg-slate-100 dark:bg-slate-700 p-1 rounded-lg border border-slate-200 dark:border-slate-600 ${isGenerating ? "opacity-50" : ""}`}
+ >
+ <button
+ onClick={() =>
+ !isGenerating &&
+ setQuestionState((prev) => ({
+ ...prev,
+ mode: "knowledge",
+ }))
+ }
+ disabled={isGenerating}
+ className={`flex items-center gap-1.5 px-3 py-1.5 rounded-md text-sm font-medium transition-all ${
+ questionState.mode === "knowledge"
+ ? "bg-white dark:bg-slate-600 text-purple-700 dark:text-purple-400 shadow-sm"
+ : isGenerating
+ ? "text-slate-400 dark:text-slate-500 cursor-not-allowed"
+ : "text-slate-500 dark:text-slate-400 hover:text-slate-700 dark:hover:text-slate-200"
+ }`}
+ >
+ <BrainCircuit className="w-4 h-4" />
+ Custom
+ </button>
+ <button
+ onClick={() =>
+ !isGenerating &&
+ setQuestionState((prev) => ({ ...prev, mode: "mimic" }))
+ }
+ disabled={isGenerating}
+ className={`flex items-center gap-1.5 px-3 py-1.5 rounded-md text-sm font-medium transition-all ${
+ questionState.mode === "mimic"
+ ? "bg-white dark:bg-slate-600 text-purple-700 dark:text-purple-400 shadow-sm"
+ : isGenerating
+ ? "text-slate-400 dark:text-slate-500 cursor-not-allowed"
+ : "text-slate-500 dark:text-slate-400 hover:text-slate-700 dark:hover:text-slate-200"
+ }`}
+ >
+ <FileText className="w-4 h-4" />
+ Mimic Exam
+ </button>
+ </div>
+
+ {/* Separator */}
+ <div className="h-6 w-px bg-slate-200 dark:bg-slate-600" />
+
+ {/* Questions/Process Tabs */}
+ <div className="flex bg-slate-100 dark:bg-slate-700 p-1 rounded-lg border border-slate-200 dark:border-slate-600">
+ <button
+ onClick={() => !isConfigMode && setActiveTab("questions")}
+ disabled={isConfigMode}
+ className={`flex items-center gap-2 px-3 py-1.5 rounded-md text-sm font-medium transition-all ${
+ !isConfigMode && activeTab === "questions"
+ ? "bg-white dark:bg-slate-600 text-purple-700 dark:text-purple-400 shadow-sm"
+ : isConfigMode
+ ? "text-slate-300 dark:text-slate-500 cursor-not-allowed"
+ : "text-slate-500 dark:text-slate-400 hover:text-slate-700 dark:hover:text-slate-200"
+ }`}
+ >
+ <FileQuestion className="w-4 h-4" />
+ Questions
+ {totalQuestions > 0 && (
+ <span className="px-1.5 py-0.5 bg-purple-100 dark:bg-purple-900/50 text-purple-700 dark:text-purple-300 text-xs rounded-full">
+ {totalQuestions}
+ </span>
+ )}
+ </button>
+ <button
+ onClick={() => !isConfigMode && setActiveTab("process")}
+ disabled={isConfigMode}
+ className={`flex items-center gap-2 px-3 py-1.5 rounded-md text-sm font-medium transition-all ${
+ !isConfigMode && activeTab === "process"
+ ? "bg-white dark:bg-slate-600 text-purple-700 dark:text-purple-400 shadow-sm"
+ : isConfigMode
+ ? "text-slate-300 dark:text-slate-500 cursor-not-allowed"
+ : "text-slate-500 dark:text-slate-400 hover:text-slate-700 dark:hover:text-slate-200"
+ }`}
+ >
+ <Activity className="w-4 h-4" />
+ Process
+ {questionState.step === "generating" && (
+ <Loader2 className="w-3 h-3 animate-spin text-purple-500 dark:text-purple-400" />
+ )}
+ </button>
+ </div>
+ </div>
+
+ <div className="flex items-center gap-4">
+ {/* Knowledge Base Selection */}
+ <div className="flex items-center gap-2">
+ <Database className="w-4 h-4 text-slate-400 dark:text-slate-500" />
+ <select
+ value={questionState.selectedKb}
+ onChange={(e) =>
+ setQuestionState((prev) => ({
+ ...prev,
+ selectedKb: e.target.value,
+ }))
+ }
+ disabled={isGenerating}
+ className={`text-sm bg-white dark:bg-slate-700 border border-slate-200 dark:border-slate-600 rounded-lg px-3 py-1.5 outline-none focus:border-purple-400 focus:ring-2 focus:ring-purple-500/20 dark:text-slate-200 ${isGenerating ? "opacity-50 cursor-not-allowed" : ""}`}
+ >
+ {kbs.map((kb) => (
+ <option key={kb} value={kb}>
+ {kb}
+ </option>
+ ))}
+ </select>
+ </div>
+
+ {!isConfigMode && (
+ <button
+ onClick={resetQuestionGen}
+ className="text-sm flex items-center gap-1.5 text-slate-500 dark:text-slate-400 hover:text-purple-600 dark:hover:text-purple-400 transition-colors px-3 py-1.5 hover:bg-purple-50 dark:hover:bg-purple-900/30 rounded-lg border border-slate-200 dark:border-slate-600"
+ >
+ <RefreshCw className="w-4 h-4" />
+ New
+ </button>
+ )}
+ </div>
+ </div>
+
+ {/* Content Area */}
+ <div className="flex-1 overflow-y-auto bg-slate-50/30 dark:bg-slate-900/30 min-h-0">
+ {/* MODE: CONFIG - Show config form */}
+ {isConfigMode && (
+ <div className="p-6">
+ <div className="max-w-2xl mx-auto space-y-8 animate-in fade-in slide-in-from-bottom-4">
+ {/* Mode Info Banner */}
+ <div
+ className={`p-4 rounded-xl border ${
+ questionState.mode === "knowledge"
+ ? "bg-purple-50 dark:bg-purple-900/30 border-purple-200 dark:border-purple-800"
+ : "bg-blue-50 dark:bg-blue-900/30 border-blue-200 dark:border-blue-800"
+ }`}
+ >
+ <div className="flex items-center gap-3">
+ {questionState.mode === "knowledge" ? (
+ <BrainCircuit className="w-6 h-6 text-purple-600 dark:text-purple-400" />
+ ) : (
+ <FileText className="w-6 h-6 text-blue-600 dark:text-blue-400" />
+ )}
+ <div>
+ <h3
+ className={`font-semibold ${
+ questionState.mode === "knowledge"
+ ? "text-purple-800 dark:text-purple-300"
+ : "text-blue-800 dark:text-blue-300"
+ }`}
+ >
+ {questionState.mode === "knowledge"
+ ? "Custom Mode"
+ : "Mimic Exam Paper Mode"}
+ </h3>
+ <p className="text-sm text-slate-600 dark:text-slate-400">
+ {questionState.mode === "knowledge"
+ ? "Generate questions based on knowledge base content"
+ : "Generate similar questions based on an exam paper"}
+ </p>
+ </div>
+ </div>
+ </div>
+
+ {/* Knowledge Base Mode Config */}
+ {questionState.mode === "knowledge" && (
+ <>
+ <div className="grid grid-cols-2 gap-6">
+ <div className="space-y-2">
+ <label className="text-xs font-bold text-slate-500 dark:text-slate-400 uppercase tracking-wider">
+ Question Count
+ </label>
+ <div className="flex items-center gap-4">
+ <input
+ type="range"
+ min="1"
+ max="10"
+ step="1"
+ value={Math.min(questionState.count, 10)}
+ onChange={(e) =>
+ setQuestionState((prev) => ({
+ ...prev,
+ count: parseInt(e.target.value),
+ }))
+ }
+ className="flex-1 accent-purple-600 h-2 bg-slate-200 dark:bg-slate-600 rounded-lg appearance-none cursor-pointer"
+ />
+ <input
+ type="number"
+ min="1"
+ max="50"
+ value={questionState.count}
+ onChange={(e) => {
+ const val = parseInt(e.target.value) || 1;
+ setQuestionState((prev) => ({
+ ...prev,
+ count: Math.max(1, Math.min(50, val)),
+ }));
+ }}
+ className="w-16 text-center font-bold text-purple-700 dark:text-purple-300 bg-purple-50 dark:bg-purple-900/30 py-1 rounded-md border border-purple-100 dark:border-purple-800 outline-none focus:border-purple-400 focus:ring-2 focus:ring-purple-500/20"
+ />
+ </div>
+ <p className="text-[10px] text-slate-400 dark:text-slate-500">
+ Use slider (1-10) or type directly (1-50)
+ </p>
+ </div>
+ </div>
+
+ <div className="space-y-2">
+ <label className="text-xs font-bold text-slate-500 dark:text-slate-400 uppercase tracking-wider">
+ Knowledge Point / Topic
+ </label>
+ <input
+ type="text"
+ value={questionState.topic}
+ onChange={(e) =>
+ setQuestionState((prev) => ({
+ ...prev,
+ topic: e.target.value,
+ }))
+ }
+ placeholder="e.g. Gradient Descent Optimization"
+ className="w-full p-4 bg-slate-50 dark:bg-slate-700 border border-slate-200 dark:border-slate-600 rounded-xl outline-none focus:border-purple-500 focus:ring-2 focus:ring-purple-500/10 transition-all text-lg dark:text-slate-200 dark:placeholder:text-slate-500"
+ />
+ </div>
+
+ <div className="grid grid-cols-2 gap-6">
+ <div className="space-y-2">
+ <label className="text-xs font-bold text-slate-500 dark:text-slate-400 uppercase tracking-wider">
+ Difficulty
+ </label>
+ <div className="flex bg-slate-50 dark:bg-slate-700 p-1 rounded-xl border border-slate-200 dark:border-slate-600">
+ {["easy", "medium", "hard"].map((lvl) => (
+ <button
+ key={lvl}
+ onClick={() =>
+ setQuestionState((prev) => ({
+ ...prev,
+ difficulty: lvl,
+ }))
+ }
+ className={`flex-1 py-2 rounded-lg text-sm font-medium capitalize transition-all ${
+ questionState.difficulty === lvl
+ ? "bg-white dark:bg-slate-600 text-purple-700 dark:text-purple-400 shadow-sm"
+ : "text-slate-500 dark:text-slate-400 hover:text-slate-700 dark:hover:text-slate-200"
+ }`}
+ >
+ {lvl}
+ </button>
+ ))}
+ </div>
+ </div>
+
+ <div className="space-y-2">
+ <label className="text-xs font-bold text-slate-500 dark:text-slate-400 uppercase tracking-wider">
+ Type
+ </label>
+ <div className="flex bg-slate-50 dark:bg-slate-700 p-1 rounded-xl border border-slate-200 dark:border-slate-600">
+ {[
+ { id: "choice", label: "Multiple Choice" },
+ { id: "written", label: "Written" },
+ ].map((t) => (
+ <button
+ key={t.id}
+ onClick={() =>
+ setQuestionState((prev) => ({
+ ...prev,
+ type: t.id,
+ }))
+ }
+ className={`flex-1 py-2 rounded-lg text-sm font-medium transition-all ${
+ questionState.type === t.id
+ ? "bg-white dark:bg-slate-600 text-purple-700 dark:text-purple-400 shadow-sm"
+ : "text-slate-500 dark:text-slate-400 hover:text-slate-700 dark:hover:text-slate-200"
+ }`}
+ >
+ {t.label}
+ </button>
+ ))}
+ </div>
+ </div>
+ </div>
+ </>
+ )}
+
+ {/* Mimic Mode Config */}
+ {questionState.mode === "mimic" && (
+ <div className="space-y-6">
+ {/* PDF Upload Section */}
+ <div className="space-y-2">
+ <label className="text-xs font-bold text-slate-500 dark:text-slate-400 uppercase tracking-wider">
+ Upload Exam Paper (PDF)
+ </label>
+ <div className="relative">
+ <input
+ type="file"
+ accept=".pdf"
+ onChange={handleFileUpload}
+ className="hidden"
+ id="pdf-upload"
+ />
+ <label
+ htmlFor="pdf-upload"
+ className="flex items-center justify-center gap-3 w-full p-6 border-2 border-dashed border-slate-300 dark:border-slate-600 rounded-xl cursor-pointer hover:border-purple-400 dark:hover:border-purple-500 hover:bg-purple-50/50 dark:hover:bg-purple-900/20 transition-all"
+ >
+ {questionState.uploadedFile ? (
+ <div className="flex items-center gap-3 text-purple-700 dark:text-purple-400">
+ <FileText className="w-8 h-8" />
+ <div>
+ <p className="font-medium">
+ {questionState.uploadedFile.name}
+ </p>
+ <p className="text-xs text-slate-500 dark:text-slate-400">
+ {(
+ questionState.uploadedFile.size /
+ 1024 /
+ 1024
+ ).toFixed(2)}{" "}
+ MB - Click to change
+ </p>
+ </div>
+ </div>
+ ) : (
+ <div className="text-center text-slate-500 dark:text-slate-400">
+ <Upload className="w-8 h-8 mx-auto mb-2 text-slate-400 dark:text-slate-500" />
+ <p className="font-medium">
+ Click to upload PDF exam paper
+ </p>
+ <p className="text-xs">
+ The system will automatically parse and generate
+ questions
+ </p>
+ </div>
+ )}
+ </label>
+ </div>
+ </div>
+
+ {/* Divider */}
+ <div className="flex items-center gap-3">
+ <div className="flex-1 h-px bg-slate-200 dark:bg-slate-600"></div>
+ <span className="text-xs text-slate-400 dark:text-slate-500 font-medium">
+ OR
+ </span>
+ <div className="flex-1 h-px bg-slate-200 dark:bg-slate-600"></div>
+ </div>
+
+ {/* Pre-parsed Directory (Optional) */}
+ <div className="space-y-2">
+ <label className="text-xs font-bold text-slate-500 dark:text-slate-400 uppercase tracking-wider">
+ Pre-parsed Directory (Optional)
+ </label>
+ <input
+ type="text"
+ value={questionState.paperPath}
+ onChange={(e) =>
+ setQuestionState((prev) => ({
+ ...prev,
+ paperPath: e.target.value,
+ uploadedFile: null,
+ }))
+ }
+ placeholder="e.g. 2211asm1"
+ className="w-full p-3 bg-slate-50 dark:bg-slate-700 border border-slate-200 dark:border-slate-600 rounded-xl outline-none focus:border-purple-500 focus:ring-2 focus:ring-purple-500/10 transition-all dark:text-slate-200 dark:placeholder:text-slate-500"
+ />
+ <p className="text-xs text-slate-500 dark:text-slate-400">
+ Or enter a pre-parsed paper directory name
+ </p>
+ </div>
+
+ <div className="space-y-2">
+ <label className="text-xs font-bold text-slate-500 dark:text-slate-400 uppercase tracking-wider">
+ Max Questions (Optional)
+ </label>
+ <div className="flex items-center gap-4">
+ <input
+ type="number"
+ min="1"
+ max="20"
+ placeholder="All"
+ value={questionState.count || ""}
+ onChange={(e) => {
+ const val = e.target.value
+ ? parseInt(e.target.value)
+ : 0;
+ setQuestionState((prev) => ({
+ ...prev,
+ count: val > 0 ? Math.min(20, val) : 0,
+ }));
+ }}
+ className="w-24 p-2 text-center bg-slate-50 dark:bg-slate-700 border border-slate-200 dark:border-slate-600 rounded-lg outline-none focus:border-purple-500 focus:ring-2 focus:ring-purple-500/10 dark:text-slate-200"
+ />
+ <span className="text-sm text-slate-500 dark:text-slate-400">
+ Leave empty to generate all questions from the paper
+ </span>
+ </div>
+ </div>
+
+ <div className="p-4 bg-gradient-to-r from-purple-50 to-blue-50 dark:from-purple-900/30 dark:to-blue-900/30 border border-purple-200 dark:border-purple-800 rounded-xl text-sm text-slate-700 dark:text-slate-300">
+ <p className="font-medium mb-2 text-purple-800 dark:text-purple-300">
+ ✨ How Mimic Mode Works
+ </p>
+ <ol className="text-xs space-y-1 list-decimal list-inside text-slate-600 dark:text-slate-400">
+ <li>Upload your exam paper PDF</li>
+ <li>Select the relevant knowledge base</li>
+ <li>
+ The system will automatically: parse PDF → extract
+ questions → generate similar new questions
+ </li>
+ <li>Progress will be displayed in real-time</li>
+ </ol>
+ </div>
+ </div>
+ )}
+
+ <button
+ onClick={handleStart}
+ disabled={
+ questionState.mode === "knowledge"
+ ? !questionState.topic.trim()
+ : !questionState.uploadedFile &&
+ !questionState.paperPath.trim()
+ }
+ className="w-full py-4 bg-purple-600 text-white rounded-xl font-bold text-lg shadow-lg shadow-purple-500/30 hover:bg-purple-700 hover:shadow-purple-500/50 active:scale-[0.98] transition-all disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2"
+ >
+ <Sparkles className="w-5 h-5" />
+ Generate Questions
+ </button>
+ </div>
+ </div>
+ )}
+
+ {/* QUESTIONS TAB */}
+ {!isConfigMode && activeTab === "questions" && (
+ <div className="p-6 h-full">
+ {/* Question Number Selector */}
+ {totalQuestions > 0 && (
+ <div className="mb-6 bg-white dark:bg-slate-800 rounded-xl border border-slate-200 dark:border-slate-700 p-4">
+ <div className="flex items-center justify-between mb-3">
+ <span className="text-sm font-semibold text-slate-700 dark:text-slate-200">
+ Questions
+ </span>
+ <span className="text-sm text-slate-500 dark:text-slate-400">
+ {totalQuestions} / {questionState.count} completed
+ {extendedCount > 0 && (
+ <span className="ml-2 text-amber-600 dark:text-amber-400">
+ ({extendedCount} extended)
+ </span>
+ )}
+ </span>
+ </div>
+ <div className="flex flex-wrap gap-2">
+ {questionState.results.map((result: any, idx: number) => (
+ <button
+ key={idx}
+ onClick={() => setActiveIdx(idx)}
+ className={`w-10 h-10 rounded-full flex items-center justify-center font-semibold text-sm border-2 transition-all ${
+ activeIdx === idx
+ ? "bg-purple-600 text-white border-purple-600 shadow-lg shadow-purple-500/30 scale-110"
+ : result.extended
+ ? "bg-amber-50 dark:bg-amber-900/30 text-amber-700 dark:text-amber-400 border-amber-300 dark:border-amber-600 hover:border-amber-400 dark:hover:border-amber-500 hover:bg-amber-100 dark:hover:bg-amber-900/50"
+ : submittedMap[idx]
+ ? "bg-emerald-50 dark:bg-emerald-900/30 text-emerald-600 dark:text-emerald-400 border-emerald-300 dark:border-emerald-600 hover:border-emerald-400 dark:hover:border-emerald-500"
+ : "bg-white dark:bg-slate-700 text-slate-600 dark:text-slate-300 border-slate-200 dark:border-slate-600 hover:border-purple-300 dark:hover:border-purple-500 hover:bg-purple-50 dark:hover:bg-purple-900/30"
+ }`}
+ >
+ {submittedMap[idx] && activeIdx !== idx ? (
+ <CheckCircle2 className="w-5 h-5" />
+ ) : result.extended && activeIdx !== idx ? (
+ <Zap className="w-4 h-4" />
+ ) : (
+ idx + 1
+ )}
+ </button>
+ ))}
+ </div>
+ </div>
+ )}
+
+ {/* No Questions Yet */}
+ {totalQuestions === 0 && questionState.step === "generating" && (
+ <div className="h-full flex flex-col items-center justify-center text-slate-400 dark:text-slate-500 gap-4">
+ <div className="relative">
+ <div className="w-16 h-16 border-4 border-purple-100 dark:border-purple-900 border-t-purple-500 rounded-full animate-spin"></div>
+ <div className="absolute inset-0 flex items-center justify-center">
+ <BrainCircuit className="w-6 h-6 text-purple-500 dark:text-purple-400" />
+ </div>
+ </div>
+ <p className="font-medium text-slate-600 dark:text-slate-300">
+ Generating questions...
+ </p>
+ <p className="text-sm text-center max-w-xs">
+ Switch to the Process tab to see detailed progress
+ </p>
+ </div>
+ )}
+
+ {/* Question Display - Left-Right Layout */}
+ {totalQuestions > 0 && currentQuestion && (
+ <div className="flex-1 flex gap-6 animate-in fade-in slide-in-from-right-4">
+ {/* Left Side: Question Area */}
+ <div className="flex-1 bg-white dark:bg-slate-800 rounded-2xl border border-slate-200 dark:border-slate-700 shadow-sm overflow-hidden flex flex-col">
+ {/* Question Header */}
+ <div className="px-6 py-4 border-b border-slate-100 dark:border-slate-700 bg-slate-50/30 dark:bg-slate-800/30">
+ <div className="flex items-center gap-2">
+ <span className="px-3 py-1 bg-purple-50 dark:bg-purple-900/30 text-purple-700 dark:text-purple-300 text-xs font-bold uppercase rounded-full border border-purple-100 dark:border-purple-800">
+ {currentQuestion.question.type ||
+ currentQuestion.question.question_type}
+ </span>
+ {currentQuestion.extended && (
+ <span className="px-3 py-1 bg-amber-50 dark:bg-amber-900/30 text-amber-700 dark:text-amber-300 text-xs font-bold uppercase rounded-full border border-amber-200 dark:border-amber-800 flex items-center gap-1">
+ <Zap className="w-3 h-3" />
+ Extended
+ </span>
+ )}
+ <button
+ onClick={() => setShowNotebookModal(true)}
+ className="ml-auto text-xs font-medium text-indigo-500 dark:text-indigo-400 hover:text-indigo-600 dark:hover:text-indigo-300 flex items-center gap-1 px-2 py-1 hover:bg-indigo-50 dark:hover:bg-indigo-900/30 rounded-lg transition-colors"
+ >
+ <Book className="w-3 h-3" />
+ Add to Notebook
+ </button>
+ </div>
+ </div>
+
+ {/* Question Content */}
+ <div className="p-6 flex-1 overflow-y-auto">
+ <h3 className="text-lg font-medium text-slate-800 dark:text-slate-200 leading-relaxed mb-6 prose dark:prose-invert max-w-none">
+ <ReactMarkdown
+ remarkPlugins={[remarkMath]}
+ rehypePlugins={[rehypeKatex]}
+ >
+ {processLatexContent(
+ currentQuestion.question.question,
+ )}
+ </ReactMarkdown>
+ </h3>
+
+ {/* Options / Input Area */}
+ {(currentQuestion.question.question_type === "choice" ||
+ currentQuestion.question.type === "choice") &&
+ currentQuestion.question.options ? (
+ <div className="space-y-3">
+ {Object.entries(currentQuestion.question.options).map(
+ ([key, val]) => (
+ <button
+ key={key}
+ onClick={() => handleAnswer(key)}
+ disabled={submittedMap[activeIdx]}
+ className={`w-full text-left p-4 rounded-xl border transition-all flex items-start gap-4 prose dark:prose-invert max-w-none ${
+ userAnswers[activeIdx] === key
+ ? submittedMap[activeIdx]
+ ? key ===
+ currentQuestion.question.correct_answer
+ ? "bg-green-50 dark:bg-green-900/30 border-green-500 text-green-800 dark:text-green-200"
+ : "bg-red-50 dark:bg-red-900/30 border-red-500 text-red-800 dark:text-red-200"
+ : "bg-purple-50 dark:bg-purple-900/30 border-purple-500 text-purple-900 dark:text-purple-200 shadow-sm"
+ : submittedMap[activeIdx] &&
+ key ===
+ currentQuestion.question
+ .correct_answer
+ ? "bg-green-50 dark:bg-green-900/30 border-green-300 dark:border-green-600 text-green-800 dark:text-green-200"
+ : "bg-white dark:bg-slate-700 border-slate-200 dark:border-slate-600 hover:bg-slate-50 dark:hover:bg-slate-600 text-slate-700 dark:text-slate-200"
+ }`}
+ >
+ <span className="font-bold shrink-0 w-6">
+ {key}.
+ </span>
+ <ReactMarkdown
+ remarkPlugins={[remarkMath]}
+ rehypePlugins={[rehypeKatex]}
+ >
+ {processLatexContent(String(val))}
+ </ReactMarkdown>
+ {submittedMap[activeIdx] &&
+ key ===
+ currentQuestion.question.correct_answer && (
+ <CheckCircle2 className="w-5 h-5 text-green-600 dark:text-green-400 ml-auto shrink-0" />
+ )}
+ </button>
+ ),
+ )}
+ </div>
+ ) : (
+ <textarea
+ value={userAnswers[activeIdx] || ""}
+ onChange={(e) => handleAnswer(e.target.value)}
+ disabled={submittedMap[activeIdx]}
+ placeholder="Type your answer here..."
+ className="w-full h-48 p-4 bg-slate-50 dark:bg-slate-700 border border-slate-200 dark:border-slate-600 rounded-xl focus:border-purple-500 focus:ring-2 focus:ring-purple-500/10 outline-none resize-none text-slate-800 dark:text-slate-200 placeholder:text-slate-400 dark:placeholder:text-slate-500"
+ />
+ )}
+ </div>
+
+ {/* Submit Button Area */}
+ <div className="p-4 border-t border-slate-100 dark:border-slate-700 bg-white dark:bg-slate-800 flex gap-3">
+ {!submittedMap[activeIdx] ? (
+ <button
+ onClick={handleSubmit}
+ disabled={!userAnswers[activeIdx]}
+ className="flex-1 py-3 bg-purple-600 text-white rounded-xl font-bold shadow-lg shadow-purple-500/20 hover:bg-purple-700 disabled:opacity-50 disabled:shadow-none transition-all"
+ >
+ Submit Answer
+ </button>
+ ) : (
+ <>
+ <div className="flex-1 py-3 bg-emerald-50 dark:bg-emerald-900/30 text-emerald-700 dark:text-emerald-300 rounded-xl font-medium text-center border border-emerald-200 dark:border-emerald-800 flex items-center justify-center gap-2">
+ <CheckCircle2 className="w-4 h-4" />
+ Submitted
+ </div>
+ {activeIdx < questionState.results.length - 1 && (
+ <button
+ onClick={() => setActiveIdx(activeIdx + 1)}
+ className="flex-1 py-3 bg-purple-600 text-white rounded-xl font-bold shadow-lg shadow-purple-500/20 hover:bg-purple-700 transition-all flex items-center justify-center gap-2"
+ >
+ Next Question
+ <ChevronRight className="w-4 h-4" />
+ </button>
+ )}
+ </>
+ )}
+ </div>
+ </div>
+
+ {/* Right Side: Answer & Validation Area (shown after submit) */}
+ <div className="w-[400px] flex flex-col gap-4">
+ {/* Answer & Explanation (shown after submit) */}
+ {submittedMap[activeIdx] ? (
+ <>
+ {/* Collapsible Validation Report - only shown after submit */}
+ <div
+ className={`rounded-xl border overflow-hidden ${
+ currentQuestion.extended
+ ? "bg-amber-50 dark:bg-amber-900/30 border-amber-200 dark:border-amber-800"
+ : "bg-slate-50 dark:bg-slate-800 border-slate-200 dark:border-slate-700"
+ }`}
+ >
+ <button
+ onClick={() => setShowValidation(!showValidation)}
+ className={`w-full px-4 py-3 flex items-center justify-between text-sm font-medium transition-colors ${
+ currentQuestion.extended
+ ? "text-amber-800 dark:text-amber-300 hover:bg-amber-100 dark:hover:bg-amber-900/50"
+ : "text-slate-700 dark:text-slate-200 hover:bg-slate-100 dark:hover:bg-slate-700"
+ }`}
+ >
+ <div className="flex items-center gap-2">
+ <AlertCircle className="w-4 h-4" />
+ Validation Report
+ <span
+ className={`px-2 py-0.5 text-xs rounded-full ${
+ currentQuestion.extended
+ ? "bg-amber-200 dark:bg-amber-800 text-amber-800 dark:text-amber-200"
+ : "bg-emerald-100 dark:bg-emerald-900/50 text-emerald-700 dark:text-emerald-300"
+ }`}
+ >
+ {currentQuestion.rounds || 1} round
+ {(currentQuestion.rounds || 1) > 1 ? "s" : ""}
+ </span>
+ </div>
+ {showValidation ? (
+ <ChevronDown className="w-4 h-4" />
+ ) : (
+ <ChevronRight className="w-4 h-4" />
+ )}
+ </button>
+
+ {showValidation && (
+ <div className="px-4 pb-4 animate-in fade-in slide-in-from-top-2">
+ <div
+ className={`p-3 rounded-lg text-sm ${
+ currentQuestion.extended
+ ? "bg-amber-100/50 dark:bg-amber-900/30"
+ : "bg-white dark:bg-slate-700 border border-slate-100 dark:border-slate-600"
+ }`}
+ >
+ {/* Header with status */}
+ <div className="flex items-center gap-2 mb-3 font-semibold flex-wrap">
+ {currentQuestion.extended ? (
+ <>
+ <Zap className="w-4 h-4 text-amber-600 dark:text-amber-400" />
+ <span className="text-amber-800 dark:text-amber-300">
+ Extended Question
+ </span>
+ </>
+ ) : currentQuestion.validation?.relevance ? (
+ <>
+ <CheckCircle2 className="w-4 h-4 text-emerald-500 dark:text-emerald-400" />
+ <span className="text-emerald-700 dark:text-emerald-300">
+ Relevance:{" "}
+ {currentQuestion.validation
+ .relevance === "high"
+ ? "High"
+ : "Partial"}
+ </span>
+ <span
+ className={`px-2 py-0.5 text-xs rounded-full ${
+ currentQuestion.validation
+ .relevance === "high"
+ ? "bg-emerald-100 dark:bg-emerald-900/50 text-emerald-700 dark:text-emerald-300"
+ : "bg-amber-100 dark:bg-amber-900/50 text-amber-700 dark:text-amber-300"
+ }`}
+ >
+ {currentQuestion.validation
+ .relevance === "high"
+ ? "Fully Covered by KB"
+ : "Extends Beyond KB"}
+ </span>
+ </>
+ ) : (
+ <>
+ <CheckCircle2 className="w-4 h-4 text-emerald-500 dark:text-emerald-400" />
+ <span className="text-emerald-700 dark:text-emerald-300">
+ Validation Passed
+ </span>
+ </>
+ )}
+ </div>
+
+ {/* KB Coverage - for custom mode */}
+ {currentQuestion.validation?.kb_coverage && (
+ <div className="mb-3">
+ <p className="text-xs font-semibold text-emerald-700 dark:text-emerald-400 uppercase tracking-wider mb-1.5 flex items-center gap-1">
+ <Database className="w-3 h-3" />
+ Knowledge Base Coverage
+ </p>
+ <div className="text-slate-700 dark:text-slate-300 text-xs leading-relaxed bg-emerald-50/50 dark:bg-emerald-900/20 p-2 rounded border border-emerald-100 dark:border-emerald-800 prose prose-xs dark:prose-invert max-w-none">
+ <ReactMarkdown
+ remarkPlugins={[remarkMath]}
+ rehypePlugins={[rehypeKatex]}
+ >
+ {processLatexContent(
+ currentQuestion.validation
+ .kb_coverage,
+ )}
+ </ReactMarkdown>
+ </div>
+ </div>
+ )}
+
+ {/* Extension Points - for custom mode when relevance is partial */}
+ {currentQuestion.validation
+ ?.extension_points && (
+ <div className="mb-3">
+ <p className="text-xs font-semibold text-amber-700 dark:text-amber-400 uppercase tracking-wider mb-1.5 flex items-center gap-1">
+ <Zap className="w-3 h-3" />
+ Extension Points
+ </p>
+ <div className="text-amber-900 dark:text-amber-200 text-xs leading-relaxed bg-amber-50/50 dark:bg-amber-900/20 p-2 rounded border border-amber-100 dark:border-amber-800 prose prose-xs dark:prose-invert max-w-none">
+ <ReactMarkdown
+ remarkPlugins={[remarkMath]}
+ rehypePlugins={[rehypeKatex]}
+ >
+ {processLatexContent(
+ currentQuestion.validation
+ .extension_points,
+ )}
+ </ReactMarkdown>
+ </div>
+ </div>
+ )}
+
+ {/* KB Connection - for extended questions */}
+ {currentQuestion.extended &&
+ currentQuestion.validation?.kb_connection && (
+ <div className="mb-3">
+ <p className="text-xs font-semibold text-amber-700 dark:text-amber-400 uppercase tracking-wider mb-1.5">
+ KB Connection
+ </p>
+ <div className="text-amber-900 dark:text-amber-200 text-xs leading-relaxed prose prose-xs dark:prose-invert max-w-none">
+ <ReactMarkdown
+ remarkPlugins={[remarkMath]}
+ rehypePlugins={[rehypeKatex]}
+ >
+ {processLatexContent(
+ currentQuestion.validation
+ .kb_connection,
+ )}
+ </ReactMarkdown>
+ </div>
+ </div>
+ )}
+
+ {/* Extended Aspects - for extended questions */}
+ {currentQuestion.extended &&
+ currentQuestion.validation
+ ?.extended_aspect && (
+ <div className="mb-3">
+ <p className="text-xs font-semibold text-amber-700 dark:text-amber-400 uppercase tracking-wider mb-1.5">
+ Extended Aspects
+ </p>
+ <div className="text-amber-900 dark:text-amber-200 text-xs leading-relaxed prose prose-xs dark:prose-invert max-w-none">
+ <ReactMarkdown
+ remarkPlugins={[remarkMath]}
+ rehypePlugins={[rehypeKatex]}
+ >
+ {processLatexContent(
+ currentQuestion.validation
+ .extended_aspect,
+ )}
+ </ReactMarkdown>
+ </div>
+ </div>
+ )}
+
+ {/* Reasoning - legacy field */}
+ {currentQuestion.validation?.reasoning && (
+ <div>
+ <p className="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wider mb-1.5">
+ Reasoning
+ </p>
+ <div className="text-slate-700 dark:text-slate-300 text-xs leading-relaxed prose prose-xs dark:prose-invert max-w-none">
+ <ReactMarkdown
+ remarkPlugins={[remarkMath]}
+ rehypePlugins={[rehypeKatex]}
+ >
+ {processLatexContent(
+ currentQuestion.validation.reasoning,
+ )}
+ </ReactMarkdown>
+ </div>
+ </div>
+ )}
+ </div>
+ </div>
+ )}
+ </div>
+
+ {/* Answer & Explanation */}
+ <div className="flex-1 bg-white dark:bg-slate-800 rounded-xl border border-slate-200 dark:border-slate-700 overflow-hidden flex flex-col animate-in fade-in slide-in-from-bottom-4">
+ <div className="px-4 py-3 border-b border-slate-100 dark:border-slate-700 bg-emerald-50 dark:bg-emerald-900/30">
+ <h4 className="text-emerald-800 dark:text-emerald-300 font-semibold flex items-center gap-2">
+ <BookOpen className="w-4 h-4" />
+ Answer & Explanation
+ </h4>
+ </div>
+ <div className="p-4 flex-1 overflow-y-auto">
+ <div className="mb-4 p-3 bg-emerald-50 dark:bg-emerald-900/30 rounded-lg border border-emerald-100 dark:border-emerald-800">
+ <p className="text-xs font-semibold text-emerald-600 dark:text-emerald-400 uppercase tracking-wider mb-1">
+ Correct Answer
+ </p>
+ <div className="text-emerald-800 dark:text-emerald-200 text-base leading-relaxed [&_.katex]:text-emerald-800 dark:[&_.katex]:text-emerald-200 [&_.katex-display]:my-3 [&_.katex-display]:overflow-x-auto">
+ <ReactMarkdown
+ remarkPlugins={[remarkMath]}
+ rehypePlugins={[rehypeKatex]}
+ className="prose prose-emerald dark:prose-invert max-w-none prose-p:my-2 prose-p:leading-relaxed"
+ >
+ {processLatexContent(
+ String(
+ currentQuestion.question.correct_answer ||
+ "",
+ ),
+ )}
+ </ReactMarkdown>
+ </div>
+ </div>
+
+ <div className="prose prose-sm prose-slate dark:prose-invert max-w-none">
+ <ReactMarkdown
+ remarkPlugins={[remarkMath]}
+ rehypePlugins={[rehypeKatex]}
+ >
+ {processLatexContent(
+ currentQuestion.question.explanation,
+ )}
+ </ReactMarkdown>
+ </div>
+ </div>
+ </div>
+ </>
+ ) : (
+ <div className="flex-1 bg-slate-50 dark:bg-slate-800 rounded-xl border border-slate-200 dark:border-slate-700 flex items-center justify-center">
+ <div className="text-center text-slate-400 dark:text-slate-500 p-6">
+ <BookOpen className="w-10 h-10 mx-auto mb-3 opacity-30" />
+ <p className="text-sm font-medium">Answer Hidden</p>
+ <p className="text-xs mt-1">
+ Submit your answer to reveal
+ </p>
+ </div>
+ </div>
+ )}
+ </div>
+ </div>
+ )}
+ </div>
+ )}
+
+ {/* PROCESS TAB */}
+ {!isConfigMode && activeTab === "process" && (
+ <div className="h-full">
+ <QuestionDashboard
+ state={dashboardState}
+ globalProgress={questionState.progress}
+ globalLogs={questionState.logs}
+ globalResults={questionState.results}
+ globalTopic={questionState.topic}
+ globalDifficulty={questionState.difficulty}
+ globalType={questionState.type}
+ globalCount={questionState.count}
+ globalStep={questionState.step}
+ globalMode={
+ questionState.mode === "knowledge" ? "custom" : "mimic"
+ }
+ selectedTaskId={selectedTaskId}
+ onTaskSelect={setSelectedTaskId}
+ tokenStats={questionState.tokenStats}
+ />
+ </div>
+ )}
+ </div>
+ </div>
+
+ {/* Add to Notebook Modal */}
+ {currentQuestion && (
+ <AddToNotebookModal
+ isOpen={showNotebookModal}
+ onClose={() => setShowNotebookModal(false)}
+ recordType="question"
+ title={`${questionState.topic} - ${currentQuestion.question.type || currentQuestion.question.question_type}`}
+ userQuery={`Topic: ${questionState.topic}\nDifficulty: ${questionState.difficulty}\nType: ${questionState.type}`}
+ output={`**Question:**\n${currentQuestion.question.question}\n\n**Options:**\n${
+ currentQuestion.question.options
+ ? Object.entries(currentQuestion.question.options)
+ .map(([k, v]) => `${k}. ${v}`)
+ .join("\n")
+ : "N/A"
+ }\n\n**Correct Answer:** ${currentQuestion.question.correct_answer}\n\n**Explanation:**\n${currentQuestion.question.explanation}`}
+ metadata={{
+ difficulty: questionState.difficulty,
+ question_type: questionState.type,
+ validation_rounds: currentQuestion.rounds,
+ extended: currentQuestion.extended,
+ }}
+ kbName={questionState.selectedKb}
+ />
+ )}
+ </div>
+ );
+}
diff --git a/web/app/research/page.tsx b/web/app/research/page.tsx
new file mode 100644
index 000000000..6d30d31e7
--- /dev/null
+++ b/web/app/research/page.tsx
@@ -0,0 +1,774 @@
+"use client";
+
+import React, { useState, useEffect, useRef } from "react";
+import {
+ Settings,
+ Sparkles,
+ Play,
+ MessageSquare,
+ Send,
+ Loader2,
+ Database,
+ GraduationCap,
+ Globe,
+ FileText,
+ Book,
+ Download,
+ FileDown,
+} from "lucide-react";
+import ReactMarkdown from "react-markdown";
+import remarkGfm from "remark-gfm";
+import remarkMath from "remark-math";
+import rehypeKatex from "rehype-katex";
+import rehypeRaw from "rehype-raw";
+import "katex/dist/katex.min.css";
+import { Mermaid } from "@/components/Mermaid";
+import { useGlobal } from "@/context/GlobalContext";
+import { apiUrl, wsUrl } from "@/lib/api";
+import AddToNotebookModal from "@/components/AddToNotebookModal";
+import { exportToPdf, preprocessMarkdownForPdf } from "@/lib/pdfExport";
+import { useResearchReducer } from "@/hooks/useResearchReducer";
+import { ResearchDashboard } from "@/components/research/ResearchDashboard";
+import { ResearchEvent } from "@/types/research";
+
+interface ChatMsg {
+ id: string;
+ role: "user" | "assistant" | "system";
+ content: string;
+ type?: "topic_proposal";
+ proposal?: string;
+ original_topic?: string;
+ iteration?: number;
+ isOptimizing?: boolean;
+}
+
+export default function ResearchPage() {
+ const {
+ researchState: globalResearchState,
+ setResearchState: setGlobalResearchState,
+ } = useGlobal();
+
+ // Local Reducer State for Deep Research Dashboard
+ const [state, dispatch] = useResearchReducer();
+ const [selectedTaskId, setSelectedTaskId] = useState<string | null>(null);
+
+ // Config State
+ const [selectedKb, setSelectedKb] = useState<string>("");
+ const [kbs, setKbs] = useState<string[]>([]);
+ const [planMode, setPlanMode] = useState<string>("medium");
+ const [enabledTools, setEnabledTools] = useState<string[]>(["RAG"]);
+ const [enableOptimization, setEnableOptimization] = useState<boolean>(true);
+
+ // Chat State
+ const [chatHistory, setChatHistory] = useState<ChatMsg[]>([]);
+ const [inputTopic, setInputTopic] = useState("");
+ const [isOptimizing, setIsOptimizing] = useState(false);
+ const chatContainerRef = useRef<HTMLDivElement>(null);
+
+ // Notebook modal state
+ const [showNotebookModal, setShowNotebookModal] = useState(false);
+
+ // PDF export state
+ const [isExportingPdf, setIsExportingPdf] = useState(false);
+ // Ref for report content (hidden rendered report for PDF)
+ const reportContentRef = useRef<HTMLDivElement>(null);
+
+ // WebSocket Ref
+ const wsRef = useRef<WebSocket | null>(null);
+
+ // Initialize Knowledge Bases
+ useEffect(() => {
+ fetch(apiUrl("/api/v1/knowledge/list"))
+ .then((res) => res.json())
+ .then((data) => {
+ if (Array.isArray(data)) {
+ const names = data.map((kb: any) => kb.name);
+ setKbs(names);
+ if (!selectedKb) {
+ const defaultKb =
+ data.find((kb: any) => kb.is_default)?.name || names[0];
+ if (defaultKb) setSelectedKb(defaultKb);
+ }
+ }
+ })
+ .catch((err) => console.error("Failed to fetch KBs:", err));
+ }, []);
+
+ // Auto-scroll Chat
+ useEffect(() => {
+ if (chatContainerRef.current) {
+ chatContainerRef.current.scrollTo({
+ top: chatContainerRef.current.scrollHeight,
+ behavior: "smooth",
+ });
+ }
+ }, [chatHistory]);
+
+ // Initial Greeting
+ useEffect(() => {
+ if (chatHistory.length === 0) {
+ setChatHistory([
+ {
+ id: "welcome",
+ role: "assistant",
+ content:
+ "Welcome to Deep Research Lab. \n\nPlease configure your settings above, then enter a research topic below.",
+ },
+ ]);
+ }
+ }, []);
+
+ // Select latest active task automatically if none selected
+ useEffect(() => {
+ if (!selectedTaskId && state.activeTaskIds.length > 0) {
+ setSelectedTaskId(state.activeTaskIds[0]);
+ }
+ }, [state.activeTaskIds, selectedTaskId]);
+
+ // Start Research Function (Local)
+ const startResearchLocal = (topic: string) => {
+ if (wsRef.current) wsRef.current.close();
+
+ // Update Global State to "running" for sidebar status
+ setGlobalResearchState((prev) => ({ ...prev, status: "running", topic }));
+
+ const ws = new WebSocket(wsUrl("/api/v1/research/run"));
+ wsRef.current = ws;
+
+ ws.onopen = () => {
+ ws.send(
+ JSON.stringify({
+ topic,
+ kb_name: selectedKb,
+ plan_mode: planMode,
+ enabled_tools: enabledTools,
+ skip_rephrase: !enableOptimization, // If we already optimized, skip internal rephrase
+ }),
+ );
+ };
+
+ ws.onmessage = (event) => {
+ try {
+ const data = JSON.parse(event.data);
+
+ // Dispatch all events to reducer
+ if (data.type === "progress") {
+ // Flatten progress event to match ResearchEvent
+ const { type, ...rest } = data;
+ // Map stage/status to event type if specific type is generic
+ let eventType = data.status as string;
+ // Map known statuses to specific event types if needed or pass through
+ dispatch({
+ type: eventType as any, // dynamic mapping
+ ...rest,
+ });
+ } else if (data.type === "log") {
+ dispatch({
+ type: "log",
+ content: data.content.content || data.content, // Handle different log formats
+ });
+ } else if (data.type === "result") {
+ dispatch({
+ type: "reporting_completed",
+ word_count: data.metadata?.report_word_count || 0,
+ sections: Object.keys(data.metadata?.statistics || {}).length, // approximate
+ citations: data.metadata?.statistics?.total_tool_calls || 0,
+ report: data.report,
+ });
+ // Update Global State to "completed"
+ setGlobalResearchState((prev) => ({
+ ...prev,
+ status: "completed",
+ report: data.report,
+ }));
+ } else if (data.type === "error") {
+ dispatch({ type: "error", content: data.content });
+ setGlobalResearchState((prev) => ({ ...prev, status: "idle" }));
+ } else {
+ // Forward other events directly
+ dispatch(data as ResearchEvent);
+ }
+ } catch (e) {
+ console.error("WS Parse Error", e);
+ }
+ };
+
+ ws.onerror = (e) => {
+ console.error("WS Error", e);
+ dispatch({ type: "error", content: "WebSocket connection failed" });
+ setGlobalResearchState((prev) => ({ ...prev, status: "idle" }));
+ };
+
+ ws.onclose = () => {
+ // Optional: handle close
+ };
+ };
+
+ const handleSendMessage = async () => {
+ if (!inputTopic.trim()) return;
+ if (state.global.stage !== "idle" && state.global.stage !== "completed")
+ return;
+
+ const userMsg: ChatMsg = {
+ id: Date.now().toString(),
+ role: "user",
+ content: inputTopic,
+ };
+
+ setChatHistory((prev) => [...prev, userMsg]);
+ setInputTopic("");
+
+ if (!enableOptimization) {
+ startResearchLocal(userMsg.content);
+ return;
+ }
+
+ setIsOptimizing(true);
+ setChatHistory((prev) => [
+ ...prev,
+ {
+ id: "optimizing",
+ role: "assistant",
+ content: "Optimizing topic...",
+ isOptimizing: true,
+ },
+ ]);
+
+ try {
+ const res = await fetch(apiUrl("/api/v1/research/optimize_topic"), {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ topic: userMsg.content,
+ iteration: 0,
+ kb_name: selectedKb,
+ }),
+ });
+ const data = await res.json();
+
+ setChatHistory((prev) => prev.filter((msg) => msg.id !== "optimizing"));
+
+ if (data.error) {
+ setChatHistory((prev) => [
+ ...prev,
+ {
+ id: Date.now().toString(),
+ role: "assistant",
+ content: `Error optimizing: ${data.error}`,
+ },
+ ]);
+ } else {
+ const optimizedTopic = data.topic || userMsg.content;
+ setChatHistory((prev) => [
+ ...prev,
+ {
+ id: Date.now().toString(),
+ role: "assistant",
+ content: `I have optimized your topic:\n\n**${optimizedTopic}**\n\n${data.reasoning || ""}\n\nStart research?`,
+ type: "topic_proposal",
+ proposal: optimizedTopic,
+ original_topic: userMsg.content,
+ },
+ ]);
+ }
+ } catch (error) {
+ setChatHistory((prev) => prev.filter((msg) => msg.id !== "optimizing"));
+ setChatHistory((prev) => [
+ ...prev,
+ {
+ id: Date.now().toString(),
+ role: "assistant",
+ content: `Network error. Try again.`,
+ },
+ ]);
+ } finally {
+ setIsOptimizing(false);
+ }
+ };
+
+ // PDF Export using the new pdfExport utility
+ const handleExportPdf = async () => {
+ if (!state.reporting.generatedReport) return;
+ if (!reportContentRef.current) return;
+
+ setIsExportingPdf(true);
+ try {
+ // Wait for Mermaid diagrams and KaTeX formulas to render
+ await new Promise((resolve) => setTimeout(resolve, 2000));
+
+ // Use the new PDF export utility
+ await exportToPdf(reportContentRef.current, {
+ filename: state.planning.originalTopic || "research-report",
+ marginLeft: 20,
+ marginRight: 20,
+ marginTop: 25,
+ marginBottom: 25,
+ showPageNumbers: true,
+ scale: 2,
+ });
+ } catch (err) {
+ console.error("PDF Export failed", err);
+ } finally {
+ setIsExportingPdf(false);
+ }
+ };
+
+ return (
+ <div className="h-[calc(100vh-4rem)] animate-fade-in flex gap-6">
+ {/* LEFT PANEL */}
+ <div className="flex-[1_1_33%] min-w-[350px] max-w-[500px] flex flex-col gap-4 h-full">
+ {/* Config Header */}
+ <div className="bg-white dark:bg-slate-800 p-4 rounded-2xl shadow-sm border border-slate-200 dark:border-slate-700 flex flex-col gap-4">
+ <div className="flex items-center justify-between">
+ <h2 className="font-bold text-slate-800 dark:text-slate-100 flex items-center gap-2">
+ <Settings className="w-5 h-5 text-slate-500 dark:text-slate-400" />
+ Configuration
+ </h2>
+ <div className="flex items-center gap-2 text-xs text-slate-500 dark:text-slate-400">
+ <div
+ className={`w-2 h-2 rounded-full ${state.global.stage !== "idle" && state.global.stage !== "completed" ? "bg-emerald-500 animate-pulse" : "bg-slate-300 dark:bg-slate-600"}`}
+ />
+ {state.global.stage === "idle"
+ ? "Idle"
+ : state.global.stage === "completed"
+ ? "Completed"
+ : "Running"}
+ </div>
+ </div>
+
+ <div className="grid grid-cols-1 gap-3">
+ {/* KB Selection */}
+ <div>
+ <label className="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wider mb-1 block">
+ Knowledge Base
+ </label>
+ <select
+ value={selectedKb}
+ onChange={(e) => setSelectedKb(e.target.value)}
+ className="w-full px-3 py-2 bg-slate-50 dark:bg-slate-700 border border-slate-200 dark:border-slate-600 rounded-lg text-sm text-slate-900 dark:text-slate-100 outline-none focus:ring-2 focus:ring-emerald-500/20"
+ >
+ {kbs.length === 0 && <option value="">Loading...</option>}
+ {kbs.map((kb) => (
+ <option key={kb} value={kb}>
+ {kb}
+ </option>
+ ))}
+ </select>
+ </div>
+
+ {/* Plan Mode */}
+ <div>
+ <label className="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wider mb-1 block">
+ Plan Mode
+ </label>
+ <div className="flex bg-slate-50 dark:bg-slate-700 p-1 rounded-lg border border-slate-200 dark:border-slate-600">
+ {["quick", "medium", "deep", "auto"].map((mode) => (
+ <button
+ key={mode}
+ onClick={() => setPlanMode(mode)}
+ className={`flex-1 py-1.5 text-xs font-medium rounded-md capitalize transition-all ${
+ planMode === mode
+ ? "bg-white dark:bg-slate-600 text-emerald-700 dark:text-emerald-400 shadow-sm border border-slate-100 dark:border-slate-500"
+ : "text-slate-500 dark:text-slate-400 hover:text-slate-700 dark:hover:text-slate-300"
+ }`}
+ >
+ {mode}
+ </button>
+ ))}
+ </div>
+ </div>
+
+ {/* Tools */}
+ <div>
+ <label className="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wider mb-1 block">
+ Research Tools
+ </label>
+ <div className="flex gap-2">
+ {[
+ { key: "RAG", label: "RAG", icon: Database },
+ { key: "Paper", label: "Paper", icon: GraduationCap },
+ { key: "Web", label: "Web", icon: Globe },
+ ].map((tool) => {
+ const isSelected = enabledTools.includes(tool.key);
+ const Icon = tool.icon;
+ return (
+ <button
+ key={tool.key}
+ onClick={() => {
+ if (isSelected && enabledTools.length === 1) return;
+ setEnabledTools((prev) =>
+ isSelected
+ ? prev.filter((t) => t !== tool.key)
+ : [...prev, tool.key],
+ );
+ }}
+ className={`flex-1 flex items-center justify-center gap-1.5 py-2 px-2 rounded-lg text-xs font-medium transition-all border ${
+ isSelected
+ ? "bg-emerald-50 dark:bg-emerald-900/30 text-emerald-700 dark:text-emerald-400 border-emerald-200 dark:border-emerald-700"
+ : "bg-slate-50 dark:bg-slate-700 text-slate-500 dark:text-slate-400 border-slate-200 dark:border-slate-600"
+ }`}
+ >
+ <Icon className="w-3.5 h-3.5" />
+ {tool.label}
+ </button>
+ );
+ })}
+ </div>
+ </div>
+
+ {/* Optimization Toggle */}
+ <div className="flex items-center justify-between bg-slate-50 dark:bg-slate-700 px-3 py-2 rounded-lg border border-slate-200 dark:border-slate-600">
+ <div className="flex items-center gap-2">
+ <Sparkles
+ className={`w-4 h-4 ${enableOptimization ? "text-indigo-500 dark:text-indigo-400" : "text-slate-400 dark:text-slate-500"}`}
+ />
+ <span className="text-sm font-medium text-slate-700 dark:text-slate-200">
+ Topic Optimization
+ </span>
+ </div>
+ <button
+ onClick={() => setEnableOptimization(!enableOptimization)}
+ className={`w-10 h-5 rounded-full relative transition-colors ${enableOptimization ? "bg-indigo-500" : "bg-slate-300 dark:bg-slate-600"}`}
+ >
+ <div
+ className={`absolute top-1 w-3 h-3 bg-white rounded-full transition-transform ${enableOptimization ? "left-6" : "left-1"}`}
+ />
+ </button>
+ </div>
+ </div>
+ </div>
+
+ {/* Chat Interface */}
+ <div className="flex-1 bg-white dark:bg-slate-800 rounded-2xl shadow-sm border border-slate-200 dark:border-slate-700 flex flex-col overflow-hidden">
+ <div className="p-3 border-b border-slate-100 dark:border-slate-700 bg-slate-50/50 dark:bg-slate-800/50 text-xs font-bold text-slate-500 dark:text-slate-400 uppercase tracking-wider flex items-center gap-2">
+ <MessageSquare className="w-4 h-4" />
+ Topic Assistant
+ </div>
+ <div
+ ref={chatContainerRef}
+ className="flex-1 overflow-y-auto p-4 space-y-4 bg-slate-50/30 dark:bg-slate-800/30"
+ >
+ {chatHistory.map((msg) => (
+ <div
+ key={msg.id}
+ className={`flex flex-col ${msg.role === "user" ? "items-end" : "items-start"}`}
+ >
+ <div
+ className={`max-w-[90%] rounded-2xl px-4 py-3 text-sm ${msg.role === "user" ? "bg-indigo-100 dark:bg-indigo-900/40 text-indigo-900 dark:text-indigo-100 rounded-tr-none" : "bg-white dark:bg-slate-700 border border-slate-200 dark:border-slate-600 text-slate-700 dark:text-slate-200 rounded-tl-none shadow-sm"}`}
+ >
+ {msg.isOptimizing ? (
+ <div className="flex items-center gap-2">
+ <Loader2 className="w-4 h-4 animate-spin text-indigo-500 dark:text-indigo-400" />
+ <span>Optimizing topic...</span>
+ </div>
+ ) : (
+ <ReactMarkdown className="prose prose-sm dark:prose-invert max-w-none">
+ {msg.content}
+ </ReactMarkdown>
+ )}
+ </div>
+ {msg.type === "topic_proposal" &&
+ msg.proposal &&
+ state.global.stage === "idle" && (
+ <div className="mt-2 flex gap-2 animate-fade-in">
+ <button
+ onClick={() => startResearchLocal(msg.proposal!)}
+ className="flex items-center gap-1.5 px-3 py-1.5 bg-emerald-600 text-white text-xs font-bold rounded-full hover:bg-emerald-700 shadow-lg shadow-emerald-500/20"
+ >
+ <Play className="w-3 h-3" /> Start Research
+ </button>
+ </div>
+ )}
+ </div>
+ ))}
+ </div>
+ <div className="p-3 bg-white dark:bg-slate-800 border-t border-slate-100 dark:border-slate-700">
+ <div className="relative flex items-center gap-2">
+ <input
+ type="text"
+ value={inputTopic}
+ onChange={(e) => setInputTopic(e.target.value)}
+ onKeyDown={(e) =>
+ e.key === "Enter" && !e.shiftKey && handleSendMessage()
+ }
+ placeholder={
+ state.global.stage !== "idle" &&
+ state.global.stage !== "completed"
+ ? "Research in progress..."
+ : "Enter research topic..."
+ }
+ disabled={
+ state.global.stage !== "idle" &&
+ state.global.stage !== "completed"
+ }
+ className="flex-1 pl-4 pr-10 py-2.5 bg-slate-100 dark:bg-slate-700 border-transparent focus:bg-white dark:focus:bg-slate-600 focus:border-indigo-500 focus:ring-2 focus:ring-indigo-500/20 rounded-xl text-sm text-slate-900 dark:text-slate-100 placeholder:text-slate-400 dark:placeholder:text-slate-500 transition-all outline-none disabled:opacity-50"
+ />
+ <button
+ onClick={handleSendMessage}
+ disabled={
+ !inputTopic.trim() ||
+ (state.global.stage !== "idle" &&
+ state.global.stage !== "completed")
+ }
+ className="p-2.5 bg-indigo-600 text-white rounded-xl hover:bg-indigo-700 disabled:opacity-50"
+ >
+ {isOptimizing ? (
+ <Loader2 className="w-4 h-4 animate-spin" />
+ ) : (
+ <Send className="w-4 h-4" />
+ )}
+ </button>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ {/* RIGHT PANEL: Research Dashboard */}
+ <div className="flex-[2_1_67%] min-w-0 flex flex-col h-full overflow-hidden bg-white dark:bg-slate-800 rounded-2xl shadow-sm border border-slate-200 dark:border-slate-700 relative">
+ <ResearchDashboard
+ state={state}
+ selectedTaskId={selectedTaskId}
+ onTaskSelect={setSelectedTaskId}
+ onAddToNotebook={() => setShowNotebookModal(true)}
+ onExportMarkdown={() => {
+ const blob = new Blob([state.reporting.generatedReport || ""], {
+ type: "text/markdown",
+ });
+ const url = URL.createObjectURL(blob);
+ const a = document.createElement("a");
+ a.href = url;
+ a.download = `${state.planning.originalTopic || "report"}.md`;
+ a.click();
+ }}
+ onExportPdf={handleExportPdf}
+ isExportingPdf={isExportingPdf}
+ />
+ {/* Hidden Render Div for PDF - uses preprocessed markdown */}
+ <div
+ style={{
+ position: "absolute",
+ top: "-9999px",
+ left: "-9999px",
+ width: "800px",
+ }}
+ >
+ <div
+ ref={reportContentRef}
+ className="bg-white"
+ style={{
+ padding: "50px 40px", // More vertical padding for better page spacing
+ fontFamily: "ui-sans-serif, system-ui, sans-serif",
+ fontSize: "14px",
+ lineHeight: "1.7",
+ color: "#1e293b",
+ }}
+ >
+ <ReactMarkdown
+ remarkPlugins={[remarkGfm, remarkMath]}
+ rehypePlugins={[rehypeKatex, rehypeRaw]}
+ components={{
+ h1: ({ node, ...props }) => (
+ <h1
+ style={{
+ fontSize: "26px",
+ fontWeight: "bold",
+ marginBottom: "20px",
+ paddingBottom: "10px",
+ borderBottom: "2px solid #e2e8f0",
+ }}
+ {...props}
+ />
+ ),
+ h2: ({ node, ...props }) => (
+ <h2
+ style={{
+ fontSize: "20px",
+ fontWeight: "bold",
+ marginTop: "28px",
+ marginBottom: "14px",
+ color: "#312e81",
+ }}
+ {...props}
+ />
+ ),
+ h3: ({ node, ...props }) => (
+ <h3
+ style={{
+ fontSize: "16px",
+ fontWeight: "600",
+ marginTop: "20px",
+ marginBottom: "10px",
+ }}
+ {...props}
+ />
+ ),
+ p: ({ node, ...props }) => (
+ <p
+ style={{ marginBottom: "14px", textAlign: "justify" }}
+ {...props}
+ />
+ ),
+ table: ({ node, ...props }) => (
+ <table
+ style={{
+ width: "100%",
+ borderCollapse: "collapse",
+ margin: "18px 0",
+ fontSize: "13px",
+ }}
+ {...props}
+ />
+ ),
+ th: ({ node, ...props }) => (
+ <th
+ style={{
+ border: "1px solid #cbd5e1",
+ padding: "10px",
+ backgroundColor: "#f1f5f9",
+ fontWeight: "600",
+ textAlign: "left",
+ }}
+ {...props}
+ />
+ ),
+ td: ({ node, ...props }) => (
+ <td
+ style={{ border: "1px solid #e2e8f0", padding: "10px" }}
+ {...props}
+ />
+ ),
+ a: ({ node, href, ...props }) => (
+ <a
+ href={href}
+ style={{ color: "#4f46e5", textDecoration: "underline" }}
+ {...props}
+ />
+ ),
+ blockquote: ({ node, ...props }) => (
+ <blockquote
+ style={{
+ borderLeft: "4px solid #c7d2fe",
+ paddingLeft: "16px",
+ margin: "18px 0",
+ color: "#475569",
+ fontStyle: "italic",
+ }}
+ {...props}
+ />
+ ),
+ ul: ({ node, ...props }) => (
+ <ul
+ style={{ marginLeft: "24px", marginBottom: "14px" }}
+ {...props}
+ />
+ ),
+ ol: ({ node, ...props }) => (
+ <ol
+ style={{ marginLeft: "24px", marginBottom: "14px" }}
+ {...props}
+ />
+ ),
+ li: ({ node, ...props }) => (
+ <li style={{ marginBottom: "6px" }} {...props} />
+ ),
+ // Handle details/summary for PDF - render as expanded
+ details: ({ node, children, ...props }) => (
+ <div
+ style={{
+ marginTop: "8px",
+ marginBottom: "8px",
+ paddingLeft: "12px",
+ borderLeft: "2px solid #e2e8f0",
+ }}
+ >
+ {children}
+ </div>
+ ),
+ summary: ({ node, children, ...props }) => (
+ <div
+ style={{
+ fontWeight: "600",
+ color: "#475569",
+ marginBottom: "8px",
+ }}
+ >
+ {children}
+ </div>
+ ),
+ code: ({ node, className, children, ...props }) => {
+ const match = /language-(\w+)/.exec(className || "");
+ const language = match ? match[1] : "";
+ const isInline = !match;
+
+ // Handle Mermaid diagrams
+ if (language === "mermaid") {
+ const chartCode = String(children).replace(/\n$/, "");
+ return <Mermaid chart={chartCode} />;
+ }
+
+ return isInline ? (
+ <code
+ style={{
+ backgroundColor: "#f1f5f9",
+ padding: "2px 6px",
+ borderRadius: "4px",
+ fontSize: "13px",
+ fontFamily: "monospace",
+ }}
+ {...props}
+ >
+ {children}
+ </code>
+ ) : (
+ <code
+ style={{
+ display: "block",
+ backgroundColor: "#1e293b",
+ color: "#e2e8f0",
+ padding: "16px",
+ borderRadius: "8px",
+ fontSize: "13px",
+ fontFamily: "monospace",
+ overflowX: "auto",
+ whiteSpace: "pre",
+ }}
+ {...props}
+ >
+ {children}
+ </code>
+ );
+ },
+ pre: ({ node, children, ...props }) => {
+ const child = React.Children.toArray(
+ children,
+ )[0] as React.ReactElement;
+ if (child?.props?.className?.includes("language-mermaid")) {
+ return <>{children}</>;
+ }
+ return (
+ <pre style={{ margin: "18px 0" }} {...props}>
+ {children}
+ </pre>
+ );
+ },
+ }}
+ >
+ {preprocessMarkdownForPdf(state.reporting.generatedReport || "")}
+ </ReactMarkdown>
+ </div>
+ </div>
+ </div>
+
+ <AddToNotebookModal
+ isOpen={showNotebookModal}
+ onClose={() => setShowNotebookModal(false)}
+ recordType="research"
+ title={state.planning.originalTopic || "Research Report"}
+ userQuery={state.planning.originalTopic || ""}
+ output={state.reporting.generatedReport || ""}
+ metadata={{ plan_mode: planMode, enabled_tools: enabledTools }}
+ kbName={selectedKb}
+ />
+ </div>
+ );
+}
diff --git a/web/app/settings/page.tsx b/web/app/settings/page.tsx
new file mode 100644
index 000000000..fcf5f5619
--- /dev/null
+++ b/web/app/settings/page.tsx
@@ -0,0 +1,948 @@
+"use client";
+
+import { useState, useEffect } from "react";
+import {
+ Settings as SettingsIcon,
+ Sun,
+ Moon,
+ Globe,
+ Save,
+ RotateCcw,
+ Loader2,
+ Check,
+ Server,
+ AlertCircle,
+ Database,
+ Search,
+ MessageSquare,
+ Volume2,
+ Cpu,
+ Key,
+ Brain,
+ Eye,
+ EyeOff,
+ RefreshCw,
+ CheckCircle,
+ XCircle,
+ Info,
+ Sliders,
+} from "lucide-react";
+import { apiUrl } from "@/lib/api";
+import { getTranslation } from "@/lib/i18n";
+
+import { useGlobal } from "@/context/GlobalContext";
+
+// --- Types matching backend ---
+
+interface UISettings {
+ theme: "light" | "dark";
+ language: "zh" | "en";
+ output_language: "zh" | "en";
+}
+
+interface EnvInfo {
+ model: string;
+ [key: string]: string;
+}
+
+// Config is dynamic, but we know some structure
+interface ConfigData {
+ system?: {
+ language?: string;
+ [key: string]: any;
+ };
+ tools?: {
+ rag_tool?: {
+ kb_base_dir?: string;
+ default_kb?: string;
+ [key: string]: any;
+ };
+ run_code?: {
+ workspace?: string;
+ allowed_roots?: string[];
+ language?: string;
+ timeout?: number;
+ sandbox?: boolean;
+ [key: string]: any;
+ };
+ web_search?: {
+ enabled?: boolean;
+ max_results?: number;
+ [key: string]: any;
+ };
+ [key: string]: any;
+ };
+ logging?: {
+ level?: string;
+ [key: string]: any;
+ };
+ tts?: {
+ default_voice?: string;
+ default_language?: string;
+ [key: string]: any;
+ };
+ [key: string]: any;
+}
+
+interface FullSettingsResponse {
+ ui: UISettings;
+ config: ConfigData;
+ env: EnvInfo;
+}
+
+// Environment variable types
+interface EnvVarInfo {
+ key: string;
+ value: string;
+ description: string;
+ category: string;
+ required: boolean;
+ default: string;
+ sensitive: boolean;
+ is_set: boolean;
+}
+
+interface EnvCategoryInfo {
+ id: string;
+ name: string;
+ description: string;
+ icon: string;
+}
+
+interface EnvConfigResponse {
+ variables: EnvVarInfo[];
+ categories: EnvCategoryInfo[];
+}
+
+interface TestResults {
+ llm: { status: string; model: string | null; error: string | null };
+ embedding: { status: string; model: string | null; error: string | null };
+ tts: { status: string; model: string | null; error: string | null };
+}
+
+// Tab types
+type SettingsTab = "general" | "environment";
+
+export default function SettingsPage() {
+ const { uiSettings, refreshSettings } = useGlobal();
+ const t = (key: string) => getTranslation(uiSettings.language, key);
+ const [activeTab, setActiveTab] = useState<SettingsTab>("general");
+ const [data, setData] = useState<FullSettingsResponse | null>(null);
+ const [loading, setLoading] = useState(true);
+ const [saving, setSaving] = useState(false);
+ const [saveSuccess, setSaveSuccess] = useState(false);
+ const [error, setError] = useState("");
+
+ // Edit states
+ const [editedConfig, setEditedConfig] = useState<ConfigData | null>(null);
+ const [editedUI, setEditedUI] = useState<UISettings | null>(null);
+
+ // Environment variables states
+ const [envConfig, setEnvConfig] = useState<EnvConfigResponse | null>(null);
+ const [editedEnvVars, setEditedEnvVars] = useState<Record<string, string>>(
+ {},
+ );
+ const [showSensitive, setShowSensitive] = useState<Record<string, boolean>>(
+ {},
+ );
+ const [envSaving, setEnvSaving] = useState(false);
+ const [envSaveSuccess, setEnvSaveSuccess] = useState(false);
+ const [envError, setEnvError] = useState("");
+ const [testResults, setTestResults] = useState<TestResults | null>(null);
+ const [testing, setTesting] = useState(false);
+
+ useEffect(() => {
+ fetchSettings();
+ fetchEnvConfig();
+ }, [uiSettings]);
+
+ const fetchSettings = async () => {
+ try {
+ const res = await fetch(apiUrl("/api/v1/settings"));
+ if (res.ok) {
+ const responseData = await res.json();
+ setData(responseData);
+ setEditedConfig(JSON.parse(JSON.stringify(responseData.config)));
+ if (!editedUI) {
+ setEditedUI(JSON.parse(JSON.stringify(responseData.ui)));
+ }
+ if (responseData.ui.theme) {
+ applyTheme(responseData.ui.theme);
+ }
+ } else {
+ setError("Failed to load settings");
+ }
+ } catch (err) {
+ setError("Failed to connect to backend");
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ const fetchEnvConfig = async () => {
+ try {
+ const res = await fetch(apiUrl("/api/v1/settings/env"));
+ if (res.ok) {
+ const responseData: EnvConfigResponse = await res.json();
+ setEnvConfig(responseData);
+ const initialValues: Record<string, string> = {};
+ responseData.variables.forEach((v) => {
+ initialValues[v.key] = v.value;
+ });
+ setEditedEnvVars(initialValues);
+ // Auto test on load
+ testEnvConfig();
+ }
+ } catch (err) {
+ console.error("Failed to fetch env config:", err);
+ }
+ };
+
+ const handleEnvVarChange = (key: string, value: string) => {
+ setEditedEnvVars((prev) => ({ ...prev, [key]: value }));
+ };
+
+ const toggleSensitiveVisibility = (key: string) => {
+ setShowSensitive((prev) => ({ ...prev, [key]: !prev[key] }));
+ };
+
+ const handleEnvSave = async () => {
+ setEnvSaving(true);
+ setEnvSaveSuccess(false);
+ setEnvError("");
+
+ try {
+ const updates = Object.entries(editedEnvVars)
+ .filter(([key, value]) => {
+ const original = envConfig?.variables.find((v) => v.key === key);
+ if (
+ original?.sensitive &&
+ value.includes("*") &&
+ value === original.value
+ ) {
+ return false;
+ }
+ return true;
+ })
+ .map(([key, value]) => ({ key, value }));
+
+ const res = await fetch(apiUrl("/api/v1/settings/env"), {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ variables: updates }),
+ });
+
+ if (!res.ok) {
+ const errorData = await res.json();
+ throw new Error(
+ errorData.detail?.errors?.join(", ") || "Failed to save",
+ );
+ }
+
+ setEnvSaveSuccess(true);
+ setTimeout(() => setEnvSaveSuccess(false), 2000);
+
+ await fetchEnvConfig();
+ await testEnvConfig();
+ } catch (err: any) {
+ setEnvError(err.message || "Failed to save environment variables");
+ } finally {
+ setEnvSaving(false);
+ }
+ };
+
+ const testEnvConfig = async () => {
+ setTesting(true);
+ try {
+ const res = await fetch(apiUrl("/api/v1/settings/env/test"), {
+ method: "POST",
+ });
+ if (res.ok) {
+ const results = await res.json();
+ setTestResults(results);
+ }
+ } catch (err) {
+ console.error("Failed to test env config:", err);
+ } finally {
+ setTesting(false);
+ }
+ };
+
+ const getCategoryIcon = (iconName: string) => {
+ switch (iconName) {
+ case "brain":
+ return <Brain className="w-4 h-4" />;
+ case "database":
+ return <Database className="w-4 h-4" />;
+ case "volume":
+ return <Volume2 className="w-4 h-4" />;
+ case "search":
+ return <Search className="w-4 h-4" />;
+ case "settings":
+ return <SettingsIcon className="w-4 h-4" />;
+ default:
+ return <Key className="w-4 h-4" />;
+ }
+ };
+
+ const getStatusIcon = (status: string) => {
+ switch (status) {
+ case "configured":
+ return <CheckCircle className="w-4 h-4 text-green-500" />;
+ case "not_configured":
+ return <XCircle className="w-4 h-4 text-amber-500" />;
+ case "error":
+ return <AlertCircle className="w-4 h-4 text-red-500" />;
+ default:
+ return <Info className="w-4 h-4 text-slate-400" />;
+ }
+ };
+
+ const applyTheme = (theme: "light" | "dark") => {
+ if (theme === "dark") {
+ document.documentElement.classList.add("dark");
+ } else {
+ document.documentElement.classList.remove("dark");
+ }
+ };
+
+ const handleSave = async () => {
+ if (!editedConfig || !editedUI) return;
+ setSaving(true);
+ setSaveSuccess(false);
+ setError("");
+
+ try {
+ const configRes = await fetch(apiUrl("/api/v1/settings/config"), {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ config: editedConfig }),
+ });
+
+ if (!configRes.ok) throw new Error("Failed to save configuration");
+
+ const uiRes = await fetch(apiUrl("/api/v1/settings/ui"), {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(editedUI),
+ });
+
+ if (!uiRes.ok) throw new Error("Failed to save UI settings");
+
+ const newConfig = await configRes.json();
+ const newUI = await uiRes.json();
+
+ setData((prev) =>
+ prev ? { ...prev, config: newConfig, ui: newUI } : null,
+ );
+
+ await refreshSettings();
+
+ setSaveSuccess(true);
+ setTimeout(() => setSaveSuccess(false), 2000);
+ } catch (err: any) {
+ setError(err.message || "Failed to save settings");
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ const handleConfigChange = (
+ section: string,
+ key: string,
+ value: any,
+ subSection?: string,
+ ) => {
+ setEditedConfig((prev) => {
+ if (!prev) return null;
+ const newConfig = { ...prev };
+
+ if (subSection) {
+ if (!newConfig[section]) newConfig[section] = {};
+ if (!newConfig[section][subSection])
+ newConfig[section][subSection] = {};
+ newConfig[section][subSection][key] = value;
+ } else {
+ if (!newConfig[section]) newConfig[section] = {};
+ newConfig[section][key] = value;
+ }
+ return newConfig;
+ });
+ };
+
+ const handleUIChange = (key: keyof UISettings, value: any) => {
+ setEditedUI((prev) => {
+ if (!prev) return null;
+ const newUI = { ...prev, [key]: value };
+ if (key === "theme") applyTheme(value);
+ return newUI;
+ });
+ };
+
+ if (loading) {
+ return (
+ <div className="h-[calc(100vh-4rem)] flex items-center justify-center">
+ <Loader2 className="w-8 h-8 animate-spin text-blue-600 dark:text-blue-400" />
+ </div>
+ );
+ }
+
+ if (!editedConfig || !editedUI)
+ return (
+ <div className="p-8 text-red-500 dark:text-red-400">
+ Error loading data
+ </div>
+ );
+
+ return (
+ <div className="h-[calc(100vh-4rem)] overflow-y-auto animate-fade-in">
+ <div className="max-w-4xl mx-auto p-8">
+ {/* Header */}
+ <div className="flex items-center justify-between mb-6">
+ <div>
+ <h1 className="text-2xl font-bold text-slate-900 dark:text-slate-100 flex items-center gap-3">
+ <div className="p-2 bg-blue-50 dark:bg-blue-900/30 rounded-xl">
+ <SettingsIcon className="w-6 h-6 text-blue-600 dark:text-blue-400" />
+ </div>
+ {t("System Settings")}
+ </h1>
+ <p className="text-slate-500 dark:text-slate-400 mt-2 ml-1">
+ {t("Manage system configuration and preferences")}
+ </p>
+ </div>
+ </div>
+
+ {/* Tab Navigation */}
+ <div className="flex items-center gap-1 p-1 bg-slate-100 dark:bg-slate-800 rounded-xl mb-6">
+ <button
+ onClick={() => setActiveTab("general")}
+ className={`flex-1 flex items-center justify-center gap-2 px-4 py-2.5 rounded-lg text-sm font-medium transition-all ${
+ activeTab === "general"
+ ? "bg-white dark:bg-slate-700 text-blue-600 dark:text-blue-400 shadow-sm"
+ : "text-slate-600 dark:text-slate-400 hover:text-slate-900 dark:hover:text-slate-200"
+ }`}
+ >
+ <Sliders className="w-4 h-4" />
+ {t("General Settings")}
+ </button>
+ <button
+ onClick={() => setActiveTab("environment")}
+ className={`flex-1 flex items-center justify-center gap-2 px-4 py-2.5 rounded-lg text-sm font-medium transition-all ${
+ activeTab === "environment"
+ ? "bg-white dark:bg-slate-700 text-blue-600 dark:text-blue-400 shadow-sm"
+ : "text-slate-600 dark:text-slate-400 hover:text-slate-900 dark:hover:text-slate-200"
+ }`}
+ >
+ <Key className="w-4 h-4" />
+ {t("Environment Variables")}
+ {testResults && (
+ <span
+ className={`ml-1 w-2 h-2 rounded-full ${
+ Object.values(testResults).every(
+ (r) => r.status === "configured",
+ )
+ ? "bg-green-500"
+ : Object.values(testResults).some(
+ (r) => r.status === "error",
+ )
+ ? "bg-red-500"
+ : "bg-amber-500"
+ }`}
+ />
+ )}
+ </button>
+ </div>
+
+ {error && (
+ <div className="mb-6 p-4 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-xl flex items-center gap-3 text-red-700 dark:text-red-400 font-medium">
+ <AlertCircle className="w-5 h-5" />
+ <span>{error}</span>
+ </div>
+ )}
+
+ {/* General Settings Tab */}
+ {activeTab === "general" && (
+ <div className="space-y-6">
+ {/* 1. Interface Settings (UI) */}
+ <section className="bg-white dark:bg-slate-800 rounded-2xl shadow-sm border border-slate-200 dark:border-slate-700 overflow-hidden transition-colors duration-200">
+ <div className="p-4 border-b border-slate-100 dark:border-slate-700 bg-slate-50/50 dark:bg-slate-800/50 flex items-center gap-2">
+ <Globe className="w-4 h-4 text-slate-500 dark:text-slate-400" />
+ <h2 className="font-semibold text-slate-900 dark:text-slate-100">
+ {t("Interface Preferences")}
+ </h2>
+ </div>
+ <div className="p-6 grid grid-cols-1 md:grid-cols-2 gap-8">
+ {/* Theme Mode */}
+ <div>
+ <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-3">
+ {t("Theme")}
+ </label>
+ <div className="flex bg-slate-100 dark:bg-slate-700 p-1 rounded-xl">
+ {["light", "dark"].map((themeOption) => (
+ <button
+ key={themeOption}
+ onClick={() => handleUIChange("theme", themeOption as any)}
+ className={`flex-1 py-2 px-4 rounded-lg text-sm font-medium flex items-center justify-center gap-2 transition-all ${
+ editedUI.theme === themeOption
+ ? "bg-white dark:bg-slate-600 text-blue-600 dark:text-blue-400 shadow-sm"
+ : "text-slate-500 dark:text-slate-400 hover:text-slate-700 dark:hover:text-slate-200"
+ }`}
+ >
+ {themeOption === "light" ? (
+ <Sun className="w-4 h-4" />
+ ) : (
+ <Moon className="w-4 h-4" />
+ )}
+ <span>{themeOption === "light" ? t("Light Mode") : t("Dark Mode")}</span>
+ </button>
+ ))}
+ </div>
+ </div>
+
+ {/* Interface Language */}
+ <div>
+ <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-3">
+ {t("Language")}
+ </label>
+ <select
+ value={editedUI.language}
+ onChange={(e) => handleUIChange("language", e.target.value)}
+ className="w-full p-2.5 bg-white dark:bg-slate-700 border border-slate-200 dark:border-slate-600 rounded-xl text-sm text-slate-900 dark:text-slate-100 focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 outline-none"
+ >
+ <option value="en">{t("English")}</option>
+ <option value="zh">{t("Chinese")}</option>
+ </select>
+ </div>
+ </div>
+ </section>
+
+ {/* 2. System Configuration */}
+ <section className="bg-white dark:bg-slate-800 rounded-2xl shadow-sm border border-slate-200 dark:border-slate-700 overflow-hidden transition-colors duration-200">
+ <div className="p-4 border-b border-slate-100 dark:border-slate-700 bg-slate-50/50 dark:bg-slate-800/50 flex items-center gap-2">
+ <Server className="w-4 h-4 text-slate-500 dark:text-slate-400" />
+ <h2 className="font-semibold text-slate-900 dark:text-slate-100">
+ {t("System Configuration")}
+ </h2>
+ </div>
+ <div className="p-6 space-y-6">
+ <div>
+ <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">
+ {t("System Language")}
+ </label>
+ <p className="text-xs text-slate-400 dark:text-slate-500 mb-3">
+ {t("Default language for system operations")}
+ </p>
+ <select
+ value={editedConfig.system?.language || "en"}
+ onChange={(e) =>
+ handleConfigChange("system", "language", e.target.value)
+ }
+ className="w-full md:w-1/2 p-2.5 bg-white dark:bg-slate-700 border border-slate-200 dark:border-slate-600 rounded-xl text-sm text-slate-900 dark:text-slate-100 focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 outline-none"
+ >
+ <option value="en">English</option>
+ <option value="zh">Chinese</option>
+ </select>
+ </div>
+ </div>
+ </section>
+
+ {/* 3. Research Tools */}
+ <section className="bg-white dark:bg-slate-800 rounded-2xl shadow-sm border border-slate-200 dark:border-slate-700 overflow-hidden transition-colors duration-200">
+ <div className="p-4 border-b border-slate-100 dark:border-slate-700 bg-slate-50/50 dark:bg-slate-800/50 flex items-center gap-2">
+ <Search className="w-4 h-4 text-slate-500 dark:text-slate-400" />
+ <h2 className="font-semibold text-slate-900 dark:text-slate-100">
+ {t("Research Tools")}
+ </h2>
+ </div>
+ <div className="p-6 grid grid-cols-1 md:grid-cols-2 gap-8">
+ {/* Web Search */}
+ <div className="p-5 bg-slate-50 dark:bg-slate-700/50 rounded-xl border border-slate-100 dark:border-slate-600">
+ <div className="flex items-center justify-between mb-4">
+ <span className="font-medium text-slate-800 dark:text-slate-200 flex items-center gap-2">
+ <Globe className="w-4 h-4 text-blue-500 dark:text-blue-400" />{" "}
+ {t("Web Search")}
+ </span>
+ <div className="relative inline-flex items-center cursor-pointer">
+ <input
+ type="checkbox"
+ checked={
+ editedConfig.tools?.web_search?.enabled ?? true
+ }
+ onChange={(e) =>
+ handleConfigChange(
+ "tools",
+ "enabled",
+ e.target.checked,
+ "web_search",
+ )
+ }
+ className="sr-only peer"
+ />
+ <div className="w-11 h-6 bg-slate-200 dark:bg-slate-600 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-100 dark:peer-focus:ring-blue-900 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 dark:after:border-slate-500 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600"></div>
+ </div>
+ </div>
+ <div>
+ <label className="block text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wider mb-2">
+ {t("Max Results")}
+ </label>
+ <input
+ type="number"
+ min="1"
+ max="20"
+ value={editedConfig.tools?.web_search?.max_results || 5}
+ onChange={(e) =>
+ handleConfigChange(
+ "tools",
+ "max_results",
+ parseInt(e.target.value),
+ "web_search",
+ )
+ }
+ className="w-full p-2 bg-white dark:bg-slate-700 border border-slate-200 dark:border-slate-600 rounded-lg text-sm text-slate-900 dark:text-slate-100"
+ />
+ </div>
+ </div>
+
+ {/* RAG / Knowledge Base */}
+ <div className="p-5 bg-slate-50 dark:bg-slate-700/50 rounded-xl border border-slate-100 dark:border-slate-600">
+ <div className="flex items-center justify-between mb-4">
+ <span className="font-medium text-slate-800 dark:text-slate-200 flex items-center gap-2">
+ <Database className="w-4 h-4 text-purple-500 dark:text-purple-400" />{" "}
+ {t("Knowledge Base")}
+ </span>
+ </div>
+ <div className="space-y-4">
+ <div>
+ <label className="block text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wider mb-2">
+ {t("Default KB")}
+ </label>
+ <input
+ type="text"
+ value={editedConfig.tools?.rag_tool?.default_kb || ""}
+ onChange={(e) =>
+ handleConfigChange(
+ "tools",
+ "default_kb",
+ e.target.value,
+ "rag_tool",
+ )
+ }
+ className="w-full p-2 bg-white dark:bg-slate-700 border border-slate-200 dark:border-slate-600 rounded-lg text-sm text-slate-900 dark:text-slate-100"
+ />
+ </div>
+ <div>
+ <label className="block text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wider mb-2">
+ {t("Base Directory")}
+ </label>
+ <input
+ type="text"
+ value={editedConfig.tools?.rag_tool?.kb_base_dir || ""}
+ onChange={(e) =>
+ handleConfigChange(
+ "tools",
+ "kb_base_dir",
+ e.target.value,
+ "rag_tool",
+ )
+ }
+ className="w-full p-2 bg-white dark:bg-slate-700 border border-slate-200 dark:border-slate-600 rounded-lg text-sm font-mono text-slate-600 dark:text-slate-300"
+ />
+ </div>
+ </div>
+ </div>
+ </div>
+ </section>
+
+ {/* 4. TTS Settings */}
+ <section className="bg-white dark:bg-slate-800 rounded-2xl shadow-sm border border-slate-200 dark:border-slate-700 overflow-hidden transition-colors duration-200">
+ <div className="p-4 border-b border-slate-100 dark:border-slate-700 bg-slate-50/50 dark:bg-slate-800/50 flex items-center gap-2">
+ <Volume2 className="w-4 h-4 text-slate-500 dark:text-slate-400" />
+ <h2 className="font-semibold text-slate-900 dark:text-slate-100">
+ {t("Text-to-Speech")}
+ </h2>
+ </div>
+ <div className="p-6 grid grid-cols-1 md:grid-cols-2 gap-8">
+ <div>
+ <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">
+ {t("Default Voice")}
+ </label>
+ <input
+ type="text"
+ value={editedConfig.tts?.default_voice || "Cherry"}
+ onChange={(e) =>
+ handleConfigChange("tts", "default_voice", e.target.value)
+ }
+ className="w-full p-2.5 bg-white dark:bg-slate-700 border border-slate-200 dark:border-slate-600 rounded-xl text-sm text-slate-900 dark:text-slate-100"
+ />
+ </div>
+ <div>
+ <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">
+ {t("Default Language")}
+ </label>
+ <input
+ type="text"
+ value={editedConfig.tts?.default_language || "English"}
+ onChange={(e) =>
+ handleConfigChange(
+ "tts",
+ "default_language",
+ e.target.value,
+ )
+ }
+ className="w-full p-2.5 bg-white dark:bg-slate-700 border border-slate-200 dark:border-slate-600 rounded-xl text-sm text-slate-900 dark:text-slate-100"
+ />
+ </div>
+ </div>
+ </section>
+
+ {/* Active Models Status */}
+ {data?.env && (
+ <section className="bg-white dark:bg-slate-800 rounded-2xl shadow-sm border border-slate-200 dark:border-slate-700 overflow-hidden transition-colors duration-200">
+ <div className="p-4 border-b border-slate-100 dark:border-slate-700 bg-slate-50/50 dark:bg-slate-800/50 flex items-center justify-between">
+ <div className="flex items-center gap-2">
+ <Cpu className="w-4 h-4 text-slate-500 dark:text-slate-400" />
+ <h2 className="font-semibold text-slate-900 dark:text-slate-100">
+ {t("Active Models")}
+ </h2>
+ </div>
+ <span className="text-xs bg-slate-200 dark:bg-slate-600 text-slate-600 dark:text-slate-300 px-2 py-1 rounded">
+ {t("Status")}
+ </span>
+ </div>
+ <div className="p-6">
+ <div className="flex items-center p-4 bg-emerald-50 dark:bg-emerald-900/20 rounded-xl border border-emerald-100 dark:border-emerald-800">
+ <div className="p-3 bg-white dark:bg-slate-700 rounded-full shadow-sm mr-4">
+ <Server className="w-6 h-6 text-emerald-600 dark:text-emerald-400" />
+ </div>
+ <div>
+ <p className="text-sm text-emerald-800 dark:text-emerald-300 font-medium mb-1">
+ {t("Active LLM Model")}
+ </p>
+ <p className="text-lg font-bold text-emerald-900 dark:text-emerald-200 font-mono">
+ {data.env.model || t("Not configured")}
+ </p>
+ <p className="text-xs text-emerald-600 dark:text-emerald-400 mt-1">
+ {t("Configure in Environment Variables tab")}
+ </p>
+ </div>
+ </div>
+ </div>
+ </section>
+ )}
+
+ {/* Save Button */}
+ <div className="flex justify-center pt-4 pb-8">
+ <button
+ onClick={handleSave}
+ disabled={saving}
+ className={`w-full max-w-sm py-4 rounded-xl font-bold text-lg flex items-center justify-center gap-3 transition-all ${
+ saving
+ ? "bg-slate-100 dark:bg-slate-700 text-slate-400 dark:text-slate-500"
+ : saveSuccess
+ ? "bg-green-500 text-white shadow-xl shadow-green-500/30 scale-105"
+ : "bg-gradient-to-r from-blue-600 to-indigo-600 text-white hover:shadow-xl hover:shadow-blue-500/30 hover:-translate-y-1"
+ }`}
+ >
+ {saving ? (
+ <Loader2 className="w-6 h-6 animate-spin" />
+ ) : saveSuccess ? (
+ <Check className="w-6 h-6" />
+ ) : (
+ <Save className="w-6 h-6" />
+ )}
+ {saveSuccess ? t("Configuration Saved") : t("Save All Changes")}
+ </button>
+ </div>
+ </div>
+ )}
+
+ {/* Environment Variables Tab */}
+ {activeTab === "environment" && envConfig && (
+ <div className="space-y-6">
+ {/* Status Overview */}
+ <section className="bg-white dark:bg-slate-800 rounded-2xl shadow-sm border border-slate-200 dark:border-slate-700 overflow-hidden transition-colors duration-200">
+ <div className="p-4 border-b border-slate-100 dark:border-slate-700 bg-slate-50/50 dark:bg-slate-800/50 flex items-center justify-between">
+ <div className="flex items-center gap-2">
+ <Cpu className="w-4 h-4 text-slate-500 dark:text-slate-400" />
+ <h2 className="font-semibold text-slate-900 dark:text-slate-100">
+ {t("Configuration Status")}
+ </h2>
+ </div>
+ <button
+ onClick={testEnvConfig}
+ disabled={testing}
+ className="px-3 py-1.5 text-xs font-medium text-slate-600 dark:text-slate-300 bg-slate-100 dark:bg-slate-700 hover:bg-slate-200 dark:hover:bg-slate-600 rounded-lg flex items-center gap-1.5 transition-colors"
+ >
+ {testing ? (
+ <Loader2 className="w-3.5 h-3.5 animate-spin" />
+ ) : (
+ <RefreshCw className="w-3.5 h-3.5" />
+ )}
+ {t("Refresh Status")}
+ </button>
+ </div>
+
+ <div className="p-6">
+ {/* Info Banner */}
+ <div className="mb-4 p-3 bg-blue-50 dark:bg-blue-900/20 border border-blue-100 dark:border-blue-800 rounded-lg text-xs text-blue-700 dark:text-blue-300 flex items-start gap-2">
+ <Info className="w-4 h-4 mt-0.5 flex-shrink-0" />
+ <div>
+ <p className="font-medium mb-1">{t("Runtime Configuration")}</p>
+ <p className="text-blue-600 dark:text-blue-400">
+ {t("Environment variables are loaded from")}{" "}
+ <code className="bg-blue-100 dark:bg-blue-800 px-1 rounded">
+ .env
+ </code>{" "}
+ {t("file on startup")}. {t("Changes made here take effect immediately but are not saved to file")}. {t("On restart, values will be reloaded from")} .env.
+ </p>
+ </div>
+ </div>
+
+ {/* Test Results */}
+ {testResults && (
+ <div className="grid grid-cols-3 gap-3">
+ {Object.entries(testResults).map(([key, result]) => (
+ <div
+ key={key}
+ className={`p-4 rounded-xl border ${
+ result.status === "configured"
+ ? "bg-green-50 dark:bg-green-900/20 border-green-200 dark:border-green-800"
+ : result.status === "not_configured"
+ ? "bg-amber-50 dark:bg-amber-900/20 border-amber-200 dark:border-amber-800"
+ : "bg-red-50 dark:bg-red-900/20 border-red-200 dark:border-red-800"
+ }`}
+ >
+ <div className="flex items-center gap-2 mb-2">
+ {getStatusIcon(result.status)}
+ <span className="text-sm font-semibold uppercase text-slate-700 dark:text-slate-200">
+ {key}
+ </span>
+ </div>
+ <p className="text-xs text-slate-600 dark:text-slate-400 truncate font-mono">
+ {result.model || result.error || "Not configured"}
+ </p>
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ </section>
+
+ {/* Environment Variables by Category */}
+ {envConfig.categories.map((category) => {
+ const categoryVars = envConfig.variables.filter(
+ (v) => v.category === category.id,
+ );
+ if (categoryVars.length === 0) return null;
+
+ return (
+ <section
+ key={category.id}
+ className="bg-white dark:bg-slate-800 rounded-2xl shadow-sm border border-slate-200 dark:border-slate-700 overflow-hidden transition-colors duration-200"
+ >
+ <div className="p-4 border-b border-slate-100 dark:border-slate-700 bg-slate-50/50 dark:bg-slate-800/50 flex items-center gap-2">
+ <div className="text-blue-500 dark:text-blue-400">
+ {getCategoryIcon(category.icon)}
+ </div>
+ <div>
+ <h2 className="font-semibold text-slate-900 dark:text-slate-100">
+ {category.name}
+ </h2>
+ <p className="text-xs text-slate-500 dark:text-slate-400">
+ {category.description}
+ </p>
+ </div>
+ </div>
+
+ <div className="p-6 space-y-5">
+ {categoryVars.map((envVar) => (
+ <div key={envVar.key} className="space-y-2">
+ <div className="flex items-center justify-between">
+ <label className="text-sm font-medium text-slate-700 dark:text-slate-300 flex items-center gap-2">
+ <code className="bg-slate-100 dark:bg-slate-700 px-2 py-0.5 rounded text-slate-800 dark:text-slate-200 text-xs">
+ {envVar.key}
+ </code>
+ {envVar.required && (
+ <span className="text-red-500 text-[10px] font-semibold">
+ REQUIRED
+ </span>
+ )}
+ {envVar.is_set && (
+ <CheckCircle className="w-3.5 h-3.5 text-green-500" />
+ )}
+ </label>
+ {envVar.sensitive && (
+ <button
+ onClick={() =>
+ toggleSensitiveVisibility(envVar.key)
+ }
+ className="text-slate-400 hover:text-slate-600 dark:hover:text-slate-300 p-1"
+ >
+ {showSensitive[envVar.key] ? (
+ <EyeOff className="w-4 h-4" />
+ ) : (
+ <Eye className="w-4 h-4" />
+ )}
+ </button>
+ )}
+ </div>
+ <p className="text-xs text-slate-500 dark:text-slate-400">
+ {envVar.description}
+ </p>
+ <input
+ type={
+ envVar.sensitive && !showSensitive[envVar.key]
+ ? "password"
+ : "text"
+ }
+ value={editedEnvVars[envVar.key] || ""}
+ onChange={(e) =>
+ handleEnvVarChange(envVar.key, e.target.value)
+ }
+ placeholder={envVar.default || `Enter ${envVar.key}`}
+ className="w-full p-3 bg-white dark:bg-slate-700 border border-slate-200 dark:border-slate-600 rounded-xl text-sm text-slate-900 dark:text-slate-100 font-mono placeholder:text-slate-300 dark:placeholder:text-slate-500 focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 outline-none"
+ />
+ </div>
+ ))}
+ </div>
+ </section>
+ );
+ })}
+
+ {/* Save Environment Variables */}
+ <div className="pt-4 pb-8">
+ {envError && (
+ <div className="mb-4 p-3 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg flex items-center gap-2 text-red-700 dark:text-red-400 text-sm">
+ <AlertCircle className="w-4 h-4" />
+ <span>{envError}</span>
+ </div>
+ )}
+ <button
+ onClick={handleEnvSave}
+ disabled={envSaving}
+ className={`w-full py-4 rounded-xl font-bold text-lg flex items-center justify-center gap-3 transition-all ${
+ envSaving
+ ? "bg-slate-100 dark:bg-slate-700 text-slate-400 dark:text-slate-500"
+ : envSaveSuccess
+ ? "bg-green-500 text-white shadow-xl shadow-green-500/30 scale-[1.02]"
+ : "bg-gradient-to-r from-amber-500 to-orange-500 text-white hover:shadow-xl hover:shadow-orange-500/30 hover:-translate-y-1"
+ }`}
+ >
+ {envSaving ? (
+ <Loader2 className="w-6 h-6 animate-spin" />
+ ) : envSaveSuccess ? (
+ <Check className="w-6 h-6" />
+ ) : (
+ <Key className="w-6 h-6" />
+ )}
+ {envSaveSuccess
+ ? t("Environment Updated!")
+ : t("Apply Environment Changes")}
+ </button>
+ </div>
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/web/app/solver/page.tsx b/web/app/solver/page.tsx
new file mode 100644
index 000000000..96add5cb8
--- /dev/null
+++ b/web/app/solver/page.tsx
@@ -0,0 +1,889 @@
+"use client";
+
+import { useState, useEffect, useRef } from "react";
+import {
+ Send,
+ Loader2,
+ Terminal,
+ Bot,
+ User,
+ CheckCircle2,
+ Book,
+ Activity,
+ Cpu,
+ DollarSign,
+ Search,
+ Sparkles,
+ FileText,
+} from "lucide-react";
+import ReactMarkdown from "react-markdown";
+import remarkMath from "remark-math";
+import rehypeKatex from "rehype-katex";
+import "katex/dist/katex.min.css";
+import { useGlobal } from "@/context/GlobalContext";
+import { API_BASE_URL, apiUrl } from "@/lib/api";
+import { processLatexContent } from "@/lib/latex";
+import AddToNotebookModal from "@/components/AddToNotebookModal";
+
+const resolveArtifactUrl = (url?: string | null, outputDir?: string) => {
+ if (!url) return "";
+
+ // Already absolute http/https URL
+ if (/^https?:\/\//i.test(url)) {
+ return url;
+ }
+
+ const normalized = url.replace(/^\.\//, "");
+
+ // Backend already rewrote to /api/outputs/solve/...
+ if (normalized.startsWith("/api/outputs/")) {
+ return `${API_BASE_URL}${normalized}`;
+ }
+
+ if (normalized.startsWith("api/outputs/")) {
+ return `${API_BASE_URL}/${normalized}`;
+ }
+
+ if (normalized.startsWith("artifacts/") && outputDir) {
+ return `${API_BASE_URL}/api/outputs/solve/${outputDir}/${normalized}`;
+ }
+
+ return url;
+};
+
+export default function SolverPage() {
+ const { solverState, setSolverState, startSolver } = useGlobal();
+
+ // Local state for input
+ const [inputQuestion, setInputQuestion] = useState("");
+ const [kbs, setKbs] = useState<string[]>([]);
+ const logContainerRef = useRef<HTMLDivElement>(null);
+ const chatEndRef = useRef<HTMLDivElement>(null);
+ const chatContainerRef = useRef<HTMLDivElement>(null);
+ const prevLogsLengthRef = useRef<number>(0);
+ const prevMessagesLengthRef = useRef<number>(0);
+ const prevIsSolvingForLogsRef = useRef<boolean>(false);
+ const prevIsSolvingForChatRef = useRef<boolean>(false);
+
+ // Notebook modal state
+ const [showNotebookModal, setShowNotebookModal] = useState(false);
+ const [notebookRecord, setNotebookRecord] = useState<{
+ title: string;
+ userQuery: string;
+ output: string;
+ } | null>(null);
+
+ useEffect(() => {
+ // Fetch knowledge bases on mount only
+ fetch(apiUrl("/api/v1/knowledge/list"))
+ .then((res) => res.json())
+ .then((data) => {
+ const names = data.map((kb: any) => kb.name);
+ setKbs(names);
+ if (!solverState.selectedKb) {
+ const defaultKb = data.find((kb: any) => kb.is_default)?.name;
+ if (defaultKb)
+ setSolverState((prev) => ({ ...prev, selectedKb: defaultKb }));
+ else if (names.length > 0)
+ setSolverState((prev) => ({ ...prev, selectedKb: names[0] }));
+ }
+ })
+ .catch((err) => console.error("Failed to fetch KBs:", err));
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
+
+ // Auto-scroll logs (only when solving and new logs are added)
+ useEffect(() => {
+ const isSolvingChanged =
+ prevIsSolvingForLogsRef.current !== solverState.isSolving;
+
+ // Reset counter when starting a new solving session
+ if (isSolvingChanged && solverState.isSolving) {
+ prevLogsLengthRef.current = 0;
+ }
+
+ if (logContainerRef.current && solverState.isSolving) {
+ const currentLogsLength = solverState.logs.length;
+ // Only scroll if there are new logs (logs length increased) and we have logs
+ if (
+ currentLogsLength > prevLogsLengthRef.current &&
+ currentLogsLength > 0
+ ) {
+ const container = logContainerRef.current;
+ // Use requestAnimationFrame to ensure DOM is updated
+ requestAnimationFrame(() => {
+ container.scrollTo({
+ top: container.scrollHeight,
+ behavior: "smooth",
+ });
+ });
+ }
+ prevLogsLengthRef.current = currentLogsLength;
+ } else if (!solverState.isSolving) {
+ // Reset when solving stops
+ prevLogsLengthRef.current = solverState.logs.length;
+ }
+
+ prevIsSolvingForLogsRef.current = solverState.isSolving;
+ }, [solverState.logs, solverState.isSolving]);
+
+ // Auto-scroll chat (only when solving and new messages are added)
+ useEffect(() => {
+ const isSolvingChanged =
+ prevIsSolvingForChatRef.current !== solverState.isSolving;
+
+ // Reset counter when starting a new solving session
+ if (isSolvingChanged && solverState.isSolving) {
+ prevMessagesLengthRef.current = solverState.messages.length;
+ }
+
+ if (chatEndRef.current && solverState.isSolving) {
+ const currentMessagesLength = solverState.messages.length;
+ // Only scroll if there are new messages (messages length increased)
+ // But don't scroll immediately when solving starts (user message was just added)
+ if (
+ currentMessagesLength > prevMessagesLengthRef.current &&
+ !isSolvingChanged
+ ) {
+ // Use requestAnimationFrame to ensure DOM is updated
+ requestAnimationFrame(() => {
+ chatEndRef.current?.scrollIntoView({ behavior: "smooth" });
+ });
+ }
+ prevMessagesLengthRef.current = currentMessagesLength;
+ } else if (!solverState.isSolving) {
+ // Reset when solving stops
+ prevMessagesLengthRef.current = solverState.messages.length;
+ }
+
+ prevIsSolvingForChatRef.current = solverState.isSolving;
+ }, [solverState.messages, solverState.isSolving]);
+
+ const handleStart = () => {
+ if (!inputQuestion.trim()) return;
+ startSolver(inputQuestion, solverState.selectedKb);
+ setInputQuestion("");
+ };
+
+ return (
+ <div className="h-[calc(100vh-4rem)] flex gap-6 animate-fade-in overflow-hidden">
+ {/* Left Panel: Chat Interface */}
+ <div className="flex-1 flex flex-col bg-white dark:bg-slate-800 rounded-2xl shadow-sm border border-slate-200 dark:border-slate-700 overflow-hidden min-h-0">
+ {/* Chat Header */}
+ <div className="p-4 border-b border-slate-100 dark:border-slate-700 bg-slate-50/50 dark:bg-slate-800/50 flex justify-between items-center backdrop-blur-sm shrink-0">
+ <div className="flex items-center gap-2 text-slate-700 dark:text-slate-200 font-semibold">
+ <div className="w-2 h-2 rounded-full bg-green-500 animate-pulse"></div>
+ Smart Solver
+ </div>
+ <div className="flex items-center gap-4">
+ <select
+ value={solverState.selectedKb}
+ onChange={(e) =>
+ setSolverState((prev) => ({
+ ...prev,
+ selectedKb: e.target.value,
+ }))
+ }
+ className="text-xs bg-white dark:bg-slate-700 border border-slate-200 dark:border-slate-600 rounded-md px-2 py-1 outline-none focus:border-blue-400 dark:text-slate-200"
+ >
+ {kbs.map((kb) => (
+ <option key={kb} value={kb}>
+ {kb}
+ </option>
+ ))}
+ </select>
+ </div>
+ </div>
+
+ {/* Chat Area */}
+ <div
+ ref={chatContainerRef}
+ className="flex-1 overflow-y-auto p-6 space-y-6 bg-slate-50/30 dark:bg-slate-900/30 min-h-0"
+ >
+ {/* Initial State */}
+ {solverState.messages.length === 0 && !solverState.isSolving && (
+ <div className="h-full flex flex-col items-center justify-center text-center max-w-md mx-auto">
+ <div className="w-16 h-16 bg-blue-100 dark:bg-blue-900/50 text-blue-600 dark:text-blue-400 rounded-2xl flex items-center justify-center mb-6 shadow-sm">
+ <Bot className="w-8 h-8" />
+ </div>
+ <h3 className="text-xl font-bold text-slate-900 dark:text-slate-100 mb-2">
+ How can I help you today?
+ </h3>
+ <p className="text-slate-500 dark:text-slate-400 mb-8 leading-relaxed">
+ I can help you solve complex STEM problems using multi-step
+ reasoning. Try asking about calculus, physics, or coding
+ algorithms.
+ </p>
+ <div className="grid grid-cols-1 gap-3 w-full text-sm">
+ {[
+ "Calculate the linear convolution of x=[1,2,3] and h=[4,5]",
+ "Explain the backpropagation algorithm in neural networks",
+ "Solve the differential equation dy/dx = x^2",
+ ].map((q, i) => (
+ <button
+ key={i}
+ onClick={() => setInputQuestion(q)}
+ className="px-4 py-3 bg-white dark:bg-slate-800 border border-slate-200 dark:border-slate-700 rounded-xl hover:border-blue-300 dark:hover:border-blue-500 hover:bg-blue-50 dark:hover:bg-blue-900/30 hover:text-blue-700 dark:hover:text-blue-400 transition-all text-left text-slate-600 dark:text-slate-300 shadow-sm"
+ >
+ {q}
+ </button>
+ ))}
+ </div>
+ </div>
+ )}
+
+ {/* Messages List */}
+ {solverState.messages.map((msg, idx) => (
+ <div
+ key={idx}
+ className="flex gap-4 w-full animate-in fade-in slide-in-from-bottom-4"
+ >
+ {msg.role === "user" ? (
+ <>
+ <div className="w-8 h-8 rounded-full bg-slate-200 dark:bg-slate-700 flex items-center justify-center shrink-0">
+ <User className="w-5 h-5 text-slate-500 dark:text-slate-400" />
+ </div>
+ <div className="flex-1 bg-slate-100 dark:bg-slate-700 px-5 py-3.5 rounded-2xl rounded-tl-none text-slate-800 dark:text-slate-200 leading-relaxed shadow-sm overflow-hidden min-w-0 break-words">
+ <div className="prose prose-slate dark:prose-invert max-w-none prose-headings:font-bold prose-p:leading-relaxed prose-pre:bg-slate-900 prose-pre:shadow-inner prose-pre:overflow-x-auto prose-code:break-words prose-a:break-all">
+ <ReactMarkdown
+ remarkPlugins={[remarkMath]}
+ rehypePlugins={[rehypeKatex]}
+ urlTransform={(url) =>
+ resolveArtifactUrl(url, msg.outputDir)
+ }
+ components={{
+ img: ({ node, src, ...props }) => (
+ <img
+ {...props}
+ src={
+ resolveArtifactUrl(src ?? "", msg.outputDir) ||
+ undefined
+ }
+ loading="lazy"
+ className="max-w-full h-auto"
+ />
+ ),
+ a: ({ node, href, ...props }) => (
+ <a
+ {...props}
+ href={
+ resolveArtifactUrl(href ?? "", msg.outputDir) ||
+ undefined
+ }
+ target="_blank"
+ rel="noreferrer"
+ className="break-all"
+ />
+ ),
+ pre: ({ node, ...props }) => (
+ <pre
+ {...props}
+ className="overflow-x-auto max-w-full"
+ />
+ ),
+ code: ({ node, inline, ...props }) => (
+ <code
+ {...props}
+ className={inline ? "break-words" : "block"}
+ />
+ ),
+ table: ({ node, ...props }) => (
+ <div className="overflow-x-auto">
+ <table {...props} className="min-w-full" />
+ </div>
+ ),
+ }}
+ >
+ {processLatexContent(msg.content)}
+ </ReactMarkdown>
+ </div>
+ </div>
+ </>
+ ) : (
+ <>
+ <div className="w-8 h-8 rounded-full bg-blue-600 flex items-center justify-center shrink-0 shadow-lg shadow-blue-500/30">
+ <Bot className="w-5 h-5 text-white" />
+ </div>
+ <div className="flex-1 bg-white dark:bg-slate-800 px-6 py-5 rounded-2xl rounded-tl-none border border-slate-200 dark:border-slate-700 shadow-sm overflow-hidden min-w-0 break-words">
+ <div className="prose prose-slate dark:prose-invert prose-blue max-w-none prose-headings:font-bold prose-p:leading-relaxed prose-pre:bg-slate-900 prose-pre:shadow-inner prose-pre:overflow-x-auto prose-code:break-words prose-a:break-all">
+ <ReactMarkdown
+ remarkPlugins={[remarkMath]}
+ rehypePlugins={[rehypeKatex]}
+ urlTransform={(url) =>
+ resolveArtifactUrl(url, msg.outputDir)
+ }
+ components={{
+ img: ({ node, src, ...props }) => (
+ <img
+ {...props}
+ src={
+ resolveArtifactUrl(src ?? "", msg.outputDir) ||
+ undefined
+ }
+ loading="lazy"
+ className="max-w-full h-auto"
+ />
+ ),
+ a: ({ node, href, ...props }) => (
+ <a
+ {...props}
+ href={
+ resolveArtifactUrl(href ?? "", msg.outputDir) ||
+ undefined
+ }
+ target="_blank"
+ rel="noreferrer"
+ className="break-all"
+ />
+ ),
+ pre: ({ node, ...props }) => (
+ <pre
+ {...props}
+ className="overflow-x-auto max-w-full"
+ />
+ ),
+ code: ({ node, inline, ...props }) => (
+ <code
+ {...props}
+ className={inline ? "break-words" : "block"}
+ />
+ ),
+ table: ({ node, ...props }) => (
+ <div className="overflow-x-auto">
+ <table {...props} className="min-w-full" />
+ </div>
+ ),
+ }}
+ >
+ {processLatexContent(msg.content)}
+ </ReactMarkdown>
+ </div>
+ <div className="mt-4 pt-4 border-t border-slate-100 dark:border-slate-700 flex items-center justify-between">
+ <div className="flex items-center gap-2 text-xs text-green-600 dark:text-green-400 font-medium">
+ <CheckCircle2 className="w-4 h-4" />
+ Verified by OpenTutor Logic Engine
+ </div>
+ <button
+ onClick={() => {
+ // Find corresponding user question
+ const userMsgIndex = solverState.messages.findIndex(
+ (m, i) =>
+ m.role === "user" &&
+ solverState.messages[i + 1]?.role ===
+ "assistant" &&
+ solverState.messages[i + 1]?.content ===
+ msg.content,
+ );
+ const userQuery =
+ userMsgIndex >= 0
+ ? solverState.messages[userMsgIndex].content
+ : solverState.question;
+ setNotebookRecord({
+ title:
+ userQuery.slice(0, 100) +
+ (userQuery.length > 100 ? "..." : ""),
+ userQuery,
+ output: msg.content,
+ });
+ setShowNotebookModal(true);
+ }}
+ className="flex items-center gap-1 px-2 py-1 text-xs text-indigo-600 dark:text-indigo-400 hover:bg-indigo-50 dark:hover:bg-indigo-900/30 rounded-lg transition-colors"
+ >
+ <Book className="w-3 h-3" />
+ Add to Notebook
+ </button>
+ </div>
+ </div>
+ </>
+ )}
+ </div>
+ ))}
+
+ {/* AI Thinking State */}
+ {solverState.isSolving && (
+ <div className="flex gap-4 w-full animate-in fade-in slide-in-from-bottom-2">
+ <div className="w-8 h-8 rounded-full bg-blue-600 flex items-center justify-center shrink-0 shadow-lg shadow-blue-500/30">
+ <Loader2 className="w-5 h-5 text-white animate-spin" />
+ </div>
+ <div className="flex flex-col gap-2 flex-1 min-w-0">
+ <div className="bg-white dark:bg-slate-800 px-5 py-4 rounded-2xl rounded-tl-none border border-slate-100 dark:border-slate-700 shadow-sm">
+ {/* Stage Display */}
+ <div className="flex items-center gap-2 text-slate-700 dark:text-slate-200 text-sm mb-3">
+ <span className="relative flex h-2 w-2">
+ <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-blue-400 opacity-75"></span>
+ <span className="relative inline-flex rounded-full h-2 w-2 bg-blue-500"></span>
+ </span>
+ <span className="font-semibold">
+ {solverState.progress.stage === "investigate" &&
+ "🔍 Investigating..."}
+ {solverState.progress.stage === "solve" &&
+ "🧮 Solving..."}
+ {solverState.progress.stage === "response" &&
+ "✍️ Responding..."}
+ {!solverState.progress.stage &&
+ "Reasoning Engine Active..."}
+ </span>
+ </div>
+
+ {/* Progress Details */}
+ {solverState.progress.stage === "investigate" &&
+ solverState.progress.progress.queries &&
+ solverState.progress.progress.queries.length > 0 && (
+ <div className="space-y-1.5">
+ <div className="text-xs text-slate-600 dark:text-slate-400 font-medium">
+ Round {solverState.progress.progress.round || 1} -
+ Tool Queries:
+ </div>
+ <div className="space-y-1">
+ {solverState.progress.progress.queries.map(
+ (query, idx) => (
+ <div
+ key={idx}
+ className="text-xs text-slate-500 dark:text-slate-400 pl-3 border-l-2 border-blue-200 dark:border-blue-600"
+ >
+ • {query}
+ </div>
+ ),
+ )}
+ </div>
+ </div>
+ )}
+
+ {solverState.progress.stage === "solve" &&
+ solverState.progress.progress.step_id && (
+ <div className="text-xs text-slate-600 dark:text-slate-400">
+ <span className="font-medium">
+ Solve step{" "}
+ {solverState.progress.progress.step_index || "?"}:
+ </span>{" "}
+ <span className="text-slate-500 dark:text-slate-400">
+ {solverState.progress.progress.step_target || ""}
+ </span>
+ </div>
+ )}
+
+ {solverState.progress.stage === "response" &&
+ solverState.progress.progress.step_id && (
+ <div className="text-xs text-slate-600 dark:text-slate-400">
+ <span className="font-medium">
+ Responding step{" "}
+ {solverState.progress.progress.step_index || "?"}:
+ </span>{" "}
+ <span className="text-slate-500 dark:text-slate-400">
+ {solverState.progress.progress.step_target || ""}
+ </span>
+ </div>
+ )}
+
+ {!solverState.progress.stage && (
+ <>
+ <div className="h-2 w-32 bg-slate-100 dark:bg-slate-700 rounded animate-pulse mb-2"></div>
+ <div className="h-2 w-48 bg-slate-100 dark:bg-slate-700 rounded animate-pulse"></div>
+ </>
+ )}
+ </div>
+ </div>
+ </div>
+ )}
+ <div ref={chatEndRef} />
+ </div>
+
+ {/* Input Area */}
+ <div className="p-4 bg-white dark:bg-slate-800 border-t border-slate-100 dark:border-slate-700 shrink-0">
+ <div className="w-full relative">
+ <input
+ type="text"
+ className="w-full px-5 py-4 pr-32 bg-slate-50 dark:bg-slate-700 border border-slate-200 dark:border-slate-600 rounded-xl focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 transition-all placeholder:text-slate-400 dark:placeholder:text-slate-500 text-slate-700 dark:text-slate-200 shadow-inner"
+ placeholder="Ask a difficult question..."
+ value={inputQuestion}
+ onChange={(e) => setInputQuestion(e.target.value)}
+ onKeyDown={(e) => e.key === "Enter" && handleStart()}
+ disabled={solverState.isSolving}
+ />
+ <div className="absolute right-2 top-2 bottom-2 flex items-center gap-2">
+ <button
+ onClick={handleStart}
+ disabled={solverState.isSolving || !inputQuestion.trim()}
+ className="h-full aspect-square bg-blue-600 text-white rounded-lg flex items-center justify-center hover:bg-blue-700 disabled:opacity-50 disabled:hover:bg-blue-600 transition-all shadow-md shadow-blue-500/20"
+ >
+ {solverState.isSolving ? (
+ <Loader2 className="w-5 h-5 animate-spin" />
+ ) : (
+ <Send className="w-5 h-5" />
+ )}
+ </button>
+ </div>
+ </div>
+ <div className="text-center text-[10px] text-slate-400 dark:text-slate-500 mt-2">
+ OpenTutor can make mistakes. Please verify important information.
+ </div>
+ </div>
+ </div>
+
+ {/* Right Panel: Logic Stream - Modern Light Theme */}
+ <div className="w-[400px] flex-shrink-0 bg-white dark:bg-slate-800 rounded-2xl shadow-sm flex flex-col overflow-hidden border border-slate-200 dark:border-slate-700 h-full">
+ {/* Header */}
+ <div className="px-4 py-3 bg-slate-50/50 dark:bg-slate-800/50 border-b border-slate-100 dark:border-slate-700 flex items-center justify-between shrink-0">
+ <div className="flex items-center gap-2 text-sm font-semibold text-slate-700 dark:text-slate-200">
+ <Activity className="w-4 h-4 text-indigo-500 dark:text-indigo-400" />
+ Logic Stream
+ </div>
+ {solverState.isSolving && (
+ <span className="flex items-center gap-1.5 text-xs text-indigo-600 dark:text-indigo-400 font-medium">
+ <span className="relative flex h-2 w-2">
+ <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-indigo-400 opacity-75"></span>
+ <span className="relative inline-flex rounded-full h-2 w-2 bg-indigo-500"></span>
+ </span>
+ Running
+ </span>
+ )}
+ </div>
+
+ {/* Performance & Cost - Horizontal Layout */}
+ {solverState.tokenStats.calls > 0 && (
+ <div className="px-4 py-2.5 bg-slate-50 dark:bg-slate-900/50 border-b border-slate-100 dark:border-slate-700 shrink-0">
+ <div className="flex items-center gap-3 flex-wrap text-xs">
+ <div className="flex items-center gap-1.5">
+ <Cpu className="w-3.5 h-3.5 text-slate-400 dark:text-slate-500" />
+ <span className="text-slate-500 dark:text-slate-400">
+ Model:
+ </span>
+ <span className="font-medium text-slate-700 dark:text-slate-300">
+ {solverState.tokenStats.model}
+ </span>
+ </div>
+ <div className="h-3 w-px bg-slate-200 dark:bg-slate-600" />
+ <div className="text-slate-500 dark:text-slate-400">
+ Calls:{" "}
+ <span className="font-medium text-slate-700 dark:text-slate-300">
+ {solverState.tokenStats.calls}
+ </span>
+ </div>
+ <div className="h-3 w-px bg-slate-200 dark:bg-slate-600" />
+ <div className="text-slate-500 dark:text-slate-400">
+ Tokens:{" "}
+ <span className="font-medium text-slate-700 dark:text-slate-300">
+ {solverState.tokenStats.tokens.toLocaleString()}
+ </span>
+ </div>
+ <div className="h-3 w-px bg-slate-200 dark:bg-slate-600" />
+ <div className="flex items-center gap-1">
+ <DollarSign className="w-3 h-3 text-amber-500" />
+ <span className="font-semibold text-amber-600 dark:text-amber-400">
+ ${solverState.tokenStats.cost.toFixed(4)}
+ </span>
+ </div>
+ </div>
+ </div>
+ )}
+
+ {/* Current Progress Display */}
+ {solverState.isSolving && solverState.progress.stage && (
+ <div className="px-4 py-3 bg-indigo-50 dark:bg-indigo-900/30 border-b border-indigo-100 dark:border-indigo-800 shrink-0">
+ <div className="flex items-center gap-2 mb-2">
+ <div
+ className={`p-1.5 rounded-lg ${
+ solverState.progress.stage === "investigate"
+ ? "bg-blue-100 dark:bg-blue-900/50 text-blue-600 dark:text-blue-400"
+ : solverState.progress.stage === "solve"
+ ? "bg-amber-100 dark:bg-amber-900/50 text-amber-600 dark:text-amber-400"
+ : "bg-emerald-100 dark:bg-emerald-900/50 text-emerald-600 dark:text-emerald-400"
+ }`}
+ >
+ {solverState.progress.stage === "investigate" && (
+ <Search className="w-3.5 h-3.5" />
+ )}
+ {solverState.progress.stage === "solve" && (
+ <Sparkles className="w-3.5 h-3.5" />
+ )}
+ {solverState.progress.stage === "response" && (
+ <FileText className="w-3.5 h-3.5" />
+ )}
+ </div>
+ <div>
+ <div className="text-xs font-semibold text-indigo-700 dark:text-indigo-300 capitalize">
+ {solverState.progress.stage === "investigate" &&
+ "Investigating"}
+ {solverState.progress.stage === "solve" && "Solving"}
+ {solverState.progress.stage === "response" && "Responding"}
+ </div>
+ {solverState.progress.progress.round && (
+ <div className="text-[10px] text-indigo-500 dark:text-indigo-400">
+ Round {solverState.progress.progress.round}
+ </div>
+ )}
+ </div>
+ </div>
+
+ {/* Investigate stage - show queries */}
+ {solverState.progress.stage === "investigate" &&
+ solverState.progress.progress.queries &&
+ solverState.progress.progress.queries.length > 0 && (
+ <div className="space-y-1 mt-2">
+ {solverState.progress.progress.queries
+ .slice(0, 3)
+ .map((query, idx) => (
+ <div
+ key={idx}
+ className="text-[10px] text-indigo-600 dark:text-indigo-400 pl-2 border-l-2 border-indigo-200 dark:border-indigo-600 truncate"
+ >
+ {query}
+ </div>
+ ))}
+ {solverState.progress.progress.queries.length > 3 && (
+ <div className="text-[10px] text-indigo-400 dark:text-indigo-500 pl-2">
+ +{solverState.progress.progress.queries.length - 3} more
+ queries...
+ </div>
+ )}
+ </div>
+ )}
+
+ {/* Solve/Response stage - show step info */}
+ {(solverState.progress.stage === "solve" ||
+ solverState.progress.stage === "response") &&
+ solverState.progress.progress.step_id && (
+ <div className="text-[10px] text-indigo-600 dark:text-indigo-400 mt-1">
+ Step {solverState.progress.progress.step_index || "?"}:{" "}
+ {solverState.progress.progress.step_target || "Processing..."}
+ </div>
+ )}
+ </div>
+ )}
+
+ {/* Activity Log */}
+ <div className="flex-1 flex flex-col min-h-0 overflow-hidden">
+ <div className="px-4 py-2 border-b border-slate-100 dark:border-slate-700 flex items-center justify-between shrink-0">
+ <h3 className="text-xs font-semibold text-slate-700 dark:text-slate-300 flex items-center gap-1.5">
+ <Terminal className="w-3.5 h-3.5 text-slate-400 dark:text-slate-500" />
+ Activity Log
+ </h3>
+ <span className="text-[10px] text-slate-400 dark:text-slate-500">
+ {solverState.logs.length} entries
+ </span>
+ </div>
+
+ <div
+ ref={logContainerRef}
+ className="flex-1 overflow-y-auto overflow-x-hidden p-3 space-y-1.5 min-h-0"
+ >
+ {solverState.logs.length === 0 && (
+ <div className="h-full flex flex-col items-center justify-center text-slate-400 dark:text-slate-500 gap-3 py-12">
+ <Activity className="w-10 h-10 opacity-20" />
+ <p className="text-sm">Waiting for logic execution...</p>
+ </div>
+ )}
+
+ {(() => {
+ // Filter and deduplicate logs
+ const filteredLogs = solverState.logs.filter((log, i) => {
+ const content = (log.content || "").trim();
+
+ // Filter empty content
+ if (!content) return false;
+
+ // Filter duplicate content (same content appeared in recent 10 logs)
+ const recentLogs = solverState.logs.slice(
+ Math.max(0, i - 10),
+ i,
+ );
+ if (
+ recentLogs.some((l) => (l.content || "").trim() === content)
+ ) {
+ return false;
+ }
+
+ // Filter some unimportant debug info
+ if (
+ content.includes("Provider List:") ||
+ (content.includes("INFO:") &&
+ !content.includes("[Stage:") &&
+ !content.includes("🔧")) ||
+ (content.match(/^\d{4}-\d{2}-\d{2}/) &&
+ !content.includes("[Stage:")) ||
+ (content.includes("INFO:MainSolver:") &&
+ !content.includes("[Stage:")) ||
+ (content.includes("INFO:investigate_agent:") &&
+ !content.includes("🔧") &&
+ !content.includes("[Stage:"))
+ ) {
+ return false;
+ }
+
+ // Fix incorrect ERROR tags
+ if (log.level === "ERROR" && content.includes("INFO:")) {
+ log.level = "INFO";
+ }
+
+ return true;
+ });
+
+ return filteredLogs.map((log, i) => {
+ const content = log.content || "";
+
+ // Clean content: remove duplicate INFO prefix
+ let cleanContent = content;
+ cleanContent = cleanContent.replace(/^INFO:[^:]+:/, "");
+ cleanContent = cleanContent.replace(
+ /^ERROR:[^:]+:INFO:/,
+ "INFO:",
+ );
+
+ // Parse stage progress format
+ const stageMatch = cleanContent.match(
+ /^([▶…✔↷⚠✖•])\s*\[Stage:([^\]]+)\]\s*(\w+)(?:\s*\|\s*(.+))?/,
+ );
+
+ // Parse tool call format
+ const toolMatch = cleanContent.match(
+ /🔧\s*\[Tool Call\]\s*Tool:\s*(.+)/,
+ );
+
+ // Parse separator line
+ const isSeparator = /^={20,}$/.test(cleanContent.trim());
+
+ // Parse errors
+ const isError =
+ (log.level === "ERROR" && !cleanContent.includes("INFO:")) ||
+ (cleanContent.includes("ERROR") &&
+ !cleanContent.includes("INFO:")) ||
+ cleanContent.includes("✖");
+
+ // Parse warnings
+ const isWarning =
+ log.level === "WARNING" ||
+ cleanContent.includes("WARNING") ||
+ cleanContent.includes("⚠");
+
+ // Parse completion markers
+ const isComplete =
+ cleanContent.includes("✔") ||
+ cleanContent.includes("✓") ||
+ cleanContent.includes("complete");
+
+ // Parse running state
+ const isRunning =
+ cleanContent.includes("…") || cleanContent.includes("▶");
+
+ // Parse skip state
+ const isSkip = cleanContent.includes("↷");
+
+ // Parse step header
+ const isStepHeader = /^---\s*Step\s+\d+:\s*S\d+\s*---/.test(
+ cleanContent,
+ );
+
+ // Parse section header
+ const isSectionHeader =
+ /^\[(Plan|Solve|Response|Analysis|Note|Finalize|PrecisionAnswer)\]\s*/.test(
+ cleanContent,
+ );
+
+ // Parse tool call detail line
+ const isToolDetail =
+ cleanContent.includes("🔧 [Tool Call]") ||
+ cleanContent.includes("Tool:") ||
+ cleanContent.includes("Status:") ||
+ cleanContent.includes("Duration:");
+
+ // Parse action lines
+ const isActionLine =
+ /^\s*•\s*/.test(cleanContent) ||
+ /^\s*\[(Investigate|Note|Solve|Response)\]\s*/.test(
+ cleanContent,
+ );
+
+ // Light/Dark theme styles
+ let className = "text-xs px-2 py-1.5 rounded break-words";
+ let prefix = "";
+
+ if (stageMatch) {
+ const [, icon, , status] = stageMatch;
+ prefix = icon;
+
+ if (status === "start" || status === "running") {
+ className +=
+ " bg-indigo-50 dark:bg-indigo-900/40 text-indigo-700 dark:text-indigo-300 border-l-2 border-indigo-300 dark:border-indigo-500";
+ } else if (status === "complete") {
+ className +=
+ " bg-emerald-50 dark:bg-emerald-900/40 text-emerald-700 dark:text-emerald-300 border-l-2 border-emerald-300 dark:border-emerald-500";
+ } else if (status === "error") {
+ className +=
+ " bg-red-50 dark:bg-red-900/40 text-red-700 dark:text-red-300 border-l-2 border-red-300 dark:border-red-500";
+ } else if (status === "warning") {
+ className +=
+ " bg-amber-50 dark:bg-amber-900/40 text-amber-700 dark:text-amber-300 border-l-2 border-amber-300 dark:border-amber-500";
+ } else if (status === "skip") {
+ className +=
+ " bg-slate-50 dark:bg-slate-800 text-slate-500 dark:text-slate-400 border-l-2 border-slate-200 dark:border-slate-600";
+ } else {
+ className +=
+ " bg-slate-50 dark:bg-slate-800 text-slate-600 dark:text-slate-400";
+ }
+ } else if (isSeparator) {
+ className +=
+ " text-slate-300 dark:text-slate-600 text-center";
+ } else if (isError) {
+ className +=
+ " bg-red-50 dark:bg-red-900/40 text-red-700 dark:text-red-300 border-l-2 border-red-300 dark:border-red-500";
+ } else if (isWarning) {
+ className +=
+ " bg-amber-50 dark:bg-amber-900/40 text-amber-700 dark:text-amber-300 border-l-2 border-amber-300 dark:border-amber-500";
+ } else if (isStepHeader) {
+ className +=
+ " bg-blue-50 dark:bg-blue-900/40 text-blue-700 dark:text-blue-300 font-semibold mt-2";
+ } else if (isSectionHeader) {
+ className +=
+ " bg-indigo-50 dark:bg-indigo-900/40 text-indigo-700 dark:text-indigo-300 font-medium mt-2";
+ } else if (toolMatch || isToolDetail) {
+ className +=
+ " bg-emerald-50 dark:bg-emerald-900/40 text-emerald-700 dark:text-emerald-300 border-l-2 border-emerald-200 dark:border-emerald-500";
+ } else if (isActionLine) {
+ className +=
+ " bg-slate-50 dark:bg-slate-800 text-slate-600 dark:text-slate-400 pl-4";
+ } else if (isComplete) {
+ className +=
+ " bg-emerald-50 dark:bg-emerald-900/40 text-emerald-700 dark:text-emerald-300";
+ } else if (isRunning) {
+ className +=
+ " bg-indigo-50 dark:bg-indigo-900/40 text-indigo-600 dark:text-indigo-300";
+ } else if (isSkip) {
+ className +=
+ " bg-slate-50 dark:bg-slate-800 text-slate-400 dark:text-slate-500";
+ } else {
+ className +=
+ " bg-slate-50 dark:bg-slate-800 text-slate-600 dark:text-slate-400 hover:bg-slate-100 dark:hover:bg-slate-700";
+ }
+
+ return (
+ <div key={i} className={className}>
+ {prefix && (
+ <span className="mr-1.5 opacity-70">{prefix}</span>
+ )}
+ {cleanContent}
+ </div>
+ );
+ });
+ })()}
+ </div>
+ </div>
+ </div>
+
+ {/* Add to Notebook Modal */}
+ {notebookRecord && (
+ <AddToNotebookModal
+ isOpen={showNotebookModal}
+ onClose={() => {
+ setShowNotebookModal(false);
+ setNotebookRecord(null);
+ }}
+ recordType="solve"
+ title={notebookRecord.title}
+ userQuery={notebookRecord.userQuery}
+ output={notebookRecord.output}
+ kbName={solverState.selectedKb}
+ />
+ )}
+ </div>
+ );
+}
diff --git a/web/components/ActivityDetail.tsx b/web/components/ActivityDetail.tsx
new file mode 100644
index 000000000..dcd45647c
--- /dev/null
+++ b/web/components/ActivityDetail.tsx
@@ -0,0 +1,218 @@
+import { useState } from "react";
+import { X, FileText, HelpCircle, Search, Clock, Database } from "lucide-react";
+
+interface ActivityDetailProps {
+ activity: any;
+ onClose: () => void;
+}
+
+export default function ActivityDetail({
+ activity,
+ onClose,
+}: ActivityDetailProps) {
+ if (!activity) return null;
+
+ return (
+ <div className="fixed inset-0 bg-black/50 backdrop-blur-sm z-50 flex items-center justify-center p-4 animate-in fade-in duration-200">
+ <div className="bg-white rounded-2xl shadow-2xl w-full max-w-3xl max-h-[85vh] flex flex-col animate-in zoom-in-95 duration-300">
+ {/* Header */}
+ <div className="p-6 border-b border-slate-100 flex justify-between items-center">
+ <div className="flex items-center gap-4">
+ <div
+ className={`w-10 h-10 rounded-xl flex items-center justify-center ${
+ activity.type === "solve"
+ ? "bg-blue-50 text-blue-600"
+ : activity.type === "question"
+ ? "bg-purple-50 text-purple-600"
+ : "bg-emerald-50 text-emerald-600"
+ }`}
+ >
+ {activity.type === "solve" && <HelpCircle className="w-5 h-5" />}
+ {activity.type === "question" && <FileText className="w-5 h-5" />}
+ {activity.type === "research" && <Search className="w-5 h-5" />}
+ </div>
+ <div>
+ <h2 className="font-bold text-slate-900 text-lg">
+ Activity Details
+ </h2>
+ <p className="text-xs text-slate-500 flex items-center gap-2">
+ <Clock className="w-3 h-3" />
+ {new Date(activity.timestamp * 1000).toLocaleString()}
+ </p>
+ </div>
+ </div>
+ <button
+ onClick={onClose}
+ className="w-8 h-8 rounded-full bg-slate-100 hover:bg-slate-200 flex items-center justify-center text-slate-500 transition-colors"
+ >
+ <X className="w-4 h-4" />
+ </button>
+ </div>
+
+ {/* Scrollable Content */}
+ <div className="flex-1 overflow-y-auto p-6 space-y-6">
+ {/* Meta Info */}
+ <div className="grid grid-cols-2 gap-4">
+ <div className="p-4 bg-slate-50 rounded-xl border border-slate-100">
+ <div className="text-xs font-bold uppercase tracking-wide text-slate-500 mb-1">
+ Type
+ </div>
+ <div className="font-medium text-slate-900 capitalize">
+ {activity.type}
+ </div>
+ </div>
+ <div className="p-4 bg-slate-50 rounded-xl border border-slate-100">
+ <div className="text-xs font-bold uppercase tracking-wide text-slate-500 mb-1">
+ Knowledge Base
+ </div>
+ <div className="font-medium text-slate-900 flex items-center gap-2">
+ <Database className="w-4 h-4 text-slate-400" />
+ {activity.content?.kb_name || "Unknown"}
+ </div>
+ </div>
+ </div>
+
+ {/* Activity Specific Content */}
+
+ {/* 1. SOLVE */}
+ {activity.type === "solve" && (
+ <>
+ <div className="space-y-2">
+ <h3 className="font-bold text-slate-900">Question</h3>
+ <div className="p-4 bg-slate-50 rounded-xl border border-slate-200 text-slate-800 leading-relaxed">
+ {activity.content.question}
+ </div>
+ </div>
+ <div className="space-y-2">
+ <h3 className="font-bold text-slate-900">Final Answer</h3>
+ <div className="p-6 bg-white rounded-xl border border-slate-200 shadow-sm prose prose-slate max-w-none">
+ {/* Simplified rendering for history view */}
+ <pre className="whitespace-pre-wrap font-sans text-sm">
+ {activity.content.answer}
+ </pre>
+ </div>
+ </div>
+ </>
+ )}
+
+ {/* 2. QUESTION */}
+ {activity.type === "question" && (
+ <>
+ <div className="space-y-2">
+ <h3 className="font-bold text-slate-900">Parameters</h3>
+ <div className="grid grid-cols-3 gap-3">
+ <div className="px-3 py-2 border rounded-lg text-sm text-slate-600">
+ <span className="font-bold">Topic:</span>{" "}
+ {activity.content?.requirement?.knowledge_point || "N/A"}
+ </div>
+ <div className="px-3 py-2 border rounded-lg text-sm text-slate-600">
+ <span className="font-bold">Difficulty:</span>{" "}
+ {activity.content?.requirement?.difficulty || "N/A"}
+ </div>
+ <div className="px-3 py-2 border rounded-lg text-sm text-slate-600">
+ <span className="font-bold">Type:</span>{" "}
+ {activity.content?.requirement?.question_type ||
+ activity.content?.question?.question_type ||
+ "N/A"}
+ </div>
+ </div>
+ </div>
+
+ <div className="space-y-2">
+ <h3 className="font-bold text-slate-900">Generated Question</h3>
+ <div className="p-6 bg-white rounded-xl border border-slate-200 shadow-sm space-y-4">
+ <p className="text-lg font-medium text-slate-900">
+ {activity.content?.question?.content ||
+ activity.content?.question?.question ||
+ "No question content"}
+ </p>
+
+ {/* Handle options as object (A, B, C, D format) or array */}
+ {activity.content?.question?.options && (
+ <div className="space-y-2">
+ {Array.isArray(activity.content.question.options)
+ ? // Array format
+ activity.content.question.options.map(
+ (opt: string, i: number) => (
+ <div
+ key={i}
+ className="p-3 border border-slate-100 rounded-lg bg-slate-50 text-sm"
+ >
+ <span className="font-bold text-purple-600 mr-2">
+ {String.fromCharCode(65 + i)}.
+ </span>
+ {opt}
+ </div>
+ ),
+ )
+ : // Object format { "A": "...", "B": "..." }
+ Object.entries(activity.content.question.options).map(
+ ([key, value]) => (
+ <div
+ key={key}
+ className="p-3 border border-slate-100 rounded-lg bg-slate-50 text-sm"
+ >
+ <span className="font-bold text-purple-600 mr-2">
+ {key}.
+ </span>
+ {value as string}
+ </div>
+ ),
+ )}
+ </div>
+ )}
+ </div>
+ </div>
+
+ <div className="space-y-2">
+ <h3 className="font-bold text-slate-900 text-green-700">
+ Correct Answer & Explanation
+ </h3>
+ <div className="p-4 bg-green-50 rounded-xl border border-green-100 text-green-800 space-y-2">
+ <p className="font-bold">
+ Answer:{" "}
+ {activity.content?.question?.answer ||
+ activity.content?.question?.correct_answer ||
+ "N/A"}
+ </p>
+ <p className="text-sm leading-relaxed">
+ {activity.content?.question?.explanation ||
+ "No explanation provided"}
+ </p>
+ </div>
+ </div>
+ </>
+ )}
+
+ {/* 3. RESEARCH */}
+ {activity.type === "research" && (
+ <>
+ <div className="space-y-2">
+ <h3 className="font-bold text-slate-900">Topic</h3>
+ <div className="text-lg font-medium text-slate-800">
+ {activity.content.topic}
+ </div>
+ </div>
+ <div className="space-y-2">
+ <h3 className="font-bold text-slate-900">Report Preview</h3>
+ <div className="p-6 bg-white rounded-xl border border-slate-200 shadow-sm max-h-96 overflow-y-auto font-mono text-xs text-slate-600">
+ {activity.content.report}
+ </div>
+ </div>
+ </>
+ )}
+ </div>
+
+ {/* Footer */}
+ <div className="p-6 border-t border-slate-100 bg-slate-50 rounded-b-2xl flex justify-end">
+ <button
+ onClick={onClose}
+ className="px-6 py-2.5 bg-slate-900 text-white rounded-xl font-medium hover:bg-slate-800 transition-colors"
+ >
+ Close
+ </button>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/web/components/AddToNotebookModal.tsx b/web/components/AddToNotebookModal.tsx
new file mode 100644
index 000000000..c17f669e8
--- /dev/null
+++ b/web/components/AddToNotebookModal.tsx
@@ -0,0 +1,369 @@
+"use client";
+
+import { useState, useEffect } from "react";
+import {
+ X,
+ BookOpen,
+ Plus,
+ Check,
+ Loader2,
+ Book,
+ FolderOpen,
+} from "lucide-react";
+import { apiUrl } from "@/lib/api";
+
+interface NotebookOption {
+ id: string;
+ name: string;
+ description: string;
+ color: string;
+ record_count: number;
+}
+
+interface AddToNotebookModalProps {
+ isOpen: boolean;
+ onClose: () => void;
+ recordType: "solve" | "question" | "research" | "co_writer";
+ title: string;
+ userQuery: string;
+ output: string;
+ metadata?: Record<string, any>;
+ kbName?: string;
+}
+
+const COLORS = [
+ "#3B82F6",
+ "#8B5CF6",
+ "#EC4899",
+ "#EF4444",
+ "#F97316",
+ "#EAB308",
+ "#22C55E",
+ "#14B8A6",
+ "#06B6D4",
+ "#6366F1",
+];
+
+export default function AddToNotebookModal({
+ isOpen,
+ onClose,
+ recordType,
+ title,
+ userQuery,
+ output,
+ metadata = {},
+ kbName,
+}: AddToNotebookModalProps) {
+ const [notebooks, setNotebooks] = useState<NotebookOption[]>([]);
+ const [selectedIds, setSelectedIds] = useState<string[]>([]);
+ const [loading, setLoading] = useState(true);
+ const [saving, setSaving] = useState(false);
+ const [showCreateForm, setShowCreateForm] = useState(false);
+ const [newNotebook, setNewNotebook] = useState({
+ name: "",
+ description: "",
+ color: "#3B82F6",
+ });
+ const [success, setSuccess] = useState(false);
+
+ useEffect(() => {
+ if (isOpen) {
+ fetchNotebooks();
+ setSelectedIds([]);
+ setSuccess(false);
+ setShowCreateForm(false);
+ }
+ }, [isOpen]);
+
+ const fetchNotebooks = async () => {
+ setLoading(true);
+ try {
+ const res = await fetch(apiUrl("/api/v1/notebook/list"));
+ const data = await res.json();
+ setNotebooks(data.notebooks || []);
+ } catch (err) {
+ console.error("Failed to fetch notebooks:", err);
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ const toggleNotebook = (id: string) => {
+ setSelectedIds((prev) =>
+ prev.includes(id) ? prev.filter((i) => i !== id) : [...prev, id],
+ );
+ };
+
+ const handleCreateNotebook = async () => {
+ if (!newNotebook.name.trim()) return;
+
+ try {
+ const res = await fetch(apiUrl("/api/v1/notebook/create"), {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(newNotebook),
+ });
+ const data = await res.json();
+ if (data.success && data.notebook) {
+ await fetchNotebooks();
+ setSelectedIds((prev) => [...prev, data.notebook.id]);
+ setShowCreateForm(false);
+ setNewNotebook({ name: "", description: "", color: "#3B82F6" });
+ }
+ } catch (err) {
+ console.error("Failed to create notebook:", err);
+ }
+ };
+
+ const handleSave = async () => {
+ if (selectedIds.length === 0) return;
+
+ setSaving(true);
+ try {
+ const res = await fetch(apiUrl("/api/v1/notebook/add_record"), {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ notebook_ids: selectedIds,
+ record_type: recordType,
+ title,
+ user_query: userQuery,
+ output,
+ metadata,
+ kb_name: kbName,
+ }),
+ });
+ const data = await res.json();
+ if (data.success) {
+ setSuccess(true);
+ setTimeout(() => {
+ onClose();
+ }, 1500);
+ }
+ } catch (err) {
+ console.error("Failed to add record:", err);
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ if (!isOpen) return null;
+
+ return (
+ <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 animate-in fade-in">
+ <div className="bg-white rounded-2xl shadow-2xl w-[480px] max-h-[80vh] flex flex-col animate-in zoom-in-95">
+ {/* Header */}
+ <div className="p-4 border-b border-slate-100 flex items-center justify-between bg-gradient-to-r from-indigo-50 to-purple-50 rounded-t-2xl">
+ <h3 className="font-bold text-slate-900 flex items-center gap-2">
+ <Book className="w-5 h-5 text-indigo-600" />
+ Add to Notebook
+ </h3>
+ <button
+ onClick={onClose}
+ className="p-1 hover:bg-white/50 rounded-lg transition-colors"
+ >
+ <X className="w-5 h-5 text-slate-500" />
+ </button>
+ </div>
+
+ {/* Content */}
+ <div className="flex-1 overflow-y-auto p-4">
+ {success ? (
+ <div className="py-12 text-center animate-in zoom-in-95">
+ <div className="w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-4">
+ <Check className="w-8 h-8 text-green-600" />
+ </div>
+ <h4 className="text-lg font-bold text-slate-900 mb-1">
+ Added Successfully!
+ </h4>
+ <p className="text-sm text-slate-500">
+ Record has been saved to {selectedIds.length} notebook
+ {selectedIds.length > 1 ? "s" : ""}
+ </p>
+ </div>
+ ) : loading ? (
+ <div className="py-12 text-center">
+ <Loader2 className="w-8 h-8 text-indigo-600 animate-spin mx-auto mb-2" />
+ <p className="text-slate-500">Loading notebooks...</p>
+ </div>
+ ) : (
+ <>
+ {/* Record Preview */}
+ <div className="mb-4 p-3 bg-slate-50 rounded-xl border border-slate-100">
+ <div className="text-xs font-bold text-slate-500 uppercase tracking-wider mb-1">
+ Record Preview
+ </div>
+ <h4 className="font-semibold text-slate-900 truncate">
+ {title}
+ </h4>
+ <p className="text-xs text-slate-500 line-clamp-2 mt-1">
+ {userQuery}
+ </p>
+ </div>
+
+ {/* Notebook Selection */}
+ <div className="mb-4">
+ <div className="flex items-center justify-between mb-2">
+ <label className="text-xs font-bold text-slate-500 uppercase tracking-wider">
+ Select Notebooks
+ </label>
+ <button
+ onClick={() => setShowCreateForm(!showCreateForm)}
+ className="text-xs text-indigo-600 hover:text-indigo-700 flex items-center gap-1"
+ >
+ <Plus className="w-3 h-3" />
+ New Notebook
+ </button>
+ </div>
+
+ {/* Create New Notebook Form */}
+ {showCreateForm && (
+ <div className="mb-3 p-3 bg-indigo-50 rounded-xl border border-indigo-100 animate-in slide-in-from-top-2">
+ <input
+ type="text"
+ value={newNotebook.name}
+ onChange={(e) =>
+ setNewNotebook((prev) => ({
+ ...prev,
+ name: e.target.value,
+ }))
+ }
+ placeholder="Notebook name"
+ className="w-full px-3 py-2 mb-2 border border-indigo-200 rounded-lg text-sm focus:ring-2 focus:ring-indigo-500/20 focus:border-indigo-500 outline-none bg-white"
+ autoFocus
+ />
+ <div className="flex items-center gap-2 mb-2">
+ <span className="text-xs text-slate-500">Color:</span>
+ <div className="flex gap-1">
+ {COLORS.slice(0, 6).map((color) => (
+ <button
+ key={color}
+ onClick={() =>
+ setNewNotebook((prev) => ({ ...prev, color }))
+ }
+ className={`w-5 h-5 rounded transition-all ${
+ newNotebook.color === color
+ ? "ring-2 ring-offset-1 ring-slate-400 scale-110"
+ : ""
+ }`}
+ style={{ backgroundColor: color }}
+ />
+ ))}
+ </div>
+ </div>
+ <div className="flex justify-end gap-2">
+ <button
+ onClick={() => setShowCreateForm(false)}
+ className="px-3 py-1.5 text-xs text-slate-600 hover:bg-white rounded-lg transition-colors"
+ >
+ Cancel
+ </button>
+ <button
+ onClick={handleCreateNotebook}
+ disabled={!newNotebook.name.trim()}
+ className="px-3 py-1.5 text-xs bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 disabled:opacity-50 flex items-center gap-1"
+ >
+ <Plus className="w-3 h-3" />
+ Create
+ </button>
+ </div>
+ </div>
+ )}
+
+ {/* Notebook List */}
+ {notebooks.length === 0 ? (
+ <div className="py-8 text-center">
+ <FolderOpen className="w-10 h-10 text-slate-200 mx-auto mb-2" />
+ <p className="text-sm text-slate-500">No notebooks yet</p>
+ <p className="text-xs text-slate-400">
+ Create your first notebook above
+ </p>
+ </div>
+ ) : (
+ <div className="space-y-2 max-h-[240px] overflow-y-auto">
+ {notebooks.map((nb) => (
+ <button
+ key={nb.id}
+ onClick={() => toggleNotebook(nb.id)}
+ className={`w-full p-3 rounded-xl flex items-center gap-3 transition-all border-2 text-left ${
+ selectedIds.includes(nb.id)
+ ? "bg-indigo-50 border-indigo-300"
+ : "bg-white border-slate-200 hover:border-indigo-200 hover:bg-slate-50"
+ }`}
+ >
+ <div
+ className="w-10 h-10 rounded-lg flex items-center justify-center shrink-0"
+ style={{
+ backgroundColor: `${nb.color}20`,
+ color: nb.color,
+ }}
+ >
+ <BookOpen className="w-5 h-5" />
+ </div>
+ <div className="flex-1 min-w-0">
+ <h4 className="font-semibold text-slate-900 truncate text-sm">
+ {nb.name}
+ </h4>
+ <p className="text-xs text-slate-500">
+ {nb.record_count} records
+ </p>
+ </div>
+ <div
+ className={`w-5 h-5 rounded-full border-2 flex items-center justify-center shrink-0 transition-all ${
+ selectedIds.includes(nb.id)
+ ? "bg-indigo-600 border-indigo-600"
+ : "border-slate-300"
+ }`}
+ >
+ {selectedIds.includes(nb.id) && (
+ <Check className="w-3 h-3 text-white" />
+ )}
+ </div>
+ </button>
+ ))}
+ </div>
+ )}
+ </div>
+ </>
+ )}
+ </div>
+
+ {/* Footer */}
+ {!success && !loading && (
+ <div className="p-4 border-t border-slate-100 flex justify-between items-center">
+ <span className="text-xs text-slate-500">
+ {selectedIds.length > 0
+ ? `${selectedIds.length} notebook${selectedIds.length > 1 ? "s" : ""} selected`
+ : "Select at least one notebook"}
+ </span>
+ <div className="flex gap-2">
+ <button
+ onClick={onClose}
+ className="px-4 py-2 text-slate-600 hover:bg-slate-100 rounded-lg transition-colors text-sm"
+ >
+ Cancel
+ </button>
+ <button
+ onClick={handleSave}
+ disabled={selectedIds.length === 0 || saving}
+ className="px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 transition-colors disabled:opacity-50 text-sm flex items-center gap-2"
+ >
+ {saving ? (
+ <>
+ <Loader2 className="w-4 h-4 animate-spin" />
+ Saving...
+ </>
+ ) : (
+ <>
+ <Book className="w-4 h-4" />
+ Add to Notebook
+ </>
+ )}
+ </button>
+ </div>
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/web/components/CoMarkerEditor.tsx b/web/components/CoMarkerEditor.tsx
new file mode 100644
index 000000000..ba4a342ec
--- /dev/null
+++ b/web/components/CoMarkerEditor.tsx
@@ -0,0 +1,2112 @@
+"use client";
+
+import React, { useState, useRef, useEffect, useCallback } from "react";
+import {
+ Wand2,
+ Minimize2,
+ Maximize2,
+ Globe,
+ Database,
+ Loader2,
+ X,
+ History,
+ Bold,
+ Italic,
+ Underline as UnderlineIcon,
+ Highlighter,
+ Strikethrough,
+ Code,
+ Heading1,
+ Heading2,
+ List,
+ ListOrdered,
+ Quote,
+ Link,
+ Image,
+ Table,
+ Minus,
+ Download,
+ FileText,
+ PenTool,
+ Sparkles,
+ Eye,
+ EyeOff,
+ Wifi,
+ WifiOff,
+ AlertCircle,
+ Book,
+ Mic,
+ Headphones,
+ Radio,
+ ChevronDown,
+ ChevronRight,
+ LayoutTemplate,
+ Import,
+} from "lucide-react";
+import AddToNotebookModal from "./AddToNotebookModal";
+import NotebookImportModal from "./NotebookImportModal";
+import { apiUrl } from "@/lib/api";
+import ReactMarkdown from "react-markdown";
+import remarkGfm from "remark-gfm";
+import remarkMath from "remark-math";
+import rehypeKatex from "rehype-katex";
+import rehypeRaw from "rehype-raw";
+import "katex/dist/katex.min.css";
+import { processLatexContent } from "@/lib/latex";
+
+interface CoWriterEditorProps {
+ initialValue?: string;
+}
+
+// AI Mark tag regex patterns
+const AI_MARK_REGEX = /<span\s+data-rough-notation="[^"]+">([^<]*)<\/span>/g;
+const AI_MARK_OPEN_TAG = /<span\s+data-rough-notation="[^"]+">/g;
+const AI_MARK_CLOSE_TAG = /<\/span>/g;
+
+export default function CoWriterEditor({
+ initialValue = "",
+}: CoWriterEditorProps) {
+ const [content, setContent] = useState(
+ initialValue ||
+ "# Welcome to Co-Writer\n\nSelect text to see the magic happen.\n\n## Features\n\n- **Bold** text with Ctrl+B\n- *Italic* text with Ctrl+I\n- <u>Underline</u> with Ctrl+U\n- <mark>Highlight</mark> with Ctrl+H\n- AI-powered editing and auto-marking\n",
+ );
+ const [selection, setSelection] = useState<{
+ start: number;
+ end: number;
+ text: string;
+ } | null>(null);
+ const [popover, setPopover] = useState<{
+ visible: boolean;
+ x: number;
+ y: number;
+ } | null>(null);
+ const [instruction, setInstruction] = useState("");
+ const [selectedAction, setSelectedAction] = useState<
+ "rewrite" | "shorten" | "expand" | "automark"
+ >("rewrite");
+ const [source, setSource] = useState<"rag" | "web" | null>(null);
+ const [selectedKb, setSelectedKb] = useState("");
+ const [kbs, setKbs] = useState<string[]>([]);
+ const [isProcessing, setIsProcessing] = useState(false);
+ const [operationHistory, setOperationHistory] = useState<any[]>([]);
+ const [showHistory, setShowHistory] = useState(false);
+ const [hideAiMarks, setHideAiMarks] = useState(false);
+ const [rawContent, setRawContent] = useState(""); // Store original content with tags
+ const [backendConnected, setBackendConnected] = useState<boolean | null>(
+ null,
+ ); // null = checking, true = connected, false = disconnected
+ const [showNotebookModal, setShowNotebookModal] = useState(false);
+ const [showImportModal, setShowImportModal] = useState(false);
+
+ // Podcast / Narration related states
+ const [isPodcastExpanded, setIsPodcastExpanded] = useState(false);
+ const [narrationStyle, setNarrationStyle] = useState<
+ "friendly" | "academic" | "concise"
+ >("friendly");
+ const [narrationScript, setNarrationScript] = useState<string>("");
+ const [narrationKeyPoints, setNarrationKeyPoints] = useState<string[]>([]);
+ const [narrationLoading, setNarrationLoading] = useState<boolean>(false);
+ const [narrationError, setNarrationError] = useState<string | null>(null);
+ const [ttsAvailable, setTtsAvailable] = useState<boolean | null>(null);
+ const [ttsVoices, setTtsVoices] = useState<
+ Array<{ id: string; name: string; description?: string }>
+ >([]);
+ const [selectedVoice, setSelectedVoice] = useState<string>("alloy");
+ const [audioInfo, setAudioInfo] = useState<{
+ audioUrl?: string;
+ audioId?: string;
+ voice?: string;
+ } | null>(null);
+ const [showNarrationNotebookModal, setShowNarrationNotebookModal] =
+ useState(false);
+
+ const textareaRef = useRef<HTMLTextAreaElement>(null);
+ const popoverRef = useRef<HTMLDivElement>(null);
+ const previewRef = useRef<HTMLDivElement>(null);
+ const editorContainerRef = useRef<HTMLDivElement>(null);
+ const isSyncingScroll = useRef(false);
+
+ // Check backend connection status
+ const checkBackendConnection = useCallback(
+ async (silent: boolean = false) => {
+ try {
+ // Use AbortController for timeout (better compatibility)
+ const controller = new AbortController();
+ const timeoutId = setTimeout(() => controller.abort(), 3000); // 3s timeout
+
+ const response = await fetch(apiUrl("/api/v1/co_writer/history"), {
+ method: "GET",
+ signal: controller.signal,
+ });
+
+ clearTimeout(timeoutId);
+
+ if (response.ok) {
+ setBackendConnected(true);
+ return true;
+ } else {
+ setBackendConnected(false);
+ return false;
+ }
+ } catch (error: any) {
+ setBackendConnected(false);
+ // Only log errors in non-silent mode to avoid console noise
+ if (
+ !silent &&
+ error.name !== "AbortError" &&
+ process.env.NODE_ENV === "development"
+ ) {
+ // Only show detailed errors in development mode
+ console.debug(
+ "Backend connection check failed (this is normal if backend is not running):",
+ error.message,
+ );
+ }
+ return false;
+ }
+ },
+ [],
+ );
+
+ // Check TTS configuration and available voices
+ useEffect(() => {
+ const fetchTtsConfig = async () => {
+ try {
+ const statusRes = await fetch(apiUrl("/api/v1/co_writer/tts/status"));
+ if (statusRes.ok) {
+ const statusData = await statusRes.json();
+ if (statusData.available) {
+ setTtsAvailable(true);
+ if (statusData.default_voice) {
+ setSelectedVoice(statusData.default_voice);
+ }
+ // Further fetch available voice list
+ const voicesRes = await fetch(
+ apiUrl("/api/v1/co_writer/tts/voices"),
+ );
+ if (voicesRes.ok) {
+ const voicesData = await voicesRes.json();
+ setTtsVoices(voicesData.voices || []);
+ }
+ } else {
+ setTtsAvailable(false);
+ }
+ } else {
+ setTtsAvailable(false);
+ }
+ } catch (e) {
+ setTtsAvailable(false);
+ }
+ };
+ // Only check once when component mounts
+ fetchTtsConfig();
+ }, []);
+
+ // Fetch KBs
+ useEffect(() => {
+ const loadData = async () => {
+ setBackendConnected(null); // Start checking
+
+ try {
+ // First check connection (silent mode to avoid console noise)
+ const isConnected = await checkBackendConnection(true);
+
+ if (isConnected) {
+ // Load knowledge base list
+ try {
+ const controller = new AbortController();
+ const timeoutId = setTimeout(() => controller.abort(), 5000);
+
+ const res = await fetch(apiUrl("/api/v1/knowledge/list"), {
+ signal: controller.signal,
+ });
+
+ clearTimeout(timeoutId);
+
+ if (res.ok) {
+ const data = await res.json();
+ setKbs(data.map((kb: any) => kb.name));
+ if (data.length > 0) setSelectedKb(data[0].name);
+ }
+ } catch (err: any) {
+ // Only show errors in development mode
+ if (process.env.NODE_ENV === "development") {
+ console.debug(
+ "Failed to fetch KBs (backend may not be running):",
+ err.message,
+ );
+ }
+ }
+
+ // Load history
+ fetchHistory();
+ }
+ } catch (error: any) {
+ // Only show errors in development mode
+ if (process.env.NODE_ENV === "development") {
+ console.debug(
+ "Failed to initialize (backend may not be running):",
+ error.message,
+ );
+ }
+ }
+ };
+
+ loadData();
+ }, [checkBackendConnection]);
+
+ const fetchHistory = () => {
+ fetch(apiUrl("/api/v1/co_writer/history"))
+ .then((res) => {
+ if (res.ok) {
+ return res.json();
+ } else {
+ throw new Error(`HTTP ${res.status}`);
+ }
+ })
+ .then((data) => {
+ setOperationHistory(data.history || []);
+ setBackendConnected(true);
+ })
+ .catch((err) => {
+ // Only show errors in development mode to avoid console noise
+ if (process.env.NODE_ENV === "development") {
+ console.debug(
+ "Failed to fetch history (backend may not be running):",
+ err.message,
+ );
+ }
+ setBackendConnected(false);
+ });
+ };
+
+ // Auto clear source when automark is selected
+ useEffect(() => {
+ if (selectedAction === "automark") {
+ setSource(null);
+ }
+ }, [selectedAction]);
+
+ // Synchronized scroll functionality
+ const handleEditorScroll = useCallback(() => {
+ if (isSyncingScroll.current) return;
+ const editor = editorContainerRef.current;
+ const preview = previewRef.current;
+ if (!editor || !preview) return;
+
+ isSyncingScroll.current = true;
+ const scrollPercentage =
+ editor.scrollTop / (editor.scrollHeight - editor.clientHeight);
+ preview.scrollTop =
+ scrollPercentage * (preview.scrollHeight - preview.clientHeight);
+
+ requestAnimationFrame(() => {
+ isSyncingScroll.current = false;
+ });
+ }, []);
+
+ const handlePreviewScroll = useCallback(() => {
+ if (isSyncingScroll.current) return;
+ const editor = editorContainerRef.current;
+ const preview = previewRef.current;
+ if (!editor || !preview) return;
+
+ isSyncingScroll.current = true;
+ const scrollPercentage =
+ preview.scrollTop / (preview.scrollHeight - preview.clientHeight);
+ editor.scrollTop =
+ scrollPercentage * (editor.scrollHeight - editor.clientHeight);
+
+ requestAnimationFrame(() => {
+ isSyncingScroll.current = false;
+ });
+ }, []);
+
+ // Hide AI Marks functionality
+ const getDisplayContent = useCallback(() => {
+ if (!hideAiMarks) return content;
+ // Remove AI tags, show content only
+ return content.replace(AI_MARK_REGEX, "$1");
+ }, [content, hideAiMarks]);
+
+ // Save original content when hideAiMarks is enabled
+ useEffect(() => {
+ if (hideAiMarks && !rawContent) {
+ setRawContent(content);
+ } else if (!hideAiMarks && rawContent) {
+ // When restoring, need to map edits back to original content
+ setRawContent("");
+ }
+ }, [hideAiMarks]);
+
+ // Merge edits with tags - smart AI mark protection
+ const mergeEditWithMarks = useCallback(
+ (original: string, oldPlain: string, newPlain: string): string => {
+ // 1. Extract all marks and their positions in plain text
+ interface MarkInfo {
+ tag: string;
+ innerText: string;
+ plainStart: number; // Start position in plain text
+ plainEnd: number; // End position in plain text
+ }
+
+ const marks: MarkInfo[] = [];
+ const regex = /<span\s+data-rough-notation="([^"]+)">([^<]*)<\/span>/g;
+ let match;
+
+ // Calculate each mark's position in plain text
+ let plainOffset = 0;
+ let lastIndex = 0;
+
+ while ((match = regex.exec(original)) !== null) {
+ const tag = match[1];
+ const innerText = match[2];
+ const htmlStart = match.index;
+ const htmlEnd = htmlStart + match[0].length;
+
+ // Calculate plain text length before mark
+ const textBefore = original.substring(lastIndex, htmlStart);
+ plainOffset += textBefore.length;
+
+ marks.push({
+ tag,
+ innerText,
+ plainStart: plainOffset,
+ plainEnd: plainOffset + innerText.length,
+ });
+
+ plainOffset += innerText.length;
+ lastIndex = htmlEnd;
+ }
+
+ // 2. Find edited area (diff between old and new text)
+ let diffStart = 0;
+ let diffEndOld = oldPlain.length;
+ let diffEndNew = newPlain.length;
+
+ // Find first different position
+ while (
+ diffStart < oldPlain.length &&
+ diffStart < newPlain.length &&
+ oldPlain[diffStart] === newPlain[diffStart]
+ ) {
+ diffStart++;
+ }
+
+ // Find last different position (from end)
+ while (
+ diffEndOld > diffStart &&
+ diffEndNew > diffStart &&
+ oldPlain[diffEndOld - 1] === newPlain[diffEndNew - 1]
+ ) {
+ diffEndOld--;
+ diffEndNew--;
+ }
+
+ // 3. Check if each mark is modified
+ // Only remove mark when edit occurs inside the marked word
+ const marksToKeep: Array<{ mark: MarkInfo; newPosition: number }> = [];
+
+ for (const mark of marks) {
+ // Check if edit is inside mark
+ const editStartsInsideMark =
+ diffStart > mark.plainStart && diffStart < mark.plainEnd;
+ const editEndsInsideMark =
+ diffEndOld > mark.plainStart && diffEndOld < mark.plainEnd;
+ const editCompletelyInsideMark =
+ diffStart >= mark.plainStart && diffEndOld <= mark.plainEnd;
+
+ // Remove mark if edit is completely inside, or starts/ends inside mark
+ if (
+ editCompletelyInsideMark ||
+ editStartsInsideMark ||
+ editEndsInsideMark
+ ) {
+ // Mark modified, don't keep
+ continue;
+ }
+
+ // Mark not modified, try to find its position in new text
+ // Calculate offset caused by edit
+ let newPosition = mark.plainStart;
+
+ if (diffEndOld <= mark.plainStart) {
+ // Edit is before mark, position needs adjustment
+ const editLengthDiff =
+ diffEndNew - diffStart - (diffEndOld - diffStart);
+ newPosition = mark.plainStart + editLengthDiff;
+ } else if (diffStart >= mark.plainEnd) {
+ // Edit is after mark, position unchanged
+ newPosition = mark.plainStart;
+ } else {
+ // Edit overlaps with mark but not inside (e.g., edit starts before and ends after mark)
+ // In this case, mark may have moved, need to search
+ const searchRadius = 50;
+ const searchStart = Math.max(0, mark.plainStart - searchRadius);
+ const searchEnd = Math.min(
+ newPlain.length,
+ mark.plainEnd + searchRadius,
+ );
+ const searchArea = newPlain.substring(searchStart, searchEnd);
+ const foundIndex = searchArea.indexOf(mark.innerText);
+
+ if (foundIndex !== -1) {
+ newPosition = searchStart + foundIndex;
+ } else {
+ // Can't find mark text, possibly deleted, skip
+ continue;
+ }
+ }
+
+ // Validate text at new position matches
+ if (
+ newPosition >= 0 &&
+ newPosition + mark.innerText.length <= newPlain.length
+ ) {
+ const textAtPosition = newPlain.substring(
+ newPosition,
+ newPosition + mark.innerText.length,
+ );
+ if (textAtPosition === mark.innerText) {
+ marksToKeep.push({ mark, newPosition });
+ }
+ }
+ }
+
+ // 4. Insert marks from end to start to avoid position offset
+ marksToKeep.sort((a, b) => b.newPosition - a.newPosition);
+
+ let result = newPlain;
+ for (const { mark, newPosition } of marksToKeep) {
+ const before = result.substring(0, newPosition);
+ const after = result.substring(newPosition + mark.innerText.length);
+ const markedText = `<span data-rough-notation="${mark.tag}">${mark.innerText}</span>`;
+ result = before + markedText + after;
+ }
+
+ return result;
+ },
+ [],
+ );
+
+ // Handle content changes in hidden mode
+ const handleContentChange = useCallback(
+ (newValue: string) => {
+ if (!hideAiMarks) {
+ setContent(newValue);
+ return;
+ }
+
+ // In hidden mode, need to protect tags
+ // Use functional update to avoid content state dependency
+ setContent((prevContent) => {
+ const oldDisplayContent = prevContent.replace(AI_MARK_REGEX, "$1");
+ const newDisplayContent = newValue;
+
+ if (oldDisplayContent === newDisplayContent) {
+ return prevContent;
+ }
+
+ // Simplified: if user edits in hidden mode, replace entire content
+ // But keep tags that weren't edited
+ return mergeEditWithMarks(
+ prevContent,
+ oldDisplayContent,
+ newDisplayContent,
+ );
+ });
+ },
+ [hideAiMarks, mergeEditWithMarks],
+ );
+
+ // Wrap selection with markers
+ const wrapSelection = useCallback((before: string, after: string) => {
+ const textarea = textareaRef.current;
+ if (!textarea) return;
+
+ const start = textarea.selectionStart;
+ const end = textarea.selectionEnd;
+ const selectedText = textarea.value.substring(start, end);
+
+ if (selectedText.length === 0) return;
+
+ // Check if already wrapped
+ const textBefore = textarea.value.substring(
+ Math.max(0, start - before.length),
+ start,
+ );
+ const textAfter = textarea.value.substring(end, end + after.length);
+
+ let newContent: string;
+ let newStart: number;
+ let newEnd: number;
+
+ if (textBefore === before && textAfter === after) {
+ // Remove wrapping
+ newContent =
+ textarea.value.substring(0, start - before.length) +
+ selectedText +
+ textarea.value.substring(end + after.length);
+ newStart = start - before.length;
+ newEnd = end - before.length;
+ } else {
+ // Add wrapping
+ newContent =
+ textarea.value.substring(0, start) +
+ before +
+ selectedText +
+ after +
+ textarea.value.substring(end);
+ newStart = start + before.length;
+ newEnd = end + before.length;
+ }
+
+ setContent(newContent);
+
+ // Restore selection after state update
+ setTimeout(() => {
+ textarea.focus();
+ textarea.setSelectionRange(newStart, newEnd);
+ }, 0);
+ }, []);
+
+ // Toggle line prefix
+ const toggleLinePrefix = useCallback((prefix: string) => {
+ const textarea = textareaRef.current;
+ if (!textarea) return;
+
+ const start = textarea.selectionStart;
+ const end = textarea.selectionEnd;
+ const lines = textarea.value.split("\n");
+
+ // Find line indices
+ let charCount = 0;
+ let startLine = 0;
+ let endLine = 0;
+
+ for (let i = 0; i < lines.length; i++) {
+ if (charCount <= start && start <= charCount + lines[i].length) {
+ startLine = i;
+ }
+ if (charCount <= end && end <= charCount + lines[i].length) {
+ endLine = i;
+ break;
+ }
+ charCount += lines[i].length + 1;
+ }
+
+ // Check if all lines have prefix
+ let allHavePrefix = true;
+ for (let i = startLine; i <= endLine; i++) {
+ if (!lines[i].startsWith(prefix)) {
+ allHavePrefix = false;
+ break;
+ }
+ }
+
+ // Toggle prefix
+ for (let i = startLine; i <= endLine; i++) {
+ if (allHavePrefix) {
+ lines[i] = lines[i].substring(prefix.length);
+ } else {
+ lines[i] = prefix + lines[i];
+ }
+ }
+
+ setContent(lines.join("\n"));
+ }, []);
+
+ // Keyboard shortcuts
+ useEffect(() => {
+ const handleKeyDown = (e: KeyboardEvent) => {
+ if (
+ !textareaRef.current ||
+ document.activeElement !== textareaRef.current
+ )
+ return;
+
+ if (e.ctrlKey || e.metaKey) {
+ switch (e.key.toLowerCase()) {
+ case "b":
+ e.preventDefault();
+ wrapSelection("**", "**");
+ break;
+ case "i":
+ e.preventDefault();
+ wrapSelection("*", "*");
+ break;
+ case "u":
+ e.preventDefault();
+ wrapSelection("<u>", "</u>");
+ break;
+ case "h":
+ e.preventDefault();
+ wrapSelection("<mark>", "</mark>");
+ break;
+ case "s":
+ if (e.shiftKey) {
+ e.preventDefault();
+ wrapSelection("~~", "~~");
+ }
+ break;
+ }
+ }
+ };
+
+ document.addEventListener("keydown", handleKeyDown);
+ return () => document.removeEventListener("keydown", handleKeyDown);
+ }, [wrapSelection]);
+
+ // Handle selection for popover
+ const handleMouseUp = (e: React.MouseEvent) => {
+ const textarea = textareaRef.current;
+ if (!textarea) return;
+
+ const start = textarea.selectionStart;
+ const end = textarea.selectionEnd;
+ const text = textarea.value.substring(start, end);
+
+ if (text.trim().length > 0) {
+ const rect = textarea.getBoundingClientRect();
+ let x = e.clientX;
+ let y = e.clientY + 10;
+
+ setSelection({ start, end, text });
+ setPopover({ visible: true, x, y });
+ setInstruction("");
+ setSelectedAction("rewrite");
+ setSource(null);
+ } else {
+ setPopover(null);
+ setSelection(null);
+ }
+ };
+
+ // Close popover on click outside
+ useEffect(() => {
+ const handleClickOutside = (event: MouseEvent) => {
+ if (
+ popoverRef.current &&
+ !popoverRef.current.contains(event.target as Node) &&
+ textareaRef.current &&
+ !textareaRef.current.contains(event.target as Node)
+ ) {
+ setPopover(null);
+ setSelection(null);
+ }
+ };
+ document.addEventListener("mousedown", handleClickOutside);
+ return () => document.removeEventListener("mousedown", handleClickOutside);
+ }, []);
+
+ const handleAction = async (
+ action: "rewrite" | "shorten" | "expand" | "automark",
+ ) => {
+ if (!selection) return;
+
+ // If backend not connected, check once first
+ if (backendConnected === false) {
+ const isConnected = await checkBackendConnection();
+ if (!isConnected) {
+ alert(
+ `❌ Backend service not connected\n\n` +
+ `Please ensure the backend is running:\n` +
+ `📍 ${apiUrl("")}\n\n` +
+ `💡 How to start:\n` +
+ ` Run in project root: python start.py\n` +
+ ` Or: python start_web.py`,
+ );
+ return;
+ }
+ }
+
+ setIsProcessing(true);
+
+ try {
+ let editedText: string;
+ const apiEndpoint =
+ action === "automark"
+ ? "/api/v1/co_writer/automark"
+ : "/api/v1/co_writer/edit";
+ const requestUrl = apiUrl(apiEndpoint);
+
+ if (action === "automark") {
+ const requestBody = { text: selection.text };
+ console.log("Sending automark request to:", requestUrl, requestBody);
+
+ const res = await fetch(requestUrl, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(requestBody),
+ });
+
+ if (!res.ok) {
+ const errorText = await res.text();
+ console.error("Automark API error:", res.status, errorText);
+ throw new Error(
+ `Failed to auto-mark text: ${res.status} ${res.statusText}\n${errorText}`,
+ );
+ }
+
+ const data = await res.json();
+ if (!data.marked_text) {
+ throw new Error("Invalid response: missing marked_text field");
+ }
+ editedText = data.marked_text;
+ } else {
+ const requestBody: any = {
+ text: selection.text,
+ instruction: instruction || `Please ${action} this text.`,
+ action,
+ };
+
+ // Only add source in non-automark mode
+ if (source) {
+ requestBody.source = source;
+ if (source === "rag" && selectedKb) {
+ requestBody.kb_name = selectedKb;
+ }
+ }
+
+ console.log("Sending edit request to:", requestUrl, requestBody);
+
+ const res = await fetch(requestUrl, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(requestBody),
+ });
+
+ if (!res.ok) {
+ const errorText = await res.text();
+ console.error("Edit API error:", res.status, errorText);
+ throw new Error(
+ `Failed to edit text: ${res.status} ${res.statusText}\n${errorText}`,
+ );
+ }
+
+ const data = await res.json();
+ if (!data.edited_text) {
+ throw new Error("Invalid response: missing edited_text field");
+ }
+ editedText = data.edited_text;
+ }
+
+ const newContent =
+ content.substring(0, selection.start) +
+ editedText +
+ content.substring(selection.end);
+ setContent(newContent);
+ setPopover(null);
+ setSelection(null);
+ fetchHistory();
+ } catch (error: any) {
+ console.error("Action error:", error);
+
+ // Update backend connection status
+ setBackendConnected(false);
+
+ // Build detailed error message
+ let errorMessage = "Error processing request";
+ const backendUrl = apiUrl("");
+
+ if (
+ error instanceof TypeError &&
+ (error.message.includes("fetch") || error.message === "Failed to fetch")
+ ) {
+ errorMessage =
+ `❌ Cannot connect to backend service\n\n` +
+ `Please ensure the backend is running:\n` +
+ `📍 ${backendUrl}\n\n` +
+ `💡 How to start:\n` +
+ ` Run in project root: python start.py\n` +
+ ` Or: python start_web.py\n\n` +
+ `If running on a different port, check NEXT_PUBLIC_API_BASE env variable`;
+ } else if (
+ error.name === "AbortError" ||
+ error.message.includes("timeout")
+ ) {
+ errorMessage =
+ `⏱️ Request timeout\n\n` +
+ `Backend response took too long, please check:\n` +
+ `1. Is the backend running properly?\n` +
+ `2. Is network connection stable?\n` +
+ `3. Is server load too high?`;
+ } else if (error.message) {
+ errorMessage = `❌ ${error.message}`;
+ } else {
+ errorMessage = `❌ Unknown error: ${String(error)}`;
+ }
+
+ alert(errorMessage);
+ } finally {
+ setIsProcessing(false);
+ }
+ };
+
+ // Export functions
+ const exportMarkdown = () => {
+ const blob = new Blob([content], { type: "text/markdown" });
+ const url = URL.createObjectURL(blob);
+ const a = document.createElement("a");
+ a.href = url;
+ a.download = "document.md";
+ a.click();
+ URL.revokeObjectURL(url);
+ };
+
+ const exportPDF = async () => {
+ if (!previewRef.current) return;
+ setIsProcessing(true);
+
+ try {
+ // Dynamically import jspdf and html2canvas
+ const [{ default: jsPDF }, { default: html2canvas }] = await Promise.all([
+ import("jspdf"),
+ import("html2canvas"),
+ ]);
+
+ // Create temp container for PDF export
+ const tempContainer = document.createElement("div");
+ tempContainer.className = "pdf-export-container";
+ tempContainer.style.cssText = `
+ position: fixed;
+ left: 0;
+ top: 0;
+ width: 210mm;
+ min-height: 297mm;
+ padding: 20mm;
+ background: white;
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
+ font-size: 12pt;
+ line-height: 1.6;
+ color: #1e293b;
+ z-index: 9999;
+ overflow: visible;
+ `;
+
+ // Clone preview content
+ const previewClone = previewRef.current.cloneNode(true) as HTMLElement;
+ tempContainer.appendChild(previewClone);
+ document.body.appendChild(tempContainer);
+
+ // Copy all related stylesheets
+ const allStyles = Array.from(document.styleSheets);
+ const styleElement = document.createElement("style");
+ styleElement.id = "pdf-export-styles";
+
+ // Collect all style rules
+ let styleText = "";
+
+ // Add base styles
+ styleText += `
+ .pdf-export-container {
+ position: fixed !important;
+ left: 0 !important;
+ top: 0 !important;
+ width: 210mm !important;
+ padding: 20mm !important;
+ background: white !important;
+ }
+
+ /* Prose styles */
+ .prose {
+ max-width: none !important;
+ color: #1e293b !important;
+ }
+
+ .prose h1, .prose h2, .prose h3, .prose h4 {
+ font-weight: 600 !important;
+ margin-top: 1.5em !important;
+ margin-bottom: 0.5em !important;
+ color: #0f172a !important;
+ }
+
+ .prose p {
+ margin-bottom: 1em !important;
+ line-height: 1.7 !important;
+ }
+
+ .prose ul, .prose ol {
+ margin-bottom: 1em !important;
+ padding-left: 1.5em !important;
+ }
+
+ .prose code {
+ background: #f1f5f9 !important;
+ padding: 0.125em 0.375em !important;
+ border-radius: 0.25em !important;
+ font-size: 0.9em !important;
+ font-family: 'Consolas', 'Monaco', monospace !important;
+ }
+
+ .prose pre {
+ background: #0f172a !important;
+ color: #e2e8f0 !important;
+ padding: 1em !important;
+ border-radius: 0.5em !important;
+ overflow-x: auto !important;
+ margin: 1em 0 !important;
+ }
+
+ .prose pre code {
+ background: transparent !important;
+ padding: 0 !important;
+ color: inherit !important;
+ }
+
+ .prose blockquote {
+ border-left: 4px solid #8b5cf6 !important;
+ padding-left: 1em !important;
+ margin: 1em 0 !important;
+ font-style: italic !important;
+ color: #475569 !important;
+ }
+
+ .prose table {
+ width: 100% !important;
+ border-collapse: collapse !important;
+ margin: 1em 0 !important;
+ }
+
+ .prose th, .prose td {
+ border: 1px solid #cbd5e1 !important;
+ padding: 0.5em !important;
+ }
+
+ .prose th {
+ background: #f1f5f9 !important;
+ font-weight: 600 !important;
+ }
+ `;
+
+ // Add complete Rough Notation styles
+ styleText += `
+ /* Rough Notation - Complete Styles */
+ .rough-notation {
+ display: inline !important;
+ position: relative !important;
+ }
+
+ /* Circle annotation */
+ .rough-circle {
+ position: relative !important;
+ display: inline-block !important;
+ padding: 0 6px !important;
+ }
+
+ .rough-circle::before {
+ content: '' !important;
+ position: absolute !important;
+ top: -4px !important;
+ left: -4px !important;
+ right: -4px !important;
+ bottom: -4px !important;
+ border: 2.5px solid #ef4444 !important;
+ border-radius: 50% !important;
+ transform: rotate(-2deg) !important;
+ pointer-events: none !important;
+ }
+
+ .rough-circle::after {
+ content: '' !important;
+ position: absolute !important;
+ top: -3px !important;
+ left: -2px !important;
+ right: -6px !important;
+ bottom: -5px !important;
+ border: 1.5px solid rgba(239, 68, 68, 0.4) !important;
+ border-radius: 45% 55% 50% 50% !important;
+ transform: rotate(1deg) !important;
+ pointer-events: none !important;
+ }
+
+ /* Highlight annotation */
+ .rough-highlight {
+ background: linear-gradient(
+ 104deg,
+ rgba(254, 240, 138, 0) 0.9%,
+ rgba(254, 240, 138, 1) 2.4%,
+ rgba(254, 240, 138, 0.5) 5.8%,
+ rgba(254, 240, 138, 0.3) 93%,
+ rgba(254, 240, 138, 0.8) 96%,
+ rgba(254, 240, 138, 0) 98%
+ ),
+ linear-gradient(
+ 183deg,
+ rgba(254, 240, 138, 0) 0%,
+ rgba(254, 240, 138, 0.4) 7.9%,
+ rgba(254, 240, 138, 0) 15%
+ ) !important;
+ padding: 0.1em 0.2em !important;
+ margin: 0 -0.2em !important;
+ border-radius: 0.2em !important;
+ box-decoration-break: clone !important;
+ -webkit-box-decoration-break: clone !important;
+ }
+
+ /* Box annotation */
+ .rough-box {
+ position: relative !important;
+ display: inline-block !important;
+ padding: 2px 6px !important;
+ }
+
+ .rough-box::before {
+ content: '' !important;
+ position: absolute !important;
+ top: -2px !important;
+ left: -3px !important;
+ right: -3px !important;
+ bottom: -2px !important;
+ border: 2px solid #3b82f6 !important;
+ border-radius: 2px !important;
+ transform: rotate(-0.5deg) skewX(-0.5deg) !important;
+ pointer-events: none !important;
+ }
+
+ .rough-box::after {
+ content: '' !important;
+ position: absolute !important;
+ top: 0px !important;
+ left: -1px !important;
+ right: -5px !important;
+ bottom: -4px !important;
+ border: 1.5px solid rgba(59, 130, 246, 0.3) !important;
+ border-radius: 1px !important;
+ transform: rotate(0.5deg) !important;
+ pointer-events: none !important;
+ }
+
+ /* Underline annotation */
+ .rough-underline {
+ position: relative !important;
+ text-decoration: none !important;
+ }
+
+ .rough-underline::after {
+ content: '' !important;
+ position: absolute !important;
+ left: 0 !important;
+ right: 0 !important;
+ bottom: -2px !important;
+ height: 4px !important;
+ background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 20 4'%3E%3Cpath d='M0 3 Q5 0 10 3 T20 3' stroke='%231e293b' stroke-width='1.5' fill='none' stroke-linecap='round'/%3E%3C/svg%3E") repeat-x !important;
+ background-size: 12px 4px !important;
+ pointer-events: none !important;
+ }
+
+ /* Bracket annotation */
+ .rough-bracket {
+ display: inline !important;
+ }
+
+ .rough-bracket-container {
+ position: relative !important;
+ padding-left: 16px !important;
+ margin-left: 4px !important;
+ }
+
+ .rough-bracket-container::before {
+ content: '' !important;
+ position: absolute !important;
+ left: 0 !important;
+ top: -4px !important;
+ bottom: -4px !important;
+ width: 10px !important;
+ border-left: 3px solid #8b5cf6 !important;
+ border-top: 3px solid #8b5cf6 !important;
+ border-bottom: 3px solid #8b5cf6 !important;
+ border-radius: 4px 0 0 4px !important;
+ transform: scaleX(0.6) !important;
+ transform-origin: left center !important;
+ pointer-events: none !important;
+ }
+
+ span.rough-bracket {
+ border-left: 3px solid #8b5cf6 !important;
+ padding-left: 8px !important;
+ margin-left: 4px !important;
+ display: inline !important;
+ position: relative !important;
+ }
+
+ span.rough-bracket::before {
+ content: '' !important;
+ position: absolute !important;
+ left: -3px !important;
+ top: -2px !important;
+ width: 8px !important;
+ height: 3px !important;
+ border-left: 3px solid #8b5cf6 !important;
+ border-top: 3px solid #8b5cf6 !important;
+ border-radius: 3px 0 0 0 !important;
+ pointer-events: none !important;
+ }
+
+ span.rough-bracket::after {
+ content: '' !important;
+ position: absolute !important;
+ left: -3px !important;
+ bottom: -2px !important;
+ width: 8px !important;
+ height: 3px !important;
+ border-left: 3px solid #8b5cf6 !important;
+ border-bottom: 3px solid #8b5cf6 !important;
+ border-radius: 0 0 0 3px !important;
+ pointer-events: none !important;
+ }
+ `;
+
+ styleElement.textContent = styleText;
+ document.head.appendChild(styleElement);
+
+ // Wait for styles to apply and render
+ await new Promise((resolve) => setTimeout(resolve, 100));
+
+ // Force layout recalculation
+ tempContainer.offsetHeight;
+
+ const canvas = await html2canvas(tempContainer, {
+ scale: 2,
+ useCORS: true,
+ logging: false,
+ backgroundColor: "#ffffff",
+ allowTaint: true,
+ removeContainer: false,
+ imageTimeout: 15000,
+ onclone: (clonedDoc) => {
+ // Ensure styles are applied in cloned document
+ const clonedStyle = clonedDoc.getElementById("pdf-export-styles");
+ if (!clonedStyle) {
+ const newStyle = clonedDoc.createElement("style");
+ newStyle.id = "pdf-export-styles";
+ newStyle.textContent = styleText;
+ clonedDoc.head.appendChild(newStyle);
+ }
+ },
+ });
+
+ // Cleanup
+ document.body.removeChild(tempContainer);
+ const styleToRemove = document.getElementById("pdf-export-styles");
+ if (styleToRemove) {
+ document.head.removeChild(styleToRemove);
+ }
+
+ const imgData = canvas.toDataURL("image/png", 1.0);
+ const pdf = new jsPDF("p", "mm", "a4");
+ const pdfWidth = pdf.internal.pageSize.getWidth();
+ const pdfHeight = pdf.internal.pageSize.getHeight();
+ const margin = 10; // 10mm margins
+ const contentWidth = pdfWidth - margin * 2;
+
+ const imgProps = pdf.getImageProperties(imgData);
+ const imgHeight = (imgProps.height * contentWidth) / imgProps.width;
+
+ let heightLeft = imgHeight;
+ let position = margin;
+
+ // Add first page
+ pdf.addImage(imgData, "PNG", margin, position, contentWidth, imgHeight);
+ heightLeft -= pdfHeight - margin * 2;
+
+ // Add subsequent pages
+ while (heightLeft > 0) {
+ pdf.addPage();
+ position = margin - (imgHeight - heightLeft);
+ pdf.addImage(imgData, "PNG", margin, position, contentWidth, imgHeight);
+ heightLeft -= pdfHeight - margin * 2;
+ }
+
+ pdf.save("document.pdf");
+ } catch (e) {
+ console.error("PDF export error:", e);
+ alert(
+ "PDF export failed, please try again. Check console for error details.",
+ );
+ } finally {
+ setIsProcessing(false);
+ }
+ };
+
+ // Toolbar button component
+ const ToolbarButton = ({
+ icon,
+ onClick,
+ title,
+ active,
+ }: {
+ icon: React.ReactNode;
+ onClick: () => void;
+ title: string;
+ active?: boolean;
+ }) => (
+ <button
+ onClick={onClick}
+ title={title}
+ className={`p-1.5 rounded transition-all ${active ? "bg-purple-100 text-purple-700" : "text-slate-500 hover:bg-slate-100 hover:text-slate-700"}`}
+ >
+ {icon}
+ </button>
+ );
+
+ const Divider = () => <div className="w-px h-5 bg-slate-200 mx-1" />;
+
+ return (
+ <div className="flex h-full gap-4">
+ {/* Left Column: Editor */}
+ <div className="flex-1 flex flex-col bg-white rounded-xl shadow-sm border border-slate-200 overflow-hidden relative">
+ {/* Toolbar */}
+ <div className="p-2 border-b border-slate-100 bg-slate-50/50 flex items-center gap-1 flex-wrap">
+ {/* Formatting */}
+ <div className="flex items-center gap-0.5">
+ <ToolbarButton
+ icon={<Bold className="w-4 h-4" />}
+ onClick={() => wrapSelection("**", "**")}
+ title="Bold (Ctrl+B)"
+ />
+ <ToolbarButton
+ icon={<Italic className="w-4 h-4" />}
+ onClick={() => wrapSelection("*", "*")}
+ title="Italic (Ctrl+I)"
+ />
+ <ToolbarButton
+ icon={<UnderlineIcon className="w-4 h-4" />}
+ onClick={() => wrapSelection("<u>", "</u>")}
+ title="Underline (Ctrl+U)"
+ />
+ <ToolbarButton
+ icon={<Highlighter className="w-4 h-4" />}
+ onClick={() => wrapSelection("<mark>", "</mark>")}
+ title="Highlight (Ctrl+H)"
+ />
+ <ToolbarButton
+ icon={<Strikethrough className="w-4 h-4" />}
+ onClick={() => wrapSelection("~~", "~~")}
+ title="Strikethrough (Ctrl+Shift+S)"
+ />
+ <ToolbarButton
+ icon={<Code className="w-4 h-4" />}
+ onClick={() => wrapSelection("`", "`")}
+ title="Inline Code"
+ />
+ </div>
+
+ <Divider />
+
+ {/* Headings */}
+ <div className="flex items-center gap-0.5">
+ <ToolbarButton
+ icon={<Heading1 className="w-4 h-4" />}
+ onClick={() => toggleLinePrefix("# ")}
+ title="Heading 1"
+ />
+ <ToolbarButton
+ icon={<Heading2 className="w-4 h-4" />}
+ onClick={() => toggleLinePrefix("## ")}
+ title="Heading 2"
+ />
+ </div>
+
+ <Divider />
+
+ {/* Lists */}
+ <div className="flex items-center gap-0.5">
+ <ToolbarButton
+ icon={<List className="w-4 h-4" />}
+ onClick={() => toggleLinePrefix("- ")}
+ title="Bullet List"
+ />
+ <ToolbarButton
+ icon={<ListOrdered className="w-4 h-4" />}
+ onClick={() => toggleLinePrefix("1. ")}
+ title="Numbered List"
+ />
+ <ToolbarButton
+ icon={<Quote className="w-4 h-4" />}
+ onClick={() => toggleLinePrefix("> ")}
+ title="Quote"
+ />
+ </div>
+
+ <Divider />
+
+ {/* Insert */}
+ <div className="flex items-center gap-0.5">
+ <ToolbarButton
+ icon={<Link className="w-4 h-4" />}
+ onClick={() => wrapSelection("[", "](url)")}
+ title="Link"
+ />
+ <ToolbarButton
+ icon={<Image className="w-4 h-4" />}
+ onClick={() => wrapSelection("![", "](url)")}
+ title="Image"
+ />
+ <ToolbarButton
+ icon={<Minus className="w-4 h-4" />}
+ onClick={() => {
+ const textarea = textareaRef.current;
+ if (!textarea) return;
+ const pos = textarea.selectionStart;
+ setContent(
+ content.substring(0, pos) +
+ "\n\n---\n\n" +
+ content.substring(pos),
+ );
+ }}
+ title="Horizontal Rule"
+ />
+ </div>
+
+ <Divider />
+
+ {/* Import from Notebook */}
+ <button
+ onClick={() => setShowImportModal(true)}
+ className="flex items-center gap-1 px-2 py-1 text-xs text-blue-600 hover:bg-blue-50 rounded transition-all"
+ title="Import from Notebook"
+ >
+ <Import className="w-3.5 h-3.5" />
+ Import
+ </button>
+
+ <div className="flex-1" />
+
+ {/* Backend Status Indicator */}
+ {backendConnected !== null && (
+ <>
+ <div
+ className={`flex items-center gap-1 px-2 py-1 text-xs rounded transition-all ${
+ backendConnected
+ ? "bg-green-50 text-green-700 border border-green-200"
+ : "bg-red-50 text-red-700 border border-red-200"
+ }`}
+ title={
+ backendConnected
+ ? `Backend connected: ${apiUrl("")}`
+ : `Backend not connected\nRun: python start.py\nAddress: ${apiUrl("")}`
+ }
+ >
+ {backendConnected ? (
+ <>
+ <Wifi className="w-3 h-3" />
+ <span className="hidden sm:inline">Connected</span>
+ </>
+ ) : (
+ <>
+ <WifiOff className="w-3 h-3" />
+ <span className="hidden sm:inline">Disconnected</span>
+ </>
+ )}
+ </div>
+ </>
+ )}
+ </div>
+
+ {/* Editor Area */}
+ <div className="flex-1 flex flex-col overflow-hidden">
+ <div className="p-2 border-b border-slate-100 bg-slate-50/30 flex justify-between items-center">
+ <div className="flex items-center gap-2">
+ <div className="text-[10px] font-bold text-slate-400 uppercase tracking-wider">
+ Editor
+ </div>
+ {hideAiMarks && (
+ <span className="text-[9px] bg-emerald-100 text-emerald-600 px-1.5 py-0.5 rounded-full font-medium">
+ Marks Hidden
+ </span>
+ )}
+ </div>
+ <div className="text-[10px] text-slate-400">
+ {content.length} chars · {content.split("\n").length} lines
+ </div>
+ </div>
+ <div
+ ref={editorContainerRef}
+ className="flex-1 overflow-y-auto"
+ onScroll={handleEditorScroll}
+ >
+ <textarea
+ ref={textareaRef}
+ value={hideAiMarks ? getDisplayContent() : content}
+ onChange={(e) => handleContentChange(e.target.value)}
+ onMouseUp={handleMouseUp}
+ className="w-full h-full min-h-full p-4 resize-none outline-none font-mono text-sm leading-relaxed text-slate-800 bg-transparent"
+ placeholder="Type your markdown here..."
+ style={{ minHeight: "100%" }}
+ />
+ </div>
+ </div>
+
+ {/* Popover */}
+ {popover && (
+ <div
+ ref={popoverRef}
+ style={{
+ position: "fixed",
+ left: Math.min(
+ window.innerWidth - 340,
+ Math.max(20, popover.x - 160),
+ ),
+ top: Math.min(window.innerHeight - 480, popover.y),
+ }}
+ className="z-50 w-[320px] bg-white rounded-xl shadow-2xl border border-slate-200 animate-in fade-in zoom-in-95 duration-200 flex flex-col"
+ >
+ <div className="p-3 border-b border-slate-100 bg-gradient-to-r from-purple-50 to-indigo-50 flex justify-between items-center rounded-t-xl">
+ <div className="flex items-center gap-2 text-xs font-bold text-slate-700">
+ <Sparkles className="w-4 h-4 text-purple-500" />
+ AI Edit Assistant
+ </div>
+ <button
+ onClick={() => setPopover(null)}
+ className="text-slate-400 hover:text-slate-600"
+ title="Close"
+ aria-label="Close dialog"
+ >
+ <X className="w-4 h-4" />
+ </button>
+ </div>
+
+ <div className="p-4 space-y-4">
+ {/* Selected Text Preview */}
+ <div className="text-xs text-slate-500 bg-slate-50 p-2 rounded-lg border border-slate-100 line-clamp-2 italic">
+ "{selection?.text}"
+ </div>
+
+ {/* Instruction Input */}
+ <div className="space-y-1">
+ <label className="text-[10px] font-bold text-slate-500 uppercase">
+ Instruction (Optional)
+ </label>
+ <input
+ type="text"
+ value={instruction}
+ onChange={(e) => setInstruction(e.target.value)}
+ placeholder="e.g. Make it more formal..."
+ className="w-full px-3 py-2 text-xs border border-slate-200 rounded-lg focus:ring-2 focus:ring-purple-500/20 focus:border-purple-500 outline-none"
+ />
+ </div>
+
+ {/* Source Selection - Only show in non-automark mode */}
+ {selectedAction !== "automark" && (
+ <div className="space-y-1">
+ <label className="text-[10px] font-bold text-slate-500 uppercase">
+ Context Source (Optional)
+ </label>
+ <div className="flex gap-2">
+ <button
+ onClick={() => setSource(source === "rag" ? null : "rag")}
+ className={`flex-1 flex items-center justify-center gap-1 py-1.5 text-xs border rounded-lg transition-all ${source === "rag" ? "bg-purple-50 border-purple-200 text-purple-700" : "bg-white border-slate-200 text-slate-600 hover:bg-slate-50"}`}
+ >
+ <Database className="w-3 h-3" />
+ RAG
+ </button>
+ <button
+ onClick={() => setSource(source === "web" ? null : "web")}
+ className={`flex-1 flex items-center justify-center gap-1 py-1.5 text-xs border rounded-lg transition-all ${source === "web" ? "bg-blue-50 border-blue-200 text-blue-700" : "bg-white border-slate-200 text-slate-600 hover:bg-slate-50"}`}
+ >
+ <Globe className="w-3 h-3" />
+ Web
+ </button>
+ </div>
+ </div>
+ )}
+
+ {/* KB Selector if RAG */}
+ {source === "rag" && kbs.length > 0 && (
+ <div className="animate-in fade-in slide-in-from-top-1">
+ <select
+ value={selectedKb}
+ onChange={(e) => setSelectedKb(e.target.value)}
+ className="w-full px-2 py-1.5 text-xs border border-slate-200 rounded-lg outline-none"
+ >
+ {kbs.map((kb) => (
+ <option key={kb} value={kb}>
+ {kb}
+ </option>
+ ))}
+ </select>
+ </div>
+ )}
+
+ {/* Actions */}
+ <div className="pt-2 border-t border-slate-100 space-y-3">
+ <div className="grid grid-cols-4 gap-1.5">
+ <button
+ onClick={() => setSelectedAction("rewrite")}
+ disabled={isProcessing}
+ className={`flex flex-col items-center gap-1 p-2 rounded-lg transition-all text-[10px] font-medium border-2 ${selectedAction === "rewrite" ? "bg-purple-50 border-purple-400 text-purple-600" : "border-transparent text-slate-600 hover:bg-purple-50 hover:text-purple-600"}`}
+ >
+ <Wand2 className="w-4 h-4" />
+ Rewrite
+ </button>
+ <button
+ onClick={() => setSelectedAction("shorten")}
+ disabled={isProcessing}
+ className={`flex flex-col items-center gap-1 p-2 rounded-lg transition-all text-[10px] font-medium border-2 ${selectedAction === "shorten" ? "bg-amber-50 border-amber-400 text-amber-600" : "border-transparent text-slate-600 hover:bg-amber-50 hover:text-amber-600"}`}
+ >
+ <Minimize2 className="w-4 h-4" />
+ Shorten
+ </button>
+ <button
+ onClick={() => setSelectedAction("expand")}
+ disabled={isProcessing}
+ className={`flex flex-col items-center gap-1 p-2 rounded-lg transition-all text-[10px] font-medium border-2 ${selectedAction === "expand" ? "bg-blue-50 border-blue-400 text-blue-600" : "border-transparent text-slate-600 hover:bg-blue-50 hover:text-blue-600"}`}
+ >
+ <Maximize2 className="w-4 h-4" />
+ Expand
+ </button>
+ <button
+ onClick={() => setSelectedAction("automark")}
+ disabled={isProcessing}
+ className={`flex flex-col items-center gap-1 p-2 rounded-lg transition-all text-[10px] font-medium border-2 ${selectedAction === "automark" ? "bg-emerald-50 border-emerald-400 text-emerald-600" : "border-transparent text-slate-600 hover:bg-emerald-50 hover:text-emerald-600"}`}
+ >
+ <PenTool className="w-4 h-4" />
+ AI Mark
+ </button>
+ </div>
+
+ {/* Submit Button */}
+ <button
+ onClick={() => handleAction(selectedAction)}
+ disabled={isProcessing}
+ className="w-full py-2.5 bg-gradient-to-r from-purple-600 to-indigo-600 text-white text-xs font-bold rounded-lg hover:from-purple-700 hover:to-indigo-700 transition-all shadow-md hover:shadow-lg disabled:opacity-50 flex items-center justify-center gap-2"
+ >
+ {isProcessing ? (
+ <>
+ <Loader2 className="w-4 h-4 animate-spin" />
+ Processing...
+ </>
+ ) : (
+ <>
+ <Sparkles className="w-4 h-4" />
+ Apply{" "}
+ {selectedAction === "automark"
+ ? "AI Mark"
+ : selectedAction.charAt(0).toUpperCase() +
+ selectedAction.slice(1)}
+ </>
+ )}
+ </button>
+ </div>
+ </div>
+ </div>
+ )}
+ </div>
+
+ {/* Right Column */}
+ <div className="flex-1 flex flex-col gap-4">
+ {/* Preview Area (Upper) */}
+ <div
+ className={`flex-1 bg-white rounded-xl shadow-sm border border-slate-200 overflow-hidden flex flex-col transition-all`}
+ >
+ {/* Preview Header & Toolbar */}
+ <div className="p-2 border-b border-slate-100 bg-slate-50/50 flex justify-between items-center">
+ <div className="flex items-center gap-2">
+ <div className="text-[10px] font-bold text-slate-400 uppercase tracking-wider">
+ Preview
+ </div>
+ <div className="flex items-center gap-1">
+ <Sparkles className="w-3 h-3 text-purple-400" />
+ <span className="text-[10px] text-slate-400">
+ Live Preview · Synced Scroll
+ </span>
+ </div>
+ </div>
+
+ {/* Moved Action Buttons to Preview Header */}
+ <div className="flex items-center gap-1">
+ <button
+ onClick={() => setShowNotebookModal(true)}
+ className="flex items-center gap-1 px-2 py-1 text-xs text-indigo-600 hover:bg-indigo-50 rounded transition-all"
+ title="Save to Notebook"
+ >
+ <Book className="w-3.5 h-3.5" />
+ Save
+ </button>
+ <Divider />
+ <button
+ onClick={() => setHideAiMarks(!hideAiMarks)}
+ className={`flex items-center gap-1 px-2 py-1 text-xs rounded transition-all ${hideAiMarks ? "bg-emerald-100 text-emerald-700" : "text-slate-600 hover:bg-slate-100"}`}
+ title={hideAiMarks ? "Show AI Marks" : "Hide AI Marks"}
+ >
+ {hideAiMarks ? (
+ <Eye className="w-3.5 h-3.5" />
+ ) : (
+ <EyeOff className="w-3.5 h-3.5" />
+ )}
+ </button>
+ <Divider />
+ <button
+ onClick={exportMarkdown}
+ className="flex items-center gap-1 px-2 py-1 text-xs text-slate-600 hover:bg-slate-100 rounded transition-all"
+ title="Export Markdown"
+ >
+ <FileText className="w-3.5 h-3.5" />
+ .md
+ </button>
+ <button
+ onClick={exportPDF}
+ disabled={isProcessing}
+ className="flex items-center gap-1 px-2 py-1 text-xs text-slate-600 hover:bg-slate-100 rounded transition-all disabled:opacity-50"
+ title="Export PDF"
+ >
+ <Download className="w-3.5 h-3.5" />
+ .pdf
+ </button>
+ <Divider />
+ <button
+ onClick={() => setShowHistory(!showHistory)}
+ className={`flex items-center gap-1 text-xs px-2 py-1 rounded transition-all ${showHistory ? "bg-purple-100 text-purple-700" : "text-slate-500 hover:bg-slate-100"}`}
+ title="History"
+ >
+ <History className="w-3.5 h-3.5" />
+ </button>
+ </div>
+ </div>
+
+ {/* Markdown Preview Content */}
+ <div className="flex-1 flex flex-col relative min-h-0">
+ <div
+ ref={previewRef}
+ className="flex-1 overflow-y-auto p-6 prose prose-slate prose-sm max-w-none prose-headings:text-slate-900 prose-p:text-slate-700 prose-a:text-purple-600 rough-notation-container"
+ onScroll={handlePreviewScroll}
+ style={{ minHeight: 0 }}
+ >
+ <ReactMarkdown
+ remarkPlugins={[remarkGfm, remarkMath]}
+ rehypePlugins={[rehypeKatex, rehypeRaw]}
+ components={{
+ mark: ({ node, ...props }) => (
+ <mark className="bg-yellow-200 px-0.5 rounded" {...props} />
+ ),
+ u: ({ node, ...props }) => (
+ <u
+ className="underline decoration-2 decoration-slate-400"
+ {...props}
+ />
+ ),
+ span: ({ node, ...props }) => {
+ const dataAttr = (props as any)["data-rough-notation"];
+ if (dataAttr) {
+ // Handwritten style annotation styles
+ const styleClasses: Record<string, string> = {
+ circle: "rough-circle",
+ highlight: "rough-highlight",
+ box: "rough-box",
+ underline: "rough-underline",
+ bracket: "rough-bracket",
+ };
+ return (
+ <span
+ className={`rough-notation ${styleClasses[dataAttr] || ""}`}
+ data-rough-notation={dataAttr}
+ {...props}
+ />
+ );
+ }
+ return <span {...props} />;
+ },
+ // Handle paragraphs containing rough-notation
+ p: ({ node, children, ...props }) => {
+ // Check if contains bracket type span
+ const childArray = React.Children.toArray(children);
+ const hasBracket = childArray.some((child: any) => {
+ if (React.isValidElement(child)) {
+ const childProps = child.props as any;
+ return (
+ childProps?.["data-rough-notation"] === "bracket"
+ );
+ }
+ return false;
+ });
+
+ if (hasBracket) {
+ return (
+ <p className="rough-bracket-container" {...props}>
+ {children}
+ </p>
+ );
+ }
+ return <p {...props}>{children}</p>;
+ },
+ table: ({ node, ...props }) => (
+ <div className="overflow-x-auto my-4">
+ <table
+ className="min-w-full border-collapse border border-slate-300"
+ {...props}
+ />
+ </div>
+ ),
+ th: ({ node, ...props }) => (
+ <th
+ className="border border-slate-300 px-3 py-2 bg-slate-100 font-semibold text-left"
+ {...props}
+ />
+ ),
+ td: ({ node, ...props }) => (
+ <td
+ className="border border-slate-300 px-3 py-2"
+ {...props}
+ />
+ ),
+ code: ({ node, className, children, ...props }) => {
+ const match = /language-(\w+)/.exec(className || "");
+ const isInline = !match && !className;
+
+ if (isInline) {
+ return (
+ <code
+ className="bg-slate-100 px-1.5 py-0.5 rounded text-sm font-mono text-pink-600"
+ {...props}
+ >
+ {children}
+ </code>
+ );
+ }
+
+ return (
+ <pre className="bg-slate-900 text-slate-100 p-4 rounded-lg overflow-x-auto my-4">
+ <code className={className} {...props}>
+ {children}
+ </code>
+ </pre>
+ );
+ },
+ blockquote: ({ node, ...props }) => (
+ <blockquote
+ className="border-l-4 border-purple-500 pl-4 my-4 italic text-slate-600 bg-purple-50/50 py-2 rounded-r"
+ {...props}
+ />
+ ),
+ }}
+ >
+ {processLatexContent(content)}
+ </ReactMarkdown>
+ </div>
+
+ {/* History Panel Overlay */}
+ {showHistory && (
+ <div className="absolute inset-0 z-10 bg-white/95 backdrop-blur-sm flex flex-col animate-in fade-in duration-200">
+ <div className="p-3 border-b border-slate-100 flex justify-between items-center bg-slate-50/50">
+ <h3 className="text-xs font-bold text-slate-600 uppercase tracking-wider">
+ Version History
+ </h3>
+ <button
+ onClick={() => setShowHistory(false)}
+ className="text-slate-400 hover:text-slate-600 p-1 hover:bg-slate-100 rounded"
+ >
+ <X className="w-4 h-4" />
+ </button>
+ </div>
+ <div className="flex-1 overflow-y-auto p-2">
+ {operationHistory.length === 0 ? (
+ <div className="text-center py-10 text-slate-400 text-sm">
+ No history available
+ </div>
+ ) : (
+ <div className="space-y-2">
+ {[...operationHistory].reverse().map((op) => (
+ <div
+ key={op.id}
+ className="p-3 bg-white border border-slate-200 rounded-lg hover:shadow-sm transition-all cursor-pointer group"
+ >
+ <div className="flex items-center justify-between mb-1">
+ <span
+ className={`text-[10px] font-bold uppercase px-1.5 py-0.5 rounded ${
+ op.action === "rewrite"
+ ? "bg-purple-100 text-purple-700"
+ : op.action === "shorten"
+ ? "bg-amber-100 text-amber-700"
+ : op.action === "automark"
+ ? "bg-emerald-100 text-emerald-700"
+ : "bg-blue-100 text-blue-700"
+ }`}
+ >
+ {op.action}
+ </span>
+ <span className="text-[10px] text-slate-400">
+ {new Date(op.timestamp).toLocaleTimeString()}
+ </span>
+ </div>
+ <div className="text-xs text-slate-600 truncate mb-1">
+ "{op.input?.original_text?.substring(0, 35)}..."
+ </div>
+ <div className="flex items-center gap-2 text-[10px] text-slate-400">
+ {op.source && (
+ <span className="flex items-center gap-0.5">
+ {op.source === "rag" ? (
+ <Database className="w-2.5 h-2.5" />
+ ) : (
+ <Globe className="w-2.5 h-2.5" />
+ )}
+ {op.source.toUpperCase()}
+ </span>
+ )}
+ </div>
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ </div>
+ )}
+ </div>
+ </div>
+
+ {/* Podcast / Narration Area (Bottom Collapsible) */}
+ <div className="shrink-0 bg-white rounded-xl shadow-sm border border-slate-200 overflow-hidden transition-all">
+ <div
+ className="p-2 bg-slate-50/50 flex justify-between items-center cursor-pointer hover:bg-slate-100/50 transition-colors"
+ onClick={() => setIsPodcastExpanded(!isPodcastExpanded)}
+ >
+ <div className="flex items-center gap-2">
+ {isPodcastExpanded ? (
+ <ChevronDown className="w-4 h-4 text-slate-400" />
+ ) : (
+ <ChevronRight className="w-4 h-4 text-slate-400" />
+ )}
+ <div className="flex items-center gap-1 text-[10px] font-bold text-slate-500 uppercase tracking-wider">
+ <Radio className="w-3.5 h-3.5 text-purple-600" />
+ Podcast Narration
+ </div>
+ </div>
+ {!isPodcastExpanded && (
+ <span className="text-[10px] text-slate-400 px-2">
+ Click to expand
+ </span>
+ )}
+ </div>
+
+ {isPodcastExpanded && (
+ <div className="p-4 border-t border-slate-100 animate-in slide-in-from-top-2">
+ <div className="flex items-center justify-between mb-2">
+ <div className="flex items-center gap-2">
+ {ttsAvailable === false && (
+ <span className="text-[10px] text-amber-600 bg-amber-100 px-1.5 py-0.5 rounded-full flex items-center gap-1">
+ <AlertCircle className="w-3 h-3" />
+ Script only (TTS not configured)
+ </span>
+ )}
+ </div>
+ </div>
+
+ <div className="flex flex-col md:flex-row gap-3">
+ <div className="flex-1 space-y-2">
+ <div className="flex gap-2">
+ <button
+ onClick={async () => {
+ if (!content.trim()) {
+ setNarrationError(
+ "Current note is empty, cannot generate narration.",
+ );
+ return;
+ }
+ setNarrationLoading(true);
+ setNarrationError(null);
+ try {
+ const res = await fetch(
+ apiUrl("/api/v1/co_writer/narrate"),
+ {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ content,
+ style: narrationStyle,
+ skip_audio: !ttsAvailable,
+ }),
+ },
+ );
+ if (!res.ok) {
+ const detail = await res.text();
+ throw new Error(detail || `HTTP ${res.status}`);
+ }
+ const data = await res.json();
+ setNarrationScript(data.script || "");
+ setNarrationKeyPoints(data.key_points || []);
+ if (data.has_audio && data.audio_url) {
+ // Ensure the audio URL is properly formatted
+ const audioUrl = data.audio_url.startsWith("http")
+ ? data.audio_url
+ : apiUrl(data.audio_url);
+ setAudioInfo({
+ audioUrl: audioUrl,
+ audioId: data.audio_id,
+ voice: data.voice,
+ });
+ } else {
+ setAudioInfo(null);
+ }
+ } catch (e: any) {
+ setNarrationError(
+ e?.message ||
+ "Failed to generate narration, please try again.",
+ );
+ } finally {
+ setNarrationLoading(false);
+ }
+ }}
+ disabled={narrationLoading}
+ className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium bg-gradient-to-r from-purple-600 to-indigo-600 text-white hover:from-purple-700 hover:to-indigo-700 disabled:opacity-60 shadow-sm"
+ >
+ {narrationLoading ? (
+ <>
+ <Loader2 className="w-3.5 h-3.5 animate-spin" />
+ Generating Podcast
+ </>
+ ) : (
+ <>
+ <Mic className="w-3.5 h-3.5" />
+ Generate Podcast
+ </>
+ )}
+ </button>
+ <button
+ onClick={() => {
+ if (!narrationScript) return;
+ setShowNarrationNotebookModal(true);
+ }}
+ disabled={!narrationScript}
+ className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium border border-slate-200 text-slate-700 hover:bg-white disabled:opacity-50"
+ >
+ <Book className="w-3.5 h-3.5" />
+ Save Podcast to Notebook
+ </button>
+ </div>
+ {narrationError && (
+ <div className="text-[11px] text-amber-700 bg-amber-50 border border-amber-200 rounded px-2 py-1 flex items-center gap-1">
+ <AlertCircle className="w-3 h-3" />
+ <span>{narrationError}</span>
+ </div>
+ )}
+ <div className="bg-white border border-slate-200 rounded-lg p-2 h-32 overflow-y-auto text-xs text-slate-700">
+ {narrationScript ? (
+ <p className="whitespace-pre-wrap leading-relaxed">
+ {narrationScript}
+ </p>
+ ) : (
+ <span className="text-slate-400">
+ After generation, the narration script will appear here.
+ </span>
+ )}
+ </div>
+ </div>
+
+ <div className="w-full md:w-56 space-y-2">
+ <div className="bg-white border border-slate-200 rounded-lg p-2 h-20 overflow-y-auto">
+ <div className="flex items-center gap-1 text-[10px] font-semibold text-slate-500 mb-1">
+ <Headphones className="w-3.5 h-3.5 text-indigo-600" />
+ Key Points
+ </div>
+ {narrationKeyPoints && narrationKeyPoints.length > 0 ? (
+ <ul className="list-disc pl-4 text-[11px] text-slate-700 space-y-0.5">
+ {narrationKeyPoints.map((kp, idx) => (
+ <li key={idx} className="leading-snug">
+ {kp}
+ </li>
+ ))}
+ </ul>
+ ) : (
+ <div className="text-[11px] text-slate-400">
+ After generation, 3-5 key points will be listed here.
+ </div>
+ )}
+ </div>
+ <div className="bg-white border border-slate-200 rounded-lg p-3">
+ <div className="flex items-center justify-between mb-2">
+ <div className="flex items-center gap-1.5 text-[10px] font-semibold text-slate-600">
+ <Headphones className="w-3.5 h-3.5 text-purple-600" />
+ Podcast Audio
+ </div>
+ {audioInfo?.voice && (
+ <span className="text-[10px] text-slate-500 bg-purple-50 px-1.5 py-0.5 rounded-full">
+ {audioInfo.voice}
+ </span>
+ )}
+ </div>
+ {audioInfo?.audioUrl ? (
+ <div className="w-full">
+ <audio
+ controls
+ className="w-full h-9"
+ style={{
+ borderRadius: "6px",
+ backgroundColor: "#f8fafc",
+ }}
+ >
+ <source src={audioInfo.audioUrl} type="audio/mpeg" />
+ Your browser does not support the audio element.
+ </audio>
+ </div>
+ ) : (
+ <div className="text-[11px] text-slate-400 italic py-2">
+ {ttsAvailable === false
+ ? "TTS not configured, script generation only."
+ : "After generation, you can play the podcast audio here."}
+ </div>
+ )}
+ </div>
+ </div>
+ </div>
+ </div>
+ )}
+ </div>
+ </div>
+
+ {/* Global Loading Overlay */}
+ {isProcessing && !popover && (
+ <div className="fixed inset-0 bg-white/80 backdrop-blur-sm z-50 flex items-center justify-center">
+ <div className="bg-white p-8 rounded-2xl shadow-2xl flex flex-col items-center gap-4 border">
+ <Loader2 className="w-8 h-8 text-purple-600 animate-spin" />
+ <span className="font-medium text-slate-700">Exporting...</span>
+ </div>
+ </div>
+ )}
+
+ {/* Add to Notebook Modal */}
+ <AddToNotebookModal
+ isOpen={showNotebookModal}
+ onClose={() => setShowNotebookModal(false)}
+ recordType="co_writer"
+ title={`Co-Writer Document - ${new Date().toLocaleDateString()}`}
+ userQuery="Co-Writer edited document"
+ output={content}
+ metadata={{
+ char_count: content.length,
+ line_count: content.split("\n").length,
+ }}
+ />
+
+ {/* Notebook Import Modal */}
+ <NotebookImportModal
+ isOpen={showImportModal}
+ onClose={() => setShowImportModal(false)}
+ onImport={(importedContent) => {
+ // Insert at current selection or end
+ const newContent = content
+ ? content + "\n\n" + importedContent
+ : importedContent;
+ setContent(newContent);
+ }}
+ />
+
+ {/* Narration save to Notebook Modal */}
+ <AddToNotebookModal
+ isOpen={showNarrationNotebookModal}
+ onClose={() => setShowNarrationNotebookModal(false)}
+ recordType="co_writer"
+ title={`Co-Writer Podcast - ${new Date().toLocaleDateString()}`}
+ userQuery={content.substring(0, 120)}
+ output={narrationScript}
+ metadata={{
+ char_count: narrationScript.length,
+ style: narrationStyle,
+ key_points: narrationKeyPoints,
+ audio_url: audioInfo?.audioUrl,
+ audio_id: audioInfo?.audioId,
+ voice: audioInfo?.voice,
+ }}
+ />
+ </div>
+ );
+}
diff --git a/web/components/CoWriterEditor.tsx b/web/components/CoWriterEditor.tsx
new file mode 100644
index 000000000..e70b70a04
--- /dev/null
+++ b/web/components/CoWriterEditor.tsx
@@ -0,0 +1,2116 @@
+"use client";
+
+import React, { useState, useRef, useEffect, useCallback } from "react";
+import {
+ Wand2,
+ Minimize2,
+ Maximize2,
+ Globe,
+ Database,
+ Loader2,
+ X,
+ History,
+ Bold,
+ Italic,
+ Underline as UnderlineIcon,
+ Highlighter,
+ Strikethrough,
+ Code,
+ Heading1,
+ Heading2,
+ List,
+ ListOrdered,
+ Quote,
+ Link,
+ Image,
+ Table,
+ Minus,
+ Download,
+ FileText,
+ PenTool,
+ Sparkles,
+ Eye,
+ EyeOff,
+ Wifi,
+ WifiOff,
+ AlertCircle,
+ Book,
+ Mic,
+ Headphones,
+ Radio,
+ ChevronDown,
+ ChevronRight,
+ LayoutTemplate,
+ Import,
+} from "lucide-react";
+import AddToNotebookModal from "./AddToNotebookModal";
+import NotebookImportModal from "./NotebookImportModal";
+import { apiUrl } from "@/lib/api";
+import ReactMarkdown from "react-markdown";
+import remarkGfm from "remark-gfm";
+import remarkMath from "remark-math";
+import rehypeKatex from "rehype-katex";
+import rehypeRaw from "rehype-raw";
+import "katex/dist/katex.min.css";
+import { processLatexContent } from "@/lib/latex";
+
+interface CoWriterEditorProps {
+ initialValue?: string;
+}
+
+// AI Mark tag regex patterns
+const AI_MARK_REGEX = /<span\s+data-rough-notation="[^"]+">([^<]*)<\/span>/g;
+const AI_MARK_OPEN_TAG = /<span\s+data-rough-notation="[^"]+">/g;
+const AI_MARK_CLOSE_TAG = /<\/span>/g;
+
+export default function CoWriterEditor({
+ initialValue = "",
+}: CoWriterEditorProps) {
+ const [content, setContent] = useState(
+ initialValue ||
+ "# Welcome to Co-Writer\n\nSelect text to see the magic happen.\n\n## Features\n\n- **Bold** text with Ctrl+B\n- *Italic* text with Ctrl+I\n- <u>Underline</u> with Ctrl+U\n- <mark>Highlight</mark> with Ctrl+H\n- AI-powered editing and auto-marking\n",
+ );
+ const [selection, setSelection] = useState<{
+ start: number;
+ end: number;
+ text: string;
+ } | null>(null);
+ const [popover, setPopover] = useState<{
+ visible: boolean;
+ x: number;
+ y: number;
+ } | null>(null);
+ const [instruction, setInstruction] = useState("");
+ const [selectedAction, setSelectedAction] = useState<
+ "rewrite" | "shorten" | "expand" | "automark"
+ >("rewrite");
+ const [source, setSource] = useState<"rag" | "web" | null>(null);
+ const [selectedKb, setSelectedKb] = useState("");
+ const [kbs, setKbs] = useState<string[]>([]);
+ const [isProcessing, setIsProcessing] = useState(false);
+ const [operationHistory, setOperationHistory] = useState<any[]>([]);
+ const [showHistory, setShowHistory] = useState(false);
+ const [hideAiMarks, setHideAiMarks] = useState(false);
+ const [rawContent, setRawContent] = useState(""); // Store original content with tags
+ const [backendConnected, setBackendConnected] = useState<boolean | null>(
+ null,
+ ); // null = checking, true = connected, false = disconnected
+ const [showNotebookModal, setShowNotebookModal] = useState(false);
+ const [showImportModal, setShowImportModal] = useState(false);
+
+ // Podcast / Narration related states
+ const [isPodcastExpanded, setIsPodcastExpanded] = useState(false);
+ const [narrationStyle, setNarrationStyle] = useState<
+ "friendly" | "academic" | "concise"
+ >("friendly");
+ const [narrationScript, setNarrationScript] = useState<string>("");
+ const [narrationKeyPoints, setNarrationKeyPoints] = useState<string[]>([]);
+ const [narrationLoading, setNarrationLoading] = useState<boolean>(false);
+ const [narrationError, setNarrationError] = useState<string | null>(null);
+ const [ttsAvailable, setTtsAvailable] = useState<boolean | null>(null);
+ const [ttsVoices, setTtsVoices] = useState<
+ Array<{ id: string; name: string; description?: string }>
+ >([]);
+ const [selectedVoice, setSelectedVoice] = useState<string>("alloy");
+ const [audioInfo, setAudioInfo] = useState<{
+ audioUrl?: string;
+ audioId?: string;
+ voice?: string;
+ } | null>(null);
+ const [showNarrationNotebookModal, setShowNarrationNotebookModal] =
+ useState(false);
+
+ const textareaRef = useRef<HTMLTextAreaElement>(null);
+ const popoverRef = useRef<HTMLDivElement>(null);
+ const previewRef = useRef<HTMLDivElement>(null);
+ const editorContainerRef = useRef<HTMLDivElement>(null);
+ const isSyncingScroll = useRef(false);
+
+ // Check backend connection status
+ const checkBackendConnection = useCallback(
+ async (silent: boolean = false) => {
+ try {
+ // Use AbortController for timeout (better compatibility)
+ const controller = new AbortController();
+ const timeoutId = setTimeout(() => controller.abort(), 3000); // 3s timeout
+
+ const response = await fetch(apiUrl("/api/v1/co_writer/history"), {
+ method: "GET",
+ signal: controller.signal,
+ });
+
+ clearTimeout(timeoutId);
+
+ if (response.ok) {
+ setBackendConnected(true);
+ return true;
+ } else {
+ setBackendConnected(false);
+ return false;
+ }
+ } catch (error: any) {
+ setBackendConnected(false);
+ // Only log errors in non-silent mode to avoid console noise
+ if (
+ !silent &&
+ error.name !== "AbortError" &&
+ process.env.NODE_ENV === "development"
+ ) {
+ // Only show detailed errors in development mode
+ console.debug(
+ "Backend connection check failed (this is normal if backend is not running):",
+ error.message,
+ );
+ }
+ return false;
+ }
+ },
+ [],
+ );
+
+ // Check TTS configuration and available voices
+ useEffect(() => {
+ const fetchTtsConfig = async () => {
+ try {
+ const statusRes = await fetch(apiUrl("/api/v1/co_writer/tts/status"));
+ if (statusRes.ok) {
+ const statusData = await statusRes.json();
+ if (statusData.available) {
+ setTtsAvailable(true);
+ if (statusData.default_voice) {
+ setSelectedVoice(statusData.default_voice);
+ }
+ // Further fetch available voice list
+ const voicesRes = await fetch(
+ apiUrl("/api/v1/co_writer/tts/voices"),
+ );
+ if (voicesRes.ok) {
+ const voicesData = await voicesRes.json();
+ setTtsVoices(voicesData.voices || []);
+ }
+ } else {
+ setTtsAvailable(false);
+ }
+ } else {
+ setTtsAvailable(false);
+ }
+ } catch (e) {
+ setTtsAvailable(false);
+ }
+ };
+ // Only check once when component mounts
+ fetchTtsConfig();
+ }, []);
+
+ // Fetch KBs
+ useEffect(() => {
+ const loadData = async () => {
+ setBackendConnected(null); // Start checking
+
+ try {
+ // First check connection (silent mode to avoid console noise)
+ const isConnected = await checkBackendConnection(true);
+
+ if (isConnected) {
+ // Load knowledge base list
+ try {
+ const controller = new AbortController();
+ const timeoutId = setTimeout(() => controller.abort(), 5000);
+
+ const res = await fetch(apiUrl("/api/v1/knowledge/list"), {
+ signal: controller.signal,
+ });
+
+ clearTimeout(timeoutId);
+
+ if (res.ok) {
+ const data = await res.json();
+ setKbs(data.map((kb: any) => kb.name));
+ if (data.length > 0) setSelectedKb(data[0].name);
+ }
+ } catch (err: any) {
+ // Only show errors in development mode
+ if (process.env.NODE_ENV === "development") {
+ console.debug(
+ "Failed to fetch KBs (backend may not be running):",
+ err.message,
+ );
+ }
+ }
+
+ // Load history
+ fetchHistory();
+ }
+ } catch (error: any) {
+ // Only show errors in development mode
+ if (process.env.NODE_ENV === "development") {
+ console.debug(
+ "Failed to initialize (backend may not be running):",
+ error.message,
+ );
+ }
+ }
+ };
+
+ loadData();
+ }, [checkBackendConnection]);
+
+ const fetchHistory = () => {
+ fetch(apiUrl("/api/v1/co_writer/history"))
+ .then((res) => {
+ if (res.ok) {
+ return res.json();
+ } else {
+ throw new Error(`HTTP ${res.status}`);
+ }
+ })
+ .then((data) => {
+ setOperationHistory(data.history || []);
+ setBackendConnected(true);
+ })
+ .catch((err) => {
+ // Only show errors in development mode to avoid console noise
+ if (process.env.NODE_ENV === "development") {
+ console.debug(
+ "Failed to fetch history (backend may not be running):",
+ err.message,
+ );
+ }
+ setBackendConnected(false);
+ });
+ };
+
+ // Auto clear source when automark is selected
+ useEffect(() => {
+ if (selectedAction === "automark") {
+ setSource(null);
+ }
+ }, [selectedAction]);
+
+ // Synchronized scroll functionality
+ const handleEditorScroll = useCallback(() => {
+ if (isSyncingScroll.current) return;
+ const editor = editorContainerRef.current;
+ const preview = previewRef.current;
+ if (!editor || !preview) return;
+
+ isSyncingScroll.current = true;
+ const scrollPercentage =
+ editor.scrollTop / (editor.scrollHeight - editor.clientHeight);
+ preview.scrollTop =
+ scrollPercentage * (preview.scrollHeight - preview.clientHeight);
+
+ requestAnimationFrame(() => {
+ isSyncingScroll.current = false;
+ });
+ }, []);
+
+ const handlePreviewScroll = useCallback(() => {
+ if (isSyncingScroll.current) return;
+ const editor = editorContainerRef.current;
+ const preview = previewRef.current;
+ if (!editor || !preview) return;
+
+ isSyncingScroll.current = true;
+ const scrollPercentage =
+ preview.scrollTop / (preview.scrollHeight - preview.clientHeight);
+ editor.scrollTop =
+ scrollPercentage * (editor.scrollHeight - editor.clientHeight);
+
+ requestAnimationFrame(() => {
+ isSyncingScroll.current = false;
+ });
+ }, []);
+
+ // Hide AI Marks functionality
+ const getDisplayContent = useCallback(() => {
+ if (!hideAiMarks) return content;
+ // Remove AI tags, show content only
+ return content.replace(AI_MARK_REGEX, "$1");
+ }, [content, hideAiMarks]);
+
+ // Save original content when hideAiMarks is enabled
+ useEffect(() => {
+ if (hideAiMarks && !rawContent) {
+ setRawContent(content);
+ } else if (!hideAiMarks && rawContent) {
+ // When restoring, need to map edits back to original content
+ setRawContent("");
+ }
+ }, [hideAiMarks]);
+
+ // Merge edits with tags - smart AI mark protection
+ const mergeEditWithMarks = useCallback(
+ (original: string, oldPlain: string, newPlain: string): string => {
+ // 1. Extract all marks and their positions in plain text
+ interface MarkInfo {
+ tag: string;
+ innerText: string;
+ plainStart: number; // Start position in plain text
+ plainEnd: number; // End position in plain text
+ }
+
+ const marks: MarkInfo[] = [];
+ const regex = /<span\s+data-rough-notation="([^"]+)">([^<]*)<\/span>/g;
+ let match;
+
+ // Calculate each mark's position in plain text
+ let plainOffset = 0;
+ let lastIndex = 0;
+
+ while ((match = regex.exec(original)) !== null) {
+ const tag = match[1];
+ const innerText = match[2];
+ const htmlStart = match.index;
+ const htmlEnd = htmlStart + match[0].length;
+
+ // Calculate plain text length before mark
+ const textBefore = original.substring(lastIndex, htmlStart);
+ plainOffset += textBefore.length;
+
+ marks.push({
+ tag,
+ innerText,
+ plainStart: plainOffset,
+ plainEnd: plainOffset + innerText.length,
+ });
+
+ plainOffset += innerText.length;
+ lastIndex = htmlEnd;
+ }
+
+ // 2. Find edited area (diff between old and new text)
+ let diffStart = 0;
+ let diffEndOld = oldPlain.length;
+ let diffEndNew = newPlain.length;
+
+ // Find first different position
+ while (
+ diffStart < oldPlain.length &&
+ diffStart < newPlain.length &&
+ oldPlain[diffStart] === newPlain[diffStart]
+ ) {
+ diffStart++;
+ }
+
+ // Find last different position (from end)
+ while (
+ diffEndOld > diffStart &&
+ diffEndNew > diffStart &&
+ oldPlain[diffEndOld - 1] === newPlain[diffEndNew - 1]
+ ) {
+ diffEndOld--;
+ diffEndNew--;
+ }
+
+ // 3. Check if each mark is modified
+ // Only remove mark when edit occurs inside the marked word
+ const marksToKeep: Array<{ mark: MarkInfo; newPosition: number }> = [];
+
+ for (const mark of marks) {
+ // Check if edit is inside mark
+ const editStartsInsideMark =
+ diffStart > mark.plainStart && diffStart < mark.plainEnd;
+ const editEndsInsideMark =
+ diffEndOld > mark.plainStart && diffEndOld < mark.plainEnd;
+ const editCompletelyInsideMark =
+ diffStart >= mark.plainStart && diffEndOld <= mark.plainEnd;
+
+ // Remove mark if edit is completely inside, or starts/ends inside mark
+ if (
+ editCompletelyInsideMark ||
+ editStartsInsideMark ||
+ editEndsInsideMark
+ ) {
+ // Mark modified, don't keep
+ continue;
+ }
+
+ // Mark not modified, try to find its position in new text
+ // Calculate offset caused by edit
+ let newPosition = mark.plainStart;
+
+ if (diffEndOld <= mark.plainStart) {
+ // Edit is before mark, position needs adjustment
+ const editLengthDiff =
+ diffEndNew - diffStart - (diffEndOld - diffStart);
+ newPosition = mark.plainStart + editLengthDiff;
+ } else if (diffStart >= mark.plainEnd) {
+ // Edit is after mark, position unchanged
+ newPosition = mark.plainStart;
+ } else {
+ // Edit overlaps with mark but not inside (e.g., edit starts before and ends after mark)
+ // In this case, mark may have moved, need to search
+ const searchRadius = 50;
+ const searchStart = Math.max(0, mark.plainStart - searchRadius);
+ const searchEnd = Math.min(
+ newPlain.length,
+ mark.plainEnd + searchRadius,
+ );
+ const searchArea = newPlain.substring(searchStart, searchEnd);
+ const foundIndex = searchArea.indexOf(mark.innerText);
+
+ if (foundIndex !== -1) {
+ newPosition = searchStart + foundIndex;
+ } else {
+ // Can't find mark text, possibly deleted, skip
+ continue;
+ }
+ }
+
+ // Validate text at new position matches
+ if (
+ newPosition >= 0 &&
+ newPosition + mark.innerText.length <= newPlain.length
+ ) {
+ const textAtPosition = newPlain.substring(
+ newPosition,
+ newPosition + mark.innerText.length,
+ );
+ if (textAtPosition === mark.innerText) {
+ marksToKeep.push({ mark, newPosition });
+ }
+ }
+ }
+
+ // 4. Insert marks from end to start to avoid position offset
+ marksToKeep.sort((a, b) => b.newPosition - a.newPosition);
+
+ let result = newPlain;
+ for (const { mark, newPosition } of marksToKeep) {
+ const before = result.substring(0, newPosition);
+ const after = result.substring(newPosition + mark.innerText.length);
+ const markedText = `<span data-rough-notation="${mark.tag}">${mark.innerText}</span>`;
+ result = before + markedText + after;
+ }
+
+ return result;
+ },
+ [],
+ );
+
+ // Handle content changes in hidden mode
+ const handleContentChange = useCallback(
+ (newValue: string) => {
+ if (!hideAiMarks) {
+ setContent(newValue);
+ return;
+ }
+
+ // In hidden mode, need to protect tags
+ // Use functional update to avoid content state dependency
+ setContent((prevContent) => {
+ const oldDisplayContent = prevContent.replace(AI_MARK_REGEX, "$1");
+ const newDisplayContent = newValue;
+
+ if (oldDisplayContent === newDisplayContent) {
+ return prevContent;
+ }
+
+ // Simplified: if user edits in hidden mode, replace entire content
+ // But keep tags that weren't edited
+ return mergeEditWithMarks(
+ prevContent,
+ oldDisplayContent,
+ newDisplayContent,
+ );
+ });
+ },
+ [hideAiMarks, mergeEditWithMarks],
+ );
+
+ // Wrap selection with markers
+ const wrapSelection = useCallback((before: string, after: string) => {
+ const textarea = textareaRef.current;
+ if (!textarea) return;
+
+ const start = textarea.selectionStart;
+ const end = textarea.selectionEnd;
+ const selectedText = textarea.value.substring(start, end);
+
+ if (selectedText.length === 0) return;
+
+ // Check if already wrapped
+ const textBefore = textarea.value.substring(
+ Math.max(0, start - before.length),
+ start,
+ );
+ const textAfter = textarea.value.substring(end, end + after.length);
+
+ let newContent: string;
+ let newStart: number;
+ let newEnd: number;
+
+ if (textBefore === before && textAfter === after) {
+ // Remove wrapping
+ newContent =
+ textarea.value.substring(0, start - before.length) +
+ selectedText +
+ textarea.value.substring(end + after.length);
+ newStart = start - before.length;
+ newEnd = end - before.length;
+ } else {
+ // Add wrapping
+ newContent =
+ textarea.value.substring(0, start) +
+ before +
+ selectedText +
+ after +
+ textarea.value.substring(end);
+ newStart = start + before.length;
+ newEnd = end + before.length;
+ }
+
+ setContent(newContent);
+
+ // Restore selection after state update
+ setTimeout(() => {
+ textarea.focus();
+ textarea.setSelectionRange(newStart, newEnd);
+ }, 0);
+ }, []);
+
+ // Toggle line prefix
+ const toggleLinePrefix = useCallback((prefix: string) => {
+ const textarea = textareaRef.current;
+ if (!textarea) return;
+
+ const start = textarea.selectionStart;
+ const end = textarea.selectionEnd;
+ const lines = textarea.value.split("\n");
+
+ // Find line indices
+ let charCount = 0;
+ let startLine = 0;
+ let endLine = 0;
+
+ for (let i = 0; i < lines.length; i++) {
+ if (charCount <= start && start <= charCount + lines[i].length) {
+ startLine = i;
+ }
+ if (charCount <= end && end <= charCount + lines[i].length) {
+ endLine = i;
+ break;
+ }
+ charCount += lines[i].length + 1;
+ }
+
+ // Check if all lines have prefix
+ let allHavePrefix = true;
+ for (let i = startLine; i <= endLine; i++) {
+ if (!lines[i].startsWith(prefix)) {
+ allHavePrefix = false;
+ break;
+ }
+ }
+
+ // Toggle prefix
+ for (let i = startLine; i <= endLine; i++) {
+ if (allHavePrefix) {
+ lines[i] = lines[i].substring(prefix.length);
+ } else {
+ lines[i] = prefix + lines[i];
+ }
+ }
+
+ setContent(lines.join("\n"));
+ }, []);
+
+ // Keyboard shortcuts
+ useEffect(() => {
+ const handleKeyDown = (e: KeyboardEvent) => {
+ if (
+ !textareaRef.current ||
+ document.activeElement !== textareaRef.current
+ )
+ return;
+
+ if (e.ctrlKey || e.metaKey) {
+ switch (e.key.toLowerCase()) {
+ case "b":
+ e.preventDefault();
+ wrapSelection("**", "**");
+ break;
+ case "i":
+ e.preventDefault();
+ wrapSelection("*", "*");
+ break;
+ case "u":
+ e.preventDefault();
+ wrapSelection("<u>", "</u>");
+ break;
+ case "h":
+ e.preventDefault();
+ wrapSelection("<mark>", "</mark>");
+ break;
+ case "s":
+ if (e.shiftKey) {
+ e.preventDefault();
+ wrapSelection("~~", "~~");
+ }
+ break;
+ }
+ }
+ };
+
+ document.addEventListener("keydown", handleKeyDown);
+ return () => document.removeEventListener("keydown", handleKeyDown);
+ }, [wrapSelection]);
+
+ // Handle selection for popover
+ const handleMouseUp = (e: React.MouseEvent) => {
+ const textarea = textareaRef.current;
+ if (!textarea) return;
+
+ const start = textarea.selectionStart;
+ const end = textarea.selectionEnd;
+ const text = textarea.value.substring(start, end);
+
+ if (text.trim().length > 0) {
+ const rect = textarea.getBoundingClientRect();
+ let x = e.clientX;
+ let y = e.clientY + 10;
+
+ setSelection({ start, end, text });
+ setPopover({ visible: true, x, y });
+ setInstruction("");
+ setSelectedAction("rewrite");
+ setSource(null);
+ } else {
+ setPopover(null);
+ setSelection(null);
+ }
+ };
+
+ // Close popover on click outside
+ useEffect(() => {
+ const handleClickOutside = (event: MouseEvent) => {
+ if (
+ popoverRef.current &&
+ !popoverRef.current.contains(event.target as Node) &&
+ textareaRef.current &&
+ !textareaRef.current.contains(event.target as Node)
+ ) {
+ setPopover(null);
+ setSelection(null);
+ }
+ };
+ document.addEventListener("mousedown", handleClickOutside);
+ return () => document.removeEventListener("mousedown", handleClickOutside);
+ }, []);
+
+ const handleAction = async (
+ action: "rewrite" | "shorten" | "expand" | "automark",
+ ) => {
+ if (!selection) return;
+
+ // If backend not connected, check once first
+ if (backendConnected === false) {
+ const isConnected = await checkBackendConnection();
+ if (!isConnected) {
+ alert(
+ `❌ Backend service not connected\n\n` +
+ `Please ensure the backend is running:\n` +
+ `📍 ${apiUrl("")}\n\n` +
+ `💡 How to start:\n` +
+ ` Run in project root: python start.py\n` +
+ ` Or: python start_web.py`,
+ );
+ return;
+ }
+ }
+
+ setIsProcessing(true);
+
+ try {
+ let editedText: string;
+ const apiEndpoint =
+ action === "automark"
+ ? "/api/v1/co_writer/automark"
+ : "/api/v1/co_writer/edit";
+ const requestUrl = apiUrl(apiEndpoint);
+
+ if (action === "automark") {
+ const requestBody = { text: selection.text };
+ console.log("Sending automark request to:", requestUrl, requestBody);
+
+ const res = await fetch(requestUrl, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(requestBody),
+ });
+
+ if (!res.ok) {
+ const errorText = await res.text();
+ console.error("Automark API error:", res.status, errorText);
+ throw new Error(
+ `Failed to auto-mark text: ${res.status} ${res.statusText}\n${errorText}`,
+ );
+ }
+
+ const data = await res.json();
+ if (!data.marked_text) {
+ throw new Error("Invalid response: missing marked_text field");
+ }
+ editedText = data.marked_text;
+ } else {
+ const requestBody: any = {
+ text: selection.text,
+ instruction: instruction || `Please ${action} this text.`,
+ action,
+ };
+
+ // Only add source in non-automark mode
+ if (source) {
+ requestBody.source = source;
+ if (source === "rag" && selectedKb) {
+ requestBody.kb_name = selectedKb;
+ }
+ }
+
+ console.log("Sending edit request to:", requestUrl, requestBody);
+
+ const res = await fetch(requestUrl, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(requestBody),
+ });
+
+ if (!res.ok) {
+ const errorText = await res.text();
+ console.error("Edit API error:", res.status, errorText);
+ throw new Error(
+ `Failed to edit text: ${res.status} ${res.statusText}\n${errorText}`,
+ );
+ }
+
+ const data = await res.json();
+ if (!data.edited_text) {
+ throw new Error("Invalid response: missing edited_text field");
+ }
+ editedText = data.edited_text;
+ }
+
+ const newContent =
+ content.substring(0, selection.start) +
+ editedText +
+ content.substring(selection.end);
+ setContent(newContent);
+ setPopover(null);
+ setSelection(null);
+ fetchHistory();
+ } catch (error: any) {
+ console.error("Action error:", error);
+
+ // Update backend connection status
+ setBackendConnected(false);
+
+ // Build detailed error message
+ let errorMessage = "Error processing request";
+ const backendUrl = apiUrl("");
+
+ if (
+ error instanceof TypeError &&
+ (error.message.includes("fetch") || error.message === "Failed to fetch")
+ ) {
+ errorMessage =
+ `❌ Cannot connect to backend service\n\n` +
+ `Please ensure the backend is running:\n` +
+ `📍 ${backendUrl}\n\n` +
+ `💡 How to start:\n` +
+ ` Run in project root: python start.py\n` +
+ ` Or: python start_web.py\n\n` +
+ `If running on a different port, check NEXT_PUBLIC_API_BASE env variable`;
+ } else if (
+ error.name === "AbortError" ||
+ error.message.includes("timeout")
+ ) {
+ errorMessage =
+ `⏱️ Request timeout\n\n` +
+ `Backend response took too long, please check:\n` +
+ `1. Is the backend running properly?\n` +
+ `2. Is network connection stable?\n` +
+ `3. Is server load too high?`;
+ } else if (error.message) {
+ errorMessage = `❌ ${error.message}`;
+ } else {
+ errorMessage = `❌ Unknown error: ${String(error)}`;
+ }
+
+ alert(errorMessage);
+ } finally {
+ setIsProcessing(false);
+ }
+ };
+
+ // Export functions
+ const exportMarkdown = () => {
+ const blob = new Blob([content], { type: "text/markdown" });
+ const url = URL.createObjectURL(blob);
+ const a = document.createElement("a");
+ a.href = url;
+ a.download = "document.md";
+ a.click();
+ URL.revokeObjectURL(url);
+ };
+
+ const exportPDF = async () => {
+ if (!previewRef.current) return;
+ setIsProcessing(true);
+
+ try {
+ // Dynamically import jspdf and html2canvas
+ const [{ default: jsPDF }, { default: html2canvas }] = await Promise.all([
+ import("jspdf"),
+ import("html2canvas"),
+ ]);
+
+ // Create temp container for PDF export
+ const tempContainer = document.createElement("div");
+ tempContainer.className = "pdf-export-container";
+ tempContainer.style.cssText = `
+ position: fixed;
+ left: 0;
+ top: 0;
+ width: 210mm;
+ min-height: 297mm;
+ padding: 20mm;
+ background: white;
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
+ font-size: 12pt;
+ line-height: 1.6;
+ color: #1e293b;
+ z-index: 9999;
+ overflow: visible;
+ `;
+
+ // Clone preview content
+ const previewClone = previewRef.current.cloneNode(true) as HTMLElement;
+ tempContainer.appendChild(previewClone);
+ document.body.appendChild(tempContainer);
+
+ // Copy all related stylesheets
+ const allStyles = Array.from(document.styleSheets);
+ const styleElement = document.createElement("style");
+ styleElement.id = "pdf-export-styles";
+
+ // Collect all style rules
+ let styleText = "";
+
+ // Add base styles
+ styleText += `
+ .pdf-export-container {
+ position: fixed !important;
+ left: 0 !important;
+ top: 0 !important;
+ width: 210mm !important;
+ padding: 20mm !important;
+ background: white !important;
+ }
+
+ /* Prose styles */
+ .prose {
+ max-width: none !important;
+ color: #1e293b !important;
+ }
+
+ .prose h1, .prose h2, .prose h3, .prose h4 {
+ font-weight: 600 !important;
+ margin-top: 1.5em !important;
+ margin-bottom: 0.5em !important;
+ color: #0f172a !important;
+ }
+
+ .prose p {
+ margin-bottom: 1em !important;
+ line-height: 1.7 !important;
+ }
+
+ .prose ul, .prose ol {
+ margin-bottom: 1em !important;
+ padding-left: 1.5em !important;
+ }
+
+ .prose code {
+ background: #f1f5f9 !important;
+ padding: 0.125em 0.375em !important;
+ border-radius: 0.25em !important;
+ font-size: 0.9em !important;
+ font-family: 'Consolas', 'Monaco', monospace !important;
+ }
+
+ .prose pre {
+ background: #0f172a !important;
+ color: #e2e8f0 !important;
+ padding: 1em !important;
+ border-radius: 0.5em !important;
+ overflow-x: auto !important;
+ margin: 1em 0 !important;
+ }
+
+ .prose pre code {
+ background: transparent !important;
+ padding: 0 !important;
+ color: inherit !important;
+ }
+
+ .prose blockquote {
+ border-left: 4px solid #8b5cf6 !important;
+ padding-left: 1em !important;
+ margin: 1em 0 !important;
+ font-style: italic !important;
+ color: #475569 !important;
+ }
+
+ .prose table {
+ width: 100% !important;
+ border-collapse: collapse !important;
+ margin: 1em 0 !important;
+ }
+
+ .prose th, .prose td {
+ border: 1px solid #cbd5e1 !important;
+ padding: 0.5em !important;
+ }
+
+ .prose th {
+ background: #f1f5f9 !important;
+ font-weight: 600 !important;
+ }
+ `;
+
+ // Add complete Rough Notation styles
+ styleText += `
+ /* Rough Notation - Complete Styles */
+ .rough-notation {
+ display: inline !important;
+ position: relative !important;
+ }
+
+ /* Circle annotation */
+ .rough-circle {
+ position: relative !important;
+ display: inline-block !important;
+ padding: 0 6px !important;
+ }
+
+ .rough-circle::before {
+ content: '' !important;
+ position: absolute !important;
+ top: -4px !important;
+ left: -4px !important;
+ right: -4px !important;
+ bottom: -4px !important;
+ border: 2.5px solid #ef4444 !important;
+ border-radius: 50% !important;
+ transform: rotate(-2deg) !important;
+ pointer-events: none !important;
+ }
+
+ .rough-circle::after {
+ content: '' !important;
+ position: absolute !important;
+ top: -3px !important;
+ left: -2px !important;
+ right: -6px !important;
+ bottom: -5px !important;
+ border: 1.5px solid rgba(239, 68, 68, 0.4) !important;
+ border-radius: 45% 55% 50% 50% !important;
+ transform: rotate(1deg) !important;
+ pointer-events: none !important;
+ }
+
+ /* Highlight annotation */
+ .rough-highlight {
+ background: linear-gradient(
+ 104deg,
+ rgba(254, 240, 138, 0) 0.9%,
+ rgba(254, 240, 138, 1) 2.4%,
+ rgba(254, 240, 138, 0.5) 5.8%,
+ rgba(254, 240, 138, 0.3) 93%,
+ rgba(254, 240, 138, 0.8) 96%,
+ rgba(254, 240, 138, 0) 98%
+ ),
+ linear-gradient(
+ 183deg,
+ rgba(254, 240, 138, 0) 0%,
+ rgba(254, 240, 138, 0.4) 7.9%,
+ rgba(254, 240, 138, 0) 15%
+ ) !important;
+ padding: 0.1em 0.2em !important;
+ margin: 0 -0.2em !important;
+ border-radius: 0.2em !important;
+ box-decoration-break: clone !important;
+ -webkit-box-decoration-break: clone !important;
+ }
+
+ /* Box annotation */
+ .rough-box {
+ position: relative !important;
+ display: inline-block !important;
+ padding: 2px 6px !important;
+ }
+
+ .rough-box::before {
+ content: '' !important;
+ position: absolute !important;
+ top: -2px !important;
+ left: -3px !important;
+ right: -3px !important;
+ bottom: -2px !important;
+ border: 2px solid #3b82f6 !important;
+ border-radius: 2px !important;
+ transform: rotate(-0.5deg) skewX(-0.5deg) !important;
+ pointer-events: none !important;
+ }
+
+ .rough-box::after {
+ content: '' !important;
+ position: absolute !important;
+ top: 0px !important;
+ left: -1px !important;
+ right: -5px !important;
+ bottom: -4px !important;
+ border: 1.5px solid rgba(59, 130, 246, 0.3) !important;
+ border-radius: 1px !important;
+ transform: rotate(0.5deg) !important;
+ pointer-events: none !important;
+ }
+
+ /* Underline annotation */
+ .rough-underline {
+ position: relative !important;
+ text-decoration: none !important;
+ }
+
+ .rough-underline::after {
+ content: '' !important;
+ position: absolute !important;
+ left: 0 !important;
+ right: 0 !important;
+ bottom: -2px !important;
+ height: 4px !important;
+ background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 20 4'%3E%3Cpath d='M0 3 Q5 0 10 3 T20 3' stroke='%231e293b' stroke-width='1.5' fill='none' stroke-linecap='round'/%3E%3C/svg%3E") repeat-x !important;
+ background-size: 12px 4px !important;
+ pointer-events: none !important;
+ }
+
+ /* Bracket annotation */
+ .rough-bracket {
+ display: inline !important;
+ }
+
+ .rough-bracket-container {
+ position: relative !important;
+ padding-left: 16px !important;
+ margin-left: 4px !important;
+ }
+
+ .rough-bracket-container::before {
+ content: '' !important;
+ position: absolute !important;
+ left: 0 !important;
+ top: -4px !important;
+ bottom: -4px !important;
+ width: 10px !important;
+ border-left: 3px solid #8b5cf6 !important;
+ border-top: 3px solid #8b5cf6 !important;
+ border-bottom: 3px solid #8b5cf6 !important;
+ border-radius: 4px 0 0 4px !important;
+ transform: scaleX(0.6) !important;
+ transform-origin: left center !important;
+ pointer-events: none !important;
+ }
+
+ span.rough-bracket {
+ border-left: 3px solid #8b5cf6 !important;
+ padding-left: 8px !important;
+ margin-left: 4px !important;
+ display: inline !important;
+ position: relative !important;
+ }
+
+ span.rough-bracket::before {
+ content: '' !important;
+ position: absolute !important;
+ left: -3px !important;
+ top: -2px !important;
+ width: 8px !important;
+ height: 3px !important;
+ border-left: 3px solid #8b5cf6 !important;
+ border-top: 3px solid #8b5cf6 !important;
+ border-radius: 3px 0 0 0 !important;
+ pointer-events: none !important;
+ }
+
+ span.rough-bracket::after {
+ content: '' !important;
+ position: absolute !important;
+ left: -3px !important;
+ bottom: -2px !important;
+ width: 8px !important;
+ height: 3px !important;
+ border-left: 3px solid #8b5cf6 !important;
+ border-bottom: 3px solid #8b5cf6 !important;
+ border-radius: 0 0 0 3px !important;
+ pointer-events: none !important;
+ }
+ `;
+
+ styleElement.textContent = styleText;
+ document.head.appendChild(styleElement);
+
+ // Wait for styles to apply and render
+ await new Promise((resolve) => setTimeout(resolve, 100));
+
+ // Force layout recalculation
+ tempContainer.offsetHeight;
+
+ const canvas = await html2canvas(tempContainer, {
+ scale: 2,
+ useCORS: true,
+ logging: false,
+ backgroundColor: "#ffffff",
+ allowTaint: true,
+ removeContainer: false,
+ imageTimeout: 15000,
+ onclone: (clonedDoc) => {
+ // Ensure styles are applied in cloned document
+ const clonedStyle = clonedDoc.getElementById("pdf-export-styles");
+ if (!clonedStyle) {
+ const newStyle = clonedDoc.createElement("style");
+ newStyle.id = "pdf-export-styles";
+ newStyle.textContent = styleText;
+ clonedDoc.head.appendChild(newStyle);
+ }
+ },
+ });
+
+ // Cleanup
+ document.body.removeChild(tempContainer);
+ const styleToRemove = document.getElementById("pdf-export-styles");
+ if (styleToRemove) {
+ document.head.removeChild(styleToRemove);
+ }
+
+ const imgData = canvas.toDataURL("image/png", 1.0);
+ const pdf = new jsPDF("p", "mm", "a4");
+ const pdfWidth = pdf.internal.pageSize.getWidth();
+ const pdfHeight = pdf.internal.pageSize.getHeight();
+ const margin = 10; // 10mm margins
+ const contentWidth = pdfWidth - margin * 2;
+
+ const imgProps = pdf.getImageProperties(imgData);
+ const imgHeight = (imgProps.height * contentWidth) / imgProps.width;
+
+ let heightLeft = imgHeight;
+ let position = margin;
+
+ // Add first page
+ pdf.addImage(imgData, "PNG", margin, position, contentWidth, imgHeight);
+ heightLeft -= pdfHeight - margin * 2;
+
+ // Add subsequent pages
+ while (heightLeft > 0) {
+ pdf.addPage();
+ position = margin - (imgHeight - heightLeft);
+ pdf.addImage(imgData, "PNG", margin, position, contentWidth, imgHeight);
+ heightLeft -= pdfHeight - margin * 2;
+ }
+
+ pdf.save("document.pdf");
+ } catch (e) {
+ console.error("PDF export error:", e);
+ alert(
+ "PDF export failed, please try again. Check console for error details.",
+ );
+ } finally {
+ setIsProcessing(false);
+ }
+ };
+
+ // Toolbar button component
+ const ToolbarButton = ({
+ icon,
+ onClick,
+ title,
+ active,
+ }: {
+ icon: React.ReactNode;
+ onClick: () => void;
+ title: string;
+ active?: boolean;
+ }) => (
+ <button
+ onClick={onClick}
+ title={title}
+ className={`p-1.5 rounded transition-all ${active ? "bg-purple-100 dark:bg-purple-900/50 text-purple-700 dark:text-purple-300" : "text-slate-500 dark:text-slate-400 hover:bg-slate-100 dark:hover:bg-slate-700 hover:text-slate-700 dark:hover:text-slate-200"}`}
+ >
+ {icon}
+ </button>
+ );
+
+ const Divider = () => (
+ <div className="w-px h-5 bg-slate-200 dark:bg-slate-600 mx-1" />
+ );
+
+ return (
+ <div className="flex h-full gap-4">
+ {/* Left Column: Editor */}
+ <div className="flex-1 flex flex-col bg-white dark:bg-slate-900 rounded-xl shadow-sm border border-slate-200 dark:border-slate-700 overflow-hidden relative">
+ {/* Toolbar */}
+ <div className="p-2 border-b border-slate-100 dark:border-slate-700 bg-slate-50/50 dark:bg-slate-800/50 flex items-center gap-1 flex-wrap">
+ {/* Formatting */}
+ <div className="flex items-center gap-0.5">
+ <ToolbarButton
+ icon={<Bold className="w-4 h-4" />}
+ onClick={() => wrapSelection("**", "**")}
+ title="Bold (Ctrl+B)"
+ />
+ <ToolbarButton
+ icon={<Italic className="w-4 h-4" />}
+ onClick={() => wrapSelection("*", "*")}
+ title="Italic (Ctrl+I)"
+ />
+ <ToolbarButton
+ icon={<UnderlineIcon className="w-4 h-4" />}
+ onClick={() => wrapSelection("<u>", "</u>")}
+ title="Underline (Ctrl+U)"
+ />
+ <ToolbarButton
+ icon={<Highlighter className="w-4 h-4" />}
+ onClick={() => wrapSelection("<mark>", "</mark>")}
+ title="Highlight (Ctrl+H)"
+ />
+ <ToolbarButton
+ icon={<Strikethrough className="w-4 h-4" />}
+ onClick={() => wrapSelection("~~", "~~")}
+ title="Strikethrough (Ctrl+Shift+S)"
+ />
+ <ToolbarButton
+ icon={<Code className="w-4 h-4" />}
+ onClick={() => wrapSelection("`", "`")}
+ title="Inline Code"
+ />
+ </div>
+
+ <Divider />
+
+ {/* Headings */}
+ <div className="flex items-center gap-0.5">
+ <ToolbarButton
+ icon={<Heading1 className="w-4 h-4" />}
+ onClick={() => toggleLinePrefix("# ")}
+ title="Heading 1"
+ />
+ <ToolbarButton
+ icon={<Heading2 className="w-4 h-4" />}
+ onClick={() => toggleLinePrefix("## ")}
+ title="Heading 2"
+ />
+ </div>
+
+ <Divider />
+
+ {/* Lists */}
+ <div className="flex items-center gap-0.5">
+ <ToolbarButton
+ icon={<List className="w-4 h-4" />}
+ onClick={() => toggleLinePrefix("- ")}
+ title="Bullet List"
+ />
+ <ToolbarButton
+ icon={<ListOrdered className="w-4 h-4" />}
+ onClick={() => toggleLinePrefix("1. ")}
+ title="Numbered List"
+ />
+ <ToolbarButton
+ icon={<Quote className="w-4 h-4" />}
+ onClick={() => toggleLinePrefix("> ")}
+ title="Quote"
+ />
+ </div>
+
+ <Divider />
+
+ {/* Insert */}
+ <div className="flex items-center gap-0.5">
+ <ToolbarButton
+ icon={<Link className="w-4 h-4" />}
+ onClick={() => wrapSelection("[", "](url)")}
+ title="Link"
+ />
+ <ToolbarButton
+ icon={<Image className="w-4 h-4" />}
+ onClick={() => wrapSelection("![", "](url)")}
+ title="Image"
+ />
+ <ToolbarButton
+ icon={<Minus className="w-4 h-4" />}
+ onClick={() => {
+ const textarea = textareaRef.current;
+ if (!textarea) return;
+ const pos = textarea.selectionStart;
+ setContent(
+ content.substring(0, pos) +
+ "\n\n---\n\n" +
+ content.substring(pos),
+ );
+ }}
+ title="Horizontal Rule"
+ />
+ </div>
+
+ <Divider />
+
+ {/* Import from Notebook */}
+ <button
+ onClick={() => setShowImportModal(true)}
+ className="flex items-center gap-1 px-2 py-1 text-xs text-blue-600 dark:text-blue-400 hover:bg-blue-50 dark:hover:bg-blue-900/30 rounded transition-all"
+ title="Import from Notebook"
+ >
+ <Import className="w-3.5 h-3.5" />
+ Import
+ </button>
+
+ <div className="flex-1" />
+
+ {/* Backend Status Indicator */}
+ {backendConnected !== null && (
+ <>
+ <div
+ className={`flex items-center gap-1 px-2 py-1 text-xs rounded transition-all ${
+ backendConnected
+ ? "bg-green-50 dark:bg-green-900/30 text-green-700 dark:text-green-400 border border-green-200 dark:border-green-800"
+ : "bg-red-50 dark:bg-red-900/30 text-red-700 dark:text-red-400 border border-red-200 dark:border-red-800"
+ }`}
+ title={
+ backendConnected
+ ? `Backend connected: ${apiUrl("")}`
+ : `Backend not connected\nRun: python start.py\nAddress: ${apiUrl("")}`
+ }
+ >
+ {backendConnected ? (
+ <>
+ <Wifi className="w-3 h-3" />
+ <span className="hidden sm:inline">Connected</span>
+ </>
+ ) : (
+ <>
+ <WifiOff className="w-3 h-3" />
+ <span className="hidden sm:inline">Disconnected</span>
+ </>
+ )}
+ </div>
+ </>
+ )}
+ </div>
+
+ {/* Editor Area */}
+ <div className="flex-1 flex flex-col overflow-hidden">
+ <div className="p-2 border-b border-slate-100 dark:border-slate-700 bg-slate-50/30 dark:bg-slate-800/30 flex justify-between items-center">
+ <div className="flex items-center gap-2">
+ <div className="text-[10px] font-bold text-slate-400 dark:text-slate-500 uppercase tracking-wider">
+ Editor
+ </div>
+ {hideAiMarks && (
+ <span className="text-[9px] bg-emerald-100 dark:bg-emerald-900/50 text-emerald-600 dark:text-emerald-400 px-1.5 py-0.5 rounded-full font-medium">
+ Marks Hidden
+ </span>
+ )}
+ </div>
+ <div className="text-[10px] text-slate-400 dark:text-slate-500">
+ {content.length} chars · {content.split("\n").length} lines
+ </div>
+ </div>
+ <div
+ ref={editorContainerRef}
+ className="flex-1 overflow-y-auto"
+ onScroll={handleEditorScroll}
+ >
+ <textarea
+ ref={textareaRef}
+ value={hideAiMarks ? getDisplayContent() : content}
+ onChange={(e) => handleContentChange(e.target.value)}
+ onMouseUp={handleMouseUp}
+ className="w-full h-full min-h-full p-4 resize-none outline-none font-mono text-sm leading-relaxed text-slate-800 dark:text-slate-200 bg-transparent placeholder-slate-400 dark:placeholder-slate-500"
+ placeholder="Type your markdown here..."
+ style={{ minHeight: "100%" }}
+ />
+ </div>
+ </div>
+
+ {/* Popover */}
+ {popover && (
+ <div
+ ref={popoverRef}
+ style={{
+ position: "fixed",
+ left: Math.min(
+ window.innerWidth - 340,
+ Math.max(20, popover.x - 160),
+ ),
+ top: Math.min(window.innerHeight - 480, popover.y),
+ }}
+ className="z-50 w-[320px] bg-white dark:bg-slate-800 rounded-xl shadow-2xl border border-slate-200 dark:border-slate-600 animate-in fade-in zoom-in-95 duration-200 flex flex-col"
+ >
+ <div className="p-3 border-b border-slate-100 dark:border-slate-700 bg-gradient-to-r from-purple-50 to-indigo-50 dark:from-purple-900/30 dark:to-indigo-900/30 flex justify-between items-center rounded-t-xl">
+ <div className="flex items-center gap-2 text-xs font-bold text-slate-700 dark:text-slate-200">
+ <Sparkles className="w-4 h-4 text-purple-500 dark:text-purple-400" />
+ AI Edit Assistant
+ </div>
+ <button
+ onClick={() => setPopover(null)}
+ className="text-slate-400 hover:text-slate-600 dark:text-slate-500 dark:hover:text-slate-300"
+ title="Close"
+ aria-label="Close dialog"
+ >
+ <X className="w-4 h-4" />
+ </button>
+ </div>
+
+ <div className="p-4 space-y-4">
+ {/* Selected Text Preview */}
+ <div className="text-xs text-slate-500 dark:text-slate-400 bg-slate-50 dark:bg-slate-700 p-2 rounded-lg border border-slate-100 dark:border-slate-600 line-clamp-2 italic">
+ "{selection?.text}"
+ </div>
+
+ {/* Instruction Input */}
+ <div className="space-y-1">
+ <label className="text-[10px] font-bold text-slate-500 dark:text-slate-400 uppercase">
+ Instruction (Optional)
+ </label>
+ <input
+ type="text"
+ value={instruction}
+ onChange={(e) => setInstruction(e.target.value)}
+ placeholder="e.g. Make it more formal..."
+ className="w-full px-3 py-2 text-xs border border-slate-200 dark:border-slate-600 rounded-lg focus:ring-2 focus:ring-purple-500/20 focus:border-purple-500 outline-none bg-white dark:bg-slate-700 text-slate-800 dark:text-slate-200 placeholder-slate-400 dark:placeholder-slate-500"
+ />
+ </div>
+
+ {/* Source Selection - Only show in non-automark mode */}
+ {selectedAction !== "automark" && (
+ <div className="space-y-1">
+ <label className="text-[10px] font-bold text-slate-500 dark:text-slate-400 uppercase">
+ Context Source (Optional)
+ </label>
+ <div className="flex gap-2">
+ <button
+ onClick={() => setSource(source === "rag" ? null : "rag")}
+ className={`flex-1 flex items-center justify-center gap-1 py-1.5 text-xs border rounded-lg transition-all ${source === "rag" ? "bg-purple-50 dark:bg-purple-900/40 border-purple-200 dark:border-purple-700 text-purple-700 dark:text-purple-300" : "bg-white dark:bg-slate-700 border-slate-200 dark:border-slate-600 text-slate-600 dark:text-slate-300 hover:bg-slate-50 dark:hover:bg-slate-600"}`}
+ >
+ <Database className="w-3 h-3" />
+ RAG
+ </button>
+ <button
+ onClick={() => setSource(source === "web" ? null : "web")}
+ className={`flex-1 flex items-center justify-center gap-1 py-1.5 text-xs border rounded-lg transition-all ${source === "web" ? "bg-blue-50 dark:bg-blue-900/40 border-blue-200 dark:border-blue-700 text-blue-700 dark:text-blue-300" : "bg-white dark:bg-slate-700 border-slate-200 dark:border-slate-600 text-slate-600 dark:text-slate-300 hover:bg-slate-50 dark:hover:bg-slate-600"}`}
+ >
+ <Globe className="w-3 h-3" />
+ Web
+ </button>
+ </div>
+ </div>
+ )}
+
+ {/* KB Selector if RAG */}
+ {source === "rag" && kbs.length > 0 && (
+ <div className="animate-in fade-in slide-in-from-top-1">
+ <select
+ value={selectedKb}
+ onChange={(e) => setSelectedKb(e.target.value)}
+ className="w-full px-2 py-1.5 text-xs border border-slate-200 dark:border-slate-600 rounded-lg outline-none bg-white dark:bg-slate-700 text-slate-800 dark:text-slate-200"
+ >
+ {kbs.map((kb) => (
+ <option key={kb} value={kb}>
+ {kb}
+ </option>
+ ))}
+ </select>
+ </div>
+ )}
+
+ {/* Actions */}
+ <div className="pt-2 border-t border-slate-100 dark:border-slate-700 space-y-3">
+ <div className="grid grid-cols-4 gap-1.5">
+ <button
+ onClick={() => setSelectedAction("rewrite")}
+ disabled={isProcessing}
+ className={`flex flex-col items-center gap-1 p-2 rounded-lg transition-all text-[10px] font-medium border-2 ${selectedAction === "rewrite" ? "bg-purple-50 dark:bg-purple-900/40 border-purple-400 dark:border-purple-600 text-purple-600 dark:text-purple-300" : "border-transparent text-slate-600 dark:text-slate-400 hover:bg-purple-50 dark:hover:bg-purple-900/30 hover:text-purple-600 dark:hover:text-purple-300"}`}
+ >
+ <Wand2 className="w-4 h-4" />
+ Rewrite
+ </button>
+ <button
+ onClick={() => setSelectedAction("shorten")}
+ disabled={isProcessing}
+ className={`flex flex-col items-center gap-1 p-2 rounded-lg transition-all text-[10px] font-medium border-2 ${selectedAction === "shorten" ? "bg-amber-50 dark:bg-amber-900/40 border-amber-400 dark:border-amber-600 text-amber-600 dark:text-amber-300" : "border-transparent text-slate-600 dark:text-slate-400 hover:bg-amber-50 dark:hover:bg-amber-900/30 hover:text-amber-600 dark:hover:text-amber-300"}`}
+ >
+ <Minimize2 className="w-4 h-4" />
+ Shorten
+ </button>
+ <button
+ onClick={() => setSelectedAction("expand")}
+ disabled={isProcessing}
+ className={`flex flex-col items-center gap-1 p-2 rounded-lg transition-all text-[10px] font-medium border-2 ${selectedAction === "expand" ? "bg-blue-50 dark:bg-blue-900/40 border-blue-400 dark:border-blue-600 text-blue-600 dark:text-blue-300" : "border-transparent text-slate-600 dark:text-slate-400 hover:bg-blue-50 dark:hover:bg-blue-900/30 hover:text-blue-600 dark:hover:text-blue-300"}`}
+ >
+ <Maximize2 className="w-4 h-4" />
+ Expand
+ </button>
+ <button
+ onClick={() => setSelectedAction("automark")}
+ disabled={isProcessing}
+ className={`flex flex-col items-center gap-1 p-2 rounded-lg transition-all text-[10px] font-medium border-2 ${selectedAction === "automark" ? "bg-emerald-50 dark:bg-emerald-900/40 border-emerald-400 dark:border-emerald-600 text-emerald-600 dark:text-emerald-300" : "border-transparent text-slate-600 dark:text-slate-400 hover:bg-emerald-50 dark:hover:bg-emerald-900/30 hover:text-emerald-600 dark:hover:text-emerald-300"}`}
+ >
+ <PenTool className="w-4 h-4" />
+ AI Mark
+ </button>
+ </div>
+
+ {/* Submit Button */}
+ <button
+ onClick={() => handleAction(selectedAction)}
+ disabled={isProcessing}
+ className="w-full py-2.5 bg-gradient-to-r from-purple-600 to-indigo-600 text-white text-xs font-bold rounded-lg hover:from-purple-700 hover:to-indigo-700 transition-all shadow-md hover:shadow-lg disabled:opacity-50 flex items-center justify-center gap-2"
+ >
+ {isProcessing ? (
+ <>
+ <Loader2 className="w-4 h-4 animate-spin" />
+ Processing...
+ </>
+ ) : (
+ <>
+ <Sparkles className="w-4 h-4" />
+ Apply{" "}
+ {selectedAction === "automark"
+ ? "AI Mark"
+ : selectedAction.charAt(0).toUpperCase() +
+ selectedAction.slice(1)}
+ </>
+ )}
+ </button>
+ </div>
+ </div>
+ </div>
+ )}
+ </div>
+
+ {/* Right Column */}
+ <div className="flex-1 flex flex-col gap-4">
+ {/* Preview Area (Upper) */}
+ <div
+ className={`flex-1 bg-white dark:bg-slate-900 rounded-xl shadow-sm border border-slate-200 dark:border-slate-700 overflow-hidden flex flex-col transition-all`}
+ >
+ {/* Preview Header & Toolbar */}
+ <div className="p-2 border-b border-slate-100 dark:border-slate-700 bg-slate-50/50 dark:bg-slate-800/50 flex justify-between items-center">
+ <div className="flex items-center gap-2">
+ <div className="text-[10px] font-bold text-slate-400 dark:text-slate-500 uppercase tracking-wider">
+ Preview
+ </div>
+ <div className="flex items-center gap-1">
+ <Sparkles className="w-3 h-3 text-purple-400" />
+ <span className="text-[10px] text-slate-400 dark:text-slate-500">
+ Live Preview · Synced Scroll
+ </span>
+ </div>
+ </div>
+
+ {/* Moved Action Buttons to Preview Header */}
+ <div className="flex items-center gap-1">
+ <button
+ onClick={() => setShowNotebookModal(true)}
+ className="flex items-center gap-1 px-2 py-1 text-xs text-indigo-600 dark:text-indigo-400 hover:bg-indigo-50 dark:hover:bg-indigo-900/30 rounded transition-all"
+ title="Save to Notebook"
+ >
+ <Book className="w-3.5 h-3.5" />
+ Save
+ </button>
+ <Divider />
+ <button
+ onClick={() => setHideAiMarks(!hideAiMarks)}
+ className={`flex items-center gap-1 px-2 py-1 text-xs rounded transition-all ${hideAiMarks ? "bg-emerald-100 dark:bg-emerald-900/40 text-emerald-700 dark:text-emerald-400" : "text-slate-600 dark:text-slate-400 hover:bg-slate-100 dark:hover:bg-slate-700"}`}
+ title={hideAiMarks ? "Show AI Marks" : "Hide AI Marks"}
+ >
+ {hideAiMarks ? (
+ <Eye className="w-3.5 h-3.5" />
+ ) : (
+ <EyeOff className="w-3.5 h-3.5" />
+ )}
+ </button>
+ <Divider />
+ <button
+ onClick={exportMarkdown}
+ className="flex items-center gap-1 px-2 py-1 text-xs text-slate-600 dark:text-slate-400 hover:bg-slate-100 dark:hover:bg-slate-700 rounded transition-all"
+ title="Export Markdown"
+ >
+ <FileText className="w-3.5 h-3.5" />
+ .md
+ </button>
+ <button
+ onClick={exportPDF}
+ disabled={isProcessing}
+ className="flex items-center gap-1 px-2 py-1 text-xs text-slate-600 dark:text-slate-400 hover:bg-slate-100 dark:hover:bg-slate-700 rounded transition-all disabled:opacity-50"
+ title="Export PDF"
+ >
+ <Download className="w-3.5 h-3.5" />
+ .pdf
+ </button>
+ <Divider />
+ <button
+ onClick={() => setShowHistory(!showHistory)}
+ className={`flex items-center gap-1 text-xs px-2 py-1 rounded transition-all ${showHistory ? "bg-purple-100 dark:bg-purple-900/40 text-purple-700 dark:text-purple-400" : "text-slate-500 dark:text-slate-400 hover:bg-slate-100 dark:hover:bg-slate-700"}`}
+ title="History"
+ >
+ <History className="w-3.5 h-3.5" />
+ </button>
+ </div>
+ </div>
+
+ {/* Markdown Preview Content */}
+ <div className="flex-1 flex flex-col relative min-h-0">
+ <div
+ ref={previewRef}
+ className="flex-1 overflow-y-auto p-6 prose prose-slate dark:prose-invert prose-sm max-w-none prose-headings:text-slate-900 dark:prose-headings:text-slate-100 prose-p:text-slate-700 dark:prose-p:text-slate-300 prose-a:text-purple-600 dark:prose-a:text-purple-400 rough-notation-container"
+ onScroll={handlePreviewScroll}
+ style={{ minHeight: 0 }}
+ >
+ <ReactMarkdown
+ remarkPlugins={[remarkGfm, remarkMath]}
+ rehypePlugins={[rehypeKatex, rehypeRaw]}
+ components={{
+ mark: ({ node, ...props }) => (
+ <mark className="bg-yellow-200 px-0.5 rounded" {...props} />
+ ),
+ u: ({ node, ...props }) => (
+ <u
+ className="underline decoration-2 decoration-slate-400"
+ {...props}
+ />
+ ),
+ span: ({ node, ...props }) => {
+ const dataAttr = (props as any)["data-rough-notation"];
+ if (dataAttr) {
+ // Handwritten style annotation styles
+ const styleClasses: Record<string, string> = {
+ circle: "rough-circle",
+ highlight: "rough-highlight",
+ box: "rough-box",
+ underline: "rough-underline",
+ bracket: "rough-bracket",
+ };
+ return (
+ <span
+ className={`rough-notation ${styleClasses[dataAttr] || ""}`}
+ data-rough-notation={dataAttr}
+ {...props}
+ />
+ );
+ }
+ return <span {...props} />;
+ },
+ // Handle paragraphs containing rough-notation
+ p: ({ node, children, ...props }) => {
+ // Check if contains bracket type span
+ const childArray = React.Children.toArray(children);
+ const hasBracket = childArray.some((child: any) => {
+ if (React.isValidElement(child)) {
+ const childProps = child.props as any;
+ return (
+ childProps?.["data-rough-notation"] === "bracket"
+ );
+ }
+ return false;
+ });
+
+ if (hasBracket) {
+ return (
+ <p className="rough-bracket-container" {...props}>
+ {children}
+ </p>
+ );
+ }
+ return <p {...props}>{children}</p>;
+ },
+ table: ({ node, ...props }) => (
+ <div className="overflow-x-auto my-4">
+ <table
+ className="min-w-full border-collapse border border-slate-300"
+ {...props}
+ />
+ </div>
+ ),
+ th: ({ node, ...props }) => (
+ <th
+ className="border border-slate-300 px-3 py-2 bg-slate-100 font-semibold text-left"
+ {...props}
+ />
+ ),
+ td: ({ node, ...props }) => (
+ <td
+ className="border border-slate-300 px-3 py-2"
+ {...props}
+ />
+ ),
+ code: ({ node, className, children, ...props }) => {
+ const match = /language-(\w+)/.exec(className || "");
+ const isInline = !match && !className;
+
+ if (isInline) {
+ return (
+ <code
+ className="bg-slate-100 px-1.5 py-0.5 rounded text-sm font-mono text-pink-600"
+ {...props}
+ >
+ {children}
+ </code>
+ );
+ }
+
+ return (
+ <pre className="bg-slate-900 text-slate-100 p-4 rounded-lg overflow-x-auto my-4">
+ <code className={className} {...props}>
+ {children}
+ </code>
+ </pre>
+ );
+ },
+ blockquote: ({ node, ...props }) => (
+ <blockquote
+ className="border-l-4 border-purple-500 pl-4 my-4 italic text-slate-600 bg-purple-50/50 py-2 rounded-r"
+ {...props}
+ />
+ ),
+ }}
+ >
+ {processLatexContent(content)}
+ </ReactMarkdown>
+ </div>
+
+ {/* History Panel Overlay */}
+ {showHistory && (
+ <div className="absolute inset-0 z-10 bg-white/95 dark:bg-slate-900/95 backdrop-blur-sm flex flex-col animate-in fade-in duration-200">
+ <div className="p-3 border-b border-slate-100 dark:border-slate-700 flex justify-between items-center bg-slate-50/50 dark:bg-slate-800/50">
+ <h3 className="text-xs font-bold text-slate-600 dark:text-slate-300 uppercase tracking-wider">
+ Version History
+ </h3>
+ <button
+ onClick={() => setShowHistory(false)}
+ className="text-slate-400 hover:text-slate-600 dark:text-slate-500 dark:hover:text-slate-300 p-1 hover:bg-slate-100 dark:hover:bg-slate-700 rounded"
+ >
+ <X className="w-4 h-4" />
+ </button>
+ </div>
+ <div className="flex-1 overflow-y-auto p-2">
+ {operationHistory.length === 0 ? (
+ <div className="text-center py-10 text-slate-400 dark:text-slate-500 text-sm">
+ No history available
+ </div>
+ ) : (
+ <div className="space-y-2">
+ {[...operationHistory].reverse().map((op) => (
+ <div
+ key={op.id}
+ className="p-3 bg-white dark:bg-slate-800 border border-slate-200 dark:border-slate-700 rounded-lg hover:shadow-sm transition-all cursor-pointer group"
+ >
+ <div className="flex items-center justify-between mb-1">
+ <span
+ className={`text-[10px] font-bold uppercase px-1.5 py-0.5 rounded ${
+ op.action === "rewrite"
+ ? "bg-purple-100 dark:bg-purple-900/50 text-purple-700 dark:text-purple-300"
+ : op.action === "shorten"
+ ? "bg-amber-100 dark:bg-amber-900/50 text-amber-700 dark:text-amber-300"
+ : op.action === "automark"
+ ? "bg-emerald-100 dark:bg-emerald-900/50 text-emerald-700 dark:text-emerald-300"
+ : "bg-blue-100 dark:bg-blue-900/50 text-blue-700 dark:text-blue-300"
+ }`}
+ >
+ {op.action}
+ </span>
+ <span className="text-[10px] text-slate-400 dark:text-slate-500">
+ {new Date(op.timestamp).toLocaleTimeString()}
+ </span>
+ </div>
+ <div className="text-xs text-slate-600 dark:text-slate-400 truncate mb-1">
+ "{op.input?.original_text?.substring(0, 35)}..."
+ </div>
+ <div className="flex items-center gap-2 text-[10px] text-slate-400 dark:text-slate-500">
+ {op.source && (
+ <span className="flex items-center gap-0.5">
+ {op.source === "rag" ? (
+ <Database className="w-2.5 h-2.5" />
+ ) : (
+ <Globe className="w-2.5 h-2.5" />
+ )}
+ {op.source.toUpperCase()}
+ </span>
+ )}
+ </div>
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ </div>
+ )}
+ </div>
+ </div>
+
+ {/* Podcast / Narration Area (Bottom Collapsible) */}
+ <div className="shrink-0 bg-white dark:bg-slate-900 rounded-xl shadow-sm border border-slate-200 dark:border-slate-700 overflow-hidden transition-all">
+ <div
+ className="p-2 bg-slate-50/50 dark:bg-slate-800/50 flex justify-between items-center cursor-pointer hover:bg-slate-100/50 dark:hover:bg-slate-700/50 transition-colors"
+ onClick={() => setIsPodcastExpanded(!isPodcastExpanded)}
+ >
+ <div className="flex items-center gap-2">
+ {isPodcastExpanded ? (
+ <ChevronDown className="w-4 h-4 text-slate-400 dark:text-slate-500" />
+ ) : (
+ <ChevronRight className="w-4 h-4 text-slate-400 dark:text-slate-500" />
+ )}
+ <div className="flex items-center gap-1 text-[10px] font-bold text-slate-500 dark:text-slate-400 uppercase tracking-wider">
+ <Radio className="w-3.5 h-3.5 text-purple-600 dark:text-purple-400" />
+ Podcast Narration
+ </div>
+ </div>
+ {!isPodcastExpanded && (
+ <span className="text-[10px] text-slate-400 dark:text-slate-500 px-2">
+ Click to expand
+ </span>
+ )}
+ </div>
+
+ {isPodcastExpanded && (
+ <div className="p-4 border-t border-slate-100 dark:border-slate-700 animate-in slide-in-from-top-2">
+ <div className="flex items-center justify-between mb-2">
+ <div className="flex items-center gap-2">
+ {ttsAvailable === false && (
+ <span className="text-[10px] text-amber-600 dark:text-amber-400 bg-amber-100 dark:bg-amber-900/40 px-1.5 py-0.5 rounded-full flex items-center gap-1">
+ <AlertCircle className="w-3 h-3" />
+ Script only (TTS not configured)
+ </span>
+ )}
+ </div>
+ </div>
+
+ <div className="flex flex-col md:flex-row gap-3">
+ <div className="flex-1 space-y-2">
+ <div className="flex gap-2">
+ <button
+ onClick={async () => {
+ if (!content.trim()) {
+ setNarrationError(
+ "Current note is empty, cannot generate narration.",
+ );
+ return;
+ }
+ setNarrationLoading(true);
+ setNarrationError(null);
+ try {
+ const res = await fetch(
+ apiUrl("/api/v1/co_writer/narrate"),
+ {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ content,
+ style: narrationStyle,
+ skip_audio: !ttsAvailable,
+ }),
+ },
+ );
+ if (!res.ok) {
+ const detail = await res.text();
+ throw new Error(detail || `HTTP ${res.status}`);
+ }
+ const data = await res.json();
+ setNarrationScript(data.script || "");
+ setNarrationKeyPoints(data.key_points || []);
+ if (data.has_audio && data.audio_url) {
+ // Ensure the audio URL is properly formatted
+ const audioUrl = data.audio_url.startsWith("http")
+ ? data.audio_url
+ : apiUrl(data.audio_url);
+ setAudioInfo({
+ audioUrl: audioUrl,
+ audioId: data.audio_id,
+ voice: data.voice,
+ });
+ } else {
+ setAudioInfo(null);
+ }
+ } catch (e: any) {
+ setNarrationError(
+ e?.message ||
+ "Failed to generate narration, please try again.",
+ );
+ } finally {
+ setNarrationLoading(false);
+ }
+ }}
+ disabled={narrationLoading}
+ className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium bg-gradient-to-r from-purple-600 to-indigo-600 text-white hover:from-purple-700 hover:to-indigo-700 disabled:opacity-60 shadow-sm"
+ >
+ {narrationLoading ? (
+ <>
+ <Loader2 className="w-3.5 h-3.5 animate-spin" />
+ Generating Podcast
+ </>
+ ) : (
+ <>
+ <Mic className="w-3.5 h-3.5" />
+ Generate Podcast
+ </>
+ )}
+ </button>
+ <button
+ onClick={() => {
+ if (!narrationScript) return;
+ setShowNarrationNotebookModal(true);
+ }}
+ disabled={!narrationScript}
+ className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium border border-slate-200 dark:border-slate-600 text-slate-700 dark:text-slate-300 hover:bg-white dark:hover:bg-slate-700 disabled:opacity-50"
+ >
+ <Book className="w-3.5 h-3.5" />
+ Save Podcast to Notebook
+ </button>
+ </div>
+ {narrationError && (
+ <div className="text-[11px] text-amber-700 dark:text-amber-400 bg-amber-50 dark:bg-amber-900/30 border border-amber-200 dark:border-amber-800 rounded px-2 py-1 flex items-center gap-1">
+ <AlertCircle className="w-3 h-3" />
+ <span>{narrationError}</span>
+ </div>
+ )}
+ <div className="bg-white dark:bg-slate-800 border border-slate-200 dark:border-slate-600 rounded-lg p-2 h-32 overflow-y-auto text-xs text-slate-700 dark:text-slate-300">
+ {narrationScript ? (
+ <p className="whitespace-pre-wrap leading-relaxed">
+ {narrationScript}
+ </p>
+ ) : (
+ <span className="text-slate-400 dark:text-slate-500">
+ After generation, the narration script will appear here.
+ </span>
+ )}
+ </div>
+ </div>
+
+ <div className="w-full md:w-56 space-y-2">
+ <div className="bg-white dark:bg-slate-800 border border-slate-200 dark:border-slate-600 rounded-lg p-2 h-20 overflow-y-auto">
+ <div className="flex items-center gap-1 text-[10px] font-semibold text-slate-500 dark:text-slate-400 mb-1">
+ <Headphones className="w-3.5 h-3.5 text-indigo-600 dark:text-indigo-400" />
+ Key Points
+ </div>
+ {narrationKeyPoints && narrationKeyPoints.length > 0 ? (
+ <ul className="list-disc pl-4 text-[11px] text-slate-700 dark:text-slate-300 space-y-0.5">
+ {narrationKeyPoints.map((kp, idx) => (
+ <li key={idx} className="leading-snug">
+ {kp}
+ </li>
+ ))}
+ </ul>
+ ) : (
+ <div className="text-[11px] text-slate-400 dark:text-slate-500">
+ After generation, 3-5 key points will be listed here.
+ </div>
+ )}
+ </div>
+ <div className="bg-white dark:bg-slate-800 border border-slate-200 dark:border-slate-600 rounded-lg p-3">
+ <div className="flex items-center justify-between mb-2">
+ <div className="flex items-center gap-1.5 text-[10px] font-semibold text-slate-600 dark:text-slate-400">
+ <Headphones className="w-3.5 h-3.5 text-purple-600 dark:text-purple-400" />
+ Podcast Audio
+ </div>
+ {audioInfo?.voice && (
+ <span className="text-[10px] text-slate-500 dark:text-slate-400 bg-purple-50 dark:bg-purple-900/40 px-1.5 py-0.5 rounded-full">
+ {audioInfo.voice}
+ </span>
+ )}
+ </div>
+ {audioInfo?.audioUrl ? (
+ <div className="w-full">
+ <audio
+ controls
+ className="w-full h-9"
+ style={{
+ borderRadius: "6px",
+ backgroundColor: "#f8fafc",
+ }}
+ >
+ <source src={audioInfo.audioUrl} type="audio/mpeg" />
+ Your browser does not support the audio element.
+ </audio>
+ </div>
+ ) : (
+ <div className="text-[11px] text-slate-400 dark:text-slate-500 italic py-2">
+ {ttsAvailable === false
+ ? "TTS not configured, script generation only."
+ : "After generation, you can play the podcast audio here."}
+ </div>
+ )}
+ </div>
+ </div>
+ </div>
+ </div>
+ )}
+ </div>
+ </div>
+
+ {/* Global Loading Overlay */}
+ {isProcessing && !popover && (
+ <div className="fixed inset-0 bg-white/80 dark:bg-slate-900/80 backdrop-blur-sm z-50 flex items-center justify-center">
+ <div className="bg-white dark:bg-slate-800 p-8 rounded-2xl shadow-2xl flex flex-col items-center gap-4 border border-slate-200 dark:border-slate-700">
+ <Loader2 className="w-8 h-8 text-purple-600 dark:text-purple-400 animate-spin" />
+ <span className="font-medium text-slate-700 dark:text-slate-200">
+ Exporting...
+ </span>
+ </div>
+ </div>
+ )}
+
+ {/* Add to Notebook Modal */}
+ <AddToNotebookModal
+ isOpen={showNotebookModal}
+ onClose={() => setShowNotebookModal(false)}
+ recordType="co_writer"
+ title={`Co-Writer Document - ${new Date().toLocaleDateString()}`}
+ userQuery="Co-Writer edited document"
+ output={content}
+ metadata={{
+ char_count: content.length,
+ line_count: content.split("\n").length,
+ }}
+ />
+
+ {/* Notebook Import Modal */}
+ <NotebookImportModal
+ isOpen={showImportModal}
+ onClose={() => setShowImportModal(false)}
+ onImport={(importedContent) => {
+ // Insert at current selection or end
+ const newContent = content
+ ? content + "\n\n" + importedContent
+ : importedContent;
+ setContent(newContent);
+ }}
+ />
+
+ {/* Narration save to Notebook Modal */}
+ <AddToNotebookModal
+ isOpen={showNarrationNotebookModal}
+ onClose={() => setShowNarrationNotebookModal(false)}
+ recordType="co_writer"
+ title={`Co-Writer Podcast - ${new Date().toLocaleDateString()}`}
+ userQuery={content.substring(0, 120)}
+ output={narrationScript}
+ metadata={{
+ char_count: narrationScript.length,
+ style: narrationStyle,
+ key_points: narrationKeyPoints,
+ audio_url: audioInfo?.audioUrl,
+ audio_id: audioInfo?.audioId,
+ voice: audioInfo?.voice,
+ }}
+ />
+ </div>
+ );
+}
diff --git a/web/components/Mermaid.tsx b/web/components/Mermaid.tsx
new file mode 100644
index 000000000..e8b380bf2
--- /dev/null
+++ b/web/components/Mermaid.tsx
@@ -0,0 +1,93 @@
+"use client";
+
+import React, { useEffect, useRef, useState } from "react";
+import mermaid from "mermaid";
+
+interface MermaidProps {
+ chart: string;
+ className?: string;
+}
+
+// Initialize mermaid with custom config
+mermaid.initialize({
+ startOnLoad: false,
+ theme: "neutral",
+ securityLevel: "loose",
+ fontFamily: "ui-sans-serif, system-ui, sans-serif",
+ flowchart: {
+ useMaxWidth: true,
+ htmlLabels: true,
+ curve: "basis",
+ },
+ themeVariables: {
+ primaryColor: "#6366f1",
+ primaryTextColor: "#1e293b",
+ primaryBorderColor: "#c7d2fe",
+ lineColor: "#94a3b8",
+ secondaryColor: "#f1f5f9",
+ tertiaryColor: "#f8fafc",
+ },
+});
+
+let mermaidIdCounter = 0;
+
+export const Mermaid: React.FC<MermaidProps> = ({ chart, className = "" }) => {
+ const containerRef = useRef<HTMLDivElement>(null);
+ const [svg, setSvg] = useState<string>("");
+ const [error, setError] = useState<string | null>(null);
+ const [id] = useState(() => `mermaid-${++mermaidIdCounter}`);
+
+ useEffect(() => {
+ const renderChart = async () => {
+ if (!chart || !containerRef.current) return;
+
+ try {
+ // Clean up the chart code
+ const cleanedChart = chart.trim();
+
+ // Validate and render
+ const { svg: renderedSvg } = await mermaid.render(id, cleanedChart);
+ setSvg(renderedSvg);
+ setError(null);
+ } catch (err) {
+ console.error("Mermaid rendering error:", err);
+ setError(
+ err instanceof Error ? err.message : "Failed to render diagram",
+ );
+ }
+ };
+
+ renderChart();
+ }, [chart, id]);
+
+ if (error) {
+ return (
+ <div
+ className={`my-4 p-4 bg-red-50 border border-red-200 rounded-lg ${className}`}
+ >
+ <p className="text-red-600 text-sm font-medium mb-2">
+ Diagram rendering error
+ </p>
+ <pre className="text-xs text-red-500 whitespace-pre-wrap">{error}</pre>
+ <details className="mt-2">
+ <summary className="text-xs text-slate-500 cursor-pointer">
+ Show source
+ </summary>
+ <pre className="mt-2 p-2 bg-slate-100 rounded text-xs overflow-x-auto">
+ {chart}
+ </pre>
+ </details>
+ </div>
+ );
+ }
+
+ return (
+ <div
+ ref={containerRef}
+ className={`my-6 flex justify-center overflow-x-auto ${className}`}
+ dangerouslySetInnerHTML={{ __html: svg }}
+ />
+ );
+};
+
+export default Mermaid;
diff --git a/web/components/NotebookImportModal.tsx b/web/components/NotebookImportModal.tsx
new file mode 100644
index 000000000..1067bb595
--- /dev/null
+++ b/web/components/NotebookImportModal.tsx
@@ -0,0 +1,354 @@
+"use client";
+
+import { useState, useEffect } from "react";
+import {
+ X,
+ BookOpen,
+ Search,
+ ChevronRight,
+ ChevronDown,
+ Loader2,
+ Check,
+ FileText,
+ Calendar,
+} from "lucide-react";
+import { apiUrl } from "@/lib/api";
+
+interface Notebook {
+ id: string;
+ name: string;
+ description: string;
+ record_count: number;
+ color: string;
+ updated_at?: string;
+}
+
+interface NotebookRecord {
+ id: string;
+ title: string;
+ user_query: string;
+ output: string;
+ type: string;
+ created_at?: string;
+}
+
+interface NotebookImportModalProps {
+ isOpen: boolean;
+ onClose: () => void;
+ onImport: (content: string, records: NotebookRecord[]) => void;
+ title?: string;
+}
+
+export default function NotebookImportModal({
+ isOpen,
+ onClose,
+ onImport,
+ title = "Import from Notebooks",
+}: NotebookImportModalProps) {
+ const [notebooks, setNotebooks] = useState<Notebook[]>([]);
+ const [loading, setLoading] = useState(true);
+ const [expandedNotebooks, setExpandedNotebooks] = useState<Set<string>>(
+ new Set(),
+ );
+ const [notebookRecords, setNotebookRecords] = useState<
+ Map<string, NotebookRecord[]>
+ >(new Map());
+ const [loadingRecords, setLoadingRecords] = useState<Set<string>>(new Set());
+ const [selectedRecords, setSelectedRecords] = useState<Set<string>>(
+ new Set(),
+ ); // Record IDs
+ const [selectedRecordsData, setSelectedRecordsData] = useState<
+ NotebookRecord[]
+ >([]);
+
+ useEffect(() => {
+ if (isOpen) {
+ fetchNotebooks();
+ } else {
+ // Reset state on close
+ setSelectedRecords(new Set());
+ setSelectedRecordsData([]);
+ setExpandedNotebooks(new Set());
+ }
+ }, [isOpen]);
+
+ const fetchNotebooks = async () => {
+ try {
+ setLoading(true);
+ const res = await fetch(apiUrl("/api/v1/notebook/list"));
+ if (res.ok) {
+ const data = await res.json();
+ const validNotebooks = (data.notebooks || []).filter(
+ (nb: Notebook) => nb.record_count > 0,
+ );
+ setNotebooks(validNotebooks);
+ }
+ } catch (error) {
+ console.error("Failed to fetch notebooks:", error);
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ const fetchRecords = async (notebookId: string) => {
+ if (notebookRecords.has(notebookId)) return;
+
+ setLoadingRecords((prev) => new Set(prev).add(notebookId));
+ try {
+ const res = await fetch(apiUrl(`/api/v1/notebook/${notebookId}`));
+ if (res.ok) {
+ const data = await res.json();
+ setNotebookRecords((prev) =>
+ new Map(prev).set(notebookId, data.records || []),
+ );
+ }
+ } catch (error) {
+ console.error(
+ `Failed to fetch records for notebook ${notebookId}:`,
+ error,
+ );
+ } finally {
+ setLoadingRecords((prev) => {
+ const next = new Set(prev);
+ next.delete(notebookId);
+ return next;
+ });
+ }
+ };
+
+ const toggleNotebook = (notebookId: string) => {
+ setExpandedNotebooks((prev) => {
+ const next = new Set(prev);
+ if (next.has(notebookId)) {
+ next.delete(notebookId);
+ } else {
+ next.add(notebookId);
+ fetchRecords(notebookId);
+ }
+ return next;
+ });
+ };
+
+ const toggleRecordSelection = (record: NotebookRecord) => {
+ setSelectedRecords((prev) => {
+ const next = new Set(prev);
+ if (next.has(record.id)) {
+ next.delete(record.id);
+ setSelectedRecordsData((current) =>
+ current.filter((r) => r.id !== record.id),
+ );
+ } else {
+ next.add(record.id);
+ setSelectedRecordsData((current) => [...current, record]);
+ }
+ return next;
+ });
+ };
+
+ const handleImport = () => {
+ // Merge content: combine outputs or user_queries + outputs
+ // For now, let's combine title + output
+ const mergedContent = selectedRecordsData
+ .map((r) => `# ${r.title}\n\n${r.output}`)
+ .join("\n\n---\n\n");
+
+ onImport(mergedContent, selectedRecordsData);
+ onClose();
+ };
+
+ if (!isOpen) return null;
+
+ return (
+ <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm animate-in fade-in duration-200">
+ <div className="w-[800px] h-[600px] bg-white rounded-2xl shadow-2xl flex flex-col overflow-hidden animate-in zoom-in-95 duration-200">
+ {/* Header */}
+ <div className="p-4 border-b border-slate-100 flex items-center justify-between bg-slate-50/50">
+ <div className="flex items-center gap-2">
+ <div className="p-2 bg-blue-100 rounded-lg">
+ <BookOpen className="w-5 h-5 text-blue-600" />
+ </div>
+ <div>
+ <h2 className="font-bold text-slate-900">{title}</h2>
+ <p className="text-xs text-slate-500">
+ Select content from your notebooks to import
+ </p>
+ </div>
+ </div>
+ <button
+ onClick={onClose}
+ className="p-2 hover:bg-slate-200 rounded-full transition-colors"
+ >
+ <X className="w-5 h-5 text-slate-500" />
+ </button>
+ </div>
+
+ {/* Content */}
+ <div className="flex-1 flex overflow-hidden">
+ {/* Notebooks List */}
+ <div className="w-1/3 border-r border-slate-100 overflow-y-auto bg-slate-50/30 p-2 space-y-2">
+ {loading ? (
+ <div className="flex items-center justify-center py-8">
+ <Loader2 className="w-6 h-6 animate-spin text-slate-400" />
+ </div>
+ ) : notebooks.length === 0 ? (
+ <div className="text-center py-8 text-slate-400 text-sm">
+ No notebooks found
+ </div>
+ ) : (
+ notebooks.map((nb) => (
+ <div
+ key={nb.id}
+ onClick={() => toggleNotebook(nb.id)}
+ className={`p-3 rounded-xl cursor-pointer transition-all border ${
+ expandedNotebooks.has(nb.id)
+ ? "bg-white border-blue-200 shadow-sm"
+ : "hover:bg-white border-transparent hover:border-slate-200"
+ }`}
+ >
+ <div className="flex items-center gap-2 mb-1">
+ {expandedNotebooks.has(nb.id) ? (
+ <ChevronDown className="w-4 h-4 text-slate-400" />
+ ) : (
+ <ChevronRight className="w-4 h-4 text-slate-400" />
+ )}
+ <div
+ className="w-3 h-3 rounded-full"
+ style={{ backgroundColor: nb.color || "#94a3b8" }}
+ />
+ <span className="font-medium text-sm text-slate-700 truncate flex-1">
+ {nb.name}
+ </span>
+ </div>
+ <div className="pl-6 text-xs text-slate-400 flex justify-between">
+ <span>{nb.record_count} records</span>
+ </div>
+ </div>
+ ))
+ )}
+ </div>
+
+ {/* Records List */}
+ <div className="flex-1 overflow-y-auto p-4 bg-white">
+ {expandedNotebooks.size === 0 ? (
+ <div className="h-full flex flex-col items-center justify-center text-slate-400">
+ <BookOpen className="w-12 h-12 mb-3 opacity-20" />
+ <p>Select a notebook to view records</p>
+ </div>
+ ) : (
+ <div className="space-y-4">
+ {Array.from(expandedNotebooks).map((nbId) => {
+ const nb = notebooks.find((n) => n.id === nbId);
+ const records = notebookRecords.get(nbId);
+ const isLoading = loadingRecords.has(nbId);
+
+ if (!nb) return null;
+
+ return (
+ <div
+ key={nbId}
+ className="animate-in fade-in slide-in-from-bottom-2"
+ >
+ <h3 className="text-xs font-bold text-slate-500 uppercase tracking-wider mb-2 pl-1 sticky top-0 bg-white py-2 z-10 flex items-center gap-2">
+ <div
+ className="w-2 h-2 rounded-full"
+ style={{ backgroundColor: nb.color }}
+ />
+ {nb.name}
+ </h3>
+
+ {isLoading ? (
+ <div className="py-4 flex justify-center">
+ <Loader2 className="w-5 h-5 animate-spin text-slate-300" />
+ </div>
+ ) : !records || records.length === 0 ? (
+ <div className="py-4 text-center text-xs text-slate-400 italic">
+ No records
+ </div>
+ ) : (
+ <div className="grid gap-2">
+ {records.map((record) => (
+ <div
+ key={record.id}
+ onClick={() => toggleRecordSelection(record)}
+ className={`p-3 rounded-xl border cursor-pointer transition-all group ${
+ selectedRecords.has(record.id)
+ ? "bg-blue-50 border-blue-200 ring-1 ring-blue-200"
+ : "bg-white border-slate-200 hover:border-blue-200 hover:shadow-sm"
+ }`}
+ >
+ <div className="flex items-start gap-3">
+ <div
+ className={`w-5 h-5 rounded border flex items-center justify-center shrink-0 mt-0.5 transition-colors ${
+ selectedRecords.has(record.id)
+ ? "bg-blue-500 border-blue-500 text-white"
+ : "border-slate-300 group-hover:border-blue-300"
+ }`}
+ >
+ {selectedRecords.has(record.id) && (
+ <Check className="w-3.5 h-3.5" />
+ )}
+ </div>
+ <div className="flex-1 min-w-0">
+ <h4 className="text-sm font-medium text-slate-900 truncate mb-0.5">
+ {record.title}
+ </h4>
+ <p className="text-xs text-slate-500 line-clamp-2">
+ {record.output}
+ </p>
+ <div className="mt-2 flex items-center gap-2">
+ <span className="px-1.5 py-0.5 bg-slate-100 text-slate-500 text-[10px] rounded font-medium uppercase">
+ {record.type}
+ </span>
+ {record.created_at && (
+ <span className="flex items-center gap-1 text-[10px] text-slate-400">
+ <Calendar className="w-3 h-3" />
+ {new Date(
+ record.created_at,
+ ).toLocaleDateString()}
+ </span>
+ )}
+ </div>
+ </div>
+ </div>
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ );
+ })}
+ </div>
+ )}
+ </div>
+ </div>
+
+ {/* Footer */}
+ <div className="p-4 border-t border-slate-100 bg-slate-50 flex justify-between items-center">
+ <div className="text-sm text-slate-500">
+ Selected{" "}
+ <span className="font-bold text-slate-900">
+ {selectedRecords.size}
+ </span>{" "}
+ items
+ </div>
+ <div className="flex items-center gap-2">
+ <button
+ onClick={onClose}
+ className="px-4 py-2 text-sm font-medium text-slate-600 hover:bg-slate-200 rounded-lg transition-colors"
+ >
+ Cancel
+ </button>
+ <button
+ onClick={handleImport}
+ disabled={selectedRecords.size === 0}
+ className="px-4 py-2 text-sm font-bold text-white bg-blue-600 hover:bg-blue-700 rounded-lg shadow-sm transition-all disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2"
+ >
+ <Check className="w-4 h-4" />
+ Import Selected
+ </button>
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/web/components/Sidebar.tsx b/web/components/Sidebar.tsx
new file mode 100644
index 000000000..2ec58ccb1
--- /dev/null
+++ b/web/components/Sidebar.tsx
@@ -0,0 +1,151 @@
+"use client";
+
+import Link from "next/link";
+import Image from "next/image";
+import { usePathname } from "next/navigation";
+import {
+ LayoutDashboard,
+ BookOpen,
+ PenTool,
+ Calculator,
+ Microscope,
+ Edit3,
+ Settings,
+ Book,
+ GraduationCap,
+ Lightbulb,
+ Github,
+} from "lucide-react";
+import { useGlobal } from "@/context/GlobalContext";
+import { getTranslation } from "@/lib/i18n";
+
+export default function Sidebar() {
+ const pathname = usePathname();
+ const { uiSettings } = useGlobal();
+ const lang = uiSettings.language;
+
+ const t = (key: string) => getTranslation(lang, key);
+
+ const navGroups = [
+ {
+ name: t("Start"),
+ items: [
+ { name: t("Dashboard"), href: "/", icon: LayoutDashboard },
+ { name: t("Knowledge Bases"), href: "/knowledge", icon: BookOpen },
+ { name: t("Notebooks"), href: "/notebook", icon: Book },
+ ],
+ },
+ {
+ name: t("Learn"),
+ items: [
+ { name: t("Question Generator"), href: "/question", icon: PenTool },
+ { name: t("Smart Solver"), href: "/solver", icon: Calculator },
+ { name: t("Guided Learning"), href: "/guide", icon: GraduationCap },
+ ],
+ },
+ {
+ name: t("Research"),
+ items: [
+ { name: t("IdeaGen"), href: "/ideagen", icon: Lightbulb },
+ { name: t("Deep Research"), href: "/research", icon: Microscope },
+ { name: t("Co-Writer"), href: "/co_writer", icon: Edit3 },
+ ],
+ },
+ ];
+
+ return (
+ <div className="w-64 bg-slate-50/50 dark:bg-slate-800/50 h-full border-r border-slate-200 dark:border-slate-700 flex flex-col backdrop-blur-xl transition-colors duration-200">
+ {/* Header */}
+ <div className="p-6 border-b border-slate-100 dark:border-slate-700">
+ <div className="flex flex-col gap-4">
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-3">
+ <div className="w-9 h-9 rounded-lg flex items-center justify-center overflow-hidden">
+ <Image
+ src="/logo.png"
+ alt="OpenTutor Logo"
+ width={38}
+ height={38}
+ className="object-contain"
+ priority
+ />
+ </div>
+ <h1 className="font-bold text-slate-900 dark:text-slate-100 tracking-tight text-lg">
+ OpenTutor
+ </h1>
+ </div>
+ <a
+ href="https://github.com/HKUDS/OpenTutor"
+ target="_blank"
+ rel="noopener noreferrer"
+ className="text-slate-400 hover:text-slate-800 dark:hover:text-slate-200 transition-colors p-1 hover:bg-slate-100 dark:hover:bg-slate-700 rounded"
+ title="View OpenTutor on GitHub"
+ >
+ <Github className="w-5 h-5" />
+ </a>
+ </div>
+
+ <div className="text-[10px] font-medium text-slate-500 dark:text-slate-400 bg-slate-100/50 dark:bg-slate-700/50 p-2 rounded-lg border border-slate-100 dark:border-slate-600">
+ ✨ Data Intelligence Lab @ HKU
+ </div>
+ </div>
+ </div>
+
+ {/* Navigation */}
+ <nav className="flex-1 overflow-y-auto p-4 space-y-6">
+ {navGroups.map((group, idx) => (
+ <div key={idx}>
+ {group.name && (
+ <div className="text-[10px] font-bold text-slate-400 dark:text-slate-500 uppercase tracking-wider px-4 mb-2">
+ {group.name}
+ </div>
+ )}
+ <div className="space-y-0.5">
+ {group.items.map((item) => {
+ const isActive = pathname === item.href;
+ return (
+ <Link
+ key={item.href}
+ href={item.href}
+ className={`group flex items-center gap-3 px-4 py-2 rounded-lg transition-all duration-200 ease-in-out border ${
+ isActive
+ ? "bg-white dark:bg-slate-700 text-blue-600 dark:text-blue-400 shadow-sm border-slate-100 dark:border-slate-600"
+ : "text-slate-600 dark:text-slate-300 hover:bg-white dark:hover:bg-slate-700 hover:text-blue-600 dark:hover:text-blue-400 hover:shadow-sm border-transparent hover:border-slate-100 dark:hover:border-slate-600"
+ }`}
+ >
+ <item.icon
+ className={`w-4 h-4 transition-colors ${
+ isActive
+ ? "text-blue-500 dark:text-blue-400"
+ : "text-slate-400 dark:text-slate-500 group-hover:text-blue-500 dark:group-hover:text-blue-400"
+ }`}
+ />
+ <span className="font-medium text-sm">{item.name}</span>
+ </Link>
+ );
+ })}
+ </div>
+ </div>
+ ))}
+ </nav>
+
+ {/* Footer */}
+ <div className="p-4 border-t border-slate-100 dark:border-slate-700 space-y-2 bg-slate-50/30 dark:bg-slate-800/30">
+ {/* Settings */}
+ <Link
+ href="/settings"
+ className={`w-full flex items-center gap-3 px-4 py-2 rounded-lg transition-all text-sm ${
+ pathname === "/settings"
+ ? "bg-white dark:bg-slate-700 text-blue-600 dark:text-blue-400 shadow-sm border border-slate-100 dark:border-slate-600"
+ : "text-slate-600 dark:text-slate-300 hover:bg-white dark:hover:bg-slate-700 hover:text-slate-900 dark:hover:text-slate-100"
+ }`}
+ >
+ <Settings
+ className={`w-4 h-4 ${pathname === "/settings" ? "text-blue-500 dark:text-blue-400" : "text-slate-400 dark:text-slate-500"}`}
+ />
+ <span>{t("Settings")}</span>
+ </Link>
+ </div>
+ </div>
+ );
+}
diff --git a/web/components/SystemStatus.tsx b/web/components/SystemStatus.tsx
new file mode 100644
index 000000000..a746d88c5
--- /dev/null
+++ b/web/components/SystemStatus.tsx
@@ -0,0 +1,439 @@
+"use client";
+
+import { useState, useEffect } from "react";
+import {
+ Wifi,
+ WifiOff,
+ Server,
+ Brain,
+ Database,
+ Volume2,
+ Loader2,
+ CheckCircle2,
+ XCircle,
+ RefreshCw,
+} from "lucide-react";
+import { apiUrl } from "@/lib/api";
+
+interface SystemStatusData {
+ backend: {
+ status: string;
+ timestamp: string;
+ };
+ llm: {
+ status: string;
+ model: string | null;
+ testable: boolean;
+ error?: string;
+ };
+ embeddings: {
+ status: string;
+ model: string | null;
+ testable: boolean;
+ error?: string;
+ };
+ tts: {
+ status: string;
+ model: string | null;
+ testable: boolean;
+ error?: string;
+ };
+}
+
+interface TestResult {
+ success: boolean;
+ message: string;
+ model?: string;
+ response_time_ms?: number;
+ error?: string;
+}
+
+type ModelType = "llm" | "embeddings" | "tts";
+
+export default function SystemStatus() {
+ const [statusData, setStatusData] = useState<SystemStatusData | null>(null);
+ const [backendConnected, setBackendConnected] = useState<boolean | null>(
+ null,
+ );
+ const [testing, setTesting] = useState<Record<ModelType, boolean>>({
+ llm: false,
+ embeddings: false,
+ tts: false,
+ });
+ const [testResults, setTestResults] = useState<
+ Record<ModelType, TestResult | null>
+ >({
+ llm: null,
+ embeddings: null,
+ tts: null,
+ });
+
+ // Check backend connection status (auto-update every 30 seconds)
+ useEffect(() => {
+ const checkBackendConnection = async () => {
+ try {
+ const controller = new AbortController();
+ const timeoutId = setTimeout(() => controller.abort(), 3000);
+
+ const response = await fetch(apiUrl("/api/v1/knowledge/health"), {
+ method: "GET",
+ signal: controller.signal,
+ });
+
+ clearTimeout(timeoutId);
+ setBackendConnected(response.ok);
+
+ // If backend is connected, fetch system status
+ if (response.ok) {
+ fetchSystemStatus();
+ }
+ } catch (error) {
+ setBackendConnected(false);
+ }
+ };
+
+ // Initial check
+ checkBackendConnection();
+
+ // Check every 30 seconds
+ const interval = setInterval(checkBackendConnection, 30000);
+
+ return () => clearInterval(interval);
+ }, []);
+
+ const fetchSystemStatus = async () => {
+ try {
+ const response = await fetch(apiUrl("/api/v1/system/status"));
+ if (response.ok) {
+ const data = await response.json();
+ setStatusData(data);
+ }
+ } catch (error) {
+ // Silently fail - backend connection check will handle this
+ }
+ };
+
+ const testModelConnection = async (modelType: ModelType) => {
+ setTesting((prev) => ({ ...prev, [modelType]: true }));
+ setTestResults((prev) => ({ ...prev, [modelType]: null }));
+
+ try {
+ const response = await fetch(apiUrl(`/api/v1/system/test/${modelType}`), {
+ method: "POST",
+ });
+
+ const result: TestResult = await response.json();
+ setTestResults((prev) => ({ ...prev, [modelType]: result }));
+
+ // Refresh system status after test
+ if (result.success) {
+ fetchSystemStatus();
+ }
+ } catch (error) {
+ setTestResults((prev) => ({
+ ...prev,
+ [modelType]: {
+ success: false,
+ message: "Test failed",
+ error: error instanceof Error ? error.message : "Unknown error",
+ },
+ }));
+ } finally {
+ setTesting((prev) => ({ ...prev, [modelType]: false }));
+ }
+ };
+
+ const getStatusColor = (status: string) => {
+ switch (status) {
+ case "online":
+ case "configured":
+ return "text-green-600 dark:text-green-400";
+ case "offline":
+ case "not_configured":
+ case "error":
+ return "text-red-600 dark:text-red-400";
+ default:
+ return "text-slate-500 dark:text-slate-400";
+ }
+ };
+
+ const getStatusBg = (status: string) => {
+ switch (status) {
+ case "online":
+ case "configured":
+ return "bg-green-50 dark:bg-green-900/30 border-green-100 dark:border-green-800";
+ case "offline":
+ case "not_configured":
+ case "error":
+ return "bg-red-50 dark:bg-red-900/30 border-red-100 dark:border-red-800";
+ default:
+ return "bg-slate-50 dark:bg-slate-800 border-slate-100 dark:border-slate-700";
+ }
+ };
+
+ const getStatusIcon = (status: string, isBackend: boolean = false) => {
+ if (isBackend) {
+ return backendConnected ? (
+ <Wifi className="w-3 h-3" />
+ ) : (
+ <WifiOff className="w-3 h-3" />
+ );
+ }
+
+ switch (status) {
+ case "online":
+ case "configured":
+ return <CheckCircle2 className="w-3 h-3" />;
+ case "offline":
+ case "not_configured":
+ case "error":
+ return <XCircle className="w-3 h-3" />;
+ default:
+ return <div className="w-3 h-3 rounded-full bg-slate-400" />;
+ }
+ };
+
+ const getStatusText = (status: string, isBackend: boolean = false) => {
+ if (isBackend) {
+ if (backendConnected === null) return "Checking...";
+ return backendConnected ? "Online" : "Offline";
+ }
+
+ switch (status) {
+ case "online":
+ return "Online";
+ case "configured":
+ return "Configured";
+ case "offline":
+ return "Offline";
+ case "not_configured":
+ return "Not Configured";
+ case "error":
+ return "Error";
+ default:
+ return "Unknown";
+ }
+ };
+
+ return (
+ <div className="space-y-3">
+ {/* Backend Status */}
+ <div
+ className={`px-3 py-2 rounded-lg flex items-center justify-between text-sm transition-colors border ${
+ backendConnected === null
+ ? "bg-slate-100 dark:bg-slate-800 text-slate-500 dark:text-slate-400 border-slate-200 dark:border-slate-700"
+ : backendConnected
+ ? "bg-green-50 dark:bg-green-900/30 text-green-700 dark:text-green-400 border-green-100 dark:border-green-800"
+ : "bg-red-50 dark:bg-red-900/30 text-red-700 dark:text-red-400 border-red-100 dark:border-red-800"
+ }`}
+ >
+ <div className="flex items-center gap-2">
+ {getStatusIcon("", true)}
+ <span className="font-medium">Backend Service</span>
+ </div>
+ <span>{getStatusText("", true)}</span>
+ </div>
+
+ {/* Model Statuses */}
+ {statusData && (
+ <>
+ {/* LLM Status */}
+ <div
+ className={`px-3 py-2.5 rounded-lg border text-sm transition-colors bg-slate-50 dark:bg-slate-800 border-slate-200 dark:border-slate-700`}
+ >
+ <div className="flex items-center justify-between mb-1.5">
+ <div className="flex items-center gap-2">
+ <Brain className="w-4 h-4 text-blue-500 dark:text-blue-400" />
+ <span className="font-medium text-slate-700 dark:text-slate-200">
+ LLM Model
+ </span>
+ </div>
+ <div className="flex items-center gap-2">
+ {statusData.llm.status === "configured" && testResults.llm && (
+ <span
+ className={`text-xs ${testResults.llm.success ? "text-green-600 dark:text-green-400" : "text-red-600 dark:text-red-400"}`}
+ >
+ {testResults.llm.success ? "✓" : "✗"}
+ </span>
+ )}
+ {getStatusIcon(statusData.llm.status)}
+ <span
+ className={`text-xs ${getStatusColor(statusData.llm.status)}`}
+ >
+ {getStatusText(statusData.llm.status)}
+ </span>
+ </div>
+ </div>
+ {statusData.llm.model && (
+ <div className="text-xs text-slate-500 dark:text-slate-400 truncate mb-1.5">
+ {statusData.llm.model}
+ </div>
+ )}
+ {statusData.llm.testable && (
+ <button
+ onClick={() => testModelConnection("llm")}
+ disabled={testing.llm || !backendConnected}
+ className="w-full mt-1.5 px-3 py-1.5 text-xs bg-white dark:bg-slate-700 hover:bg-slate-100 dark:hover:bg-slate-600 border border-slate-200 dark:border-slate-600 text-slate-700 dark:text-slate-200 rounded transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-1.5"
+ >
+ {testing.llm ? (
+ <>
+ <Loader2 className="w-3.5 h-3.5 animate-spin" />
+ <span>Testing...</span>
+ </>
+ ) : (
+ <>
+ <RefreshCw className="w-3.5 h-3.5" />
+ <span>Test Connection</span>
+ </>
+ )}
+ </button>
+ )}
+ {testResults.llm && (
+ <div
+ className={`mt-1.5 text-xs ${testResults.llm.success ? "text-green-600 dark:text-green-400" : "text-red-600 dark:text-red-400"}`}
+ >
+ {testResults.llm.message}
+ {testResults.llm.response_time_ms && (
+ <span className="text-slate-500 dark:text-slate-400 ml-1">
+ ({testResults.llm.response_time_ms}ms)
+ </span>
+ )}
+ </div>
+ )}
+ </div>
+
+ {/* Embeddings Status */}
+ <div
+ className={`px-3 py-2.5 rounded-lg border text-sm transition-colors bg-slate-50 dark:bg-slate-800 border-slate-200 dark:border-slate-700`}
+ >
+ <div className="flex items-center justify-between mb-1.5">
+ <div className="flex items-center gap-2">
+ <Database className="w-4 h-4 text-purple-500 dark:text-purple-400" />
+ <span className="font-medium text-slate-700 dark:text-slate-200">
+ Embeddings
+ </span>
+ </div>
+ <div className="flex items-center gap-2">
+ {statusData.embeddings.status === "configured" &&
+ testResults.embeddings && (
+ <span
+ className={`text-xs ${testResults.embeddings.success ? "text-green-600 dark:text-green-400" : "text-red-600 dark:text-red-400"}`}
+ >
+ {testResults.embeddings.success ? "✓" : "✗"}
+ </span>
+ )}
+ {getStatusIcon(statusData.embeddings.status)}
+ <span
+ className={`text-xs ${getStatusColor(statusData.embeddings.status)}`}
+ >
+ {getStatusText(statusData.embeddings.status)}
+ </span>
+ </div>
+ </div>
+ {statusData.embeddings.model && (
+ <div className="text-xs text-slate-500 dark:text-slate-400 truncate mb-1.5">
+ {statusData.embeddings.model}
+ </div>
+ )}
+ {statusData.embeddings.testable && (
+ <button
+ onClick={() => testModelConnection("embeddings")}
+ disabled={testing.embeddings || !backendConnected}
+ className="w-full mt-1.5 px-3 py-1.5 text-xs bg-white dark:bg-slate-700 hover:bg-slate-100 dark:hover:bg-slate-600 border border-slate-200 dark:border-slate-600 text-slate-700 dark:text-slate-200 rounded transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-1.5"
+ >
+ {testing.embeddings ? (
+ <>
+ <Loader2 className="w-3.5 h-3.5 animate-spin" />
+ <span>Testing...</span>
+ </>
+ ) : (
+ <>
+ <RefreshCw className="w-3.5 h-3.5" />
+ <span>Test Connection</span>
+ </>
+ )}
+ </button>
+ )}
+ {testResults.embeddings && (
+ <div
+ className={`mt-1.5 text-xs ${testResults.embeddings.success ? "text-green-600 dark:text-green-400" : "text-red-600 dark:text-red-400"}`}
+ >
+ {testResults.embeddings.message}
+ {testResults.embeddings.response_time_ms && (
+ <span className="text-slate-500 dark:text-slate-400 ml-1">
+ ({testResults.embeddings.response_time_ms}ms)
+ </span>
+ )}
+ </div>
+ )}
+ </div>
+
+ {/* TTS Status */}
+ <div
+ className={`px-3 py-2.5 rounded-lg border text-sm transition-colors bg-slate-50 dark:bg-slate-800 border-slate-200 dark:border-slate-700`}
+ >
+ <div className="flex items-center justify-between mb-1.5">
+ <div className="flex items-center gap-2">
+ <Volume2 className="w-4 h-4 text-emerald-500 dark:text-emerald-400" />
+ <span className="font-medium text-slate-700 dark:text-slate-200">
+ TTS Model
+ </span>
+ </div>
+ <div className="flex items-center gap-2">
+ {statusData.tts.status === "configured" && testResults.tts && (
+ <span
+ className={`text-xs ${testResults.tts.success ? "text-green-600 dark:text-green-400" : "text-red-600 dark:text-red-400"}`}
+ >
+ {testResults.tts.success ? "✓" : "✗"}
+ </span>
+ )}
+ {getStatusIcon(statusData.tts.status)}
+ <span
+ className={`text-xs ${getStatusColor(statusData.tts.status)}`}
+ >
+ {getStatusText(statusData.tts.status)}
+ </span>
+ </div>
+ </div>
+ {statusData.tts.model && (
+ <div className="text-xs text-slate-500 dark:text-slate-400 truncate mb-1.5">
+ {statusData.tts.model}
+ </div>
+ )}
+ {statusData.tts.testable && (
+ <button
+ onClick={() => testModelConnection("tts")}
+ disabled={testing.tts || !backendConnected}
+ className="w-full mt-1.5 px-3 py-1.5 text-xs bg-white dark:bg-slate-700 hover:bg-slate-100 dark:hover:bg-slate-600 border border-slate-200 dark:border-slate-600 text-slate-700 dark:text-slate-200 rounded transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-1.5"
+ >
+ {testing.tts ? (
+ <>
+ <Loader2 className="w-3.5 h-3.5 animate-spin" />
+ <span>Testing...</span>
+ </>
+ ) : (
+ <>
+ <RefreshCw className="w-3.5 h-3.5" />
+ <span>Test Connection</span>
+ </>
+ )}
+ </button>
+ )}
+ {testResults.tts && (
+ <div
+ className={`mt-1.5 text-xs ${testResults.tts.success ? "text-green-600 dark:text-green-400" : "text-red-600 dark:text-red-400"}`}
+ >
+ {testResults.tts.message}
+ {testResults.tts.response_time_ms && (
+ <span className="text-slate-500 dark:text-slate-400 ml-1">
+ ({testResults.tts.response_time_ms}ms)
+ </span>
+ )}
+ </div>
+ )}
+ </div>
+ </>
+ )}
+ </div>
+ );
+}
diff --git a/web/components/index.ts b/web/components/index.ts
new file mode 100644
index 000000000..4971dfbdd
--- /dev/null
+++ b/web/components/index.ts
@@ -0,0 +1,15 @@
+/**
+ * Component Export Index
+ * Unified management of all public component exports
+ */
+
+// Layout Components
+export { default as Sidebar } from "./Sidebar";
+
+// Feature Components
+export { default as ActivityDetail } from "./ActivityDetail";
+export { default as CoWriterEditor } from "./CoWriterEditor";
+export { default as AddToNotebookModal } from "./AddToNotebookModal";
+
+// Re-export types if needed
+export type {} from "./AddToNotebookModal";
diff --git a/web/components/question/ActiveQuestionDetail.tsx b/web/components/question/ActiveQuestionDetail.tsx
new file mode 100644
index 000000000..485b58fb0
--- /dev/null
+++ b/web/components/question/ActiveQuestionDetail.tsx
@@ -0,0 +1,366 @@
+import React from "react";
+import { QuestionTask } from "../../types/question";
+import {
+ Terminal,
+ FileQuestion,
+ CheckCircle2,
+ AlertCircle,
+ Loader2,
+ Search,
+ Target,
+ Zap,
+ Link2,
+ Lightbulb,
+ BookOpen,
+} from "lucide-react";
+import ReactMarkdown from "react-markdown";
+import remarkMath from "remark-math";
+import rehypeKatex from "rehype-katex";
+import { processLatexContent } from "@/lib/latex";
+
+interface ActiveQuestionDetailProps {
+ task: QuestionTask | null;
+ mode?: "custom" | "mimic";
+}
+
+const getStatusBadge = (status: QuestionTask["status"], extended?: boolean) => {
+ if (status === "done" && extended) {
+ return (
+ <span className="px-2 py-0.5 rounded text-[10px] font-bold uppercase tracking-wider bg-amber-100 dark:bg-amber-900/40 text-amber-700 dark:text-amber-300 flex items-center gap-1">
+ <Zap className="w-3 h-3" />
+ Extended
+ </span>
+ );
+ }
+ switch (status) {
+ case "done":
+ return (
+ <span className="px-2 py-0.5 rounded text-[10px] font-bold uppercase tracking-wider bg-emerald-100 dark:bg-emerald-900/40 text-emerald-700 dark:text-emerald-300">
+ Done
+ </span>
+ );
+ case "generating":
+ return (
+ <span className="px-2 py-0.5 rounded text-[10px] font-bold uppercase tracking-wider bg-indigo-100 dark:bg-indigo-900/40 text-indigo-700 dark:text-indigo-300 flex items-center gap-1">
+ <Loader2 className="w-3 h-3 animate-spin" />
+ Generating
+ </span>
+ );
+ case "analyzing":
+ return (
+ <span className="px-2 py-0.5 rounded text-[10px] font-bold uppercase tracking-wider bg-purple-100 dark:bg-purple-900/40 text-purple-700 dark:text-purple-300 flex items-center gap-1">
+ <Search className="w-3 h-3" />
+ Analyzing
+ </span>
+ );
+ case "validating":
+ return (
+ <span className="px-2 py-0.5 rounded text-[10px] font-bold uppercase tracking-wider bg-amber-100 dark:bg-amber-900/40 text-amber-700 dark:text-amber-300 flex items-center gap-1">
+ <Search className="w-3 h-3" />
+ Validating
+ </span>
+ );
+ case "error":
+ return (
+ <span className="px-2 py-0.5 rounded text-[10px] font-bold uppercase tracking-wider bg-red-100 dark:bg-red-900/40 text-red-700 dark:text-red-300">
+ Error
+ </span>
+ );
+ default:
+ return (
+ <span className="px-2 py-0.5 rounded text-[10px] font-bold uppercase tracking-wider bg-slate-100 dark:bg-slate-700 text-slate-600 dark:text-slate-400">
+ Pending
+ </span>
+ );
+ }
+};
+
+export const ActiveQuestionDetail: React.FC<ActiveQuestionDetailProps> = ({
+ task,
+ mode = "custom",
+}) => {
+ const isMimicMode = mode === "mimic";
+ if (!task) {
+ return (
+ <div className="h-full flex flex-col items-center justify-center text-slate-400 dark:text-slate-500 bg-slate-50/50 dark:bg-slate-800/50 rounded-xl border border-slate-200 dark:border-slate-700">
+ <Terminal className="w-12 h-12 mb-3 opacity-20" />
+ <p className="text-sm">Select a question task to view details</p>
+ </div>
+ );
+ }
+
+ return (
+ <div className="h-full flex flex-col bg-white dark:bg-slate-800 rounded-xl border border-slate-200 dark:border-slate-700 shadow-sm overflow-hidden">
+ {/* Header */}
+ <div className="p-4 border-b border-slate-100 dark:border-slate-700 bg-slate-50/50 dark:bg-slate-800/50 flex justify-between items-center">
+ <div className="flex items-center gap-2 overflow-hidden">
+ <FileQuestion className="w-4 h-4 text-slate-500 dark:text-slate-400 shrink-0" />
+ <h3
+ className="font-semibold text-slate-800 dark:text-slate-200 text-sm truncate"
+ title={task.id}
+ >
+ {task.id}
+ </h3>
+ </div>
+ <div className="flex items-center gap-2 shrink-0">
+ {task.round && (
+ <span className="text-xs font-mono text-slate-400 dark:text-slate-500">
+ Round {task.round}
+ </span>
+ )}
+ {getStatusBadge(task.status, task.extended)}
+ </div>
+ </div>
+
+ {/* Content */}
+ <div className="flex-1 overflow-y-auto p-4 space-y-4">
+ {/* Focus / Origin Question Section */}
+ <div
+ className={`rounded-lg p-4 border ${isMimicMode ? "bg-amber-50 dark:bg-amber-900/30 border-amber-100 dark:border-amber-800" : "bg-indigo-50 dark:bg-indigo-900/30 border-indigo-100 dark:border-indigo-800"}`}
+ >
+ <div className="flex items-center gap-2 mb-2">
+ {isMimicMode ? (
+ <>
+ <BookOpen className="w-4 h-4 text-amber-600 dark:text-amber-400" />
+ <span className="text-xs font-bold uppercase tracking-wider text-amber-700 dark:text-amber-300">
+ Origin Question
+ </span>
+ </>
+ ) : (
+ <>
+ <Target className="w-4 h-4 text-indigo-500 dark:text-indigo-400" />
+ <span className="text-xs font-bold uppercase tracking-wider text-indigo-600 dark:text-indigo-400">
+ Focus
+ </span>
+ </>
+ )}
+ </div>
+ {isMimicMode ? (
+ <div className="prose prose-sm dark:prose-invert max-w-none text-amber-900 dark:text-amber-200">
+ {task.focus ? (
+ <ReactMarkdown
+ remarkPlugins={[remarkMath]}
+ rehypePlugins={[rehypeKatex]}
+ >
+ {processLatexContent(task.focus)}
+ </ReactMarkdown>
+ ) : (
+ <span className="text-amber-600 dark:text-amber-400 italic">
+ N/A
+ </span>
+ )}
+ </div>
+ ) : (
+ <>
+ <p className="text-sm text-indigo-800 dark:text-indigo-200">
+ {task.focus || "N/A"}
+ </p>
+ {task.scenarioHint && (
+ <p className="text-xs text-indigo-600 dark:text-indigo-400 mt-2 italic">
+ Hint: {task.scenarioHint}
+ </p>
+ )}
+ </>
+ )}
+ </div>
+
+ {/* Error Section */}
+ {task.error && (
+ <div className="bg-red-50 dark:bg-red-900/30 rounded-lg p-4 border border-red-100 dark:border-red-800">
+ <div className="flex items-center gap-2 mb-2">
+ <AlertCircle className="w-4 h-4 text-red-500 dark:text-red-400" />
+ <span className="text-xs font-bold uppercase tracking-wider text-red-600 dark:text-red-400">
+ Error
+ </span>
+ </div>
+ <p className="text-sm text-red-800 dark:text-red-200">
+ {task.error}
+ </p>
+ </div>
+ )}
+
+ {/* Generated Question */}
+ {task.result?.question && (
+ <div className="space-y-4">
+ {/* Extension Analysis (for extended questions) */}
+ {task.extended && task.result.validation && (
+ <>
+ {task.result.validation.kb_connection && (
+ <div className="bg-amber-50 dark:bg-amber-900/30 rounded-lg p-4 border border-amber-100 dark:border-amber-800">
+ <div className="flex items-center gap-2 mb-2">
+ <Link2 className="w-4 h-4 text-amber-600 dark:text-amber-400" />
+ <span className="text-xs font-bold uppercase tracking-wider text-amber-700 dark:text-amber-300">
+ Knowledge Base Connection
+ </span>
+ </div>
+ <p className="text-sm text-amber-800 dark:text-amber-200">
+ {task.result.validation.kb_connection}
+ </p>
+ </div>
+ )}
+ {task.result.validation.extended_aspect && (
+ <div className="bg-orange-50 dark:bg-orange-900/30 rounded-lg p-4 border border-orange-100 dark:border-orange-800">
+ <div className="flex items-center gap-2 mb-2">
+ <Lightbulb className="w-4 h-4 text-orange-600 dark:text-orange-400" />
+ <span className="text-xs font-bold uppercase tracking-wider text-orange-700 dark:text-orange-300">
+ Extended Aspects
+ </span>
+ </div>
+ <p className="text-sm text-orange-800 dark:text-orange-200">
+ {task.result.validation.extended_aspect}
+ </p>
+ </div>
+ )}
+ </>
+ )}
+
+ <div
+ className={`rounded-lg p-4 border ${task.extended ? "bg-amber-50 dark:bg-amber-900/30 border-amber-100 dark:border-amber-800" : "bg-emerald-50 dark:bg-emerald-900/30 border-emerald-100 dark:border-emerald-800"}`}
+ >
+ <div className="flex items-center gap-2 mb-2">
+ {task.extended ? (
+ <Zap className="w-4 h-4 text-amber-600 dark:text-amber-400" />
+ ) : (
+ <CheckCircle2 className="w-4 h-4 text-emerald-500 dark:text-emerald-400" />
+ )}
+ <span
+ className={`text-xs font-bold uppercase tracking-wider ${task.extended ? "text-amber-700 dark:text-amber-300" : "text-emerald-600 dark:text-emerald-400"}`}
+ >
+ {task.extended ? "Extended Question" : "Generated Question"}
+ </span>
+ </div>
+ <div className="text-sm text-slate-800 dark:text-slate-200 prose prose-sm dark:prose-invert max-w-none">
+ <ReactMarkdown
+ remarkPlugins={[remarkMath]}
+ rehypePlugins={[rehypeKatex]}
+ >
+ {task.result.question.question}
+ </ReactMarkdown>
+ </div>
+ </div>
+
+ {/* Options (for choice questions) */}
+ {task.result.question.options && (
+ <div className="bg-slate-50 dark:bg-slate-700 rounded-lg p-4 border border-slate-100 dark:border-slate-600">
+ <span className="text-xs font-bold uppercase tracking-wider text-slate-500 dark:text-slate-400 block mb-2">
+ Options
+ </span>
+ <div className="space-y-2">
+ {Object.entries(task.result.question.options).map(
+ ([key, value]) => (
+ <div key={key} className="flex items-start gap-2">
+ <span className="font-semibold text-sm text-slate-600 dark:text-slate-400">
+ {key}.
+ </span>
+ <span className="text-sm text-slate-700 dark:text-slate-300">
+ {value}
+ </span>
+ </div>
+ ),
+ )}
+ </div>
+ </div>
+ )}
+
+ {/* Answer */}
+ <div className="bg-blue-50 dark:bg-blue-900/30 rounded-lg p-4 border border-blue-100 dark:border-blue-800">
+ <span className="text-xs font-bold uppercase tracking-wider text-blue-600 dark:text-blue-400 block mb-2">
+ Correct Answer
+ </span>
+ <div className="text-sm text-slate-800 dark:text-slate-200 prose prose-sm dark:prose-invert max-w-none">
+ <ReactMarkdown
+ remarkPlugins={[remarkMath]}
+ rehypePlugins={[rehypeKatex]}
+ >
+ {task.result.question.correct_answer}
+ </ReactMarkdown>
+ </div>
+ </div>
+
+ {/* Explanation */}
+ {task.result.question.explanation && (
+ <div className="bg-purple-50 dark:bg-purple-900/30 rounded-lg p-4 border border-purple-100 dark:border-purple-800">
+ <span className="text-xs font-bold uppercase tracking-wider text-purple-600 dark:text-purple-400 block mb-2">
+ Explanation
+ </span>
+ <div className="text-sm text-slate-700 dark:text-slate-300 prose prose-sm dark:prose-invert max-w-none">
+ <ReactMarkdown
+ remarkPlugins={[remarkMath]}
+ rehypePlugins={[rehypeKatex]}
+ >
+ {task.result.question.explanation}
+ </ReactMarkdown>
+ </div>
+ </div>
+ )}
+
+ {/* Validation Info */}
+ {task.result.validation && (
+ <div className="bg-slate-50 dark:bg-slate-700 rounded-lg p-4 border border-slate-100 dark:border-slate-600">
+ <span className="text-xs font-bold uppercase tracking-wider text-slate-500 dark:text-slate-400 block mb-2">
+ Validation Summary
+ </span>
+ <div className="text-xs text-slate-600 dark:text-slate-400 space-y-1">
+ <p>
+ <strong>Status:</strong>{" "}
+ <span
+ className={
+ task.result.validation.decision === "approve"
+ ? "text-emerald-600 dark:text-emerald-400 font-medium"
+ : task.result.validation.decision === "extended"
+ ? "text-amber-600 dark:text-amber-400 font-medium"
+ : "text-amber-600 dark:text-amber-400"
+ }
+ >
+ {task.result.validation.decision === "extended"
+ ? "Extended (beyond KB scope)"
+ : task.result.validation.decision}
+ </span>
+ </p>
+ <p>
+ <strong>Rounds:</strong> {task.result.rounds}
+ </p>
+ {task.result.validation.reasoning && (
+ <p className="mt-2 text-slate-500 dark:text-slate-400 italic">
+ {task.result.validation.reasoning}
+ </p>
+ )}
+ </div>
+ </div>
+ )}
+ </div>
+ )}
+
+ {/* Waiting state */}
+ {!task.result && !task.error && task.status === "pending" && (
+ <div className="text-center py-10 text-slate-400 dark:text-slate-500 text-xs italic">
+ Waiting to start generation...
+ </div>
+ )}
+
+ {/* In progress state */}
+ {!task.result &&
+ !task.error &&
+ (task.status === "generating" ||
+ task.status === "analyzing" ||
+ task.status === "validating") && (
+ <div className="flex flex-col items-center justify-center py-10">
+ <Loader2 className="w-8 h-8 text-indigo-500 dark:text-indigo-400 animate-spin mb-3" />
+ <p className="text-sm text-slate-500 dark:text-slate-400">
+ {task.status === "generating"
+ ? "Generating question..."
+ : task.status === "analyzing"
+ ? "Analyzing relevance..."
+ : "Validating question..."}
+ </p>
+ {task.round && (
+ <p className="text-xs text-slate-400 dark:text-slate-500 mt-1">
+ Round {task.round}
+ </p>
+ )}
+ </div>
+ )}
+ </div>
+ </div>
+ );
+};
diff --git a/web/components/question/QuestionDashboard.tsx b/web/components/question/QuestionDashboard.tsx
new file mode 100644
index 000000000..44c2f2373
--- /dev/null
+++ b/web/components/question/QuestionDashboard.tsx
@@ -0,0 +1,819 @@
+import React, { useState, useEffect } from "react";
+import {
+ QuestionState,
+ QuestionTokenStats,
+ QuestionTask,
+} from "../../types/question";
+import { QuestionTaskGrid } from "./QuestionTaskGrid";
+import { ActiveQuestionDetail } from "./ActiveQuestionDetail";
+import {
+ GitBranch,
+ Zap,
+ CheckCircle2,
+ Loader2,
+ LayoutDashboard,
+ Activity,
+ Clock,
+ Search,
+ FileQuestion,
+ Target,
+ AlertCircle,
+ DollarSign,
+ Cpu,
+ ChevronRight,
+ Database,
+ RefreshCw,
+ Sparkles,
+} from "lucide-react";
+
+type ProcessTab = "planning" | "generating";
+
+// Progress info from GlobalContext
+interface GlobalContextProgress {
+ stage:
+ | "planning"
+ | "researching"
+ | "generating"
+ | "validating"
+ | "complete"
+ // Mimic mode stages
+ | "uploading"
+ | "parsing"
+ | "extracting"
+ | null;
+ progress: {
+ current?: number;
+ total?: number;
+ round?: number;
+ max_rounds?: number;
+ status?: string;
+ };
+ subFocuses?: Array<{ id: string; focus: string; scenario_hint?: string }>;
+ activeQuestions?: string[];
+ completedQuestions?: number;
+ failedQuestions?: number;
+ extendedQuestions?: number;
+}
+
+// Logs from GlobalContext
+interface LogEntry {
+ type: string;
+ content: string;
+ timestamp?: number;
+ level?: string;
+}
+
+interface QuestionDashboardProps {
+ // Support both QuestionState (from reducer) and GlobalContext data
+ state?: QuestionState;
+ // GlobalContext data (alternative to state)
+ globalProgress?: GlobalContextProgress;
+ globalLogs?: LogEntry[];
+ globalResults?: any[];
+ globalTopic?: string;
+ globalDifficulty?: string;
+ globalType?: string;
+ globalCount?: number;
+ globalStep?: "config" | "generating" | "result";
+ globalMode?: "custom" | "mimic"; // Mode for different progress display
+ // Common props
+ selectedTaskId: string | null;
+ onTaskSelect: (taskId: string) => void;
+ tokenStats?: QuestionTokenStats;
+}
+
+export const QuestionDashboard: React.FC<QuestionDashboardProps> = ({
+ state,
+ globalProgress,
+ globalLogs = [],
+ globalResults = [],
+ globalTopic = "",
+ globalDifficulty = "",
+ globalType = "",
+ globalCount = 0,
+ globalStep = "config",
+ globalMode = "custom",
+ selectedTaskId,
+ onTaskSelect,
+ tokenStats,
+}) => {
+ // Determine if using QuestionState or GlobalContext data
+ const useGlobalContext = !state || state.global.stage === "idle";
+
+ // Extract data from either source
+ const stage = useGlobalContext
+ ? globalProgress?.stage ||
+ (globalStep === "generating"
+ ? "generating"
+ : globalStep === "result"
+ ? "complete"
+ : "idle")
+ : state!.global.stage;
+
+ const isIdle = stage === "idle" || stage === null;
+ const isCompleted = stage === "complete" || globalStep === "result";
+ const isPlanning = stage === "planning";
+ const isResearching = stage === "researching";
+ const isGenerating = stage === "generating" || stage === "validating";
+
+ // Mimic mode stages
+ const isUploading = stage === "uploading";
+ const isParsing = stage === "parsing";
+ const isExtracting = stage === "extracting";
+ const isMimicMode = globalMode === "mimic";
+ const isMimicPlanning = isUploading || isParsing || isExtracting;
+
+ const completedQuestions = useGlobalContext
+ ? globalProgress?.completedQuestions || globalResults.length
+ : state!.global.completedQuestions;
+
+ const totalQuestions = useGlobalContext
+ ? globalProgress?.progress?.total || globalCount
+ : state!.global.totalQuestions;
+
+ const failedQuestions = useGlobalContext
+ ? globalProgress?.failedQuestions || 0
+ : state!.global.failedQuestions;
+
+ const extendedCount = useGlobalContext
+ ? globalProgress?.extendedQuestions ||
+ globalResults.filter((r: any) => r.extended).length
+ : state!.global.extendedQuestions || 0;
+
+ const subFocuses = useGlobalContext
+ ? globalProgress?.subFocuses || []
+ : state!.subFocuses;
+
+ const logs = useGlobalContext ? globalLogs : state!.logs;
+ const results = useGlobalContext ? globalResults : state!.results;
+
+ // Build tasks from results when using GlobalContext
+ const tasks = useGlobalContext
+ ? buildTasksFromResults(globalResults, globalProgress, globalMode)
+ : state!.tasks;
+
+ const activeTaskIds = useGlobalContext
+ ? globalProgress?.activeQuestions || []
+ : state!.activeTaskIds;
+
+ const [activeProcessTab, setActiveProcessTab] =
+ useState<ProcessTab>("planning");
+
+ const steps: { id: ProcessTab; label: string; icon: React.ElementType }[] = [
+ { id: "planning", label: "Planning", icon: GitBranch },
+ { id: "generating", label: "Generating", icon: Zap },
+ ];
+
+ const stageOrder: Record<string, number> = {
+ idle: -1,
+ planning: 0,
+ researching: 0,
+ // Mimic mode stages map to planning
+ uploading: 0,
+ parsing: 0,
+ extracting: 0,
+ generating: 1,
+ validating: 1,
+ complete: 2,
+ };
+
+ const currentStageIndex = stageOrder[stage || "idle"] ?? -1;
+
+ // Check if a tab has content
+ const isTabAvailable = (tabId: ProcessTab): boolean => {
+ const tabIndex = steps.findIndex((s) => s.id === tabId);
+ return currentStageIndex >= tabIndex;
+ };
+
+ // Check if a tab is currently active
+ const isTabCurrentlyActive = (tabId: ProcessTab): boolean => {
+ if (tabId === "planning") {
+ return isPlanning || isResearching || isMimicPlanning;
+ }
+ return isGenerating;
+ };
+
+ // Auto-switch to current stage tab when stage changes
+ useEffect(() => {
+ if (isPlanning || isResearching || isMimicPlanning) {
+ setActiveProcessTab("planning");
+ } else if (isGenerating) {
+ setActiveProcessTab("generating");
+ }
+ }, [isPlanning, isResearching, isGenerating, isMimicPlanning]);
+
+ // Clickable Step Tabs
+ const StepTabs = () => (
+ <div className="flex items-center gap-1 bg-slate-100/80 dark:bg-slate-700/80 backdrop-blur-sm p-1 rounded-xl border border-slate-200/50 dark:border-slate-600/50 shadow-sm">
+ {steps.map((step, idx) => {
+ const available = isTabAvailable(step.id);
+ const isCurrentStage = isTabCurrentlyActive(step.id);
+ const isSelected = activeProcessTab === step.id;
+ const isPassed = currentStageIndex > idx || isCompleted;
+
+ return (
+ <button
+ key={step.id}
+ onClick={() => available && setActiveProcessTab(step.id)}
+ disabled={!available}
+ className={`
+ flex items-center gap-2 px-4 py-2 rounded-lg transition-all relative
+ ${
+ isSelected
+ ? "bg-white dark:bg-slate-600 shadow-sm border border-slate-200 dark:border-slate-500 text-indigo-700 dark:text-indigo-300"
+ : available
+ ? "hover:bg-white/50 dark:hover:bg-slate-600/50 text-slate-600 dark:text-slate-300"
+ : "text-slate-300 dark:text-slate-500 cursor-not-allowed"
+ }
+ `}
+ >
+ {/* Status indicator */}
+ {isPassed ? (
+ <CheckCircle2 className="w-4 h-4 text-emerald-500 dark:text-emerald-400" />
+ ) : isCurrentStage ? (
+ <Loader2 className="w-4 h-4 text-indigo-500 dark:text-indigo-400 animate-spin" />
+ ) : available ? (
+ <step.icon className="w-4 h-4" />
+ ) : (
+ <Clock className="w-4 h-4 text-slate-300 dark:text-slate-500" />
+ )}
+ <span className="text-sm font-medium">{step.label}</span>
+
+ {/* Active indicator dot */}
+ {isCurrentStage && !isCompleted && (
+ <span className="absolute -top-1 -right-1 flex h-2.5 w-2.5">
+ <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-indigo-400 opacity-75"></span>
+ <span className="relative inline-flex rounded-full h-2.5 w-2.5 bg-indigo-500"></span>
+ </span>
+ )}
+ </button>
+ );
+ })}
+ </div>
+ );
+
+ // Planning Content with Timeline
+ const PlanningContent = () => {
+ const progressStatus = globalProgress?.progress?.status;
+
+ // Custom mode steps
+ const customModeSteps = [
+ {
+ id: "init",
+ label: "Initializing",
+ icon: Sparkles,
+ active: isPlanning && !progressStatus,
+ done:
+ isResearching ||
+ progressStatus === "generating_queries" ||
+ progressStatus === "retrieving" ||
+ progressStatus === "creating_plan" ||
+ progressStatus === "plan_ready" ||
+ isGenerating ||
+ isCompleted,
+ },
+ {
+ id: "query",
+ label: "Generating Search Queries",
+ icon: Search,
+ active:
+ progressStatus === "generating_queries" ||
+ progressStatus === "splitting_queries",
+ done:
+ isResearching ||
+ progressStatus === "retrieving" ||
+ progressStatus === "creating_plan" ||
+ progressStatus === "plan_ready" ||
+ isGenerating ||
+ isCompleted,
+ },
+ {
+ id: "research",
+ label: "Retrieving Background Knowledge",
+ icon: Database,
+ active: isResearching || progressStatus === "retrieving",
+ done:
+ progressStatus === "creating_plan" ||
+ progressStatus === "plan_ready" ||
+ progressStatus === "completed" ||
+ isGenerating ||
+ isCompleted,
+ },
+ {
+ id: "plan",
+ label: "Creating Question Plan",
+ icon: Target,
+ active:
+ progressStatus === "creating_plan" ||
+ progressStatus === "planning_focuses",
+ done:
+ progressStatus === "plan_ready" ||
+ subFocuses.length > 0 ||
+ isGenerating ||
+ isCompleted,
+ },
+ ];
+
+ // Mimic mode steps - use stage directly for clearer logic
+ const mimicModeSteps = [
+ {
+ id: "upload",
+ label: "Uploading PDF",
+ icon: Sparkles,
+ active: isUploading,
+ done: isParsing || isExtracting || isGenerating || isCompleted,
+ },
+ {
+ id: "parse",
+ label: "Parsing PDF (MinerU)",
+ icon: RefreshCw,
+ active: isParsing,
+ done: isExtracting || isGenerating || isCompleted,
+ },
+ {
+ id: "extract",
+ label: "Extracting Reference Questions",
+ icon: Search,
+ active: isExtracting,
+ done: isGenerating || isCompleted,
+ },
+ {
+ id: "ready",
+ label: "Ready to Generate",
+ icon: Target,
+ active: false,
+ done: isGenerating || isCompleted,
+ },
+ ];
+
+ const planningSteps = isMimicMode ? mimicModeSteps : customModeSteps;
+
+ return (
+ <div className="flex-1 flex gap-6 overflow-hidden">
+ {/* Left: Timeline */}
+ <div className="flex-1 bg-white dark:bg-slate-800 rounded-xl border border-slate-200 dark:border-slate-700 shadow-sm p-6 overflow-y-auto">
+ <h3 className="font-bold text-slate-700 dark:text-slate-200 mb-6 flex items-center gap-2">
+ <GitBranch className="w-5 h-5 text-indigo-500 dark:text-indigo-400" />
+ Planning Progress
+ </h3>
+
+ {/* Topic Info - Custom Mode */}
+ {!isMimicMode && globalTopic && (
+ <div className="mb-6 p-4 bg-indigo-50 dark:bg-indigo-900/30 rounded-lg border border-indigo-100 dark:border-indigo-800">
+ <div className="flex items-center gap-3 mb-2">
+ <div className="text-xs font-bold text-indigo-500 dark:text-indigo-400 uppercase tracking-wider">
+ Topic
+ </div>
+ </div>
+ <p className="text-sm text-indigo-900 dark:text-indigo-200 font-medium">
+ {globalTopic}
+ </p>
+ <div className="flex gap-4 mt-2 text-xs text-indigo-600 dark:text-indigo-400">
+ <span>
+ Difficulty:{" "}
+ <strong className="capitalize">{globalDifficulty}</strong>
+ </span>
+ <span>
+ Type: <strong className="capitalize">{globalType}</strong>
+ </span>
+ <span>
+ Count: <strong>{globalCount}</strong>
+ </span>
+ </div>
+ </div>
+ )}
+
+ {/* Mode Info - Mimic Mode */}
+ {isMimicMode && (
+ <div className="mb-6 p-4 bg-amber-50 dark:bg-amber-900/30 rounded-lg border border-amber-100 dark:border-amber-800">
+ <div className="flex items-center gap-3 mb-2">
+ <div className="text-xs font-bold text-amber-600 dark:text-amber-400 uppercase tracking-wider">
+ Mimic Exam Mode
+ </div>
+ </div>
+ <p className="text-sm text-amber-900 dark:text-amber-200 font-medium">
+ Generating questions based on reference exam paper
+ </p>
+ {totalQuestions > 0 && (
+ <div className="flex gap-4 mt-2 text-xs text-amber-700 dark:text-amber-400">
+ <span>
+ Reference Questions: <strong>{totalQuestions}</strong>
+ </span>
+ </div>
+ )}
+ </div>
+ )}
+
+ {/* Timeline Steps */}
+ <div className="space-y-4">
+ {planningSteps.map((step, idx) => (
+ <div key={step.id} className="flex items-start gap-3">
+ <div
+ className={`flex-shrink-0 w-8 h-8 rounded-full flex items-center justify-center ${
+ step.done
+ ? "bg-emerald-100 dark:bg-emerald-900/40 text-emerald-600 dark:text-emerald-400"
+ : step.active
+ ? "bg-indigo-100 dark:bg-indigo-900/40 text-indigo-600 dark:text-indigo-400"
+ : "bg-slate-100 dark:bg-slate-700 text-slate-400 dark:text-slate-500"
+ }`}
+ >
+ {step.done ? (
+ <CheckCircle2 className="w-4 h-4" />
+ ) : step.active ? (
+ <Loader2 className="w-4 h-4 animate-spin" />
+ ) : (
+ <step.icon className="w-4 h-4" />
+ )}
+ </div>
+ <div className="flex-1 pt-1">
+ <p
+ className={`text-sm font-medium ${
+ step.done
+ ? "text-emerald-700 dark:text-emerald-300"
+ : step.active
+ ? "text-indigo-700 dark:text-indigo-300"
+ : "text-slate-400 dark:text-slate-500"
+ }`}
+ >
+ {step.label}
+ </p>
+ {step.active && (
+ <p className="text-xs text-slate-500 dark:text-slate-400 mt-1 animate-pulse">
+ Processing...
+ </p>
+ )}
+ </div>
+ </div>
+ ))}
+ </div>
+
+ {/* Sub-Focuses Preview */}
+ {subFocuses.length > 0 && (
+ <div className="mt-6 pt-4 border-t border-slate-100 dark:border-slate-700">
+ <p className="text-xs font-bold text-slate-400 dark:text-slate-500 uppercase tracking-wider mb-3">
+ Question Focuses ({subFocuses.length})
+ </p>
+ <div className="space-y-2 max-h-48 overflow-y-auto">
+ {subFocuses.map((focus: any) => (
+ <div
+ key={focus.id}
+ className="px-3 py-2 bg-slate-50 dark:bg-slate-700 text-slate-700 dark:text-slate-300 text-xs rounded-lg border border-slate-100 dark:border-slate-600"
+ >
+ <div className="flex items-center gap-2 font-semibold text-indigo-600 dark:text-indigo-400">
+ <Target className="w-3 h-3" />
+ {focus.id}
+ </div>
+ <p className="mt-1 text-slate-600 dark:text-slate-400">
+ {focus.focus}
+ </p>
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+ </div>
+
+ {/* Right: Live Logs */}
+ <div className="w-[350px] bg-white dark:bg-slate-800 rounded-xl border border-slate-200 dark:border-slate-700 shadow-sm flex flex-col">
+ <div className="px-4 py-3 border-b border-slate-100 dark:border-slate-700 flex items-center justify-between">
+ <h3 className="font-bold text-slate-700 dark:text-slate-200 flex items-center gap-2">
+ <Activity className="w-4 h-4 text-indigo-500 dark:text-indigo-400" />
+ Live Logs
+ </h3>
+ <span className="text-xs text-slate-400 dark:text-slate-500">
+ {logs.length} entries
+ </span>
+ </div>
+ <div className="flex-1 overflow-y-auto p-3 space-y-2">
+ {logs.length === 0 ? (
+ <div className="text-center text-slate-400 dark:text-slate-500 py-8">
+ <Activity className="w-8 h-8 mx-auto mb-2 opacity-30" />
+ <p className="text-xs">Waiting for logs...</p>
+ </div>
+ ) : (
+ logs.slice(-50).map((log: any, idx: number) => (
+ <div
+ key={idx}
+ className={`text-xs px-2 py-1.5 rounded ${
+ log.type === "error"
+ ? "bg-red-50 dark:bg-red-900/40 text-red-700 dark:text-red-300"
+ : log.type === "success"
+ ? "bg-emerald-50 dark:bg-emerald-900/40 text-emerald-700 dark:text-emerald-300"
+ : "bg-slate-50 dark:bg-slate-700 text-slate-600 dark:text-slate-400"
+ }`}
+ >
+ {log.content}
+ </div>
+ ))
+ )}
+ </div>
+ </div>
+ </div>
+ );
+ };
+
+ // Generating Content with Question Progress
+ const GeneratingContent = () => {
+ const hasContent = Object.keys(tasks).length > 0 || results.length > 0;
+
+ if (!hasContent) {
+ return (
+ <div className="flex-1 flex items-center justify-center">
+ <div className="text-center">
+ <Loader2 className="w-12 h-12 mx-auto mb-3 text-indigo-500 dark:text-indigo-400 animate-spin" />
+ <p className="text-slate-600 dark:text-slate-300 font-medium">
+ Initializing question generation...
+ </p>
+ <p className="text-slate-400 dark:text-slate-500 text-sm mt-1">
+ Preparing tasks...
+ </p>
+ </div>
+ </div>
+ );
+ }
+
+ return (
+ <div className="flex-1 min-h-0 flex gap-6">
+ {/* Left: Task Grid */}
+ <div className="flex-[3] min-w-0 flex flex-col gap-4">
+ <div className="flex items-center justify-between">
+ <h3 className="font-bold text-slate-700 dark:text-slate-200 flex items-center gap-2">
+ <FileQuestion className="w-4 h-4 text-amber-500 dark:text-amber-400" />
+ Question Tasks
+ {isCompleted && (
+ <span className="text-xs font-normal text-slate-400 dark:text-slate-500 ml-2">
+ (Completed)
+ </span>
+ )}
+ </h3>
+ <div className="flex items-center gap-3 text-xs text-slate-500 dark:text-slate-400">
+ {isGenerating && activeTaskIds.length > 0 && (
+ <span className="text-indigo-600 dark:text-indigo-400 font-medium">
+ {activeTaskIds.length} active
+ </span>
+ )}
+ <span>
+ {completedQuestions} / {totalQuestions} completed
+ </span>
+ {extendedCount > 0 && (
+ <span className="text-amber-600 dark:text-amber-400">
+ {extendedCount} extended
+ </span>
+ )}
+ {failedQuestions > 0 && (
+ <span className="text-red-500 dark:text-red-400">
+ {failedQuestions} failed
+ </span>
+ )}
+ </div>
+ </div>
+ <div className="flex-1 overflow-y-auto pr-2">
+ <QuestionTaskGrid
+ tasks={tasks}
+ activeTaskIds={isGenerating ? activeTaskIds : []}
+ selectedTaskId={selectedTaskId}
+ onTaskSelect={onTaskSelect}
+ mode={globalMode}
+ />
+ </div>
+ </div>
+
+ {/* Right: Active Details */}
+ <div className="flex-[2] min-w-[400px] flex flex-col gap-4">
+ <h3 className="font-bold text-slate-700 dark:text-slate-200 flex items-center gap-2">
+ <Activity className="w-4 h-4 text-indigo-500 dark:text-indigo-400" />
+ {isGenerating ? "Active Question" : "Question Details"}
+ </h3>
+ <div className="flex-1 min-h-0">
+ <ActiveQuestionDetail
+ task={selectedTaskId ? tasks[selectedTaskId] : null}
+ mode={globalMode}
+ />
+ </div>
+ </div>
+ </div>
+ );
+ };
+
+ return (
+ <div className="flex flex-col h-full bg-slate-50/50 dark:bg-slate-900/50">
+ {/* Top Bar: Progress & Global Status */}
+ <div className="bg-white dark:bg-slate-800 border-b border-slate-200 dark:border-slate-700 px-6 py-4 flex items-center justify-between shadow-sm shrink-0 z-20 relative">
+ <div className="flex items-center gap-4">
+ <div
+ className={`p-2 rounded-lg ${
+ isIdle
+ ? "bg-slate-100 dark:bg-slate-700 text-slate-400 dark:text-slate-500"
+ : isCompleted
+ ? "bg-emerald-100 dark:bg-emerald-900/40 text-emerald-600 dark:text-emerald-400"
+ : "bg-indigo-100 dark:bg-indigo-900/40 text-indigo-600 dark:text-indigo-400"
+ }`}
+ >
+ {isCompleted ? (
+ <CheckCircle2 className="w-5 h-5" />
+ ) : isIdle ? (
+ <FileQuestion className="w-5 h-5" />
+ ) : (
+ <LayoutDashboard className="w-5 h-5" />
+ )}
+ </div>
+ <div>
+ <h2 className="text-lg font-bold text-slate-800 dark:text-slate-100">
+ {isIdle
+ ? "Ready to Generate"
+ : isCompleted
+ ? "Generation Complete"
+ : "Question Generation"}
+ </h2>
+ <div className="flex items-center gap-2 text-xs text-slate-500 dark:text-slate-400 mt-0.5">
+ <span
+ className={`uppercase font-bold tracking-wider ${isCompleted ? "text-emerald-600 dark:text-emerald-400" : ""}`}
+ >
+ {stage || "idle"}
+ </span>
+ {totalQuestions > 0 && (
+ <>
+ <span>•</span>
+ <span>
+ {completedQuestions} / {totalQuestions} questions
+ </span>
+ </>
+ )}
+ {extendedCount > 0 && (
+ <>
+ <span>•</span>
+ <span className="text-amber-600 dark:text-amber-400 flex items-center gap-1">
+ <Zap className="w-3 h-3" />
+ {extendedCount} extended
+ </span>
+ </>
+ )}
+ {failedQuestions > 0 && (
+ <>
+ <span>•</span>
+ <span className="text-red-500 dark:text-red-400 flex items-center gap-1">
+ <AlertCircle className="w-3 h-3" />
+ {failedQuestions} failed
+ </span>
+ </>
+ )}
+ </div>
+ </div>
+ </div>
+
+ {/* Performance & Cost Stats */}
+ <div className="flex items-center gap-4">
+ {tokenStats && tokenStats.calls > 0 && (
+ <div className="flex items-center gap-4 px-4 py-2 bg-slate-50 dark:bg-slate-700 rounded-lg border border-slate-200 dark:border-slate-600">
+ <div className="flex items-center gap-2">
+ <Cpu className="w-4 h-4 text-slate-400 dark:text-slate-500" />
+ <span className="text-xs text-slate-500 dark:text-slate-400">
+ <span className="font-medium text-slate-700 dark:text-slate-300">
+ {tokenStats.model}
+ </span>
+ </span>
+ </div>
+ <div className="h-4 w-px bg-slate-200 dark:bg-slate-600" />
+ <div className="text-xs text-slate-500 dark:text-slate-400">
+ Calls:{" "}
+ <span className="font-medium text-slate-700 dark:text-slate-300">
+ {tokenStats.calls}
+ </span>
+ </div>
+ <div className="h-4 w-px bg-slate-200 dark:bg-slate-600" />
+ <div className="text-xs text-slate-500 dark:text-slate-400">
+ Tokens:{" "}
+ <span className="font-medium text-slate-700 dark:text-slate-300">
+ {tokenStats.tokens.toLocaleString()}
+ </span>
+ </div>
+ <div className="h-4 w-px bg-slate-200 dark:bg-slate-600" />
+ <div className="flex items-center gap-1">
+ <DollarSign className="w-3 h-3 text-amber-500" />
+ <span className="text-xs font-semibold text-amber-600 dark:text-amber-400">
+ ${tokenStats.cost.toFixed(4)}
+ </span>
+ </div>
+ </div>
+ )}
+
+ {/* Results Summary (when complete) */}
+ {isCompleted && results.length > 0 && (
+ <div className="flex items-center gap-2 bg-emerald-50 dark:bg-emerald-900/30 px-4 py-2 rounded-lg border border-emerald-100 dark:border-emerald-800">
+ <CheckCircle2 className="w-4 h-4 text-emerald-500 dark:text-emerald-400" />
+ <span className="text-sm font-medium text-emerald-700 dark:text-emerald-300">
+ {results.length} question{results.length > 1 ? "s" : ""}{" "}
+ generated
+ </span>
+ </div>
+ )}
+ </div>
+ </div>
+
+ {/* Main Content Area */}
+ <div className="flex-1 flex flex-col min-h-0 overflow-hidden">
+ {/* Idle State */}
+ {isIdle ? (
+ <div className="flex-1 flex items-center justify-center p-6">
+ <div className="bg-white dark:bg-slate-800 rounded-xl border border-slate-200 dark:border-slate-700 shadow-sm p-8 flex flex-col items-center justify-center text-center max-w-lg w-full">
+ <div className="w-16 h-16 bg-slate-100 dark:bg-slate-700 rounded-full flex items-center justify-center mb-4">
+ <FileQuestion className="w-8 h-8 text-slate-400 dark:text-slate-500" />
+ </div>
+ <h3 className="text-lg font-semibold text-slate-800 dark:text-slate-100 mb-2">
+ Ready to Generate Questions
+ </h3>
+ <p className="text-slate-500 dark:text-slate-400 text-sm">
+ Configure your requirements and click Generate to start.
+ </p>
+ </div>
+ </div>
+ ) : (
+ <>
+ {/* Step Tabs */}
+ <div className="px-6 pt-4 pb-2 flex justify-center shrink-0">
+ <StepTabs />
+ </div>
+
+ {/* Tab Content */}
+ <div className="flex-1 overflow-hidden p-6 flex flex-col">
+ {activeProcessTab === "planning" && <PlanningContent />}
+ {activeProcessTab === "generating" && <GeneratingContent />}
+ </div>
+ </>
+ )}
+ </div>
+ </div>
+ );
+};
+
+// Helper function to build tasks from results
+function buildTasksFromResults(
+ results: any[],
+ progress?: GlobalContextProgress,
+ mode?: "custom" | "mimic",
+): Record<string, QuestionTask> {
+ const tasks: Record<string, QuestionTask> = {};
+ const isMimicMode = mode === "mimic";
+
+ // First, create tasks from subFocuses if available (custom mode)
+ if (progress?.subFocuses && !isMimicMode) {
+ progress.subFocuses.forEach((focus, idx) => {
+ const existingResult = results.find(
+ (r: any) =>
+ r.question?.knowledge_point?.includes(focus.focus.slice(0, 20)) ||
+ idx < results.length,
+ );
+
+ tasks[focus.id] = {
+ id: focus.id,
+ focus: focus.focus,
+ scenarioHint: focus.scenario_hint,
+ status: idx < results.length ? "done" : "pending",
+ result:
+ idx < results.length
+ ? {
+ success: true,
+ question_id: focus.id,
+ question: results[idx]?.question,
+ validation: results[idx]?.validation,
+ rounds: results[idx]?.rounds || 1,
+ extended: results[idx]?.extended,
+ }
+ : undefined,
+ extended: results[idx]?.extended,
+ lastUpdate: Date.now(),
+ };
+ });
+ }
+
+ // If no subFocuses or mimic mode, create tasks from results directly
+ if (Object.keys(tasks).length === 0 && results.length > 0) {
+ results.forEach((result: any, idx: number) => {
+ const id = `q_${idx + 1}`;
+ // For mimic mode, use reference_question as focus (full original question)
+ // For custom mode fallback, use generated question preview
+ const focus = isMimicMode
+ ? result.reference_question || `Reference Question ${idx + 1}`
+ : result.question?.question?.slice(0, 50) + "..." ||
+ `Question ${idx + 1}`;
+
+ tasks[id] = {
+ id,
+ focus,
+ status: "done",
+ result: {
+ success: true,
+ question_id: id,
+ question: result.question,
+ validation: result.validation,
+ rounds: result.rounds || 1,
+ extended: result.extended,
+ },
+ extended: result.extended,
+ lastUpdate: Date.now(),
+ };
+ });
+ }
+
+ return tasks;
+}
diff --git a/web/components/question/QuestionTaskGrid.tsx b/web/components/question/QuestionTaskGrid.tsx
new file mode 100644
index 000000000..3bf69bd71
--- /dev/null
+++ b/web/components/question/QuestionTaskGrid.tsx
@@ -0,0 +1,232 @@
+import React from "react";
+import { QuestionTask } from "../../types/question";
+import {
+ CheckCircle2,
+ Loader2,
+ Clock,
+ AlertCircle,
+ Activity,
+ FileQuestion,
+ Search,
+ Zap,
+ BookOpen,
+} from "lucide-react";
+import ReactMarkdown from "react-markdown";
+import remarkMath from "remark-math";
+import rehypeKatex from "rehype-katex";
+import { processLatexContent } from "@/lib/latex";
+
+interface QuestionTaskGridProps {
+ tasks: Record<string, QuestionTask>;
+ activeTaskIds: string[];
+ selectedTaskId: string | null;
+ onTaskSelect: (taskId: string) => void;
+ mode?: "custom" | "mimic";
+}
+
+const getStatusIcon = (status: QuestionTask["status"], extended?: boolean) => {
+ if (status === "done" && extended) {
+ return <Zap className="w-4 h-4 text-amber-500" />;
+ }
+ switch (status) {
+ case "done":
+ return <CheckCircle2 className="w-4 h-4 text-emerald-500" />;
+ case "generating":
+ return <Loader2 className="w-4 h-4 text-indigo-500 animate-spin" />;
+ case "analyzing":
+ return <Search className="w-4 h-4 text-purple-500 animate-pulse" />;
+ case "validating":
+ return <Search className="w-4 h-4 text-amber-500 animate-pulse" />;
+ case "error":
+ return <AlertCircle className="w-4 h-4 text-red-500" />;
+ default:
+ return <Clock className="w-4 h-4 text-slate-400" />;
+ }
+};
+
+const getStatusColor = (status: QuestionTask["status"], extended?: boolean) => {
+ if (status === "done" && extended) {
+ return "bg-amber-100 dark:bg-amber-900/40 text-amber-700 dark:text-amber-300";
+ }
+ switch (status) {
+ case "done":
+ return "bg-emerald-100 dark:bg-emerald-900/40 text-emerald-700 dark:text-emerald-300";
+ case "generating":
+ return "bg-indigo-100 dark:bg-indigo-900/40 text-indigo-700 dark:text-indigo-300";
+ case "analyzing":
+ return "bg-purple-100 dark:bg-purple-900/40 text-purple-700 dark:text-purple-300";
+ case "validating":
+ return "bg-amber-100 dark:bg-amber-900/40 text-amber-700 dark:text-amber-300";
+ case "error":
+ return "bg-red-100 dark:bg-red-900/40 text-red-700 dark:text-red-300";
+ default:
+ return "bg-slate-100 dark:bg-slate-700 text-slate-600 dark:text-slate-400";
+ }
+};
+
+export const QuestionTaskGrid: React.FC<QuestionTaskGridProps> = ({
+ tasks,
+ activeTaskIds,
+ selectedTaskId,
+ onTaskSelect,
+ mode = "custom",
+}) => {
+ const isMimicMode = mode === "mimic";
+ // Sort tasks: Active first, then by status
+ const sortedTasks = Object.values(tasks).sort((a, b) => {
+ const score = (task: QuestionTask) => {
+ if (activeTaskIds.includes(task.id)) return 4;
+ if (
+ task.status === "generating" ||
+ task.status === "analyzing" ||
+ task.status === "validating"
+ )
+ return 3;
+ if (task.status === "pending") return 2;
+ return 1;
+ };
+ return score(b) - score(a);
+ });
+
+ if (sortedTasks.length === 0) {
+ return (
+ <div className="flex flex-col items-center justify-center p-8 text-slate-400 dark:text-slate-500 border-2 border-dashed border-slate-200 dark:border-slate-700 rounded-xl">
+ <Activity className="w-8 h-8 mb-2 opacity-50" />
+ <p className="text-sm">No questions initialized yet</p>
+ </div>
+ );
+ }
+
+ return (
+ <div className="grid grid-cols-1 xl:grid-cols-2 gap-4">
+ {sortedTasks.map((task) => {
+ const isActive = activeTaskIds.includes(task.id);
+ const isSelected = selectedTaskId === task.id;
+
+ return (
+ <div
+ key={task.id}
+ onClick={() => onTaskSelect(task.id)}
+ className={`
+ relative p-4 rounded-xl border cursor-pointer transition-all duration-200
+ hover:shadow-md flex flex-col gap-3
+ ${
+ isSelected
+ ? "bg-indigo-50/50 dark:bg-indigo-900/30 border-indigo-500 ring-1 ring-indigo-500"
+ : "bg-white dark:bg-slate-800 border-slate-200 dark:border-slate-700 hover:border-indigo-300 dark:hover:border-indigo-500"
+ }
+ ${isActive ? "shadow-sm" : "opacity-90"}
+ `}
+ >
+ {/* Active Indicator Pulse */}
+ {isActive && (
+ <div className="absolute top-4 right-4 flex h-2 w-2">
+ <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-indigo-400 opacity-75"></span>
+ <span className="relative inline-flex rounded-full h-2 w-2 bg-indigo-500"></span>
+ </div>
+ )}
+
+ <div className="flex items-start gap-3">
+ <div
+ className={`p-2 rounded-lg shrink-0 ${
+ task.status === "done" && task.extended
+ ? "bg-amber-50 dark:bg-amber-900/30"
+ : task.status === "done"
+ ? "bg-emerald-50 dark:bg-emerald-900/30"
+ : task.status === "error"
+ ? "bg-red-50 dark:bg-red-900/30"
+ : isActive
+ ? "bg-indigo-50 dark:bg-indigo-900/30"
+ : "bg-slate-100 dark:bg-slate-700"
+ }`}
+ >
+ {getStatusIcon(task.status, task.extended)}
+ </div>
+ <div className="flex-1 min-w-0">
+ <div className="flex items-start justify-between gap-2">
+ <h4
+ className="text-sm font-semibold text-slate-800 dark:text-slate-200 line-clamp-1 pr-4"
+ title={task.id}
+ >
+ {task.id}
+ </h4>
+ </div>
+ <div className="flex items-center gap-2 mt-1.5">
+ <span
+ className={`text-[10px] px-2 py-0.5 rounded-full font-medium uppercase tracking-wide ${getStatusColor(task.status, task.extended)}`}
+ >
+ {task.extended ? "extended" : task.status}
+ </span>
+ {task.round && task.maxRounds && (
+ <span className="text-[10px] text-slate-400 dark:text-slate-500 font-medium">
+ ROUND {task.round} / {task.maxRounds}
+ </span>
+ )}
+ </div>
+ </div>
+ </div>
+
+ {/* Focus / Origin Question */}
+ <div
+ className={`bg-slate-50 dark:bg-slate-700 rounded-lg p-2.5 border border-slate-100 dark:border-slate-600 ${isMimicMode ? "min-h-[80px]" : "min-h-[48px]"}`}
+ >
+ {isMimicMode ? (
+ <div className="text-xs text-slate-600 dark:text-slate-400">
+ <div className="flex items-center gap-1 mb-2">
+ <BookOpen className="w-3 h-3 text-amber-500 dark:text-amber-400" />
+ <span className="font-semibold text-amber-600 dark:text-amber-400">
+ Origin Question:
+ </span>
+ </div>
+ <div className="prose prose-xs dark:prose-invert max-w-none leading-relaxed text-slate-700 dark:text-slate-300">
+ {task.focus ? (
+ <ReactMarkdown
+ remarkPlugins={[remarkMath]}
+ rehypePlugins={[rehypeKatex]}
+ >
+ {processLatexContent(task.focus)}
+ </ReactMarkdown>
+ ) : (
+ <span className="text-slate-400 dark:text-slate-500 italic">
+ Waiting to start...
+ </span>
+ )}
+ </div>
+ </div>
+ ) : (
+ <p className="text-xs text-slate-600 dark:text-slate-400 line-clamp-2 leading-relaxed">
+ <span className="font-medium text-slate-400 dark:text-slate-500 mr-1">
+ Focus:
+ </span>
+ {task.focus || "Waiting to start..."}
+ </p>
+ )}
+ </div>
+
+ {/* Result preview or error */}
+ {task.result?.question && (
+ <div
+ className={`flex items-center gap-1.5 text-xs ${task.extended ? "text-amber-600 dark:text-amber-400" : "text-emerald-600 dark:text-emerald-400"}`}
+ >
+ {task.extended ? (
+ <Zap className="w-3 h-3" />
+ ) : (
+ <FileQuestion className="w-3 h-3" />
+ )}
+ <span className="line-clamp-1">
+ {task.result.question.question?.slice(0, 50)}...
+ </span>
+ </div>
+ )}
+ {task.error && (
+ <div className="flex items-center gap-1.5 text-xs text-red-600 dark:text-red-400">
+ <AlertCircle className="w-3 h-3" />
+ <span className="line-clamp-1">{task.error}</span>
+ </div>
+ )}
+ </div>
+ );
+ })}
+ </div>
+ );
+};
diff --git a/web/components/question/index.ts b/web/components/question/index.ts
new file mode 100644
index 000000000..abcf1103f
--- /dev/null
+++ b/web/components/question/index.ts
@@ -0,0 +1,3 @@
+export { QuestionDashboard } from "./QuestionDashboard";
+export { QuestionTaskGrid } from "./QuestionTaskGrid";
+export { ActiveQuestionDetail } from "./ActiveQuestionDetail";
diff --git a/web/components/research/ActiveTaskDetail.tsx b/web/components/research/ActiveTaskDetail.tsx
new file mode 100644
index 000000000..a08bd437a
--- /dev/null
+++ b/web/components/research/ActiveTaskDetail.tsx
@@ -0,0 +1,183 @@
+import React, { useEffect, useRef } from "react";
+import { TaskState, ThoughtEntry } from "../../types/research";
+import {
+ Terminal,
+ BrainCircuit,
+ Search,
+ PenTool,
+ CheckCircle2,
+ AlertTriangle,
+ ChevronRight,
+ Database,
+} from "lucide-react";
+import ReactMarkdown from "react-markdown";
+
+interface ActiveTaskDetailProps {
+ task: TaskState | null;
+}
+
+const getThoughtIcon = (type: ThoughtEntry["type"]) => {
+ switch (type) {
+ case "sufficiency":
+ return <BrainCircuit className="w-4 h-4 text-violet-500" />;
+ case "plan":
+ return <Search className="w-4 h-4 text-blue-500" />;
+ case "tool_call":
+ return <Database className="w-4 h-4 text-amber-500" />;
+ case "note":
+ return <PenTool className="w-4 h-4 text-emerald-500" />;
+ case "error":
+ return <AlertTriangle className="w-4 h-4 text-red-500" />;
+ default:
+ return <Terminal className="w-4 h-4 text-slate-400" />;
+ }
+};
+
+const formatTimestamp = (ts: number) => {
+ return new Date(ts).toLocaleTimeString(undefined, {
+ hour12: false,
+ hour: "2-digit",
+ minute: "2-digit",
+ second: "2-digit",
+ });
+};
+
+export const ActiveTaskDetail: React.FC<ActiveTaskDetailProps> = ({ task }) => {
+ const scrollRef = useRef<HTMLDivElement>(null);
+
+ // Auto-scroll to bottom when new thoughts arrive
+ useEffect(() => {
+ if (scrollRef.current) {
+ scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
+ }
+ }, [task?.thoughts.length]);
+
+ if (!task) {
+ return (
+ <div className="h-full flex flex-col items-center justify-center text-slate-400 dark:text-slate-500 bg-slate-50/50 dark:bg-slate-800/50 rounded-xl border border-slate-200 dark:border-slate-700">
+ <Terminal className="w-12 h-12 mb-3 opacity-20" />
+ <p className="text-sm">Select a task to view execution details</p>
+ </div>
+ );
+ }
+
+ return (
+ <div className="h-full flex flex-col bg-white dark:bg-slate-800 rounded-xl border border-slate-200 dark:border-slate-700 shadow-sm overflow-hidden">
+ {/* Header */}
+ <div className="p-4 border-b border-slate-100 dark:border-slate-700 bg-slate-50/50 dark:bg-slate-800/50 flex justify-between items-center">
+ <div className="flex items-center gap-2 overflow-hidden">
+ <Terminal className="w-4 h-4 text-slate-500 dark:text-slate-400 shrink-0" />
+ <h3
+ className="font-semibold text-slate-800 dark:text-slate-100 text-sm truncate"
+ title={task.topic}
+ >
+ {task.topic}
+ </h3>
+ </div>
+ <div className="flex items-center gap-2 shrink-0">
+ <span className="text-xs font-mono text-slate-400 dark:text-slate-500">
+ {task.id}
+ </span>
+ <div
+ className={`px-2 py-0.5 rounded text-[10px] font-bold uppercase tracking-wider ${
+ task.status === "running"
+ ? "bg-indigo-100 dark:bg-indigo-900/50 text-indigo-700 dark:text-indigo-300"
+ : task.status === "completed"
+ ? "bg-emerald-100 dark:bg-emerald-900/50 text-emerald-700 dark:text-emerald-300"
+ : task.status === "failed"
+ ? "bg-red-100 dark:bg-red-900/50 text-red-700 dark:text-red-300"
+ : "bg-slate-100 dark:bg-slate-700 text-slate-600 dark:text-slate-400"
+ }`}
+ >
+ {task.status}
+ </div>
+ </div>
+ </div>
+
+ {/* Content Stream */}
+ <div
+ ref={scrollRef}
+ className="flex-1 overflow-y-auto p-4 space-y-4 font-mono text-sm"
+ >
+ {task.thoughts.length === 0 ? (
+ <div className="text-center py-10 text-slate-400 dark:text-slate-500 text-xs italic">
+ Waiting for execution logs...
+ </div>
+ ) : (
+ task.thoughts.map((thought, idx) => (
+ <div key={idx} className="flex gap-3 animate-fade-in group">
+ {/* Timeline Line */}
+ <div className="flex flex-col items-center shrink-0 w-8">
+ <div
+ className={`w-8 h-8 rounded-full flex items-center justify-center border ${
+ thought.type === "error"
+ ? "bg-red-50 dark:bg-red-900/40 border-red-200 dark:border-red-800"
+ : thought.type === "sufficiency"
+ ? "bg-violet-50 dark:bg-violet-900/40 border-violet-200 dark:border-violet-800"
+ : thought.type === "tool_call"
+ ? "bg-amber-50 dark:bg-amber-900/40 border-amber-200 dark:border-amber-800"
+ : "bg-slate-50 dark:bg-slate-700 border-slate-200 dark:border-slate-600"
+ }`}
+ >
+ {getThoughtIcon(thought.type)}
+ </div>
+ {idx < task.thoughts.length - 1 && (
+ <div className="w-px h-full bg-slate-100 dark:bg-slate-700 my-1 group-hover:bg-slate-200 dark:group-hover:bg-slate-600 transition-colors" />
+ )}
+ </div>
+
+ {/* Content Bubble */}
+ <div className="flex-1 min-w-0 pb-2">
+ <div className="flex items-center gap-2 mb-1">
+ <span
+ className={`text-xs font-bold uppercase tracking-wider ${
+ thought.type === "error"
+ ? "text-red-600 dark:text-red-400"
+ : thought.type === "sufficiency"
+ ? "text-violet-600 dark:text-violet-400"
+ : thought.type === "tool_call"
+ ? "text-amber-600 dark:text-amber-400"
+ : "text-slate-600 dark:text-slate-400"
+ }`}
+ >
+ {thought.type.replace("_", " ")}
+ </span>
+ <span className="text-[10px] text-slate-400 dark:text-slate-500">
+ {formatTimestamp(thought.timestamp)}
+ </span>
+ </div>
+
+ <div className="text-slate-700 dark:text-slate-200 leading-relaxed bg-slate-50/50 dark:bg-slate-700/50 rounded-lg p-3 border border-slate-100/50 dark:border-slate-600/50">
+ <ReactMarkdown
+ components={{
+ p: ({ children }) => (
+ <p className="mb-1 last:mb-0 break-words">{children}</p>
+ ),
+ code: ({ node, className, children, ...props }) => {
+ const match = /language-(\w+)/.exec(className || "");
+ return !className?.includes("language-") ? (
+ <code
+ className="bg-slate-200/50 dark:bg-slate-600/50 px-1 py-0.5 rounded text-xs text-slate-800 dark:text-slate-200"
+ {...props}
+ >
+ {children}
+ </code>
+ ) : (
+ <code className={className} {...props}>
+ {children}
+ </code>
+ );
+ },
+ }}
+ >
+ {thought.content}
+ </ReactMarkdown>
+ </div>
+ </div>
+ </div>
+ ))
+ )}
+ </div>
+ </div>
+ );
+};
diff --git a/web/components/research/ResearchDashboard.tsx b/web/components/research/ResearchDashboard.tsx
new file mode 100644
index 000000000..ad463c632
--- /dev/null
+++ b/web/components/research/ResearchDashboard.tsx
@@ -0,0 +1,854 @@
+import React, { useState, useEffect } from "react";
+import { ResearchState } from "../../types/research";
+import { TaskGrid } from "./TaskGrid";
+import { ActiveTaskDetail } from "./ActiveTaskDetail";
+import ReactMarkdown from "react-markdown";
+import remarkGfm from "remark-gfm";
+import remarkMath from "remark-math";
+import rehypeKatex from "rehype-katex";
+import rehypeRaw from "rehype-raw";
+import "katex/dist/katex.min.css";
+import { Mermaid } from "../Mermaid";
+import {
+ GitBranch,
+ Zap,
+ PenTool,
+ CheckCircle2,
+ Loader2,
+ LayoutDashboard,
+ Activity,
+ FileText,
+ ListTree,
+ Sparkles,
+ BarChart3,
+ FileOutput,
+ Search,
+ Clock,
+ Book,
+ Download,
+ FileDown,
+} from "lucide-react";
+
+type ProcessTab = "planning" | "researching" | "reporting";
+
+interface ResearchDashboardProps {
+ state: ResearchState;
+ selectedTaskId: string | null;
+ onTaskSelect: (taskId: string) => void;
+ onAddToNotebook?: () => void;
+ onExportMarkdown?: () => void;
+ onExportPdf?: () => void;
+ isExportingPdf?: boolean;
+}
+
+export const ResearchDashboard: React.FC<ResearchDashboardProps> = ({
+ state,
+ selectedTaskId,
+ onTaskSelect,
+ onAddToNotebook,
+ onExportMarkdown,
+ onExportPdf,
+ isExportingPdf = false,
+}) => {
+ const { global, tasks, activeTaskIds, planning, reporting } = state;
+ const [activeView, setActiveView] = useState<"process" | "report">("process");
+ const [activeProcessTab, setActiveProcessTab] =
+ useState<ProcessTab>("planning");
+
+ const steps: { id: ProcessTab; label: string; icon: React.ElementType }[] = [
+ { id: "planning", label: "Planning", icon: GitBranch },
+ { id: "researching", label: "Researching", icon: Zap },
+ { id: "reporting", label: "Reporting", icon: PenTool },
+ ];
+
+ const stageOrder: Record<string, number> = {
+ idle: -1,
+ planning: 0,
+ researching: 1,
+ reporting: 2,
+ completed: 3,
+ };
+
+ const currentStageIndex = stageOrder[global.stage] ?? -1;
+ const isCompleted = global.stage === "completed";
+
+ // Check if a tab has content (has been reached)
+ const isTabAvailable = (tabId: ProcessTab): boolean => {
+ const tabIndex = steps.findIndex((s) => s.id === tabId);
+ return currentStageIndex >= tabIndex;
+ };
+
+ // Check if a tab is currently active (the system is in this stage)
+ const isTabCurrentlyActive = (tabId: ProcessTab): boolean => {
+ return global.stage === tabId;
+ };
+
+ // Auto-switch to current stage tab when stage changes
+ useEffect(() => {
+ if (global.stage === "planning") {
+ setActiveProcessTab("planning");
+ } else if (global.stage === "researching") {
+ setActiveProcessTab("researching");
+ } else if (global.stage === "reporting") {
+ setActiveProcessTab("reporting");
+ }
+ // When completed, stay on current tab (user can browse freely)
+ }, [global.stage]);
+
+ // Auto-switch to report view when research completes and report is available
+ useEffect(() => {
+ if (
+ global.stage === "completed" &&
+ reporting.generatedReport &&
+ activeView === "process"
+ ) {
+ const timer = setTimeout(() => {
+ setActiveView("report");
+ }, 1500);
+ return () => clearTimeout(timer);
+ }
+ }, [global.stage, reporting.generatedReport]);
+
+ // Reset to process view when a new research starts
+ useEffect(() => {
+ if (global.stage === "planning") {
+ setActiveView("process");
+ }
+ }, [global.stage]);
+
+ // Clickable Step Tabs
+ const StepTabs = () => (
+ <div className="flex items-center gap-1 bg-slate-100/80 dark:bg-slate-800/80 backdrop-blur-sm p-1 rounded-xl border border-slate-200/50 dark:border-slate-700/50 shadow-sm">
+ {steps.map((step, idx) => {
+ const available = isTabAvailable(step.id);
+ const isCurrentStage = isTabCurrentlyActive(step.id);
+ const isSelected = activeProcessTab === step.id;
+ const isPassed = currentStageIndex > idx || isCompleted;
+
+ return (
+ <button
+ key={step.id}
+ onClick={() => available && setActiveProcessTab(step.id)}
+ disabled={!available}
+ className={`
+ flex items-center gap-2 px-4 py-2 rounded-lg transition-all relative
+ ${
+ isSelected
+ ? "bg-white dark:bg-slate-700 shadow-sm border border-slate-200 dark:border-slate-600 text-indigo-700 dark:text-indigo-300"
+ : available
+ ? "hover:bg-white/50 dark:hover:bg-slate-700/50 text-slate-600 dark:text-slate-300"
+ : "text-slate-300 dark:text-slate-600 cursor-not-allowed"
+ }
+ `}
+ >
+ {/* Status indicator */}
+ {isPassed ? (
+ <CheckCircle2 className="w-4 h-4 text-emerald-500" />
+ ) : isCurrentStage ? (
+ <Loader2 className="w-4 h-4 text-indigo-500 animate-spin" />
+ ) : available ? (
+ <step.icon className="w-4 h-4" />
+ ) : (
+ <Clock className="w-4 h-4 text-slate-300" />
+ )}
+ <span className="text-sm font-medium">{step.label}</span>
+
+ {/* Active indicator dot */}
+ {isCurrentStage && !isCompleted && (
+ <span className="absolute -top-1 -right-1 flex h-2.5 w-2.5">
+ <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-indigo-400 opacity-75"></span>
+ <span className="relative inline-flex rounded-full h-2.5 w-2.5 bg-indigo-500"></span>
+ </span>
+ )}
+ </button>
+ );
+ })}
+ </div>
+ );
+
+ // Planning Content
+ const PlanningContent = () => {
+ const isActive = global.stage === "planning";
+
+ return (
+ <div className="flex-1 flex items-center justify-center">
+ <div
+ className={`bg-white dark:bg-slate-800 rounded-xl border shadow-sm p-8 flex flex-col items-center justify-center text-center max-w-2xl w-full ${
+ isActive
+ ? "border-blue-200 dark:border-blue-800"
+ : "border-slate-200 dark:border-slate-700"
+ }`}
+ >
+ <div
+ className={`w-16 h-16 rounded-full flex items-center justify-center mb-4 ${
+ isActive
+ ? "bg-blue-50 dark:bg-blue-900/40"
+ : "bg-slate-50 dark:bg-slate-700"
+ }`}
+ >
+ <GitBranch
+ className={`w-8 h-8 ${isActive ? "text-blue-500 dark:text-blue-400" : "text-slate-400 dark:text-slate-500"}`}
+ />
+ </div>
+
+ {isActive && (
+ <Loader2 className="w-6 h-6 text-blue-500 dark:text-blue-400 animate-spin mb-4" />
+ )}
+ {!isActive && currentStageIndex > 0 && (
+ <CheckCircle2 className="w-6 h-6 text-emerald-500 dark:text-emerald-400 mb-4" />
+ )}
+
+ <h3 className="text-lg font-semibold text-slate-800 dark:text-slate-100 mb-2">
+ {isActive ? "Planning Research Strategy" : "Research Plan"}
+ </h3>
+
+ {isActive && (
+ <p className="text-slate-500 dark:text-slate-400 text-sm mb-4">
+ {planning.progress || "Initializing..."}
+ </p>
+ )}
+
+ {/* Topic Info */}
+ {(planning.originalTopic || planning.optimizedTopic) && (
+ <div className="w-full mt-4 bg-slate-50 dark:bg-slate-700 rounded-lg p-4 border border-slate-100 dark:border-slate-600 text-left">
+ {planning.originalTopic && (
+ <div className="mb-3">
+ <p className="text-xs font-semibold text-slate-400 dark:text-slate-500 uppercase tracking-wider mb-1">
+ Original Topic
+ </p>
+ <p className="text-sm text-slate-700 dark:text-slate-200">
+ {planning.originalTopic}
+ </p>
+ </div>
+ )}
+ {planning.optimizedTopic &&
+ planning.optimizedTopic !== planning.originalTopic && (
+ <div>
+ <p className="text-xs font-semibold text-slate-400 dark:text-slate-500 uppercase tracking-wider mb-1">
+ Optimized Topic
+ </p>
+ <p className="text-sm text-slate-700 dark:text-slate-200">
+ {planning.optimizedTopic}
+ </p>
+ </div>
+ )}
+ </div>
+ )}
+
+ {/* Sub Topics */}
+ {planning.subTopics.length > 0 && (
+ <div className="w-full mt-4">
+ <p className="text-xs font-semibold text-slate-400 dark:text-slate-500 uppercase tracking-wider mb-3 text-left">
+ Research Sub-topics ({planning.subTopics.length})
+ </p>
+ <div className="flex flex-wrap gap-2">
+ {planning.subTopics.map((topic, i) => (
+ <span
+ key={i}
+ className="px-3 py-1.5 bg-blue-50 dark:bg-blue-900/40 text-blue-700 dark:text-blue-300 text-xs rounded-lg border border-blue-100 dark:border-blue-800 font-medium"
+ >
+ {topic.sub_topic}
+ </span>
+ ))}
+ </div>
+ </div>
+ )}
+ </div>
+ </div>
+ );
+ };
+
+ // Researching Content
+ const ResearchingContent = () => {
+ const isActive = global.stage === "researching";
+ const hasContent = Object.keys(tasks).length > 0;
+
+ if (!hasContent) {
+ return (
+ <div className="flex-1 flex items-center justify-center">
+ <div className="text-center text-slate-400 dark:text-slate-500">
+ <Zap className="w-12 h-12 mx-auto mb-3 opacity-30" />
+ <p>No research data yet</p>
+ </div>
+ </div>
+ );
+ }
+
+ return (
+ <div className="flex-1 min-h-0 flex gap-6">
+ {/* Left: Task Grid - flex-[3] means 3 parts of available space */}
+ <div className="flex-[3] min-w-[200px] flex flex-col gap-4 overflow-hidden">
+ <div className="flex items-center justify-between shrink-0">
+ <h3 className="font-bold text-slate-700 dark:text-slate-200 flex items-center gap-2">
+ <Zap className="w-4 h-4 text-amber-500 dark:text-amber-400" />
+ Research Tasks
+ {!isActive && (
+ <span className="text-xs font-normal text-slate-400 dark:text-slate-500 ml-2">
+ (History)
+ </span>
+ )}
+ </h3>
+ <div className="flex items-center gap-3 text-xs text-slate-500 dark:text-slate-400">
+ {isActive && (
+ <span className="text-indigo-600 dark:text-indigo-400 font-medium">
+ {state.activeTaskIds.length} active
+ </span>
+ )}
+ <span>
+ {global.completedBlocks} / {global.totalBlocks} completed
+ </span>
+ </div>
+ </div>
+ <div className="flex-1 overflow-y-auto pr-2">
+ <TaskGrid
+ tasks={tasks}
+ activeTaskIds={isActive ? activeTaskIds : []}
+ selectedTaskId={selectedTaskId}
+ onTaskSelect={onTaskSelect}
+ />
+ </div>
+ </div>
+
+ {/* Right: Active Details - flex-[2] means 2 parts of available space */}
+ {/* Both sides shrink proportionally (3:2 ratio) when space is limited */}
+ <div className="flex-[2] min-w-[280px] flex flex-col gap-4 overflow-hidden">
+ <h3 className="font-bold text-slate-700 dark:text-slate-200 flex items-center gap-2 shrink-0">
+ <Activity className="w-4 h-4 text-indigo-500 dark:text-indigo-400" />
+ {isActive ? "Live Execution" : "Execution History"}
+ </h3>
+ <div className="flex-1 min-h-0 overflow-hidden">
+ <ActiveTaskDetail
+ task={selectedTaskId ? tasks[selectedTaskId] : null}
+ />
+ </div>
+ </div>
+ </div>
+ );
+ };
+
+ // Reporting Content
+ const ReportingContent = () => {
+ const isActive = global.stage === "reporting";
+
+ return (
+ <div className="flex-1 flex items-center justify-center">
+ <div
+ className={`bg-white dark:bg-slate-800 rounded-xl border shadow-sm p-8 flex flex-col items-center justify-center text-center max-w-lg w-full ${
+ isActive
+ ? "border-purple-200 dark:border-purple-800"
+ : isCompleted
+ ? "border-emerald-200 dark:border-emerald-800"
+ : "border-slate-200 dark:border-slate-700"
+ }`}
+ >
+ <div
+ className={`w-16 h-16 rounded-full flex items-center justify-center mb-4 ${
+ isActive
+ ? "bg-purple-50 dark:bg-purple-900/40"
+ : isCompleted
+ ? "bg-emerald-50 dark:bg-emerald-900/40"
+ : "bg-slate-50 dark:bg-slate-700"
+ }`}
+ >
+ {isCompleted ? (
+ <Sparkles className="w-8 h-8 text-emerald-500 dark:text-emerald-400" />
+ ) : (
+ <PenTool
+ className={`w-8 h-8 ${isActive ? "text-purple-500 dark:text-purple-400" : "text-slate-400 dark:text-slate-500"}`}
+ />
+ )}
+ </div>
+
+ {isActive && (
+ <Loader2 className="w-6 h-6 text-purple-500 dark:text-purple-400 animate-spin mb-4" />
+ )}
+ {isCompleted && (
+ <CheckCircle2 className="w-6 h-6 text-emerald-500 dark:text-emerald-400 mb-4" />
+ )}
+
+ <h3 className="text-lg font-semibold text-slate-800 dark:text-slate-100 mb-2">
+ {isCompleted
+ ? "Report Generated!"
+ : isActive
+ ? "Generating Report"
+ : "Report Generation"}
+ </h3>
+
+ {/* Current Section Being Written */}
+ {isActive && reporting.currentSection && (
+ <div className="bg-purple-50 dark:bg-purple-900/30 border border-purple-100 dark:border-purple-800 rounded-lg px-4 py-2 mb-4 w-full">
+ <p className="text-xs text-purple-600 dark:text-purple-400 font-medium uppercase tracking-wider mb-1">
+ Currently Writing
+ </p>
+ <p className="text-purple-800 dark:text-purple-200 font-semibold">
+ {reporting.currentSection}
+ </p>
+ {reporting.totalSections &&
+ reporting.sectionIndex !== undefined && (
+ <p className="text-xs text-purple-500 dark:text-purple-400 mt-1">
+ Section {reporting.sectionIndex + 1} of{" "}
+ {reporting.totalSections}
+ </p>
+ )}
+ </div>
+ )}
+
+ {/* Progress Bar */}
+ {isActive &&
+ reporting.totalSections &&
+ reporting.sectionIndex !== undefined && (
+ <div className="w-full mb-4">
+ <div className="h-2 bg-purple-100 dark:bg-purple-900/40 rounded-full overflow-hidden">
+ <div
+ className="h-full bg-purple-500 rounded-full transition-all duration-500"
+ style={{
+ width: `${((reporting.sectionIndex + 1) / reporting.totalSections) * 100}%`,
+ }}
+ />
+ </div>
+ <p className="text-xs text-slate-400 dark:text-slate-500 mt-1">
+ {Math.round(
+ ((reporting.sectionIndex + 1) / reporting.totalSections) *
+ 100,
+ )}
+ % complete
+ </p>
+ </div>
+ )}
+
+ {isActive && (
+ <p className="text-slate-500 dark:text-slate-400 text-sm mb-4">
+ {reporting.progress || "Processing research findings..."}
+ </p>
+ )}
+
+ {/* Stats */}
+ <div className="flex items-center gap-6 text-sm text-slate-600 dark:text-slate-300 mt-2">
+ {global.totalBlocks > 0 && (
+ <div className="flex items-center gap-1.5">
+ <ListTree
+ className={`w-4 h-4 ${isCompleted ? "text-emerald-500 dark:text-emerald-400" : "text-slate-400 dark:text-slate-500"}`}
+ />
+ <span>{global.totalBlocks} topics</span>
+ </div>
+ )}
+ {reporting.wordCount && (
+ <div className="flex items-center gap-1.5">
+ <FileText
+ className={`w-4 h-4 ${isCompleted ? "text-emerald-500 dark:text-emerald-400" : "text-slate-400 dark:text-slate-500"}`}
+ />
+ <span>{reporting.wordCount.toLocaleString()} words</span>
+ </div>
+ )}
+ {reporting.outline && reporting.outline.sections.length > 0 && (
+ <div className="flex items-center gap-1.5">
+ <FileText className="w-4 h-4 text-slate-400 dark:text-slate-500" />
+ <span>{reporting.outline.sections.length} sections</span>
+ </div>
+ )}
+ </div>
+
+ {/* Outline Preview */}
+ {reporting.outline && reporting.outline.sections.length > 0 && (
+ <div className="mt-6 w-full text-left bg-slate-50 dark:bg-slate-700 rounded-lg p-4 border border-slate-100 dark:border-slate-600 max-h-[200px] overflow-y-auto">
+ <p className="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wider mb-3">
+ Report Outline
+ </p>
+ <ul className="space-y-2">
+ {reporting.outline.sections.map((section, i) => (
+ <li
+ key={i}
+ className="flex items-center gap-2 text-sm text-slate-600 dark:text-slate-300"
+ >
+ <span
+ className={`w-5 h-5 rounded text-xs flex items-center justify-center font-medium shrink-0 ${
+ isActive &&
+ reporting.sectionIndex !== undefined &&
+ i + 1 === reporting.sectionIndex
+ ? "bg-purple-500 text-white animate-pulse"
+ : isCompleted ||
+ (reporting.sectionIndex !== undefined &&
+ i + 1 < reporting.sectionIndex)
+ ? "bg-emerald-100 dark:bg-emerald-900/50 text-emerald-600 dark:text-emerald-400"
+ : "bg-purple-100 dark:bg-purple-900/50 text-purple-600 dark:text-purple-400"
+ }`}
+ >
+ {isCompleted ||
+ (reporting.sectionIndex !== undefined &&
+ i + 1 < reporting.sectionIndex)
+ ? "✓"
+ : i + 1}
+ </span>
+ <span
+ className={`line-clamp-1 ${
+ isActive &&
+ reporting.sectionIndex !== undefined &&
+ i + 1 === reporting.sectionIndex
+ ? "text-purple-700 dark:text-purple-300 font-medium"
+ : ""
+ }`}
+ >
+ {section.title.replace(/^##\s*\d*\.?\s*/, "")}
+ </span>
+ </li>
+ ))}
+ </ul>
+ </div>
+ )}
+
+ {/* View Report Button (when completed) */}
+ {isCompleted && reporting.generatedReport && (
+ <button
+ onClick={() => setActiveView("report")}
+ className="mt-6 flex items-center justify-center gap-2 w-full py-3 px-4 bg-indigo-600 hover:bg-indigo-700 text-white rounded-xl font-medium transition-colors shadow-sm"
+ >
+ <FileText className="w-4 h-4" />
+ View Full Report
+ </button>
+ )}
+ </div>
+ </div>
+ );
+ };
+
+ return (
+ <div className="flex flex-col h-full bg-slate-50/50 dark:bg-slate-900/50">
+ {/* Top Bar: Progress & Global Status */}
+ <div className="bg-white dark:bg-slate-800 border-b border-slate-200 dark:border-slate-700 px-6 py-4 flex items-center justify-between shadow-sm shrink-0 z-20 relative">
+ <div className="flex items-center gap-4">
+ <div
+ className={`p-2 rounded-lg ${
+ global.stage === "idle"
+ ? "bg-slate-100 dark:bg-slate-700 text-slate-400 dark:text-slate-500"
+ : global.stage === "completed"
+ ? "bg-emerald-100 dark:bg-emerald-900/40 text-emerald-600 dark:text-emerald-400"
+ : "bg-indigo-100 dark:bg-indigo-900/40 text-indigo-600 dark:text-indigo-400"
+ }`}
+ >
+ {isCompleted ? (
+ <CheckCircle2 className="w-5 h-5" />
+ ) : (
+ <LayoutDashboard className="w-5 h-5" />
+ )}
+ </div>
+ <div>
+ <h2 className="text-lg font-bold text-slate-800 dark:text-slate-100">
+ {global.stage === "idle"
+ ? "Ready to Research"
+ : global.stage === "completed"
+ ? "Research Complete"
+ : planning.optimizedTopic ||
+ planning.originalTopic ||
+ "Research Dashboard"}
+ </h2>
+ <div className="flex items-center gap-2 text-xs text-slate-500 dark:text-slate-400 mt-0.5">
+ <span
+ className={`uppercase font-bold tracking-wider ${isCompleted ? "text-emerald-600 dark:text-emerald-400" : ""}`}
+ >
+ {global.stage}
+ </span>
+ {global.totalBlocks > 0 && (
+ <>
+ <span>•</span>
+ <span>
+ {global.completedBlocks} / {global.totalBlocks} topics
+ completed
+ </span>
+ </>
+ )}
+ {state.executionMode === "parallel" && (
+ <>
+ <span>•</span>
+ <span className="text-violet-600 dark:text-violet-400 font-medium">
+ Parallel Mode
+ </span>
+ </>
+ )}
+ </div>
+ </div>
+ </div>
+
+ {/* View Switcher */}
+ <div className="flex bg-slate-100 dark:bg-slate-700 p-1 rounded-lg border border-slate-200 dark:border-slate-600">
+ <button
+ onClick={() => setActiveView("process")}
+ className={`flex items-center gap-2 px-4 py-1.5 rounded-md text-sm font-medium transition-all ${
+ activeView === "process"
+ ? "bg-white dark:bg-slate-600 text-indigo-600 dark:text-indigo-300 shadow-sm border border-slate-100 dark:border-slate-500"
+ : "text-slate-500 dark:text-slate-400 hover:text-slate-700 dark:hover:text-slate-200"
+ }`}
+ >
+ <BarChart3 className="w-4 h-4" />
+ Process
+ </button>
+ <button
+ onClick={() => setActiveView("report")}
+ disabled={
+ !reporting.generatedReport && global.stage !== "completed"
+ }
+ className={`flex items-center gap-2 px-4 py-1.5 rounded-md text-sm font-medium transition-all ${
+ activeView === "report"
+ ? "bg-white dark:bg-slate-600 text-indigo-600 dark:text-indigo-300 shadow-sm border border-slate-100 dark:border-slate-500"
+ : !reporting.generatedReport && global.stage !== "completed"
+ ? "text-slate-300 dark:text-slate-600 cursor-not-allowed"
+ : "text-slate-500 dark:text-slate-400 hover:text-slate-700 dark:hover:text-slate-200"
+ }`}
+ >
+ <FileOutput className="w-4 h-4" />
+ Report
+ </button>
+ </div>
+ </div>
+
+ {/* Main Content Area */}
+ {activeView === "process" ? (
+ <div className="flex-1 flex flex-col min-h-0 overflow-hidden">
+ {/* Idle State */}
+ {global.stage === "idle" ? (
+ <div className="flex-1 flex items-center justify-center p-6">
+ <div className="bg-white dark:bg-slate-800 rounded-xl border border-slate-200 dark:border-slate-700 shadow-sm p-8 flex flex-col items-center justify-center text-center max-w-lg w-full">
+ <div className="w-16 h-16 bg-slate-100 dark:bg-slate-700 rounded-full flex items-center justify-center mb-4">
+ <Search className="w-8 h-8 text-slate-400 dark:text-slate-500" />
+ </div>
+ <h3 className="text-lg font-semibold text-slate-800 dark:text-slate-100 mb-2">
+ Ready to Research
+ </h3>
+ <p className="text-slate-500 dark:text-slate-400 text-sm">
+ Enter a topic in the left panel to start deep research.
+ </p>
+ </div>
+ </div>
+ ) : (
+ <>
+ {/* Step Tabs */}
+ <div className="px-6 pt-4 pb-2 flex justify-center shrink-0">
+ <StepTabs />
+ </div>
+
+ {/* Tab Content */}
+ <div className="flex-1 overflow-hidden p-6 flex flex-col">
+ {activeProcessTab === "planning" && <PlanningContent />}
+ {activeProcessTab === "researching" && <ResearchingContent />}
+ {activeProcessTab === "reporting" && <ReportingContent />}
+ </div>
+ </>
+ )}
+ </div>
+ ) : (
+ <div className="flex-1 flex flex-col min-h-0 overflow-hidden">
+ {/* Report Toolbar */}
+ <div className="px-6 py-3 border-b border-slate-100 dark:border-slate-700 flex justify-end items-center bg-white dark:bg-slate-800 shrink-0">
+ <div className="flex gap-2">
+ {onAddToNotebook && (
+ <button
+ onClick={onAddToNotebook}
+ className="text-indigo-600 dark:text-indigo-400 hover:text-indigo-700 dark:hover:text-indigo-300 flex items-center gap-1.5 text-sm px-3 py-1.5 rounded-lg hover:bg-indigo-50 dark:hover:bg-indigo-900/30 transition-all"
+ >
+ <Book className="w-4 h-4" /> Add to Notebook
+ </button>
+ )}
+ {onExportMarkdown && (
+ <button
+ onClick={onExportMarkdown}
+ className="text-slate-500 dark:text-slate-400 hover:text-slate-700 dark:hover:text-slate-200 flex items-center gap-1.5 text-sm px-3 py-1.5 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-700 transition-all"
+ >
+ <Download className="w-4 h-4" /> Markdown
+ </button>
+ )}
+ {onExportPdf && (
+ <button
+ onClick={onExportPdf}
+ disabled={isExportingPdf}
+ className="text-slate-500 dark:text-slate-400 hover:text-slate-700 dark:hover:text-slate-200 flex items-center gap-1.5 text-sm px-3 py-1.5 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-700 transition-all disabled:opacity-50"
+ >
+ {isExportingPdf ? (
+ <Loader2 className="w-4 h-4 animate-spin" />
+ ) : (
+ <FileDown className="w-4 h-4" />
+ )}{" "}
+ PDF
+ </button>
+ )}
+ </div>
+ </div>
+
+ {/* Report Content */}
+ <div
+ className="flex-1 overflow-y-auto bg-slate-50/30 dark:bg-slate-900/30 p-8"
+ id="report-scroll-container"
+ >
+ <div className="max-w-4xl mx-auto bg-white dark:bg-slate-800 rounded-xl shadow-sm border border-slate-200 dark:border-slate-700 p-12 min-h-[500px]">
+ {reporting.generatedReport ? (
+ <article className="prose prose-slate dark:prose-invert max-w-none prose-headings:text-slate-800 dark:prose-headings:text-slate-100 prose-p:text-slate-600 dark:prose-p:text-slate-300 prose-a:text-indigo-600 dark:prose-a:text-indigo-400 prose-img:rounded-xl prose-table:border-collapse prose-th:border prose-th:border-slate-300 dark:prose-th:border-slate-600 prose-th:bg-slate-50 dark:prose-th:bg-slate-700 prose-th:p-2 prose-td:border prose-td:border-slate-200 dark:prose-td:border-slate-600 prose-td:p-2">
+ {/* Add scroll-margin-top style for anchor targets */}
+ <style>{`
+ [id^="ref-"] { scroll-margin-top: 20px; }
+ `}</style>
+ <ReactMarkdown
+ remarkPlugins={[remarkGfm, remarkMath]}
+ rehypePlugins={[rehypeKatex, rehypeRaw]}
+ components={{
+ h1: ({ node, ...props }) => (
+ <h1
+ className="text-3xl font-bold mb-6 pb-2 border-b border-slate-200 dark:border-slate-700"
+ {...props}
+ />
+ ),
+ h2: ({ node, ...props }) => (
+ <h2
+ className="text-2xl font-bold mt-8 mb-4 text-indigo-900 dark:text-indigo-300"
+ {...props}
+ />
+ ),
+ h3: ({ node, ...props }) => (
+ <h3
+ className="text-xl font-semibold mt-6 mb-3 text-slate-800 dark:text-slate-200"
+ {...props}
+ />
+ ),
+ p: ({ node, ...props }) => (
+ <p
+ className="leading-relaxed mb-4 text-slate-600 dark:text-slate-300"
+ {...props}
+ />
+ ),
+ li: ({ node, ...props }) => (
+ <li className="mb-2" {...props} />
+ ),
+ table: ({ node, ...props }) => (
+ <div className="overflow-x-auto my-6">
+ <table
+ className="min-w-full border-collapse border border-slate-300 dark:border-slate-600 text-sm"
+ {...props}
+ />
+ </div>
+ ),
+ thead: ({ node, ...props }) => (
+ <thead
+ className="bg-slate-50 dark:bg-slate-700"
+ {...props}
+ />
+ ),
+ th: ({ node, ...props }) => (
+ <th
+ className="border border-slate-300 dark:border-slate-600 px-4 py-2 text-left font-semibold text-slate-700 dark:text-slate-200"
+ {...props}
+ />
+ ),
+ td: ({ node, ...props }) => (
+ <td
+ className="border border-slate-200 dark:border-slate-600 px-4 py-2 text-slate-600 dark:text-slate-300"
+ {...props}
+ />
+ ),
+ blockquote: ({ node, ...props }) => (
+ <blockquote
+ className="border-l-4 border-indigo-300 dark:border-indigo-600 pl-4 py-2 my-4 bg-indigo-50/50 dark:bg-indigo-900/30 text-slate-600 dark:text-slate-300 italic"
+ {...props}
+ />
+ ),
+ a: ({ node, href, ...props }) => {
+ // Handle internal anchor links for smooth scrolling within the container
+ const handleClick = (
+ e: React.MouseEvent<HTMLAnchorElement>,
+ ) => {
+ if (href?.startsWith("#")) {
+ e.preventDefault();
+ const targetId = href.slice(1);
+ const targetElement =
+ document.getElementById(targetId);
+ const scrollContainer = document.getElementById(
+ "report-scroll-container",
+ );
+ if (targetElement && scrollContainer) {
+ // Calculate scroll position within the container
+ const containerRect =
+ scrollContainer.getBoundingClientRect();
+ const targetRect =
+ targetElement.getBoundingClientRect();
+ const offset =
+ targetRect.top -
+ containerRect.top +
+ scrollContainer.scrollTop -
+ 20;
+ scrollContainer.scrollTo({
+ top: offset,
+ behavior: "smooth",
+ });
+ }
+ }
+ };
+ return (
+ <a
+ href={href}
+ onClick={handleClick}
+ className="text-indigo-600 dark:text-indigo-400 hover:text-indigo-800 dark:hover:text-indigo-300 underline decoration-indigo-300 dark:decoration-indigo-600 hover:decoration-indigo-500 dark:hover:decoration-indigo-400"
+ {...props}
+ />
+ );
+ },
+ code: ({ node, className, children, ...props }) => {
+ const match = /language-(\w+)/.exec(className || "");
+ const language = match ? match[1] : "";
+ const isInline = !match;
+
+ // Handle Mermaid diagrams
+ if (language === "mermaid") {
+ const chartCode = String(children).replace(/\n$/, "");
+ return <Mermaid chart={chartCode} />;
+ }
+
+ return isInline ? (
+ <code
+ className="bg-slate-100 dark:bg-slate-700 text-slate-800 dark:text-slate-200 px-1.5 py-0.5 rounded text-sm font-mono"
+ {...props}
+ >
+ {children}
+ </code>
+ ) : (
+ <code
+ className={`${className} block bg-slate-900 text-slate-100 p-4 rounded-lg overflow-x-auto text-sm`}
+ {...props}
+ >
+ {children}
+ </code>
+ );
+ },
+ pre: ({ node, children, ...props }) => {
+ // Check if this pre contains a mermaid code block
+ const child = React.Children.toArray(
+ children,
+ )[0] as React.ReactElement;
+ if (
+ child?.props?.className?.includes("language-mermaid")
+ ) {
+ // Mermaid is rendered by the code component, so just return children without pre wrapper
+ return <>{children}</>;
+ }
+ return (
+ <pre
+ className="bg-slate-900 rounded-lg overflow-hidden my-4"
+ {...props}
+ >
+ {children}
+ </pre>
+ );
+ },
+ }}
+ >
+ {reporting.generatedReport}
+ </ReactMarkdown>
+ </article>
+ ) : (
+ <div className="flex flex-col items-center justify-center h-64 text-slate-400 dark:text-slate-500">
+ <Loader2 className="w-8 h-8 mb-4 animate-spin opacity-50" />
+ <p>Generating report preview...</p>
+ </div>
+ )}
+ </div>
+ </div>
+ </div>
+ )}
+ </div>
+ );
+};
diff --git a/web/components/research/TaskGrid.tsx b/web/components/research/TaskGrid.tsx
new file mode 100644
index 000000000..f8477a356
--- /dev/null
+++ b/web/components/research/TaskGrid.tsx
@@ -0,0 +1,192 @@
+import React from "react";
+import { TaskState } from "../../types/research";
+import {
+ CheckCircle2,
+ Loader2,
+ Clock,
+ AlertCircle,
+ Database,
+ Globe,
+ GraduationCap,
+ Code,
+ FileSearch,
+ Activity,
+} from "lucide-react";
+
+interface TaskGridProps {
+ tasks: Record<string, TaskState>;
+ activeTaskIds: string[];
+ selectedTaskId: string | null;
+ onTaskSelect: (taskId: string) => void;
+}
+
+const getStatusIcon = (status: TaskState["status"]) => {
+ switch (status) {
+ case "completed":
+ return (
+ <CheckCircle2 className="w-4 h-4 text-emerald-500 dark:text-emerald-400" />
+ );
+ case "running":
+ return (
+ <Loader2 className="w-4 h-4 text-indigo-500 dark:text-indigo-400 animate-spin" />
+ );
+ case "failed":
+ return <AlertCircle className="w-4 h-4 text-red-500 dark:text-red-400" />;
+ default:
+ return <Clock className="w-4 h-4 text-slate-400 dark:text-slate-500" />;
+ }
+};
+
+const getToolIcon = (toolName: string) => {
+ if (toolName.includes("rag"))
+ return <Database className="w-3 h-3 text-blue-500 dark:text-blue-400" />;
+ if (toolName.includes("web"))
+ return <Globe className="w-3 h-3 text-green-500 dark:text-green-400" />;
+ if (toolName.includes("paper"))
+ return (
+ <GraduationCap className="w-3 h-3 text-purple-500 dark:text-purple-400" />
+ );
+ if (toolName.includes("code"))
+ return <Code className="w-3 h-3 text-orange-500 dark:text-orange-400" />;
+ return <FileSearch className="w-3 h-3 text-slate-500 dark:text-slate-400" />;
+};
+
+export const TaskGrid: React.FC<TaskGridProps> = ({
+ tasks,
+ activeTaskIds,
+ selectedTaskId,
+ onTaskSelect,
+}) => {
+ // Sort tasks: Active first, then running, then pending, then completed/failed
+ const sortedTasks = Object.values(tasks).sort((a, b) => {
+ const score = (task: TaskState) => {
+ if (activeTaskIds.includes(task.id)) return 4;
+ if (task.status === "running") return 3;
+ if (task.status === "pending") return 2;
+ return 1;
+ };
+ return score(b) - score(a);
+ });
+
+ if (sortedTasks.length === 0) {
+ return (
+ <div className="flex flex-col items-center justify-center p-8 text-slate-400 dark:text-slate-500 border-2 border-dashed border-slate-200 dark:border-slate-700 rounded-xl">
+ <Activity className="w-8 h-8 mb-2 opacity-50" />
+ <p className="text-sm">No tasks initialized yet</p>
+ </div>
+ );
+ }
+
+ return (
+ <div className="grid grid-cols-1 xl:grid-cols-2 gap-4">
+ {sortedTasks.map((task) => {
+ const isActive = activeTaskIds.includes(task.id);
+ const isSelected = selectedTaskId === task.id;
+
+ return (
+ <div
+ key={task.id}
+ onClick={() => onTaskSelect(task.id)}
+ className={`
+ relative p-4 rounded-xl border cursor-pointer transition-all duration-200
+ hover:shadow-md flex flex-col gap-3
+ ${
+ isSelected
+ ? "bg-indigo-50/50 dark:bg-indigo-900/30 border-indigo-500 ring-1 ring-indigo-500"
+ : "bg-white dark:bg-slate-800 border-slate-200 dark:border-slate-700 hover:border-indigo-300 dark:hover:border-indigo-600"
+ }
+ ${isActive ? "shadow-sm" : "opacity-90"}
+ `}
+ >
+ {/* Active Indicator Pulse */}
+ {isActive && (
+ <div className="absolute top-4 right-4 flex h-2 w-2">
+ <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-indigo-400 opacity-75"></span>
+ <span className="relative inline-flex rounded-full h-2 w-2 bg-indigo-500"></span>
+ </div>
+ )}
+
+ <div className="flex items-start gap-3">
+ <div
+ className={`p-2 rounded-lg shrink-0 ${
+ task.status === "completed"
+ ? "bg-emerald-50 dark:bg-emerald-900/40"
+ : task.status === "failed"
+ ? "bg-red-50 dark:bg-red-900/40"
+ : isActive
+ ? "bg-indigo-50 dark:bg-indigo-900/40"
+ : "bg-slate-100 dark:bg-slate-700"
+ }`}
+ >
+ {getStatusIcon(task.status)}
+ </div>
+ <div className="flex-1 min-w-0">
+ <div className="flex items-start justify-between gap-2">
+ <h4
+ className="text-sm font-semibold text-slate-800 dark:text-slate-100 line-clamp-1 pr-4"
+ title={task.topic}
+ >
+ {task.topic}
+ </h4>
+ </div>
+ <div className="flex items-center gap-2 mt-1.5 flex-wrap">
+ <span
+ className={`text-[10px] px-2 py-0.5 rounded-full font-medium uppercase tracking-wide shrink-0 ${
+ task.status === "completed"
+ ? "bg-emerald-100 dark:bg-emerald-900/50 text-emerald-700 dark:text-emerald-300"
+ : task.status === "failed"
+ ? "bg-red-100 dark:bg-red-900/50 text-red-700 dark:text-red-300"
+ : task.status === "running"
+ ? "bg-indigo-100 dark:bg-indigo-900/50 text-indigo-700 dark:text-indigo-300"
+ : "bg-slate-100 dark:bg-slate-700 text-slate-600 dark:text-slate-400"
+ }`}
+ >
+ {task.status}
+ </span>
+ {task.maxIterations > 0 && (
+ <span className="text-[10px] text-slate-400 dark:text-slate-500 font-medium whitespace-nowrap shrink-0">
+ {task.iteration}/{task.maxIterations}
+ </span>
+ )}
+ </div>
+ </div>
+ </div>
+
+ {/* Current Action / Summary */}
+ <div className="bg-slate-50 dark:bg-slate-700 rounded-lg p-2.5 min-h-[48px] border border-slate-100 dark:border-slate-600">
+ <p className="text-xs text-slate-600 dark:text-slate-300 line-clamp-2 leading-relaxed">
+ <span className="font-medium text-slate-400 dark:text-slate-500 mr-1">
+ Current Action:
+ </span>
+ {task.currentAction || "Waiting to start..."}
+ </p>
+ </div>
+
+ {/* Tools Used Footer */}
+ {task.toolsUsed.length > 0 && (
+ <div className="flex items-center gap-1.5 overflow-hidden">
+ <span className="text-[10px] text-slate-400 dark:text-slate-500 uppercase font-medium mr-1">
+ Tools:
+ </span>
+ {task.toolsUsed.slice(0, 5).map((tool, idx) => (
+ <div
+ key={idx}
+ className="p-1.5 bg-white dark:bg-slate-700 rounded-md border border-slate-200 dark:border-slate-600 shadow-sm"
+ title={tool}
+ >
+ {getToolIcon(tool)}
+ </div>
+ ))}
+ {task.toolsUsed.length > 5 && (
+ <span className="text-[10px] text-slate-400 dark:text-slate-500 ml-1 font-medium">
+ +{task.toolsUsed.length - 5}
+ </span>
+ )}
+ </div>
+ )}
+ </div>
+ );
+ })}
+ </div>
+ );
+};
diff --git a/web/components/ui/Button.tsx b/web/components/ui/Button.tsx
new file mode 100644
index 000000000..2888bd264
--- /dev/null
+++ b/web/components/ui/Button.tsx
@@ -0,0 +1,58 @@
+"use client";
+
+import React from "react";
+import { Loader2 } from "lucide-react";
+
+interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {
+ variant?: "primary" | "secondary" | "danger" | "ghost";
+ size?: "sm" | "md" | "lg";
+ loading?: boolean;
+ icon?: React.ReactNode;
+ children: React.ReactNode;
+}
+
+const variantStyles = {
+ primary:
+ "bg-indigo-600 text-white hover:bg-indigo-700 shadow-md shadow-indigo-500/20",
+ secondary: "bg-slate-100 text-slate-700 hover:bg-slate-200",
+ danger: "bg-red-600 text-white hover:bg-red-700 shadow-md shadow-red-500/20",
+ ghost: "text-slate-600 hover:bg-slate-100",
+};
+
+const sizeStyles = {
+ sm: "px-3 py-1.5 text-xs",
+ md: "px-4 py-2 text-sm",
+ lg: "px-6 py-3 text-base",
+};
+
+export default function Button({
+ variant = "primary",
+ size = "md",
+ loading = false,
+ icon,
+ children,
+ className = "",
+ disabled,
+ ...props
+}: ButtonProps) {
+ return (
+ <button
+ className={`
+ inline-flex items-center justify-center gap-2 font-medium rounded-lg transition-all
+ disabled:opacity-50 disabled:cursor-not-allowed
+ ${variantStyles[variant]}
+ ${sizeStyles[size]}
+ ${className}
+ `}
+ disabled={disabled || loading}
+ {...props}
+ >
+ {loading ? (
+ <Loader2 className="w-4 h-4 animate-spin" />
+ ) : icon ? (
+ icon
+ ) : null}
+ {children}
+ </button>
+ );
+}
diff --git a/web/components/ui/Modal.tsx b/web/components/ui/Modal.tsx
new file mode 100644
index 000000000..23ff271cf
--- /dev/null
+++ b/web/components/ui/Modal.tsx
@@ -0,0 +1,85 @@
+"use client";
+
+import React, { useEffect } from "react";
+import { X } from "lucide-react";
+
+interface ModalProps {
+ isOpen: boolean;
+ onClose: () => void;
+ title?: string;
+ children: React.ReactNode;
+ size?: "sm" | "md" | "lg" | "xl";
+ showCloseButton?: boolean;
+}
+
+const sizeStyles = {
+ sm: "max-w-sm",
+ md: "max-w-md",
+ lg: "max-w-lg",
+ xl: "max-w-xl",
+};
+
+export default function Modal({
+ isOpen,
+ onClose,
+ title,
+ children,
+ size = "md",
+ showCloseButton = true,
+}: ModalProps) {
+ // Close on escape key
+ useEffect(() => {
+ const handleEscape = (e: KeyboardEvent) => {
+ if (e.key === "Escape") onClose();
+ };
+
+ if (isOpen) {
+ document.addEventListener("keydown", handleEscape);
+ document.body.style.overflow = "hidden";
+ }
+
+ return () => {
+ document.removeEventListener("keydown", handleEscape);
+ document.body.style.overflow = "unset";
+ };
+ }, [isOpen, onClose]);
+
+ if (!isOpen) return null;
+
+ return (
+ <div className="fixed inset-0 z-50 flex items-center justify-center">
+ {/* Backdrop */}
+ <div
+ className="absolute inset-0 bg-black/50 animate-in fade-in"
+ onClick={onClose}
+ />
+
+ {/* Modal Content */}
+ <div
+ className={`
+ relative bg-white rounded-2xl shadow-2xl w-full mx-4
+ animate-in zoom-in-95 fade-in
+ ${sizeStyles[size]}
+ `}
+ >
+ {/* Header */}
+ {(title || showCloseButton) && (
+ <div className="flex items-center justify-between p-4 border-b border-slate-100">
+ {title && <h3 className="font-bold text-slate-900">{title}</h3>}
+ {showCloseButton && (
+ <button
+ onClick={onClose}
+ className="p-1 hover:bg-slate-100 rounded-lg transition-colors ml-auto"
+ >
+ <X className="w-5 h-5 text-slate-500" />
+ </button>
+ )}
+ </div>
+ )}
+
+ {/* Body */}
+ {children}
+ </div>
+ </div>
+ );
+}
diff --git a/web/components/ui/index.ts b/web/components/ui/index.ts
new file mode 100644
index 000000000..a85e8a039
--- /dev/null
+++ b/web/components/ui/index.ts
@@ -0,0 +1,7 @@
+/**
+ * UI Component Export Index
+ * Basic UI Component Library
+ */
+
+export { default as Button } from "./Button";
+export { default as Modal } from "./Modal";
diff --git a/web/context/GlobalContext.tsx b/web/context/GlobalContext.tsx
new file mode 100644
index 000000000..ec6c7b365
--- /dev/null
+++ b/web/context/GlobalContext.tsx
@@ -0,0 +1,1340 @@
+"use client";
+
+import React, {
+ createContext,
+ useContext,
+ useRef,
+ useState,
+ useEffect,
+} from "react";
+import { wsUrl, apiUrl } from "@/lib/api";
+
+// --- Types ---
+interface LogEntry {
+ type: string;
+ content: string;
+ timestamp?: number;
+ level?: string;
+}
+
+interface ChatMessage {
+ role: "user" | "assistant";
+ content: string;
+ outputDir?: string;
+}
+
+// Agent Status
+interface AgentStatus {
+ [key: string]: "pending" | "running" | "done" | "error";
+}
+
+// Token Stats
+interface TokenStats {
+ model: string;
+ calls: number;
+ tokens: number;
+ input_tokens: number;
+ output_tokens: number;
+ cost: number;
+}
+
+// Progress Info
+interface ProgressInfo {
+ stage: "investigate" | "solve" | "response" | null;
+ progress: {
+ round?: number;
+ queries?: string[];
+ step_index?: number;
+ step_id?: string;
+ step_target?: string;
+ };
+}
+
+// Solver State
+interface SolverState {
+ isSolving: boolean;
+ logs: LogEntry[];
+ messages: ChatMessage[];
+ question: string;
+ selectedKb: string;
+ agentStatus: AgentStatus;
+ tokenStats: TokenStats;
+ progress: ProgressInfo;
+}
+
+// Question Progress Info
+interface QuestionProgressInfo {
+ stage:
+ | "planning"
+ | "researching"
+ | "generating"
+ | "validating"
+ | "complete"
+ // Mimic mode stages
+ | "uploading"
+ | "parsing"
+ | "extracting"
+ | null;
+ progress: {
+ current?: number;
+ total?: number;
+ round?: number;
+ max_rounds?: number;
+ status?: string;
+ };
+ // Parallel generation info
+ subFocuses?: Array<{ id: string; focus: string; scenario_hint?: string }>;
+ activeQuestions?: string[];
+ completedQuestions?: number;
+ failedQuestions?: number;
+ extendedQuestions?: number; // Count of extended questions
+}
+
+// Question Agent Status
+interface QuestionAgentStatus {
+ [key: string]: "pending" | "running" | "done" | "error";
+}
+
+// Question Token Stats
+interface QuestionTokenStats {
+ model: string;
+ calls: number;
+ tokens: number;
+ input_tokens: number;
+ output_tokens: number;
+ cost: number;
+}
+
+// Question State
+interface QuestionState {
+ step: "config" | "generating" | "result";
+ mode: "knowledge" | "mimic"; // Two modes: KB-based generation vs upload exam mimic
+ logs: LogEntry[];
+ results: any[]; // Array of QuestionResult
+ topic: string;
+ difficulty: string;
+ type: string;
+ count: number;
+ selectedKb: string;
+ progress: QuestionProgressInfo;
+ agentStatus: QuestionAgentStatus;
+ tokenStats: QuestionTokenStats;
+ // Upload exam mode related
+ uploadedFile: File | null;
+ paperPath: string;
+}
+
+// Active Task Info (for parallel mode)
+interface ActiveTaskInfo {
+ block_id: string;
+ sub_topic: string;
+ status: string;
+ iteration: number;
+ max_iterations?: number;
+ current_tool?: string;
+ current_query?: string;
+ tools_used?: string[];
+}
+
+// Query Info (for tracking all queries)
+interface QueryInfo {
+ query: string;
+ tool_type: string;
+ rationale?: string;
+ iteration: number;
+}
+
+// Research Progress
+interface ResearchProgress {
+ stage: "planning" | "researching" | "reporting" | null;
+ status: string;
+ // Execution mode
+ executionMode?: "series" | "parallel";
+ // Planning details
+ totalBlocks?: number;
+ // Researching details
+ currentBlock?: number;
+ currentSubTopic?: string;
+ currentBlockId?: string;
+ iterations?: number;
+ maxIterations?: number;
+ toolsUsed?: string[];
+ // Current action details (for real-time display)
+ currentTool?: string;
+ currentQuery?: string;
+ currentRationale?: string;
+ queriesUsed?: QueryInfo[];
+ // Parallel mode specific
+ activeTasks?: ActiveTaskInfo[];
+ activeCount?: number;
+ completedCount?: number;
+ // Reporting details
+ keptBlocks?: number;
+ sections?: number;
+ wordCount?: number;
+ citations?: number;
+}
+
+// Research State
+interface ResearchState {
+ status: "idle" | "running" | "completed";
+ logs: LogEntry[];
+ report: string | null;
+ topic: string;
+ selectedKb: string;
+ progress: ResearchProgress;
+}
+
+// IdeaGen Types
+interface ResearchIdea {
+ id: string;
+ knowledge_point: string;
+ description: string;
+ research_ideas: string[];
+ statement: string;
+ expanded: boolean;
+ selected: boolean;
+}
+
+interface IdeaGenState {
+ isGenerating: boolean;
+ generationStatus: string;
+ generatedIdeas: ResearchIdea[];
+ progress: { current: number; total: number } | null;
+}
+
+interface GlobalContextType {
+ // Solver
+ solverState: SolverState;
+ setSolverState: React.Dispatch<React.SetStateAction<SolverState>>;
+ startSolver: (question: string, kb: string) => void;
+
+ // Question
+ questionState: QuestionState;
+ setQuestionState: React.Dispatch<React.SetStateAction<QuestionState>>;
+ startQuestionGen: (
+ topic: string,
+ diff: string,
+ type: string,
+ count: number,
+ kb: string,
+ ) => void;
+ startMimicQuestionGen: (
+ file: File | null,
+ paperPath: string,
+ kb: string,
+ maxQuestions?: number,
+ ) => void;
+ resetQuestionGen: () => void;
+
+ // Research
+ researchState: ResearchState;
+ setResearchState: React.Dispatch<React.SetStateAction<ResearchState>>;
+ startResearch: (
+ topic: string,
+ kb: string,
+ planMode?: string,
+ enabledTools?: string[],
+ skipRephrase?: boolean,
+ ) => void;
+
+ // IdeaGen
+ ideaGenState: IdeaGenState;
+ setIdeaGenState: React.Dispatch<React.SetStateAction<IdeaGenState>>;
+
+ // UI Settings
+ uiSettings: { theme: "light" | "dark"; language: "en" | "zh" };
+ refreshSettings: () => Promise<void>;
+}
+
+const GlobalContext = createContext<GlobalContextType | undefined>(undefined);
+
+export function GlobalProvider({ children }: { children: React.ReactNode }) {
+ // --- UI Settings Logic ---
+ const [uiSettings, setUiSettings] = useState<{
+ theme: "light" | "dark";
+ language: "en" | "zh";
+ }>({ theme: "light", language: "en" });
+
+ const refreshSettings = async () => {
+ try {
+ const res = await fetch(apiUrl("/api/v1/settings"));
+ if (res.ok) {
+ const data = await res.json();
+ if (data.ui) {
+ setUiSettings({
+ theme: data.ui.theme,
+ language: data.ui.language,
+ });
+ // Apply theme immediately
+ if (data.ui.theme === "dark") {
+ document.documentElement.classList.add("dark");
+ } else {
+ document.documentElement.classList.remove("dark");
+ }
+ }
+ }
+ } catch (e) {
+ console.error("Failed to load settings", e);
+ }
+ };
+
+ useEffect(() => {
+ refreshSettings();
+ }, []);
+
+ // --- Solver Logic ---
+ const [solverState, setSolverState] = useState<SolverState>({
+ isSolving: false,
+ logs: [],
+ messages: [],
+ question: "",
+ selectedKb: "",
+ agentStatus: {
+ InvestigateAgent: "pending",
+ NoteAgent: "pending",
+ ManagerAgent: "pending",
+ SolveAgent: "pending",
+ ToolAgent: "pending",
+ ResponseAgent: "pending",
+ PrecisionAnswerAgent: "pending",
+ },
+ tokenStats: {
+ model: "Unknown",
+ calls: 0,
+ tokens: 0,
+ input_tokens: 0,
+ output_tokens: 0,
+ cost: 0.0,
+ },
+ progress: {
+ stage: null,
+ progress: {},
+ },
+ });
+ const solverWs = useRef<WebSocket | null>(null);
+
+ const startSolver = (question: string, kb: string) => {
+ if (solverWs.current) solverWs.current.close();
+
+ setSolverState((prev) => ({
+ ...prev,
+ isSolving: true,
+ logs: [],
+ messages: [...prev.messages, { role: "user", content: question }],
+ question,
+ selectedKb: kb,
+ agentStatus: {
+ InvestigateAgent: "pending",
+ NoteAgent: "pending",
+ ManagerAgent: "pending",
+ SolveAgent: "pending",
+ ToolAgent: "pending",
+ ResponseAgent: "pending",
+ PrecisionAnswerAgent: "pending",
+ },
+ tokenStats: {
+ model: "Unknown",
+ calls: 0,
+ tokens: 0,
+ input_tokens: 0,
+ output_tokens: 0,
+ cost: 0.0,
+ },
+ progress: {
+ stage: null,
+ progress: {},
+ },
+ }));
+
+ const ws = new WebSocket(wsUrl("/api/v1/solve"));
+ solverWs.current = ws;
+
+ ws.onopen = () => {
+ ws.send(JSON.stringify({ question, kb_name: kb }));
+ addSolverLog({ type: "system", content: "Initializing connection..." });
+ };
+
+ ws.onmessage = (event) => {
+ const data = JSON.parse(event.data);
+ if (data.type === "log") {
+ addSolverLog(data);
+ } else if (data.type === "agent_status") {
+ setSolverState((prev) => ({
+ ...prev,
+ agentStatus: data.all_agents || {
+ ...prev.agentStatus,
+ [data.agent]: data.status,
+ },
+ }));
+ } else if (data.type === "token_stats") {
+ setSolverState((prev) => ({
+ ...prev,
+ tokenStats: data.stats || prev.tokenStats,
+ }));
+ } else if (data.type === "progress") {
+ setSolverState((prev) => ({
+ ...prev,
+ progress: {
+ stage: data.stage,
+ progress: data.progress || {},
+ },
+ }));
+ } else if (data.type === "result") {
+ // Extract relative path from output_dir if possible, or just store the full path name
+ // data.output_dir is likely absolute path on server.
+ // We need the directory name to construct URL: /api/outputs/solve/{dir_name}/...
+ // Assuming output_dir ends with "solve_YYYYMMDD_HHMMSS"
+ let dirName = "";
+ if (data.output_dir) {
+ const parts = data.output_dir.split(/[/\\]/);
+ dirName = parts[parts.length - 1];
+ }
+
+ setSolverState((prev) => ({
+ ...prev,
+ messages: [
+ ...prev.messages,
+ {
+ role: "assistant",
+ content: data.final_answer,
+ outputDir: dirName,
+ },
+ ],
+ isSolving: false,
+ }));
+ ws.close();
+ } else if (data.type === "error") {
+ addSolverLog({
+ type: "error",
+ content: `Error: ${data.content || data.message || "Unknown error"}`,
+ });
+ setSolverState((prev) => ({ ...prev, isSolving: false }));
+ }
+ };
+
+ ws.onerror = () => {
+ addSolverLog({ type: "error", content: "Connection error" });
+ setSolverState((prev) => ({
+ ...prev,
+ isSolving: false,
+ agentStatus: {
+ InvestigateAgent: "error",
+ NoteAgent: "error",
+ ManagerAgent: "error",
+ SolveAgent: "error",
+ ToolAgent: "error",
+ ResponseAgent: "error",
+ PrecisionAnswerAgent: "error",
+ },
+ progress: {
+ stage: null,
+ progress: {},
+ },
+ }));
+ };
+
+ ws.onclose = () => {
+ // Clean up WebSocket reference on close
+ if (solverWs.current === ws) {
+ solverWs.current = null;
+ }
+ };
+ };
+
+ const addSolverLog = (log: LogEntry) => {
+ setSolverState((prev) => ({ ...prev, logs: [...prev.logs, log] }));
+ };
+
+ // --- Question Logic ---
+ const [questionState, setQuestionState] = useState<QuestionState>({
+ step: "config",
+ mode: "knowledge",
+ logs: [],
+ results: [],
+ topic: "",
+ difficulty: "medium",
+ type: "choice",
+ count: 1,
+ selectedKb: "",
+ progress: {
+ stage: null,
+ progress: {},
+ subFocuses: [],
+ activeQuestions: [],
+ completedQuestions: 0,
+ failedQuestions: 0,
+ },
+ agentStatus: {
+ QuestionGenerationAgent: "pending",
+ ValidationWorkflow: "pending",
+ RetrievalTool: "pending",
+ },
+ tokenStats: {
+ model: "Unknown",
+ calls: 0,
+ tokens: 0,
+ input_tokens: 0,
+ output_tokens: 0,
+ cost: 0.0,
+ },
+ uploadedFile: null,
+ paperPath: "",
+ });
+ const questionWs = useRef<WebSocket | null>(null);
+
+ const startQuestionGen = (
+ topic: string,
+ diff: string,
+ type: string,
+ count: number,
+ kb: string,
+ ) => {
+ if (questionWs.current) questionWs.current.close();
+
+ setQuestionState((prev) => ({
+ ...prev,
+ step: "generating",
+ mode: "knowledge",
+ logs: [],
+ results: [],
+ topic,
+ difficulty: diff,
+ type,
+ count,
+ selectedKb: kb,
+ progress: {
+ stage: count > 1 ? "planning" : "generating",
+ progress: { current: 0, total: count },
+ subFocuses: [],
+ activeQuestions: [],
+ completedQuestions: 0,
+ failedQuestions: 0,
+ },
+ agentStatus: {
+ QuestionGenerationAgent: "pending",
+ ValidationWorkflow: "pending",
+ RetrievalTool: "pending",
+ },
+ tokenStats: {
+ model: "Unknown",
+ calls: 0,
+ tokens: 0,
+ input_tokens: 0,
+ output_tokens: 0,
+ cost: 0.0,
+ },
+ }));
+
+ const ws = new WebSocket(wsUrl("/api/v1/question/generate"));
+ questionWs.current = ws;
+
+ ws.onopen = () => {
+ ws.send(
+ JSON.stringify({
+ requirement: {
+ knowledge_point: topic,
+ difficulty: diff,
+ question_type: type,
+ additional_requirements: "Ensure clarity and academic rigor.",
+ },
+ count: count,
+ kb_name: kb,
+ }),
+ );
+ addQuestionLog({ type: "system", content: "Initializing Generator..." });
+ };
+
+ ws.onmessage = (event) => {
+ const data = JSON.parse(event.data);
+ if (data.type === "log") {
+ addQuestionLog(data);
+ // Parse progress info from log content (fallback for any remaining print statements)
+ if (data.content.includes("Generating question")) {
+ const match = data.content.match(/(\d+)\/(\d+)/);
+ if (match) {
+ setQuestionState((prev) => ({
+ ...prev,
+ progress: {
+ stage: "generating",
+ progress: {
+ current: parseInt(match[1]),
+ total: parseInt(match[2]),
+ },
+ },
+ }));
+ }
+ }
+ if (data.content.includes("Round") || data.content.includes("round")) {
+ const match = data.content.match(/Round\s+(\d+)/i);
+ if (match) {
+ setQuestionState((prev) => ({
+ ...prev,
+ progress: {
+ ...prev.progress,
+ progress: {
+ ...prev.progress.progress,
+ round: parseInt(match[1]),
+ },
+ },
+ }));
+ }
+ }
+ if (
+ data.content.includes("Validation") ||
+ data.content.includes("validation")
+ ) {
+ setQuestionState((prev) => ({
+ ...prev,
+ progress: {
+ stage: "validating",
+ progress: prev.progress.progress,
+ },
+ }));
+ }
+ } else if (data.type === "agent_status") {
+ // Handle agent status updates
+ setQuestionState((prev) => ({
+ ...prev,
+ agentStatus: data.all_agents || {
+ ...prev.agentStatus,
+ [data.agent]: data.status,
+ },
+ }));
+ } else if (data.type === "token_stats") {
+ // Handle token statistics updates
+ setQuestionState((prev) => ({
+ ...prev,
+ tokenStats: data.stats || prev.tokenStats,
+ }));
+ } else if (data.type === "progress") {
+ // Handle structured progress updates (including parallel generation stages)
+ setQuestionState((prev) => ({
+ ...prev,
+ progress: {
+ stage: data.stage || prev.progress.stage,
+ progress: {
+ ...prev.progress.progress,
+ ...data.progress,
+ total: data.total ?? prev.progress.progress.total,
+ },
+ subFocuses:
+ data.focuses || data.sub_focuses || prev.progress.subFocuses,
+ activeQuestions: prev.progress.activeQuestions,
+ completedQuestions:
+ data.completed ?? prev.progress.completedQuestions,
+ failedQuestions: data.failed ?? prev.progress.failedQuestions,
+ },
+ }));
+ } else if (data.type === "question_update") {
+ // Handle individual question updates (custom mode)
+ const statusLabel =
+ data.status === "analyzing"
+ ? "Analyzing relevance"
+ : data.status === "generating"
+ ? "Generating"
+ : data.status === "done"
+ ? "Completed"
+ : data.status;
+ addQuestionLog({
+ type: data.status === "done" ? "success" : "system",
+ content: `[${data.question_id}] ${statusLabel}${data.focus ? `: ${data.focus.slice(0, 50)}...` : ""}`,
+ });
+ } else if (data.type === "question_error") {
+ // Handle individual question errors in parallel mode
+ addQuestionLog({
+ type: "error",
+ content: `[${data.question_id}] Error: ${data.error}${data.reason ? ` - ${data.reason}` : ""}`,
+ });
+ } else if (data.type === "knowledge_saved") {
+ // Handle knowledge saved event (custom mode)
+ addQuestionLog({
+ type: "success",
+ content: `Background knowledge retrieved (${data.queries?.length || 0} queries)`,
+ });
+ } else if (data.type === "plan_ready") {
+ // Handle plan ready event (custom mode)
+ const focuses = data.focuses || data.plan?.focuses || [];
+ setQuestionState((prev) => ({
+ ...prev,
+ progress: {
+ ...prev.progress,
+ stage: "planning",
+ subFocuses: focuses,
+ progress: {
+ ...prev.progress.progress,
+ status: "plan_ready",
+ },
+ },
+ }));
+ addQuestionLog({
+ type: "success",
+ content: `Question plan created with ${focuses.length} focuses`,
+ });
+ } else if (data.type === "batch_summary") {
+ // Handle batch summary from custom mode generation
+ setQuestionState((prev) => ({
+ ...prev,
+ progress: {
+ ...prev.progress,
+ subFocuses:
+ data.sub_focuses ||
+ data.plan?.focuses ||
+ prev.progress.subFocuses,
+ completedQuestions: data.completed || prev.results.length,
+ failedQuestions: data.failed || 0,
+ progress: {
+ ...prev.progress.progress,
+ current: data.completed || prev.results.length,
+ total: data.requested || prev.count,
+ },
+ },
+ }));
+ addQuestionLog({
+ type: "success",
+ content: `Generation complete: ${data.completed}/${data.requested} questions generated${data.failed > 0 ? `, ${data.failed} failed` : ""}`,
+ });
+ } else if (data.type === "result") {
+ const isExtended =
+ data.extended || data.validation?.decision === "extended";
+ const questionPreview =
+ data.question?.question?.slice(0, 50) || "Unknown";
+ addQuestionLog({
+ type: "success",
+ content: `Question ${data.question_id || (data.index !== undefined ? `#${data.index + 1}` : "")} generated: ${questionPreview}...`,
+ });
+ setQuestionState((prev) => ({
+ ...prev,
+ results: [
+ ...prev.results,
+ {
+ question: data.question,
+ validation: data.validation,
+ rounds: data.rounds || 1,
+ extended: isExtended,
+ },
+ ],
+ progress: {
+ ...prev.progress,
+ stage: "generating",
+ completedQuestions: prev.results.length + 1,
+ progress: {
+ ...prev.progress.progress,
+ current: prev.results.length + 1,
+ total: prev.count,
+ round: data.rounds || 1,
+ },
+ extendedQuestions:
+ (prev.progress.extendedQuestions || 0) + (isExtended ? 1 : 0),
+ },
+ }));
+ } else if (data.type === "complete") {
+ setQuestionState((prev) => ({
+ ...prev,
+ step: "result",
+ progress: {
+ ...prev.progress,
+ stage: "complete",
+ completedQuestions: prev.results.length,
+ },
+ }));
+ ws.close();
+ } else if (data.type === "error") {
+ addQuestionLog({
+ type: "error",
+ content: `Error: ${data.content || data.message || "Unknown error"}`,
+ });
+ setQuestionState((prev) => ({
+ ...prev,
+ progress: {
+ stage: null,
+ progress: {},
+ },
+ }));
+ }
+ };
+
+ ws.onerror = () => {
+ addQuestionLog({ type: "error", content: "WebSocket connection error" });
+ setQuestionState((prev) => ({
+ ...prev,
+ step: "config",
+ progress: {
+ stage: null,
+ progress: {},
+ },
+ agentStatus: {
+ QuestionGenerationAgent: "pending",
+ ValidationWorkflow: "pending",
+ RetrievalTool: "pending",
+ },
+ }));
+ };
+
+ ws.onclose = () => {
+ // Clean up WebSocket reference on close
+ if (questionWs.current === ws) {
+ questionWs.current = null;
+ }
+ };
+ };
+
+ const startMimicQuestionGen = async (
+ file: File | null,
+ paperPath: string,
+ kb: string,
+ maxQuestions?: number,
+ ) => {
+ if (questionWs.current) questionWs.current.close();
+
+ // Support two modes: PDF upload or pre-parsed directory
+ const hasFile = file !== null;
+ const hasParsedPath = paperPath && paperPath.trim() !== "";
+
+ if (!hasFile && !hasParsedPath) {
+ addQuestionLog({
+ type: "error",
+ content: "Please upload a PDF file or provide a parsed exam directory",
+ });
+ return;
+ }
+
+ setQuestionState((prev) => ({
+ ...prev,
+ step: "generating",
+ mode: "mimic",
+ logs: [],
+ results: [],
+ selectedKb: kb,
+ uploadedFile: file,
+ paperPath: paperPath,
+ progress: {
+ stage: hasFile ? "uploading" : "parsing", // Start with uploading for PDF, parsing for pre-parsed
+ progress: { current: 0, total: maxQuestions || 1 },
+ },
+ agentStatus: {
+ QuestionGenerationAgent: "pending",
+ ValidationWorkflow: "pending",
+ RetrievalTool: "pending",
+ },
+ tokenStats: {
+ model: "Unknown",
+ calls: 0,
+ tokens: 0,
+ input_tokens: 0,
+ output_tokens: 0,
+ cost: 0.0,
+ },
+ }));
+
+ const ws = new WebSocket(wsUrl("/api/v1/question/mimic"));
+ questionWs.current = ws;
+
+ ws.onopen = async () => {
+ if (hasFile && file) {
+ // Convert file to base64
+ addQuestionLog({
+ type: "system",
+ content: "Preparing to upload PDF file...",
+ });
+ const reader = new FileReader();
+ reader.onload = () => {
+ const base64Data = (reader.result as string).split(",")[1]; // Remove data:application/pdf;base64, prefix
+ ws.send(
+ JSON.stringify({
+ mode: "upload",
+ pdf_data: base64Data,
+ pdf_name: file.name,
+ kb_name: kb,
+ max_questions: maxQuestions,
+ }),
+ );
+ addQuestionLog({
+ type: "system",
+ content: `Uploaded: ${file.name}, parsing...`,
+ });
+ };
+ reader.readAsDataURL(file);
+ } else {
+ // Use pre-parsed directory
+ ws.send(
+ JSON.stringify({
+ mode: "parsed",
+ paper_path: paperPath,
+ kb_name: kb,
+ max_questions: maxQuestions,
+ }),
+ );
+ addQuestionLog({
+ type: "system",
+ content: "Initializing Mimic Generator...",
+ });
+ }
+ };
+
+ ws.onmessage = (event) => {
+ const data = JSON.parse(event.data);
+
+ if (data.type === "log") {
+ addQuestionLog(data);
+ } else if (data.type === "status") {
+ // Status updates for mimic mode stages
+ const stageMap: Record<string, string> = {
+ init: "uploading",
+ upload: "uploading",
+ parsing: "parsing",
+ processing: "extracting",
+ };
+ const mappedStage = stageMap[data.stage] || data.stage;
+
+ addQuestionLog({
+ type: "system",
+ content: data.content || data.message || `Stage: ${data.stage}`,
+ });
+
+ // Update progress stage based on status event
+ if (mappedStage) {
+ setQuestionState((prev) => ({
+ ...prev,
+ progress: {
+ ...prev.progress,
+ stage: mappedStage,
+ },
+ }));
+ }
+ } else if (data.type === "progress") {
+ // Progress updates for mimic mode (parsing, extracting, generating)
+ const stage = data.stage || "generating";
+ const message = data.message || "";
+
+ addQuestionLog({
+ type: "system",
+ content: message,
+ });
+
+ setQuestionState((prev) => ({
+ ...prev,
+ progress: {
+ ...prev.progress,
+ stage: stage,
+ progress: {
+ ...prev.progress.progress,
+ current: data.current ?? prev.progress.progress.current,
+ total:
+ data.total_questions ??
+ data.total ??
+ prev.progress.progress.total,
+ status: data.status,
+ },
+ },
+ }));
+
+ // Store reference questions info when extracting is complete
+ if (
+ stage === "extracting" &&
+ data.status === "complete" &&
+ data.reference_questions
+ ) {
+ setQuestionState((prev) => ({
+ ...prev,
+ progress: {
+ ...prev.progress,
+ progress: {
+ ...prev.progress.progress,
+ total: data.total_questions || data.reference_questions.length,
+ },
+ },
+ }));
+ }
+ } else if (data.type === "question_update") {
+ // Individual question status update during generation
+ const statusMessage =
+ data.status === "generating"
+ ? `Generating mimic question ${data.index}...`
+ : data.status === "failed"
+ ? `Question ${data.index} failed: ${data.error}`
+ : `Question ${data.index}: ${data.status}`;
+
+ addQuestionLog({
+ type: data.status === "failed" ? "warning" : "system",
+ content: statusMessage,
+ });
+
+ if (data.current !== undefined) {
+ setQuestionState((prev) => ({
+ ...prev,
+ progress: {
+ ...prev.progress,
+ progress: {
+ ...prev.progress.progress,
+ current: data.current,
+ },
+ },
+ }));
+ }
+ } else if (data.type === "result") {
+ // Single question result
+ const isExtended =
+ data.extended || data.validation?.decision === "extended";
+
+ addQuestionLog({
+ type: "success",
+ content: `✅ Question ${data.index || (data.current ?? 0)} generated successfully`,
+ });
+
+ setQuestionState((prev) => ({
+ ...prev,
+ results: [
+ ...prev.results,
+ {
+ question: data.question,
+ validation: data.validation,
+ rounds: data.rounds || 1,
+ reference_question: data.reference_question,
+ extended: isExtended,
+ },
+ ],
+ progress: {
+ ...prev.progress,
+ stage: "generating",
+ progress: {
+ ...prev.progress.progress,
+ current: data.current ?? prev.results.length + 1,
+ total: data.total ?? prev.progress.progress.total ?? 1,
+ },
+ extendedQuestions:
+ (prev.progress.extendedQuestions || 0) + (isExtended ? 1 : 0),
+ },
+ }));
+ } else if (data.type === "summary") {
+ // Final summary for mimic mode
+ addQuestionLog({
+ type: "success",
+ content: `Generation complete: ${data.successful}/${data.total_reference} succeeded`,
+ });
+
+ setQuestionState((prev) => ({
+ ...prev,
+ progress: {
+ ...prev.progress,
+ stage: "generating",
+ progress: {
+ current: data.successful,
+ total: data.total_reference,
+ },
+ completedQuestions: data.successful,
+ failedQuestions: data.failed,
+ },
+ }));
+ } else if (data.type === "complete") {
+ addQuestionLog({
+ type: "success",
+ content: "✅ Mimic generation completed!",
+ });
+
+ setQuestionState((prev) => ({
+ ...prev,
+ step: "result",
+ progress: {
+ ...prev.progress,
+ stage: "complete",
+ completedQuestions: prev.results.length,
+ },
+ }));
+ ws.close();
+ } else if (data.type === "error") {
+ addQuestionLog({
+ type: "error",
+ content: `Error: ${data.content || data.message || "Unknown error"}`,
+ });
+ setQuestionState((prev) => ({
+ ...prev,
+ step: "config",
+ progress: {
+ stage: null,
+ progress: {},
+ },
+ }));
+ }
+ };
+
+ ws.onerror = () => {
+ addQuestionLog({ type: "error", content: "WebSocket connection error" });
+ setQuestionState((prev) => ({ ...prev, step: "config" }));
+ };
+ };
+
+ const resetQuestionGen = () => {
+ setQuestionState((prev) => ({
+ ...prev,
+ step: "config",
+ results: [],
+ logs: [],
+ progress: {
+ stage: null,
+ progress: {},
+ subFocuses: [],
+ activeQuestions: [],
+ completedQuestions: 0,
+ failedQuestions: 0,
+ },
+ agentStatus: {
+ QuestionGenerationAgent: "pending",
+ ValidationWorkflow: "pending",
+ RetrievalTool: "pending",
+ },
+ tokenStats: {
+ model: "Unknown",
+ calls: 0,
+ tokens: 0,
+ input_tokens: 0,
+ output_tokens: 0,
+ cost: 0.0,
+ },
+ uploadedFile: null,
+ paperPath: "",
+ }));
+ };
+
+ const addQuestionLog = (log: LogEntry) => {
+ setQuestionState((prev) => ({ ...prev, logs: [...prev.logs, log] }));
+ };
+
+ // --- Research Logic ---
+ const [researchState, setResearchState] = useState<ResearchState>({
+ status: "idle",
+ logs: [],
+ report: null,
+ topic: "",
+ selectedKb: "",
+ progress: {
+ stage: null,
+ status: "",
+ executionMode: undefined,
+ totalBlocks: undefined,
+ currentBlock: undefined,
+ currentSubTopic: undefined,
+ currentBlockId: undefined,
+ iterations: undefined,
+ maxIterations: undefined,
+ toolsUsed: undefined,
+ currentTool: undefined,
+ currentQuery: undefined,
+ currentRationale: undefined,
+ queriesUsed: undefined,
+ activeTasks: undefined,
+ activeCount: undefined,
+ completedCount: undefined,
+ keptBlocks: undefined,
+ sections: undefined,
+ wordCount: undefined,
+ citations: undefined,
+ },
+ });
+ const researchWs = useRef<WebSocket | null>(null);
+
+ const startResearch = (
+ topic: string,
+ kb: string,
+ planMode: string = "medium",
+ enabledTools: string[] = ["RAG"],
+ skipRephrase: boolean = false,
+ ) => {
+ if (researchWs.current) researchWs.current.close();
+
+ setResearchState((prev) => ({
+ ...prev,
+ status: "running",
+ logs: [],
+ report: null,
+ topic,
+ selectedKb: kb,
+ progress: {
+ stage: null,
+ status: "",
+ executionMode: undefined,
+ totalBlocks: undefined,
+ currentBlock: undefined,
+ currentSubTopic: undefined,
+ currentBlockId: undefined,
+ iterations: undefined,
+ maxIterations: undefined,
+ toolsUsed: undefined,
+ currentTool: undefined,
+ currentQuery: undefined,
+ currentRationale: undefined,
+ queriesUsed: undefined,
+ activeTasks: undefined,
+ activeCount: undefined,
+ completedCount: undefined,
+ keptBlocks: undefined,
+ sections: undefined,
+ wordCount: undefined,
+ citations: undefined,
+ },
+ }));
+
+ const ws = new WebSocket(wsUrl("/api/v1/research/run"));
+ researchWs.current = ws;
+
+ ws.onopen = () => {
+ ws.send(
+ JSON.stringify({
+ topic,
+ kb_name: kb,
+ plan_mode: planMode,
+ enabled_tools: enabledTools,
+ skip_rephrase: skipRephrase,
+ }),
+ );
+ addResearchLog({
+ type: "system",
+ content: `Starting Research Pipeline (Plan: ${planMode}, Tools: ${enabledTools.join("+")}, Optimization: ${!skipRephrase ? "On" : "Off/Pre-done"})...`,
+ });
+ };
+
+ ws.onmessage = (event) => {
+ const data = JSON.parse(event.data);
+ if (data.type === "log") {
+ addResearchLog(data);
+ } else if (data.type === "progress") {
+ // Handle structured progress messages with enhanced fields
+ setResearchState((prev) => {
+ // Parse active tasks for parallel mode
+ const activeTasks: ActiveTaskInfo[] =
+ data.active_tasks?.map((t: any) => ({
+ block_id: t.block_id,
+ sub_topic: t.sub_topic,
+ status: t.status,
+ iteration: t.iteration || 0,
+ max_iterations: t.max_iterations,
+ current_tool: t.current_tool,
+ current_query: t.current_query,
+ tools_used: t.tools_used,
+ })) ?? prev.progress.activeTasks;
+
+ // Parse queries used
+ const queriesUsed: QueryInfo[] =
+ data.queries_used?.map((q: any) => ({
+ query: q.query,
+ tool_type: q.tool_type,
+ rationale: q.rationale,
+ iteration: q.iteration,
+ })) ?? prev.progress.queriesUsed;
+
+ return {
+ ...prev,
+ progress: {
+ stage: data.stage,
+ status: data.status,
+ // Execution mode
+ executionMode: data.execution_mode ?? prev.progress.executionMode,
+ // Planning details
+ totalBlocks: data.total_blocks ?? prev.progress.totalBlocks,
+ // Researching details
+ currentBlock: data.current_block ?? prev.progress.currentBlock,
+ currentSubTopic: data.sub_topic ?? prev.progress.currentSubTopic,
+ currentBlockId: data.block_id ?? prev.progress.currentBlockId,
+ iterations:
+ data.iteration ?? data.iterations ?? prev.progress.iterations,
+ maxIterations: data.max_iterations ?? prev.progress.maxIterations,
+ toolsUsed: data.tools_used ?? prev.progress.toolsUsed,
+ // Current action details
+ currentTool: data.tool_type ?? prev.progress.currentTool,
+ currentQuery: data.query ?? prev.progress.currentQuery,
+ currentRationale:
+ data.rationale ?? prev.progress.currentRationale,
+ queriesUsed: queriesUsed,
+ // Parallel mode specific
+ activeTasks: activeTasks,
+ activeCount: data.active_count ?? prev.progress.activeCount,
+ completedCount:
+ data.completed_count ?? prev.progress.completedCount,
+ // Reporting details
+ keptBlocks: data.kept_blocks ?? prev.progress.keptBlocks,
+ sections: data.sections ?? prev.progress.sections,
+ wordCount: data.word_count ?? prev.progress.wordCount,
+ citations: data.citations ?? prev.progress.citations,
+ },
+ };
+ });
+ } else if (data.type === "result") {
+ setResearchState((prev) => ({
+ ...prev,
+ status: "completed",
+ report: data.report,
+ }));
+ ws.close();
+ } else if (data.type === "error") {
+ addResearchLog({
+ type: "error",
+ content: `Error: ${data.content || data.message || "Unknown error"}`,
+ });
+ setResearchState((prev) => ({ ...prev, status: "idle" }));
+ }
+ };
+
+ ws.onerror = () => {
+ addResearchLog({ type: "error", content: "WebSocket connection error" });
+ setResearchState((prev) => ({
+ ...prev,
+ status: "idle",
+ progress: {
+ stage: null,
+ status: "",
+ executionMode: undefined,
+ activeTasks: undefined,
+ },
+ }));
+ };
+
+ ws.onclose = () => {
+ // Clean up WebSocket reference on close
+ if (researchWs.current === ws) {
+ researchWs.current = null;
+ }
+ };
+ };
+
+ const addResearchLog = (log: LogEntry) => {
+ setResearchState((prev) => ({ ...prev, logs: [...prev.logs, log] }));
+ };
+
+ // --- IdeaGen Logic ---
+ const [ideaGenState, setIdeaGenState] = useState<IdeaGenState>({
+ isGenerating: false,
+ generationStatus: "",
+ generatedIdeas: [],
+ progress: null,
+ });
+
+ return (
+ <GlobalContext.Provider
+ value={{
+ solverState,
+ setSolverState,
+ startSolver,
+ questionState,
+ setQuestionState,
+ startQuestionGen,
+ startMimicQuestionGen,
+ resetQuestionGen,
+ researchState,
+ setResearchState,
+ startResearch,
+ ideaGenState,
+ setIdeaGenState,
+ uiSettings,
+ refreshSettings,
+ }}
+ >
+ {children}
+ </GlobalContext.Provider>
+ );
+}
+
+export const useGlobal = () => {
+ const context = useContext(GlobalContext);
+ if (!context) throw new Error("useGlobal must be used within GlobalProvider");
+ return context;
+};
diff --git a/web/hooks/useQuestionReducer.ts b/web/hooks/useQuestionReducer.ts
new file mode 100644
index 000000000..b46b1e9cc
--- /dev/null
+++ b/web/hooks/useQuestionReducer.ts
@@ -0,0 +1,417 @@
+import { useReducer } from "react";
+import {
+ QuestionState,
+ QuestionEvent,
+ QuestionTask,
+ QuestionLogEntry,
+ QuestionResult,
+ QuestionFailure,
+ QuestionFocus,
+} from "../types/question";
+
+export const initialQuestionState: QuestionState = {
+ global: {
+ stage: "idle",
+ startTime: 0,
+ totalQuestions: 0,
+ completedQuestions: 0,
+ failedQuestions: 0,
+ extendedQuestions: 0,
+ },
+ planning: {
+ topic: "",
+ difficulty: "",
+ questionType: "",
+ queries: [],
+ progress: "",
+ },
+ tasks: {},
+ activeTaskIds: [],
+ results: [],
+ failures: [],
+ subFocuses: [],
+ logs: [],
+};
+
+// Helper to create a log entry
+const createLog = (
+ content: string,
+ type: QuestionLogEntry["type"] = "info",
+): QuestionLogEntry => ({
+ id: Math.random().toString(36).substring(7),
+ timestamp: Date.now(),
+ type,
+ content,
+});
+
+// Helper to ensure a task exists in state
+const ensureTask = (
+ state: QuestionState,
+ taskId: string,
+ focus: string = "",
+): QuestionTask => {
+ if (state.tasks[taskId]) {
+ return state.tasks[taskId];
+ }
+ return {
+ id: taskId,
+ focus: focus,
+ status: "pending",
+ round: 0,
+ lastUpdate: Date.now(),
+ };
+};
+
+export const questionReducer = (
+ state: QuestionState,
+ event: QuestionEvent,
+): QuestionState => {
+ // Common log handling
+ const newLog = event.type === "log" ? createLog(event.content || "") : null;
+ const logs = newLog ? [...state.logs, newLog] : state.logs;
+
+ switch (event.type) {
+ // --- Progress events (from backend) ---
+ case "progress": {
+ const stage = event.stage as QuestionState["global"]["stage"];
+ const status = event.status || "";
+
+ // Planning stage
+ if (stage === "planning") {
+ if (status === "splitting_queries") {
+ return {
+ ...state,
+ global: {
+ ...state.global,
+ stage: "planning",
+ startTime: state.global.startTime || Date.now(),
+ totalQuestions: event.total || state.global.totalQuestions,
+ },
+ planning: {
+ ...state.planning,
+ progress: "Splitting into search queries...",
+ },
+ logs: [...logs, createLog("Planning started - splitting queries")],
+ };
+ }
+ if (status === "planning_focuses") {
+ return {
+ ...state,
+ planning: {
+ ...state.planning,
+ progress: "Planning sub-focuses for each question...",
+ },
+ logs: [...logs, createLog("Planning sub-focuses")],
+ };
+ }
+ }
+
+ // Researching stage
+ if (stage === "researching") {
+ return {
+ ...state,
+ global: {
+ ...state.global,
+ stage: "researching",
+ },
+ planning: {
+ ...state.planning,
+ queries: event.queries || state.planning.queries,
+ progress: "Retrieving knowledge from database...",
+ },
+ logs: [...logs, createLog("Researching knowledge base")],
+ };
+ }
+
+ // Generating stage
+ if (stage === "generating") {
+ const focuses = event.focuses || event.sub_focuses || [];
+ const newTasks: Record<string, QuestionTask> = {};
+
+ // Initialize tasks from focuses
+ if (focuses.length > 0) {
+ focuses.forEach((f: QuestionFocus) => {
+ newTasks[f.id] = {
+ id: f.id,
+ focus: f.focus,
+ scenarioHint: f.scenario_hint,
+ status: "pending",
+ lastUpdate: Date.now(),
+ };
+ });
+ }
+
+ return {
+ ...state,
+ global: {
+ ...state.global,
+ stage: "generating",
+ totalQuestions:
+ event.total || focuses.length || state.global.totalQuestions,
+ },
+ subFocuses: focuses.length > 0 ? focuses : state.subFocuses,
+ tasks: focuses.length > 0 ? newTasks : state.tasks,
+ logs: [
+ ...logs,
+ createLog(
+ `Starting parallel generation of ${event.total || focuses.length} questions`,
+ ),
+ ],
+ };
+ }
+
+ // Complete stage
+ if (stage === "complete") {
+ return {
+ ...state,
+ global: {
+ ...state.global,
+ stage: "complete",
+ completedQuestions:
+ event.completed || state.global.completedQuestions,
+ failedQuestions: event.failed || state.global.failedQuestions,
+ },
+ logs: [...logs, createLog("Generation completed", "success")],
+ };
+ }
+
+ return state;
+ }
+
+ // --- Question-specific update ---
+ case "question_update": {
+ const questionId = event.question_id;
+ if (!questionId) return state;
+
+ const existingTask =
+ state.tasks[questionId] ||
+ ensureTask(state, questionId, event.focus || "");
+
+ const statusMap: Record<string, QuestionTask["status"]> = {
+ generating: "generating",
+ validating: "validating",
+ done: "done",
+ error: "error",
+ };
+
+ const newStatus = statusMap[event.status || ""] || existingTask.status;
+
+ // Track active tasks
+ let activeTaskIds = [...state.activeTaskIds];
+ if (newStatus === "generating" || newStatus === "validating") {
+ if (!activeTaskIds.includes(questionId)) {
+ activeTaskIds.push(questionId);
+ }
+ } else if (newStatus === "done" || newStatus === "error") {
+ activeTaskIds = activeTaskIds.filter((id) => id !== questionId);
+ }
+
+ return {
+ ...state,
+ tasks: {
+ ...state.tasks,
+ [questionId]: {
+ ...existingTask,
+ status: newStatus,
+ round: event.round || existingTask.round,
+ focus: event.focus || existingTask.focus,
+ lastUpdate: Date.now(),
+ },
+ },
+ activeTaskIds,
+ };
+ }
+
+ // --- Result received ---
+ case "result":
+ case "question_result": {
+ const questionId = event.question_id || `q_${(event.index || 0) + 1}`;
+ const isExtended =
+ event.extended || event.validation?.decision === "extended";
+ const result: QuestionResult = {
+ success: true,
+ question_id: questionId,
+ question: event.question,
+ validation: event.validation || {},
+ rounds: event.rounds || 1,
+ focus: event.focus,
+ extended: isExtended,
+ };
+
+ const existingTask = state.tasks[questionId];
+
+ return {
+ ...state,
+ tasks: {
+ ...state.tasks,
+ [questionId]: {
+ ...(existingTask || ensureTask(state, questionId)),
+ status: "done",
+ result,
+ extended: isExtended,
+ lastUpdate: Date.now(),
+ },
+ },
+ activeTaskIds: state.activeTaskIds.filter((id) => id !== questionId),
+ results: [...state.results, result],
+ global: {
+ ...state.global,
+ completedQuestions: state.global.completedQuestions + 1,
+ extendedQuestions:
+ state.global.extendedQuestions + (isExtended ? 1 : 0),
+ },
+ logs: [
+ ...logs,
+ createLog(
+ `Question ${questionId} ${isExtended ? "extended" : "generated successfully"} (${result.rounds} rounds)`,
+ isExtended ? "warning" : "success",
+ ),
+ ],
+ };
+ }
+
+ // --- Question error ---
+ case "question_error": {
+ const questionId = event.question_id || "unknown";
+ const failure: QuestionFailure = {
+ question_id: questionId,
+ error: event.error || event.content || "Unknown error",
+ reason: event.reason,
+ };
+
+ const existingTask = state.tasks[questionId];
+
+ return {
+ ...state,
+ tasks: {
+ ...state.tasks,
+ [questionId]: {
+ ...(existingTask || ensureTask(state, questionId)),
+ status: "error",
+ error: failure.error,
+ lastUpdate: Date.now(),
+ },
+ },
+ activeTaskIds: state.activeTaskIds.filter((id) => id !== questionId),
+ failures: [...state.failures, failure],
+ global: {
+ ...state.global,
+ failedQuestions: state.global.failedQuestions + 1,
+ },
+ logs: [
+ ...logs,
+ createLog(`Question ${questionId} failed: ${failure.error}`, "error"),
+ ],
+ };
+ }
+
+ // --- Batch summary ---
+ case "batch_summary": {
+ return {
+ ...state,
+ global: {
+ ...state.global,
+ totalQuestions: event.requested || state.global.totalQuestions,
+ completedQuestions:
+ event.completed || state.global.completedQuestions,
+ failedQuestions: event.failed || state.global.failedQuestions,
+ },
+ subFocuses: event.sub_focuses || state.subFocuses,
+ logs: [
+ ...logs,
+ createLog(
+ `Batch summary: ${event.completed}/${event.requested} completed, ${event.failed} failed`,
+ ),
+ ],
+ };
+ }
+
+ // --- Status updates ---
+ case "status": {
+ if (event.content === "started") {
+ return {
+ ...state,
+ global: {
+ ...state.global,
+ stage: "planning",
+ startTime: Date.now(),
+ },
+ logs: [...logs, createLog("Question generation started")],
+ };
+ }
+ return state;
+ }
+
+ case "agent_status": {
+ // Agent status updates (for debugging/display)
+ return {
+ ...state,
+ logs: [
+ ...logs,
+ createLog(
+ `Agent status update: ${JSON.stringify(event.all_agents)}`,
+ "system",
+ ),
+ ],
+ };
+ }
+
+ case "token_stats": {
+ // Token stats (can be displayed in UI)
+ return {
+ ...state,
+ logs: [
+ ...logs,
+ createLog(
+ `Token usage: ${event.stats?.tokens || 0} tokens`,
+ "system",
+ ),
+ ],
+ };
+ }
+
+ // --- Complete signal ---
+ case "complete": {
+ return {
+ ...state,
+ global: {
+ ...state.global,
+ stage: "complete",
+ },
+ logs: [...logs, createLog("Question generation completed", "success")],
+ };
+ }
+
+ // --- Error ---
+ case "error": {
+ return {
+ ...state,
+ logs: [
+ ...logs,
+ createLog(event.content || "An error occurred", "error"),
+ ],
+ };
+ }
+
+ // --- Log ---
+ case "log": {
+ return {
+ ...state,
+ logs,
+ };
+ }
+
+ default:
+ return { ...state, logs };
+ }
+};
+
+export const useQuestionReducer = () => {
+ return useReducer(questionReducer, initialQuestionState);
+};
+
+// Reset helper
+export const resetQuestionState = (): QuestionState => ({
+ ...initialQuestionState,
+ logs: [],
+});
diff --git a/web/hooks/useResearchReducer.ts b/web/hooks/useResearchReducer.ts
new file mode 100644
index 000000000..dbbcdeacb
--- /dev/null
+++ b/web/hooks/useResearchReducer.ts
@@ -0,0 +1,546 @@
+import { useReducer } from "react";
+import {
+ ResearchState,
+ ResearchEvent,
+ TaskState,
+ ThoughtEntry,
+ LogEntry,
+ TopicBlock,
+ ReportOutline,
+} from "../types/research";
+
+export const initialResearchState: ResearchState = {
+ global: {
+ stage: "idle",
+ startTime: 0,
+ totalBlocks: 0,
+ completedBlocks: 0,
+ },
+ planning: {
+ originalTopic: "",
+ optimizedTopic: "",
+ subTopics: [],
+ progress: "",
+ },
+ tasks: {},
+ activeTaskIds: [],
+ executionMode: "series",
+ reporting: {
+ outline: null,
+ progress: "",
+ },
+ logs: [],
+};
+
+// Helper to create a log entry
+const createLog = (
+ message: string,
+ type: LogEntry["type"] = "info",
+): LogEntry => ({
+ id: Math.random().toString(36).substring(7),
+ timestamp: Date.now(),
+ type,
+ message,
+});
+
+// Helper to ensure a task exists in state
+const ensureTask = (
+ state: ResearchState,
+ blockId: string,
+ topic: string = "",
+): TaskState => {
+ if (state.tasks[blockId]) {
+ return state.tasks[blockId];
+ }
+ return {
+ id: blockId,
+ topic: topic,
+ status: "pending",
+ iteration: 0,
+ maxIterations: 0, // Will be updated from events
+ currentAction: "Initialized",
+ toolsUsed: [],
+ thoughts: [],
+ lastUpdate: Date.now(),
+ };
+};
+
+// Helper to add a thought to a task
+const addThought = (task: TaskState, thought: ThoughtEntry): TaskState => ({
+ ...task,
+ thoughts: [...task.thoughts, thought],
+ lastUpdate: Date.now(),
+});
+
+export const researchReducer = (
+ state: ResearchState,
+ event: ResearchEvent,
+): ResearchState => {
+ // Common log handling
+ const newLog = event.type === "log" ? createLog(event.content) : null;
+ const logs = newLog ? [...state.logs, newLog] : state.logs;
+
+ switch (event.type) {
+ // --- Planning Phase ---
+ case "planning_started":
+ return {
+ ...state,
+ global: {
+ ...state.global,
+ stage: "planning",
+ startTime: Date.now(),
+ },
+ planning: {
+ ...state.planning,
+ originalTopic: event.user_topic || "",
+ progress: "Initializing planning...",
+ },
+ logs: [...logs, createLog("Planning started")],
+ };
+
+ case "rephrase_completed":
+ return {
+ ...state,
+ planning: {
+ ...state.planning,
+ optimizedTopic: event.optimized_topic,
+ progress: "Topic rephrased",
+ },
+ logs: [...logs, createLog(`Topic optimized: ${event.optimized_topic}`)],
+ };
+
+ case "decompose_started":
+ return {
+ ...state,
+ planning: {
+ ...state.planning,
+ progress: `Decomposing into sub-topics (Mode: ${event.mode})...`,
+ },
+ };
+
+ case "decompose_completed":
+ return {
+ ...state,
+ planning: {
+ ...state.planning,
+ progress: `Decomposition completed (${event.generated_subtopics} subtopics)`,
+ },
+ logs: [
+ ...logs,
+ createLog(`Generated ${event.generated_subtopics} subtopics`),
+ ],
+ };
+
+ case "queue_seeded":
+ // Backend sends seeded blocks one by one or we might just wait for planning_completed
+ // But we can capture the total blocks here if available
+ return {
+ ...state,
+ global: {
+ ...state.global,
+ totalBlocks: event.total_blocks || state.global.totalBlocks,
+ },
+ planning: {
+ ...state.planning,
+ progress: `Added topic: ${event.sub_topic}`,
+ },
+ };
+
+ case "planning_completed":
+ return {
+ ...state,
+ global: {
+ ...state.global,
+ totalBlocks: event.total_blocks,
+ },
+ logs: [...logs, createLog("Planning phase completed", "success")],
+ };
+
+ // --- Researching Phase ---
+ case "researching_started":
+ // Initialize tasks based on blocks we might have received or just prepare
+ return {
+ ...state,
+ global: {
+ ...state.global,
+ stage: "researching",
+ totalBlocks: event.total_blocks || state.global.totalBlocks,
+ },
+ executionMode: event.execution_mode || "series",
+ logs: [
+ ...logs,
+ createLog(
+ `Research started in ${event.execution_mode || "series"} mode`,
+ ),
+ ],
+ };
+
+ case "block_started": {
+ const blockId = event.block_id;
+ const subTopic = event.sub_topic;
+ const task = ensureTask(state, blockId, subTopic);
+
+ return {
+ ...state,
+ tasks: {
+ ...state.tasks,
+ [blockId]: {
+ ...task,
+ status: "running",
+ topic: subTopic || task.topic,
+ lastUpdate: Date.now(),
+ },
+ },
+ // In series mode, update global current block tracking if provided
+ global: {
+ ...state.global,
+ ...(event.current_block
+ ? { completedBlocks: event.current_block - 1 }
+ : {}),
+ },
+ logs: [...logs, createLog(`Started research on: ${subTopic}`)],
+ };
+ }
+
+ case "parallel_status_update": {
+ // Bulk update for parallel mode
+ const activeTasks = event.active_tasks || [];
+ const updatedTasks = { ...state.tasks };
+ const activeIds: string[] = [];
+
+ activeTasks.forEach((t: any) => {
+ const blockId = t.block_id;
+ activeIds.push(blockId);
+
+ const existingTask =
+ updatedTasks[blockId] || ensureTask(state, blockId, t.sub_topic);
+
+ // Don't overwrite status if task is already completed or failed
+ const shouldUpdateStatus =
+ existingTask.status !== "completed" &&
+ existingTask.status !== "failed";
+
+ updatedTasks[blockId] = {
+ ...existingTask,
+ status: shouldUpdateStatus ? "running" : existingTask.status,
+ iteration: t.iteration,
+ maxIterations: t.max_iterations,
+ currentAction: shouldUpdateStatus
+ ? t.current_query
+ ? `Query: ${t.current_query}`
+ : t.status
+ : existingTask.currentAction,
+ currentTool: t.current_tool,
+ currentQuery: t.current_query,
+ lastUpdate: Date.now(),
+ };
+ });
+
+ // Also filter out completed/failed tasks from activeIds
+ const filteredActiveIds = activeIds.filter((id) => {
+ const task = updatedTasks[id];
+ return task && task.status !== "completed" && task.status !== "failed";
+ });
+
+ return {
+ ...state,
+ tasks: updatedTasks,
+ activeTaskIds: filteredActiveIds,
+ global: {
+ ...state.global,
+ completedBlocks:
+ event.completed_count || state.global.completedBlocks,
+ },
+ };
+ }
+
+ case "block_completed": {
+ const blockId = event.block_id;
+ return {
+ ...state,
+ tasks: {
+ ...state.tasks,
+ [blockId]: {
+ ...(state.tasks[blockId] || ensureTask(state, blockId)),
+ status: "completed",
+ currentAction: "Research completed",
+ lastUpdate: Date.now(),
+ toolsUsed:
+ event.tools_used || state.tasks[blockId]?.toolsUsed || [],
+ },
+ },
+ // Remove completed task from activeTaskIds
+ activeTaskIds: state.activeTaskIds.filter((id) => id !== blockId),
+ global: {
+ ...state.global,
+ completedBlocks: (state.global.completedBlocks || 0) + 1,
+ },
+ logs: [...logs, createLog(`Completed: ${event.sub_topic}`, "success")],
+ };
+ }
+
+ case "block_failed": {
+ const blockId = event.block_id;
+ return {
+ ...state,
+ tasks: {
+ ...state.tasks,
+ [blockId]: {
+ ...(state.tasks[blockId] || ensureTask(state, blockId)),
+ status: "failed",
+ currentAction: `Failed: ${event.error}`,
+ lastUpdate: Date.now(),
+ thoughts: [
+ ...(state.tasks[blockId]?.thoughts || []),
+ { type: "error", content: event.error, timestamp: Date.now() },
+ ],
+ },
+ },
+ // Remove failed task from activeTaskIds
+ activeTaskIds: state.activeTaskIds.filter((id) => id !== blockId),
+ logs: [
+ ...logs,
+ createLog(`Failed: ${event.sub_topic} - ${event.error}`, "error"),
+ ],
+ };
+ }
+
+ // --- Agent Details (Thoughts) ---
+ case "checking_sufficiency": {
+ const blockId = event.block_id;
+ if (!blockId || !state.tasks[blockId]) return state;
+
+ const task = state.tasks[blockId];
+ return {
+ ...state,
+ tasks: {
+ ...state.tasks,
+ [blockId]: addThought(task, {
+ type: "sufficiency",
+ content: `Iteration ${event.iteration}: Checking knowledge sufficiency...`,
+ timestamp: Date.now(),
+ }),
+ },
+ };
+ }
+
+ case "knowledge_sufficient": {
+ const blockId = event.block_id;
+ if (!blockId || !state.tasks[blockId]) return state;
+
+ const task = state.tasks[blockId];
+ return {
+ ...state,
+ tasks: {
+ ...state.tasks,
+ [blockId]: addThought(task, {
+ type: "sufficiency",
+ content: `Knowledge sufficient. Reason: ${event.reason}`,
+ timestamp: Date.now(),
+ }),
+ },
+ };
+ }
+
+ case "generating_query": {
+ const blockId = event.block_id;
+ if (!blockId || !state.tasks[blockId]) return state;
+
+ return {
+ ...state,
+ tasks: {
+ ...state.tasks,
+ [blockId]: {
+ ...state.tasks[blockId],
+ currentAction: "Generating query plan...",
+ },
+ },
+ };
+ }
+
+ case "tool_calling": {
+ const blockId = event.block_id;
+ if (!blockId || !state.tasks[blockId]) return state;
+
+ const task = state.tasks[blockId];
+ return {
+ ...state,
+ tasks: {
+ ...state.tasks,
+ [blockId]: {
+ ...addThought(task, {
+ type: "plan",
+ content: `Rationale: ${event.rationale}`,
+ timestamp: Date.now(),
+ }),
+ currentAction: `Using ${event.tool_type}: ${event.query}`,
+ toolsUsed: Array.from(
+ new Set([...task.toolsUsed, event.tool_type]),
+ ),
+ },
+ },
+ };
+ }
+
+ case "tool_completed": {
+ const blockId = event.block_id;
+ if (!blockId || !state.tasks[blockId]) return state;
+
+ const task = state.tasks[blockId];
+ return {
+ ...state,
+ tasks: {
+ ...state.tasks,
+ [blockId]: addThought(task, {
+ type: "tool_call",
+ content: `Used ${event.tool_type} with query "${event.query}"`,
+ timestamp: Date.now(),
+ }),
+ },
+ };
+ }
+
+ case "processing_notes": {
+ const blockId = event.block_id;
+ if (!blockId || !state.tasks[blockId]) return state;
+
+ return {
+ ...state,
+ tasks: {
+ ...state.tasks,
+ [blockId]: {
+ ...state.tasks[blockId],
+ currentAction: "Processing notes and citations...",
+ },
+ },
+ };
+ }
+
+ case "new_topic_added": {
+ // A new topic was discovered during research
+ const newTopic = event.new_topic;
+ const newBlockId = `block_${Math.random().toString(36).substr(2, 9)}`; // Backend should provide ID theoretically but usually it adds to queue end
+ // If backend provides ID in event, use it. But typically new_topic_added event might lack ID until queue_seeded.
+ // Assuming queue_seeded will follow or handle this.
+ // But for UI feedback:
+ return {
+ ...state,
+ logs: [...logs, createLog(`New topic discovered: ${newTopic}`, "info")],
+ };
+ }
+
+ case "researching_completed":
+ return {
+ ...state,
+ global: {
+ ...state.global,
+ completedBlocks: state.global.totalBlocks,
+ },
+ logs: [...logs, createLog("Research phase completed", "success")],
+ };
+
+ // --- Reporting Phase ---
+ case "reporting_started":
+ return {
+ ...state,
+ global: {
+ ...state.global,
+ stage: "reporting",
+ },
+ reporting: {
+ ...state.reporting,
+ progress: "Starting report generation...",
+ },
+ logs: [...logs, createLog("Reporting started")],
+ };
+
+ case "deduplicate_completed":
+ return {
+ ...state,
+ reporting: {
+ ...state.reporting,
+ progress: `Deduplication completed. Kept ${event.kept_blocks} blocks.`,
+ },
+ };
+
+ case "outline_completed":
+ // Determine the generated outline sections count
+ const outlineData = event as any; // Full outline payload might be in event
+ // But usually event just says outline_completed.
+ // If the outline data is passed in payload:
+ return {
+ ...state,
+ reporting: {
+ ...state.reporting,
+ progress: `Outline generated (${event.sections} sections).`,
+ totalSections: event.sections ? event.sections + 2 : undefined, // +2 for intro and conclusion
+ // If the event contained the outline structure, we would update it here
+ // But usually the client fetches report or it's pushed separately.
+ // Assuming for now just progress update.
+ },
+ logs: [...logs, createLog("Report outline generated")],
+ };
+
+ case "writing_section":
+ return {
+ ...state,
+ reporting: {
+ ...state.reporting,
+ progress: `Writing: ${event.current_section}`,
+ currentSection: event.current_section,
+ sectionIndex: event.section_index,
+ totalSections: event.total_sections,
+ },
+ };
+
+ case "writing_completed":
+ return {
+ ...state,
+ reporting: {
+ ...state.reporting,
+ progress: "Report writing completed.",
+ },
+ logs: [...logs, createLog("Report writing completed", "success")],
+ };
+
+ case "reporting_completed":
+ return {
+ ...state,
+ global: {
+ ...state.global,
+ stage: "completed",
+ },
+ reporting: {
+ ...state.reporting,
+ wordCount: event.word_count,
+ sectionCount: event.sections,
+ citationCount: event.citations,
+ generatedReport: event.report, // Store the generated report
+ progress: "All done!",
+ },
+ logs: [
+ ...logs,
+ createLog(
+ `Research finished! Report: ${event.word_count} words`,
+ "success",
+ ),
+ ],
+ };
+
+ case "error":
+ return {
+ ...state,
+ logs: [
+ ...logs,
+ createLog(event.content || "An error occurred", "error"),
+ ],
+ };
+
+ default:
+ return { ...state, logs };
+ }
+};
+
+export const useResearchReducer = () => {
+ return useReducer(researchReducer, initialResearchState);
+};
diff --git a/web/lib/api.ts b/web/lib/api.ts
new file mode 100644
index 000000000..0c2795432
--- /dev/null
+++ b/web/lib/api.ts
@@ -0,0 +1,58 @@
+// API configuration and utility functions
+
+// Get API base URL from environment variable
+// This is automatically set by start_web.py based on config/main.yaml
+// The .env.local file is auto-generated on startup with the correct backend port
+export const API_BASE_URL =
+ process.env.NEXT_PUBLIC_API_BASE ||
+ (() => {
+ if (typeof window !== "undefined") {
+ console.error("NEXT_PUBLIC_API_BASE is not set.");
+ console.error(
+ "Please configure server ports in config/main.yaml and restart the application using: python scripts/start_web.py",
+ );
+ console.error(
+ "The .env.local file will be automatically generated with the correct backend port.",
+ );
+ }
+ // No fallback - port must be configured in config/main.yaml
+ throw new Error(
+ "NEXT_PUBLIC_API_BASE is not configured. Please set server ports in config/main.yaml and restart.",
+ );
+ })();
+
+/**
+ * Construct a full API URL from a path
+ * @param path - API path (e.g., '/api/v1/knowledge/list')
+ * @returns Full URL (e.g., 'http://localhost:8000/api/v1/knowledge/list')
+ */
+export function apiUrl(path: string): string {
+ // Remove leading slash if present to avoid double slashes
+ const normalizedPath = path.startsWith("/") ? path : `/${path}`;
+
+ // Remove trailing slash from base URL if present
+ const base = API_BASE_URL.endsWith("/")
+ ? API_BASE_URL.slice(0, -1)
+ : API_BASE_URL;
+
+ return `${base}${normalizedPath}`;
+}
+
+/**
+ * Construct a WebSocket URL from a path
+ * @param path - WebSocket path (e.g., '/api/v1/solve')
+ * @returns WebSocket URL (e.g., 'ws://localhost:{backend_port}/api/v1/solve')
+ * Note: backend_port is configured in config/main.yaml
+ */
+export function wsUrl(path: string): string {
+ // Convert http:// to ws:// or https:// to wss://
+ const base = API_BASE_URL.replace(/^http:/, "ws:").replace(/^https:/, "wss:");
+
+ // Remove leading slash if present to avoid double slashes
+ const normalizedPath = path.startsWith("/") ? path : `/${path}`;
+
+ // Remove trailing slash from base URL if present
+ const normalizedBase = base.endsWith("/") ? base.slice(0, -1) : base;
+
+ return `${normalizedBase}${normalizedPath}`;
+}
diff --git a/web/lib/i18n.ts b/web/lib/i18n.ts
new file mode 100644
index 000000000..c10c1f539
--- /dev/null
+++ b/web/lib/i18n.ts
@@ -0,0 +1,200 @@
+export const translations = {
+ en: {
+ // Sidebar
+ Start: "Start",
+ Learn: "Learn",
+ Research: "Research",
+ Dashboard: "Dashboard",
+ "Question Generator": "Question Generator",
+ "Smart Solver": "Smart Solver",
+ IdeaGen: "IdeaGen",
+ "Deep Research": "Deep Research",
+ "Co-Writer": "Co-Writer",
+ "Guided Learning": "Guided Learning",
+ "Knowledge Bases": "Knowledge Bases",
+ Notebooks: "Notebooks",
+ Settings: "Settings",
+
+ // Common
+ Loading: "Loading...",
+ Save: "Save",
+ Cancel: "Cancel",
+ Error: "Error",
+ Success: "Success",
+ "View All": "View All",
+ Refresh: "Refresh",
+ "Create": "Create",
+
+ // Settings Page
+ "System Settings": "System Settings",
+ "Manage system configuration and preferences": "Manage system configuration and preferences",
+ "General Settings": "General Settings",
+ "Environment Variables": "Environment Variables",
+ "Interface Preferences": "Interface Preferences",
+ Theme: "Theme",
+ "Light Mode": "Light Mode",
+ "Dark Mode": "Dark Mode",
+ Language: "Language",
+ English: "English",
+ Chinese: "Chinese",
+ "System Configuration": "System Configuration",
+ "System Language": "System Language",
+ "Default language for system operations": "Default language for system operations",
+ "Research Tools": "Research Tools",
+ "Web Search": "Web Search",
+ "Max Results": "Max Results",
+ "Knowledge Base": "Knowledge Base",
+ "Default KB": "Default KB",
+ "Base Directory": "Base Directory",
+ "Text-to-Speech": "Text-to-Speech",
+ "Default Voice": "Default Voice",
+ "Default Language": "Default Language",
+ "Active Models": "Active Models",
+ Status: "Status",
+ "Active LLM Model": "Active LLM Model",
+ "Not configured": "Not configured",
+ "Configure in Environment Variables tab": "Configure in Environment Variables tab",
+ "Save All Changes": "Save All Changes",
+ "Configuration Saved": "Configuration Saved",
+ "Configuration Status": "Configuration Status",
+ "Refresh Status": "Refresh Status",
+ "Runtime Configuration": "Runtime Configuration",
+ "Environment variables are loaded from": "Environment variables are loaded from",
+ "file on startup": "file on startup",
+ "Changes made here take effect immediately but are not saved to file": "Changes made here take effect immediately but are not saved to file",
+ "On restart, values will be reloaded from": "On restart, values will be reloaded from",
+ "Apply Environment Changes": "Apply Environment Changes",
+ "Environment Updated!": "Environment Updated!",
+ "REQUIRED": "REQUIRED",
+ "Error loading data": "Error loading data",
+ "Failed to load settings": "Failed to load settings",
+ "Failed to connect to backend": "Failed to connect to backend",
+
+ // Dashboard Page
+ "Overview of your recent learning activities": "Overview of your recent learning activities",
+ "Recent Activity": "Recent Activity",
+ "Loading activities...": "Loading activities...",
+ "No recent activity found": "No recent activity found",
+ "Start solving problems or generating questions!": "Start solving problems or generating questions!",
+ "Problem Solved": "Problem Solved",
+ "Question Generated": "Question Generated",
+ "Research Report": "Research Report",
+ Activity: "Activity",
+ "My Notebooks": "My Notebooks",
+ records: "records",
+ Solve: "Solve",
+ Question: "Question",
+ "No notebooks yet": "No notebooks yet",
+ "Create your first notebook": "Create your first notebook",
+ "System Status": "System Status",
+ "Quick Actions": "Quick Actions",
+ "Ask a Question": "Ask a Question",
+ "Generate Quiz": "Generate Quiz",
+ "Start Research": "Start Research",
+ },
+ zh: {
+ // Sidebar
+ Start: "开始",
+ Learn: "学习",
+ Research: "研究",
+ Dashboard: "仪表盘",
+ "Question Generator": "题目生成器",
+ "Smart Solver": "智能解题",
+ IdeaGen: "创意生成",
+ "Deep Research": "深度研究",
+ "Co-Writer": "智能写作",
+ "Guided Learning": "引导式学习",
+ "Knowledge Bases": "知识库",
+ Notebooks: "笔记本",
+ Settings: "设置",
+
+ // Common
+ Loading: "加载中...",
+ Save: "保存",
+ Cancel: "取消",
+ Error: "错误",
+ Success: "成功",
+ "View All": "查看全部",
+ Refresh: "刷新",
+ "Create": "创建",
+
+ // Settings Page
+ "System Settings": "系统设置",
+ "Manage system configuration and preferences": "管理系统配置和偏好设置",
+ "General Settings": "常规设置",
+ "Environment Variables": "环境变量",
+ "Interface Preferences": "界面偏好",
+ Theme: "主题",
+ "Light Mode": "浅色模式",
+ "Dark Mode": "深色模式",
+ Language: "语言",
+ English: "英语",
+ Chinese: "中文",
+ "System Configuration": "系统配置",
+ "System Language": "系统语言",
+ "Default language for system operations": "系统操作的默认语言",
+ "Research Tools": "研究工具",
+ "Web Search": "网络搜索",
+ "Max Results": "最大结果数",
+ "Knowledge Base": "知识库",
+ "Default KB": "默认知识库",
+ "Base Directory": "基础目录",
+ "Text-to-Speech": "文字转语音",
+ "Default Voice": "默认语音",
+ "Default Language": "默认语言",
+ "Active Models": "活动模型",
+ Status: "状态",
+ "Active LLM Model": "当前 LLM 模型",
+ "Not configured": "未配置",
+ "Configure in Environment Variables tab": "请在环境变量标签页中配置",
+ "Save All Changes": "保存所有更改",
+ "Configuration Saved": "配置已保存",
+ "Configuration Status": "配置状态",
+ "Refresh Status": "刷新状态",
+ "Runtime Configuration": "运行时配置",
+ "Environment variables are loaded from": "环境变量从",
+ "file on startup": "文件加载于启动时",
+ "Changes made here take effect immediately but are not saved to file": "此处的更改立即生效但不会保存到文件",
+ "On restart, values will be reloaded from": "重启后,值将从以下文件重新加载",
+ "Apply Environment Changes": "应用环境变量更改",
+ "Environment Updated!": "环境变量已更新!",
+ "REQUIRED": "必填",
+ "Error loading data": "加载数据出错",
+ "Failed to load settings": "加载设置失败",
+ "Failed to connect to backend": "连接后端失败",
+
+ // Dashboard Page
+ "Overview of your recent learning activities": "您最近的学习活动概览",
+ "Recent Activity": "最近活动",
+ "Loading activities...": "加载活动中...",
+ "No recent activity found": "未找到最近活动",
+ "Start solving problems or generating questions!": "开始解题或生成题目吧!",
+ "Problem Solved": "问题已解决",
+ "Question Generated": "题目已生成",
+ "Research Report": "研究报告",
+ Activity: "活动",
+ "My Notebooks": "我的笔记本",
+ records: "条记录",
+ Solve: "解题",
+ Question: "题目",
+ "No notebooks yet": "暂无笔记本",
+ "Create your first notebook": "创建您的第一个笔记本",
+ "System Status": "系统状态",
+ "Quick Actions": "快捷操作",
+ "Ask a Question": "提问问题",
+ "Generate Quiz": "生成测验",
+ "Start Research": "开始研究",
+ },
+};
+
+export type Language = "en" | "zh";
+
+export function getTranslation(lang: Language, key: string): string {
+ const dict = translations[lang] || translations.en;
+ return dict[key as keyof typeof dict] || key;
+}
+
+// Hook helper for components
+export function useTranslation(lang: Language) {
+ return (key: string) => getTranslation(lang, key);
+}
diff --git a/web/lib/latex.ts b/web/lib/latex.ts
new file mode 100644
index 000000000..a144e19e8
--- /dev/null
+++ b/web/lib/latex.ts
@@ -0,0 +1,55 @@
+/**
+ * Utility functions for LaTeX processing
+ *
+ * remark-math only supports $...$ and $$...$$ delimiters by default.
+ * Many LLMs output LaTeX using \(...\) and \[...\] delimiters.
+ * This utility converts between formats.
+ */
+
+/**
+ * Convert LaTeX delimiters from \(...\) and \[...\] to $...$ and $$...$$
+ * This makes the content compatible with remark-math for ReactMarkdown rendering.
+ *
+ * @param content - The content containing LaTeX with \(...\) or \[...\] delimiters
+ * @returns Content with $...$ and $$...$$ delimiters
+ */
+export function convertLatexDelimiters(content: string): string {
+ if (!content) return content;
+
+ let result = content;
+
+ // Convert \[...\] to $$...$$ (block math)
+ // Use a regex that handles multiline content
+ // Note: In JSON strings, \[ becomes \\[ which in JS becomes \[
+ result = result.replace(/\\\[([\s\S]*?)\\\]/g, "\n$$\n$1\n$$\n");
+
+ // Convert \(...\) to $...$ (inline math)
+ // Be careful not to match escaped parentheses in other contexts
+ result = result.replace(/\\\(([\s\S]*?)\\\)/g, " $$$1$$ ");
+
+ // Also handle cases where LaTeX is directly in the text without proper delimiters
+ // e.g., standalone \lim, \frac, etc. that should be wrapped
+ // This is a common issue with LLM outputs
+
+ // Clean up multiple consecutive newlines
+ result = result.replace(/\n{3,}/g, "\n\n");
+
+ return result;
+}
+
+/**
+ * Process content for ReactMarkdown rendering with proper LaTeX support
+ * This is a convenience wrapper that applies all necessary transformations.
+ *
+ * @param content - The raw content to process
+ * @returns Processed content ready for ReactMarkdown with remark-math
+ */
+export function processLatexContent(content: string): string {
+ if (!content) return "";
+
+ // Convert to string if not already
+ const str = String(content);
+
+ // Apply delimiter conversion
+ return convertLatexDelimiters(str);
+}
diff --git a/web/lib/pdfExport.ts b/web/lib/pdfExport.ts
new file mode 100644
index 000000000..027c8eddc
--- /dev/null
+++ b/web/lib/pdfExport.ts
@@ -0,0 +1,309 @@
+/**
+ * PDF Export Utility for Research Reports
+ *
+ * This module handles the conversion of HTML content to PDF with proper:
+ * - Page margins and spacing
+ * - SVG to image conversion (for Mermaid diagrams)
+ * - Correct page splitting without content overlap
+ * - Page numbering
+ */
+
+import jsPDF from "jspdf";
+import html2canvas from "html2canvas";
+
+export interface PdfExportOptions {
+ /** Filename for the PDF (without .pdf extension) */
+ filename?: string;
+ /** Left margin in mm */
+ marginLeft?: number;
+ /** Right margin in mm */
+ marginRight?: number;
+ /** Top margin in mm */
+ marginTop?: number;
+ /** Bottom margin in mm */
+ marginBottom?: number;
+ /** Whether to show page numbers */
+ showPageNumbers?: boolean;
+ /** Scale factor for rendering (higher = better quality but slower) */
+ scale?: number;
+}
+
+const defaultOptions: Required<PdfExportOptions> = {
+ filename: "report",
+ marginLeft: 20,
+ marginRight: 20,
+ marginTop: 25,
+ marginBottom: 25,
+ showPageNumbers: true,
+ scale: 2,
+};
+
+/**
+ * Convert all SVG elements in an element to PNG images
+ * This is necessary because html2canvas has limited SVG support
+ */
+async function convertSvgsToImages(element: HTMLElement): Promise<void> {
+ const svgs = element.querySelectorAll("svg");
+
+ const conversionPromises = Array.from(svgs).map(async (svg) => {
+ try {
+ const bbox = svg.getBoundingClientRect();
+ const width = Math.max(bbox.width, 100);
+ const height = Math.max(bbox.height, 100);
+
+ // Clone and set explicit dimensions
+ const clonedSvg = svg.cloneNode(true) as SVGElement;
+ clonedSvg.setAttribute("width", String(width));
+ clonedSvg.setAttribute("height", String(height));
+ clonedSvg.setAttribute("xmlns", "http://www.w3.org/2000/svg");
+
+ // Serialize to string
+ const serializer = new XMLSerializer();
+ let svgString = serializer.serializeToString(clonedSvg);
+
+ // Ensure proper XML encoding
+ if (!svgString.includes("xmlns=")) {
+ svgString = svgString.replace(
+ "<svg",
+ '<svg xmlns="http://www.w3.org/2000/svg"',
+ );
+ }
+
+ // Create blob and URL
+ const svgBlob = new Blob([svgString], {
+ type: "image/svg+xml;charset=utf-8",
+ });
+ const url = URL.createObjectURL(svgBlob);
+
+ // Load as image
+ const img = new Image();
+
+ await new Promise<void>((resolve, reject) => {
+ img.onload = () => {
+ // Create high-res canvas
+ const canvas = document.createElement("canvas");
+ const scale = 2;
+ canvas.width = width * scale;
+ canvas.height = height * scale;
+
+ const ctx = canvas.getContext("2d");
+ if (ctx) {
+ ctx.fillStyle = "white";
+ ctx.fillRect(0, 0, canvas.width, canvas.height);
+ ctx.scale(scale, scale);
+ ctx.drawImage(img, 0, 0, width, height);
+
+ // Create replacement image element
+ const replacement = document.createElement("img");
+ replacement.src = canvas.toDataURL("image/png");
+ replacement.style.width = `${width}px`;
+ replacement.style.height = `${height}px`;
+ replacement.style.display = "block";
+ replacement.style.margin = "16px auto";
+
+ svg.parentNode?.replaceChild(replacement, svg);
+ }
+ URL.revokeObjectURL(url);
+ resolve();
+ };
+
+ img.onerror = () => {
+ URL.revokeObjectURL(url);
+ // Don't reject, just log and continue
+ console.warn("Failed to convert SVG, skipping");
+ resolve();
+ };
+ });
+
+ img.src = url;
+ } catch (err) {
+ console.warn("SVG conversion error:", err);
+ }
+ });
+
+ await Promise.all(conversionPromises);
+}
+
+/**
+ * Split a tall canvas into page-sized chunks
+ */
+function splitCanvasIntoPages(
+ canvas: HTMLCanvasElement,
+ pageWidth: number,
+ pageHeight: number,
+ marginLeft: number,
+ marginTop: number,
+ marginBottom: number,
+): HTMLCanvasElement[] {
+ const contentWidth = pageWidth - marginLeft * 2;
+ const contentHeight = pageHeight - marginTop - marginBottom;
+
+ // Calculate dimensions in canvas pixels
+ const imgWidth = contentWidth;
+ const imgHeight = (canvas.height * imgWidth) / canvas.width;
+
+ // Convert content height to image pixels
+ const pageHeightInImgPixels = (contentHeight / imgWidth) * canvas.width;
+
+ const numPages = Math.ceil(canvas.height / pageHeightInImgPixels);
+ const pages: HTMLCanvasElement[] = [];
+
+ for (let i = 0; i < numPages; i++) {
+ const pageCanvas = document.createElement("canvas");
+ pageCanvas.width = canvas.width;
+ pageCanvas.height = Math.min(
+ pageHeightInImgPixels,
+ canvas.height - i * pageHeightInImgPixels,
+ );
+
+ const ctx = pageCanvas.getContext("2d");
+ if (ctx) {
+ ctx.fillStyle = "white";
+ ctx.fillRect(0, 0, pageCanvas.width, pageCanvas.height);
+
+ // Draw the portion of the original canvas for this page
+ ctx.drawImage(
+ canvas,
+ 0,
+ i * pageHeightInImgPixels, // Source x, y
+ canvas.width,
+ pageCanvas.height, // Source width, height
+ 0,
+ 0, // Destination x, y
+ canvas.width,
+ pageCanvas.height, // Destination width, height
+ );
+ }
+
+ pages.push(pageCanvas);
+ }
+
+ return pages;
+}
+
+/**
+ * Export HTML element to PDF
+ */
+export async function exportToPdf(
+ element: HTMLElement,
+ options: PdfExportOptions = {},
+): Promise<void> {
+ const opts = { ...defaultOptions, ...options };
+
+ // Clone element to avoid modifying the original
+ const clone = element.cloneNode(true) as HTMLElement;
+ clone.style.position = "absolute";
+ clone.style.top = "-99999px";
+ clone.style.left = "-99999px";
+ clone.style.width = "800px";
+ clone.style.backgroundColor = "white";
+ document.body.appendChild(clone);
+
+ try {
+ // Wait for any async rendering
+ await new Promise((resolve) => setTimeout(resolve, 500));
+
+ // Convert SVGs to images
+ await convertSvgsToImages(clone);
+
+ // Additional wait for image loading
+ await new Promise((resolve) => setTimeout(resolve, 300));
+
+ // Capture as canvas
+ const canvas = await html2canvas(clone, {
+ scale: opts.scale,
+ useCORS: true,
+ logging: false,
+ backgroundColor: "#ffffff",
+ windowWidth: 800,
+ allowTaint: true,
+ });
+
+ // PDF dimensions
+ const pageWidth = 210; // A4 width in mm
+ const pageHeight = 297; // A4 height in mm
+
+ // Split canvas into pages
+ const pages = splitCanvasIntoPages(
+ canvas,
+ pageWidth,
+ pageHeight,
+ opts.marginLeft,
+ opts.marginTop,
+ opts.marginBottom,
+ );
+
+ // Create PDF
+ const pdf = new jsPDF("p", "mm", "a4");
+ const contentWidth = pageWidth - opts.marginLeft - opts.marginRight;
+ const contentHeight = pageHeight - opts.marginTop - opts.marginBottom;
+
+ for (let i = 0; i < pages.length; i++) {
+ if (i > 0) {
+ pdf.addPage();
+ }
+
+ const pageCanvas = pages[i];
+ const imgData = pageCanvas.toDataURL("image/png");
+
+ // Calculate height for this page's content
+ const imgHeight = (pageCanvas.height * contentWidth) / pageCanvas.width;
+
+ // Add image to PDF
+ pdf.addImage(
+ imgData,
+ "PNG",
+ opts.marginLeft,
+ opts.marginTop,
+ contentWidth,
+ Math.min(imgHeight, contentHeight),
+ );
+
+ // Add page number
+ if (opts.showPageNumbers) {
+ pdf.setFontSize(10);
+ pdf.setTextColor(128, 128, 128);
+ pdf.text(`${i + 1} / ${pages.length}`, pageWidth / 2, pageHeight - 10, {
+ align: "center",
+ });
+ }
+ }
+
+ // Save PDF
+ pdf.save(`${opts.filename}.pdf`);
+ } finally {
+ // Clean up
+ document.body.removeChild(clone);
+ }
+}
+
+/**
+ * Preprocess markdown content for PDF export
+ * - Expands <details> tags
+ * - Cleans up formatting
+ */
+export function preprocessMarkdownForPdf(markdown: string): string {
+ if (!markdown) return markdown;
+
+ let result = markdown;
+
+ // Remove <details> and </details> tags
+ result = result.replace(/<details\s*>/gi, "");
+ result = result.replace(/<\/details\s*>/gi, "");
+
+ // Convert <summary>...</summary> to bold headers
+ result = result.replace(
+ /<summary\s*>([^<]*)<\/summary\s*>/gi,
+ "\n\n**$1**\n",
+ );
+
+ // Remove empty anchor tags
+ result = result.replace(/<a\s+id="[^"]*"\s*><\/a>/gi, "");
+
+ // Clean up excessive newlines
+ result = result.replace(/\n{4,}/g, "\n\n\n");
+
+ return result;
+}
+
+export default exportToPdf;
diff --git a/web/next-env.d.ts b/web/next-env.d.ts
new file mode 100644
index 000000000..4f11a03dc
--- /dev/null
+++ b/web/next-env.d.ts
@@ -0,0 +1,5 @@
+/// <reference types="next" />
+/// <reference types="next/image-types/global" />
+
+// NOTE: This file should not be edited
+// see https://nextjs.org/docs/basic-features/typescript for more information.
diff --git a/web/next.config.js b/web/next.config.js
new file mode 100644
index 000000000..db3fef397
--- /dev/null
+++ b/web/next.config.js
@@ -0,0 +1,25 @@
+/** @type {import('next').NextConfig} */
+const path = require("path");
+
+const nextConfig = {
+ // Handle ESM packages compatibility
+ experimental: {
+ esmExternals: "loose",
+ },
+ webpack: (config, { isServer }) => {
+ // Fix for mermaid's cytoscape dependency - use CJS version
+ config.resolve.alias = {
+ ...config.resolve.alias,
+ cytoscape: path.resolve(
+ __dirname,
+ "node_modules/cytoscape/dist/cytoscape.cjs.js",
+ ),
+ };
+
+ return config;
+ },
+ // Transpile mermaid and related packages
+ transpilePackages: ["mermaid"],
+};
+
+module.exports = nextConfig;
diff --git a/web/package-lock.json b/web/package-lock.json
new file mode 100644
index 000000000..a0626d94b
--- /dev/null
+++ b/web/package-lock.json
@@ -0,0 +1,8997 @@
+{
+ "name": "opentutor-web",
+ "version": "0.1.0",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "opentutor-web",
+ "version": "0.1.0",
+ "dependencies": {
+ "clsx": "^2.0.0",
+ "cytoscape": "^3.33.1",
+ "framer-motion": "^10.16.4",
+ "html2canvas": "^1.4.1",
+ "jspdf": "^2.5.1",
+ "lucide-react": "^0.294.0",
+ "mermaid": "^11.12.2",
+ "next": "14.0.3",
+ "react": "^18",
+ "react-dom": "^18",
+ "react-markdown": "^9.0.1",
+ "rehype-katex": "^7.0.0",
+ "rehype-raw": "^7.0.0",
+ "remark-gfm": "^4.0.0",
+ "remark-math": "^6.0.0",
+ "tailwind-merge": "^2.0.0"
+ },
+ "devDependencies": {
+ "@types/node": "^20",
+ "@types/react": "^18",
+ "@types/react-dom": "^18",
+ "autoprefixer": "^10.0.1",
+ "eslint": "^8",
+ "eslint-config-next": "14.0.3",
+ "postcss": "^8",
+ "tailwindcss": "^3.3.0",
+ "typescript": "^5"
+ }
+ },
+ "node_modules/@alloc/quick-lru": {
+ "version": "5.2.0",
+ "resolved": "https://registry.npmmirror.com/@alloc/quick-lru/-/quick-lru-5.2.0.tgz",
+ "integrity": "sha512-UrcABB+4bUrFABwbluTIBErXwvbsU/V7TZWfmbgJfbkwiBuziS9gxdODUyuiecfdGQ85jglMW6juS3+z5TsKLw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=10"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/@antfu/install-pkg": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/@antfu/install-pkg/-/install-pkg-1.1.0.tgz",
+ "integrity": "sha512-MGQsmw10ZyI+EJo45CdSER4zEb+p31LpDAFp2Z3gkSd1yqVZGi0Ebx++YTEMonJy4oChEMLsxZ64j8FH6sSqtQ==",
+ "license": "MIT",
+ "dependencies": {
+ "package-manager-detector": "^1.3.0",
+ "tinyexec": "^1.0.1"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/antfu"
+ }
+ },
+ "node_modules/@babel/runtime": {
+ "version": "7.28.4",
+ "resolved": "https://registry.npmmirror.com/@babel/runtime/-/runtime-7.28.4.tgz",
+ "integrity": "sha512-Q/N6JNWvIvPnLDvjlE1OUBLPQHH6l3CltCEsHIujp45zQUSSh8K+gHnaEX45yAT1nyngnINhvWtzN+Nb9D8RAQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@braintree/sanitize-url": {
+ "version": "7.1.1",
+ "resolved": "https://registry.npmjs.org/@braintree/sanitize-url/-/sanitize-url-7.1.1.tgz",
+ "integrity": "sha512-i1L7noDNxtFyL5DmZafWy1wRVhGehQmzZaz1HiN5e7iylJMSZR7ekOV7NsIqa5qBldlLrsKv4HbgFUVlQrz8Mw==",
+ "license": "MIT"
+ },
+ "node_modules/@chevrotain/cst-dts-gen": {
+ "version": "11.0.3",
+ "resolved": "https://registry.npmjs.org/@chevrotain/cst-dts-gen/-/cst-dts-gen-11.0.3.tgz",
+ "integrity": "sha512-BvIKpRLeS/8UbfxXxgC33xOumsacaeCKAjAeLyOn7Pcp95HiRbrpl14S+9vaZLolnbssPIUuiUd8IvgkRyt6NQ==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@chevrotain/gast": "11.0.3",
+ "@chevrotain/types": "11.0.3",
+ "lodash-es": "4.17.21"
+ }
+ },
+ "node_modules/@chevrotain/gast": {
+ "version": "11.0.3",
+ "resolved": "https://registry.npmjs.org/@chevrotain/gast/-/gast-11.0.3.tgz",
+ "integrity": "sha512-+qNfcoNk70PyS/uxmj3li5NiECO+2YKZZQMbmjTqRI3Qchu8Hig/Q9vgkHpI3alNjr7M+a2St5pw5w5F6NL5/Q==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@chevrotain/types": "11.0.3",
+ "lodash-es": "4.17.21"
+ }
+ },
+ "node_modules/@chevrotain/regexp-to-ast": {
+ "version": "11.0.3",
+ "resolved": "https://registry.npmjs.org/@chevrotain/regexp-to-ast/-/regexp-to-ast-11.0.3.tgz",
+ "integrity": "sha512-1fMHaBZxLFvWI067AVbGJav1eRY7N8DDvYCTwGBiE/ytKBgP8azTdgyrKyWZ9Mfh09eHWb5PgTSO8wi7U824RA==",
+ "license": "Apache-2.0"
+ },
+ "node_modules/@chevrotain/types": {
+ "version": "11.0.3",
+ "resolved": "https://registry.npmjs.org/@chevrotain/types/-/types-11.0.3.tgz",
+ "integrity": "sha512-gsiM3G8b58kZC2HaWR50gu6Y1440cHiJ+i3JUvcp/35JchYejb2+5MVeJK0iKThYpAa/P2PYFV4hoi44HD+aHQ==",
+ "license": "Apache-2.0"
+ },
+ "node_modules/@chevrotain/utils": {
+ "version": "11.0.3",
+ "resolved": "https://registry.npmjs.org/@chevrotain/utils/-/utils-11.0.3.tgz",
+ "integrity": "sha512-YslZMgtJUyuMbZ+aKvfF3x1f5liK4mWNxghFRv7jqRR9C3R3fAOGTTKvxXDa2Y1s9zSbcpuO0cAxDYsc9SrXoQ==",
+ "license": "Apache-2.0"
+ },
+ "node_modules/@emnapi/core": {
+ "version": "1.7.1",
+ "resolved": "https://registry.npmmirror.com/@emnapi/core/-/core-1.7.1.tgz",
+ "integrity": "sha512-o1uhUASyo921r2XtHYOHy7gdkGLge8ghBEQHMWmyJFoXlpU58kIrhhN3w26lpQb6dspetweapMn2CSNwQ8I4wg==",
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "@emnapi/wasi-threads": "1.1.0",
+ "tslib": "^2.4.0"
+ }
+ },
+ "node_modules/@emnapi/runtime": {
+ "version": "1.7.1",
+ "resolved": "https://registry.npmmirror.com/@emnapi/runtime/-/runtime-1.7.1.tgz",
+ "integrity": "sha512-PVtJr5CmLwYAU9PZDMITZoR5iAOShYREoR45EyyLrbntV50mdePTgUn4AmOw90Ifcj+x2kRjdzr1HP3RrNiHGA==",
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "tslib": "^2.4.0"
+ }
+ },
+ "node_modules/@emnapi/wasi-threads": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmmirror.com/@emnapi/wasi-threads/-/wasi-threads-1.1.0.tgz",
+ "integrity": "sha512-WI0DdZ8xFSbgMjR1sFsKABJ/C5OnRrjT06JXbZKexJGrDuPTzZdDYfFlsgcCXCyf+suG5QU2e/y1Wo2V/OapLQ==",
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "tslib": "^2.4.0"
+ }
+ },
+ "node_modules/@emotion/is-prop-valid": {
+ "version": "0.8.8",
+ "resolved": "https://registry.npmmirror.com/@emotion/is-prop-valid/-/is-prop-valid-0.8.8.tgz",
+ "integrity": "sha512-u5WtneEAr5IDG2Wv65yhunPSMLIpuKsbuOktRojfrEiEvRyC85LgPMZI63cr7NUqT8ZIGdSVg8ZKGxIug4lXcA==",
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "@emotion/memoize": "0.7.4"
+ }
+ },
+ "node_modules/@emotion/memoize": {
+ "version": "0.7.4",
+ "resolved": "https://registry.npmmirror.com/@emotion/memoize/-/memoize-0.7.4.tgz",
+ "integrity": "sha512-Ja/Vfqe3HpuzRsG1oBtWTHk2PGZ7GR+2Vz5iYGelAw8dx32K0y7PjVuxK6z1nMpZOqAFsRUPCkK1YjJ56qJlgw==",
+ "license": "MIT",
+ "optional": true
+ },
+ "node_modules/@eslint-community/eslint-utils": {
+ "version": "4.9.0",
+ "resolved": "https://registry.npmmirror.com/@eslint-community/eslint-utils/-/eslint-utils-4.9.0.tgz",
+ "integrity": "sha512-ayVFHdtZ+hsq1t2Dy24wCmGXGe4q9Gu3smhLYALJrr473ZH27MsnSL+LKUlimp4BWJqMDMLmPpx/Q9R3OAlL4g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "eslint-visitor-keys": "^3.4.3"
+ },
+ "engines": {
+ "node": "^12.22.0 || ^14.17.0 || >=16.0.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/eslint"
+ },
+ "peerDependencies": {
+ "eslint": "^6.0.0 || ^7.0.0 || >=8.0.0"
+ }
+ },
+ "node_modules/@eslint-community/regexpp": {
+ "version": "4.12.2",
+ "resolved": "https://registry.npmmirror.com/@eslint-community/regexpp/-/regexpp-4.12.2.tgz",
+ "integrity": "sha512-EriSTlt5OC9/7SXkRSCAhfSxxoSUgBm33OH+IkwbdpgoqsSsUg7y3uh+IICI/Qg4BBWr3U2i39RpmycbxMq4ew==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": "^12.0.0 || ^14.0.0 || >=16.0.0"
+ }
+ },
+ "node_modules/@eslint/eslintrc": {
+ "version": "2.1.4",
+ "resolved": "https://registry.npmmirror.com/@eslint/eslintrc/-/eslintrc-2.1.4.tgz",
+ "integrity": "sha512-269Z39MS6wVJtsoUl10L60WdkhJVdPG24Q4eZTH3nnF6lpvSShEK3wQjDX9JRWAUPvPh7COouPpU9IrqaZFvtQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "ajv": "^6.12.4",
+ "debug": "^4.3.2",
+ "espree": "^9.6.0",
+ "globals": "^13.19.0",
+ "ignore": "^5.2.0",
+ "import-fresh": "^3.2.1",
+ "js-yaml": "^4.1.0",
+ "minimatch": "^3.1.2",
+ "strip-json-comments": "^3.1.1"
+ },
+ "engines": {
+ "node": "^12.22.0 || ^14.17.0 || >=16.0.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/eslint"
+ }
+ },
+ "node_modules/@eslint/js": {
+ "version": "8.57.1",
+ "resolved": "https://registry.npmmirror.com/@eslint/js/-/js-8.57.1.tgz",
+ "integrity": "sha512-d9zaMRSTIKDLhctzH12MtXvJKSSUhaHcjV+2Z+GK+EEY7XKpP5yR4x+N3TAcHTcu963nIr+TMcCb4DBCYX1z6Q==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": "^12.22.0 || ^14.17.0 || >=16.0.0"
+ }
+ },
+ "node_modules/@humanwhocodes/config-array": {
+ "version": "0.13.0",
+ "resolved": "https://registry.npmmirror.com/@humanwhocodes/config-array/-/config-array-0.13.0.tgz",
+ "integrity": "sha512-DZLEEqFWQFiyK6h5YIeynKx7JlvCYWL0cImfSRXZ9l4Sg2efkFGTuFf6vzXjK1cq6IYkU+Eg/JizXw+TD2vRNw==",
+ "deprecated": "Use @eslint/config-array instead",
+ "dev": true,
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@humanwhocodes/object-schema": "^2.0.3",
+ "debug": "^4.3.1",
+ "minimatch": "^3.0.5"
+ },
+ "engines": {
+ "node": ">=10.10.0"
+ }
+ },
+ "node_modules/@humanwhocodes/module-importer": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmmirror.com/@humanwhocodes/module-importer/-/module-importer-1.0.1.tgz",
+ "integrity": "sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "engines": {
+ "node": ">=12.22"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/nzakas"
+ }
+ },
+ "node_modules/@humanwhocodes/object-schema": {
+ "version": "2.0.3",
+ "resolved": "https://registry.npmmirror.com/@humanwhocodes/object-schema/-/object-schema-2.0.3.tgz",
+ "integrity": "sha512-93zYdMES/c1D69yZiKDBj0V24vqNzB/koF26KPaagAfd3P/4gUlh3Dys5ogAK+Exi9QyzlD8x/08Zt7wIKcDcA==",
+ "deprecated": "Use @eslint/object-schema instead",
+ "dev": true,
+ "license": "BSD-3-Clause"
+ },
+ "node_modules/@iconify/types": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/@iconify/types/-/types-2.0.0.tgz",
+ "integrity": "sha512-+wluvCrRhXrhyOmRDJ3q8mux9JkKy5SJ/v8ol2tu4FVjyYvtEzkc/3pK15ET6RKg4b4w4BmTk1+gsCUhf21Ykg==",
+ "license": "MIT"
+ },
+ "node_modules/@iconify/utils": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/@iconify/utils/-/utils-3.1.0.tgz",
+ "integrity": "sha512-Zlzem1ZXhI1iHeeERabLNzBHdOa4VhQbqAcOQaMKuTuyZCpwKbC2R4Dd0Zo3g9EAc+Y4fiarO8HIHRAth7+skw==",
+ "license": "MIT",
+ "dependencies": {
+ "@antfu/install-pkg": "^1.1.0",
+ "@iconify/types": "^2.0.0",
+ "mlly": "^1.8.0"
+ }
+ },
+ "node_modules/@jridgewell/gen-mapping": {
+ "version": "0.3.13",
+ "resolved": "https://registry.npmmirror.com/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz",
+ "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@jridgewell/sourcemap-codec": "^1.5.0",
+ "@jridgewell/trace-mapping": "^0.3.24"
+ }
+ },
+ "node_modules/@jridgewell/resolve-uri": {
+ "version": "3.1.2",
+ "resolved": "https://registry.npmmirror.com/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz",
+ "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6.0.0"
+ }
+ },
+ "node_modules/@jridgewell/sourcemap-codec": {
+ "version": "1.5.5",
+ "resolved": "https://registry.npmmirror.com/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz",
+ "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@jridgewell/trace-mapping": {
+ "version": "0.3.31",
+ "resolved": "https://registry.npmmirror.com/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz",
+ "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@jridgewell/resolve-uri": "^3.1.0",
+ "@jridgewell/sourcemap-codec": "^1.4.14"
+ }
+ },
+ "node_modules/@mermaid-js/parser": {
+ "version": "0.6.3",
+ "resolved": "https://registry.npmjs.org/@mermaid-js/parser/-/parser-0.6.3.tgz",
+ "integrity": "sha512-lnjOhe7zyHjc+If7yT4zoedx2vo4sHaTmtkl1+or8BRTnCtDmcTpAjpzDSfCZrshM5bCoz0GyidzadJAH1xobA==",
+ "license": "MIT",
+ "dependencies": {
+ "langium": "3.3.1"
+ }
+ },
+ "node_modules/@napi-rs/wasm-runtime": {
+ "version": "0.2.12",
+ "resolved": "https://registry.npmmirror.com/@napi-rs/wasm-runtime/-/wasm-runtime-0.2.12.tgz",
+ "integrity": "sha512-ZVWUcfwY4E/yPitQJl481FjFo3K22D6qF0DuFH6Y/nbnE11GY5uguDxZMGXPQ8WQ0128MXQD7TnfHyK4oWoIJQ==",
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "@emnapi/core": "^1.4.3",
+ "@emnapi/runtime": "^1.4.3",
+ "@tybys/wasm-util": "^0.10.0"
+ }
+ },
+ "node_modules/@next/env": {
+ "version": "14.0.3",
+ "resolved": "https://registry.npmmirror.com/@next/env/-/env-14.0.3.tgz",
+ "integrity": "sha512-7xRqh9nMvP5xrW4/+L0jgRRX+HoNRGnfJpD+5Wq6/13j3dsdzxO3BCXn7D3hMqsDb+vjZnJq+vI7+EtgrYZTeA==",
+ "license": "MIT"
+ },
+ "node_modules/@next/eslint-plugin-next": {
+ "version": "14.0.3",
+ "resolved": "https://registry.npmmirror.com/@next/eslint-plugin-next/-/eslint-plugin-next-14.0.3.tgz",
+ "integrity": "sha512-j4K0n+DcmQYCVnSAM+UByTVfIHnYQy2ODozfQP+4RdwtRDfobrIvKq1K4Exb2koJ79HSSa7s6B2SA8T/1YR3RA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "glob": "7.1.7"
+ }
+ },
+ "node_modules/@next/swc-darwin-arm64": {
+ "version": "14.0.3",
+ "resolved": "https://registry.npmmirror.com/@next/swc-darwin-arm64/-/swc-darwin-arm64-14.0.3.tgz",
+ "integrity": "sha512-64JbSvi3nbbcEtyitNn2LEDS/hcleAFpHdykpcnrstITFlzFgB/bW0ER5/SJJwUPj+ZPY+z3e+1jAfcczRLVGw==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">= 10"
+ }
+ },
+ "node_modules/@next/swc-darwin-x64": {
+ "version": "14.0.3",
+ "resolved": "https://registry.npmmirror.com/@next/swc-darwin-x64/-/swc-darwin-x64-14.0.3.tgz",
+ "integrity": "sha512-RkTf+KbAD0SgYdVn1XzqE/+sIxYGB7NLMZRn9I4Z24afrhUpVJx6L8hsRnIwxz3ERE2NFURNliPjJ2QNfnWicQ==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">= 10"
+ }
+ },
+ "node_modules/@next/swc-linux-arm64-gnu": {
+ "version": "14.0.3",
+ "resolved": "https://registry.npmmirror.com/@next/swc-linux-arm64-gnu/-/swc-linux-arm64-gnu-14.0.3.tgz",
+ "integrity": "sha512-3tBWGgz7M9RKLO6sPWC6c4pAw4geujSwQ7q7Si4d6bo0l6cLs4tmO+lnSwFp1Tm3lxwfMk0SgkJT7EdwYSJvcg==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 10"
+ }
+ },
+ "node_modules/@next/swc-linux-arm64-musl": {
+ "version": "14.0.3",
+ "resolved": "https://registry.npmmirror.com/@next/swc-linux-arm64-musl/-/swc-linux-arm64-musl-14.0.3.tgz",
+ "integrity": "sha512-v0v8Kb8j8T23jvVUWZeA2D8+izWspeyeDGNaT2/mTHWp7+37fiNfL8bmBWiOmeumXkacM/AB0XOUQvEbncSnHA==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 10"
+ }
+ },
+ "node_modules/@next/swc-linux-x64-gnu": {
+ "version": "14.0.3",
+ "resolved": "https://registry.npmmirror.com/@next/swc-linux-x64-gnu/-/swc-linux-x64-gnu-14.0.3.tgz",
+ "integrity": "sha512-VM1aE1tJKLBwMGtyBR21yy+STfl0MapMQnNrXkxeyLs0GFv/kZqXS5Jw/TQ3TSUnbv0QPDf/X8sDXuMtSgG6eg==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 10"
+ }
+ },
+ "node_modules/@next/swc-linux-x64-musl": {
+ "version": "14.0.3",
+ "resolved": "https://registry.npmmirror.com/@next/swc-linux-x64-musl/-/swc-linux-x64-musl-14.0.3.tgz",
+ "integrity": "sha512-64EnmKy18MYFL5CzLaSuUn561hbO1Gk16jM/KHznYP3iCIfF9e3yULtHaMy0D8zbHfxset9LTOv6cuYKJgcOxg==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 10"
+ }
+ },
+ "node_modules/@next/swc-win32-arm64-msvc": {
+ "version": "14.0.3",
+ "resolved": "https://registry.npmmirror.com/@next/swc-win32-arm64-msvc/-/swc-win32-arm64-msvc-14.0.3.tgz",
+ "integrity": "sha512-WRDp8QrmsL1bbGtsh5GqQ/KWulmrnMBgbnb+59qNTW1kVi1nG/2ndZLkcbs2GX7NpFLlToLRMWSQXmPzQm4tog==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">= 10"
+ }
+ },
+ "node_modules/@next/swc-win32-ia32-msvc": {
+ "version": "14.0.3",
+ "resolved": "https://registry.npmmirror.com/@next/swc-win32-ia32-msvc/-/swc-win32-ia32-msvc-14.0.3.tgz",
+ "integrity": "sha512-EKffQeqCrj+t6qFFhIFTRoqb2QwX1mU7iTOvMyLbYw3QtqTw9sMwjykyiMlZlrfm2a4fA84+/aeW+PMg1MjuTg==",
+ "cpu": [
+ "ia32"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">= 10"
+ }
+ },
+ "node_modules/@next/swc-win32-x64-msvc": {
+ "version": "14.0.3",
+ "resolved": "https://registry.npmmirror.com/@next/swc-win32-x64-msvc/-/swc-win32-x64-msvc-14.0.3.tgz",
+ "integrity": "sha512-ERhKPSJ1vQrPiwrs15Pjz/rvDHZmkmvbf/BjPN/UCOI++ODftT0GtasDPi0j+y6PPJi5HsXw+dpRaXUaw4vjuQ==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">= 10"
+ }
+ },
+ "node_modules/@nodelib/fs.scandir": {
+ "version": "2.1.5",
+ "resolved": "https://registry.npmmirror.com/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz",
+ "integrity": "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@nodelib/fs.stat": "2.0.5",
+ "run-parallel": "^1.1.9"
+ },
+ "engines": {
+ "node": ">= 8"
+ }
+ },
+ "node_modules/@nodelib/fs.stat": {
+ "version": "2.0.5",
+ "resolved": "https://registry.npmmirror.com/@nodelib/fs.stat/-/fs.stat-2.0.5.tgz",
+ "integrity": "sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 8"
+ }
+ },
+ "node_modules/@nodelib/fs.walk": {
+ "version": "1.2.8",
+ "resolved": "https://registry.npmmirror.com/@nodelib/fs.walk/-/fs.walk-1.2.8.tgz",
+ "integrity": "sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@nodelib/fs.scandir": "2.1.5",
+ "fastq": "^1.6.0"
+ },
+ "engines": {
+ "node": ">= 8"
+ }
+ },
+ "node_modules/@nolyfill/is-core-module": {
+ "version": "1.0.39",
+ "resolved": "https://registry.npmmirror.com/@nolyfill/is-core-module/-/is-core-module-1.0.39.tgz",
+ "integrity": "sha512-nn5ozdjYQpUCZlWGuxcJY/KpxkWQs4DcbMCmKojjyrYDEAGy4Ce19NN4v5MduafTwJlbKc99UA8YhSVqq9yPZA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=12.4.0"
+ }
+ },
+ "node_modules/@rtsao/scc": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmmirror.com/@rtsao/scc/-/scc-1.1.0.tgz",
+ "integrity": "sha512-zt6OdqaDoOnJ1ZYsCYGt9YmWzDXl4vQdKTyJev62gFhRGKdx7mcT54V9KIjg+d2wi9EXsPvAPKe7i7WjfVWB8g==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@rushstack/eslint-patch": {
+ "version": "1.15.0",
+ "resolved": "https://registry.npmmirror.com/@rushstack/eslint-patch/-/eslint-patch-1.15.0.tgz",
+ "integrity": "sha512-ojSshQPKwVvSMR8yT2L/QtUkV5SXi/IfDiJ4/8d6UbTPjiHVmxZzUAzGD8Tzks1b9+qQkZa0isUOvYObedITaw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@swc/helpers": {
+ "version": "0.5.2",
+ "resolved": "https://registry.npmmirror.com/@swc/helpers/-/helpers-0.5.2.tgz",
+ "integrity": "sha512-E4KcWTpoLHqwPHLxidpOqQbcrZVgi0rsmmZXUle1jXmJfuIf/UWpczUJ7MZZ5tlxytgJXyp0w4PGkkeLiuIdZw==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "tslib": "^2.4.0"
+ }
+ },
+ "node_modules/@tybys/wasm-util": {
+ "version": "0.10.1",
+ "resolved": "https://registry.npmmirror.com/@tybys/wasm-util/-/wasm-util-0.10.1.tgz",
+ "integrity": "sha512-9tTaPJLSiejZKx+Bmog4uSubteqTvFrVrURwkmHixBo0G4seD0zUxp98E1DzUBJxLQ3NPwXrGKDiVjwx/DpPsg==",
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "tslib": "^2.4.0"
+ }
+ },
+ "node_modules/@types/d3": {
+ "version": "7.4.3",
+ "resolved": "https://registry.npmjs.org/@types/d3/-/d3-7.4.3.tgz",
+ "integrity": "sha512-lZXZ9ckh5R8uiFVt8ogUNf+pIrK4EsWrx2Np75WvF/eTpJ0FMHNhjXk8CKEx/+gpHbNQyJWehbFaTvqmHWB3ww==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/d3-array": "*",
+ "@types/d3-axis": "*",
+ "@types/d3-brush": "*",
+ "@types/d3-chord": "*",
+ "@types/d3-color": "*",
+ "@types/d3-contour": "*",
+ "@types/d3-delaunay": "*",
+ "@types/d3-dispatch": "*",
+ "@types/d3-drag": "*",
+ "@types/d3-dsv": "*",
+ "@types/d3-ease": "*",
+ "@types/d3-fetch": "*",
+ "@types/d3-force": "*",
+ "@types/d3-format": "*",
+ "@types/d3-geo": "*",
+ "@types/d3-hierarchy": "*",
+ "@types/d3-interpolate": "*",
+ "@types/d3-path": "*",
+ "@types/d3-polygon": "*",
+ "@types/d3-quadtree": "*",
+ "@types/d3-random": "*",
+ "@types/d3-scale": "*",
+ "@types/d3-scale-chromatic": "*",
+ "@types/d3-selection": "*",
+ "@types/d3-shape": "*",
+ "@types/d3-time": "*",
+ "@types/d3-time-format": "*",
+ "@types/d3-timer": "*",
+ "@types/d3-transition": "*",
+ "@types/d3-zoom": "*"
+ }
+ },
+ "node_modules/@types/d3-array": {
+ "version": "3.2.2",
+ "resolved": "https://registry.npmjs.org/@types/d3-array/-/d3-array-3.2.2.tgz",
+ "integrity": "sha512-hOLWVbm7uRza0BYXpIIW5pxfrKe0W+D5lrFiAEYR+pb6w3N2SwSMaJbXdUfSEv+dT4MfHBLtn5js0LAWaO6otw==",
+ "license": "MIT"
+ },
+ "node_modules/@types/d3-axis": {
+ "version": "3.0.6",
+ "resolved": "https://registry.npmjs.org/@types/d3-axis/-/d3-axis-3.0.6.tgz",
+ "integrity": "sha512-pYeijfZuBd87T0hGn0FO1vQ/cgLk6E1ALJjfkC0oJ8cbwkZl3TpgS8bVBLZN+2jjGgg38epgxb2zmoGtSfvgMw==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/d3-selection": "*"
+ }
+ },
+ "node_modules/@types/d3-brush": {
+ "version": "3.0.6",
+ "resolved": "https://registry.npmjs.org/@types/d3-brush/-/d3-brush-3.0.6.tgz",
+ "integrity": "sha512-nH60IZNNxEcrh6L1ZSMNA28rj27ut/2ZmI3r96Zd+1jrZD++zD3LsMIjWlvg4AYrHn/Pqz4CF3veCxGjtbqt7A==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/d3-selection": "*"
+ }
+ },
+ "node_modules/@types/d3-chord": {
+ "version": "3.0.6",
+ "resolved": "https://registry.npmjs.org/@types/d3-chord/-/d3-chord-3.0.6.tgz",
+ "integrity": "sha512-LFYWWd8nwfwEmTZG9PfQxd17HbNPksHBiJHaKuY1XeqscXacsS2tyoo6OdRsjf+NQYeB6XrNL3a25E3gH69lcg==",
+ "license": "MIT"
+ },
+ "node_modules/@types/d3-color": {
+ "version": "3.1.3",
+ "resolved": "https://registry.npmjs.org/@types/d3-color/-/d3-color-3.1.3.tgz",
+ "integrity": "sha512-iO90scth9WAbmgv7ogoq57O9YpKmFBbmoEoCHDB2xMBY0+/KVrqAaCDyCE16dUspeOvIxFFRI+0sEtqDqy2b4A==",
+ "license": "MIT"
+ },
+ "node_modules/@types/d3-contour": {
+ "version": "3.0.6",
+ "resolved": "https://registry.npmjs.org/@types/d3-contour/-/d3-contour-3.0.6.tgz",
+ "integrity": "sha512-BjzLgXGnCWjUSYGfH1cpdo41/hgdWETu4YxpezoztawmqsvCeep+8QGfiY6YbDvfgHz/DkjeIkkZVJavB4a3rg==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/d3-array": "*",
+ "@types/geojson": "*"
+ }
+ },
+ "node_modules/@types/d3-delaunay": {
+ "version": "6.0.4",
+ "resolved": "https://registry.npmjs.org/@types/d3-delaunay/-/d3-delaunay-6.0.4.tgz",
+ "integrity": "sha512-ZMaSKu4THYCU6sV64Lhg6qjf1orxBthaC161plr5KuPHo3CNm8DTHiLw/5Eq2b6TsNP0W0iJrUOFscY6Q450Hw==",
+ "license": "MIT"
+ },
+ "node_modules/@types/d3-dispatch": {
+ "version": "3.0.7",
+ "resolved": "https://registry.npmjs.org/@types/d3-dispatch/-/d3-dispatch-3.0.7.tgz",
+ "integrity": "sha512-5o9OIAdKkhN1QItV2oqaE5KMIiXAvDWBDPrD85e58Qlz1c1kI/J0NcqbEG88CoTwJrYe7ntUCVfeUl2UJKbWgA==",
+ "license": "MIT"
+ },
+ "node_modules/@types/d3-drag": {
+ "version": "3.0.7",
+ "resolved": "https://registry.npmjs.org/@types/d3-drag/-/d3-drag-3.0.7.tgz",
+ "integrity": "sha512-HE3jVKlzU9AaMazNufooRJ5ZpWmLIoc90A37WU2JMmeq28w1FQqCZswHZ3xR+SuxYftzHq6WU6KJHvqxKzTxxQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/d3-selection": "*"
+ }
+ },
+ "node_modules/@types/d3-dsv": {
+ "version": "3.0.7",
+ "resolved": "https://registry.npmjs.org/@types/d3-dsv/-/d3-dsv-3.0.7.tgz",
+ "integrity": "sha512-n6QBF9/+XASqcKK6waudgL0pf/S5XHPPI8APyMLLUHd8NqouBGLsU8MgtO7NINGtPBtk9Kko/W4ea0oAspwh9g==",
+ "license": "MIT"
+ },
+ "node_modules/@types/d3-ease": {
+ "version": "3.0.2",
+ "resolved": "https://registry.npmjs.org/@types/d3-ease/-/d3-ease-3.0.2.tgz",
+ "integrity": "sha512-NcV1JjO5oDzoK26oMzbILE6HW7uVXOHLQvHshBUW4UMdZGfiY6v5BeQwh9a9tCzv+CeefZQHJt5SRgK154RtiA==",
+ "license": "MIT"
+ },
+ "node_modules/@types/d3-fetch": {
+ "version": "3.0.7",
+ "resolved": "https://registry.npmjs.org/@types/d3-fetch/-/d3-fetch-3.0.7.tgz",
+ "integrity": "sha512-fTAfNmxSb9SOWNB9IoG5c8Hg6R+AzUHDRlsXsDZsNp6sxAEOP0tkP3gKkNSO/qmHPoBFTxNrjDprVHDQDvo5aA==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/d3-dsv": "*"
+ }
+ },
+ "node_modules/@types/d3-force": {
+ "version": "3.0.10",
+ "resolved": "https://registry.npmjs.org/@types/d3-force/-/d3-force-3.0.10.tgz",
+ "integrity": "sha512-ZYeSaCF3p73RdOKcjj+swRlZfnYpK1EbaDiYICEEp5Q6sUiqFaFQ9qgoshp5CzIyyb/yD09kD9o2zEltCexlgw==",
+ "license": "MIT"
+ },
+ "node_modules/@types/d3-format": {
+ "version": "3.0.4",
+ "resolved": "https://registry.npmjs.org/@types/d3-format/-/d3-format-3.0.4.tgz",
+ "integrity": "sha512-fALi2aI6shfg7vM5KiR1wNJnZ7r6UuggVqtDA+xiEdPZQwy/trcQaHnwShLuLdta2rTymCNpxYTiMZX/e09F4g==",
+ "license": "MIT"
+ },
+ "node_modules/@types/d3-geo": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/@types/d3-geo/-/d3-geo-3.1.0.tgz",
+ "integrity": "sha512-856sckF0oP/diXtS4jNsiQw/UuK5fQG8l/a9VVLeSouf1/PPbBE1i1W852zVwKwYCBkFJJB7nCFTbk6UMEXBOQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/geojson": "*"
+ }
+ },
+ "node_modules/@types/d3-hierarchy": {
+ "version": "3.1.7",
+ "resolved": "https://registry.npmjs.org/@types/d3-hierarchy/-/d3-hierarchy-3.1.7.tgz",
+ "integrity": "sha512-tJFtNoYBtRtkNysX1Xq4sxtjK8YgoWUNpIiUee0/jHGRwqvzYxkq0hGVbbOGSz+JgFxxRu4K8nb3YpG3CMARtg==",
+ "license": "MIT"
+ },
+ "node_modules/@types/d3-interpolate": {
+ "version": "3.0.4",
+ "resolved": "https://registry.npmjs.org/@types/d3-interpolate/-/d3-interpolate-3.0.4.tgz",
+ "integrity": "sha512-mgLPETlrpVV1YRJIglr4Ez47g7Yxjl1lj7YKsiMCb27VJH9W8NVM6Bb9d8kkpG/uAQS5AmbA48q2IAolKKo1MA==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/d3-color": "*"
+ }
+ },
+ "node_modules/@types/d3-path": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/@types/d3-path/-/d3-path-3.1.1.tgz",
+ "integrity": "sha512-VMZBYyQvbGmWyWVea0EHs/BwLgxc+MKi1zLDCONksozI4YJMcTt8ZEuIR4Sb1MMTE8MMW49v0IwI5+b7RmfWlg==",
+ "license": "MIT"
+ },
+ "node_modules/@types/d3-polygon": {
+ "version": "3.0.2",
+ "resolved": "https://registry.npmjs.org/@types/d3-polygon/-/d3-polygon-3.0.2.tgz",
+ "integrity": "sha512-ZuWOtMaHCkN9xoeEMr1ubW2nGWsp4nIql+OPQRstu4ypeZ+zk3YKqQT0CXVe/PYqrKpZAi+J9mTs05TKwjXSRA==",
+ "license": "MIT"
+ },
+ "node_modules/@types/d3-quadtree": {
+ "version": "3.0.6",
+ "resolved": "https://registry.npmjs.org/@types/d3-quadtree/-/d3-quadtree-3.0.6.tgz",
+ "integrity": "sha512-oUzyO1/Zm6rsxKRHA1vH0NEDG58HrT5icx/azi9MF1TWdtttWl0UIUsjEQBBh+SIkrpd21ZjEv7ptxWys1ncsg==",
+ "license": "MIT"
+ },
+ "node_modules/@types/d3-random": {
+ "version": "3.0.3",
+ "resolved": "https://registry.npmjs.org/@types/d3-random/-/d3-random-3.0.3.tgz",
+ "integrity": "sha512-Imagg1vJ3y76Y2ea0871wpabqp613+8/r0mCLEBfdtqC7xMSfj9idOnmBYyMoULfHePJyxMAw3nWhJxzc+LFwQ==",
+ "license": "MIT"
+ },
+ "node_modules/@types/d3-scale": {
+ "version": "4.0.9",
+ "resolved": "https://registry.npmjs.org/@types/d3-scale/-/d3-scale-4.0.9.tgz",
+ "integrity": "sha512-dLmtwB8zkAeO/juAMfnV+sItKjlsw2lKdZVVy6LRr0cBmegxSABiLEpGVmSJJ8O08i4+sGR6qQtb6WtuwJdvVw==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/d3-time": "*"
+ }
+ },
+ "node_modules/@types/d3-scale-chromatic": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/@types/d3-scale-chromatic/-/d3-scale-chromatic-3.1.0.tgz",
+ "integrity": "sha512-iWMJgwkK7yTRmWqRB5plb1kadXyQ5Sj8V/zYlFGMUBbIPKQScw+Dku9cAAMgJG+z5GYDoMjWGLVOvjghDEFnKQ==",
+ "license": "MIT"
+ },
+ "node_modules/@types/d3-selection": {
+ "version": "3.0.11",
+ "resolved": "https://registry.npmjs.org/@types/d3-selection/-/d3-selection-3.0.11.tgz",
+ "integrity": "sha512-bhAXu23DJWsrI45xafYpkQ4NtcKMwWnAC/vKrd2l+nxMFuvOT3XMYTIj2opv8vq8AO5Yh7Qac/nSeP/3zjTK0w==",
+ "license": "MIT"
+ },
+ "node_modules/@types/d3-shape": {
+ "version": "3.1.7",
+ "resolved": "https://registry.npmjs.org/@types/d3-shape/-/d3-shape-3.1.7.tgz",
+ "integrity": "sha512-VLvUQ33C+3J+8p+Daf+nYSOsjB4GXp19/S/aGo60m9h1v6XaxjiT82lKVWJCfzhtuZ3yD7i/TPeC/fuKLLOSmg==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/d3-path": "*"
+ }
+ },
+ "node_modules/@types/d3-time": {
+ "version": "3.0.4",
+ "resolved": "https://registry.npmjs.org/@types/d3-time/-/d3-time-3.0.4.tgz",
+ "integrity": "sha512-yuzZug1nkAAaBlBBikKZTgzCeA+k1uy4ZFwWANOfKw5z5LRhV0gNA7gNkKm7HoK+HRN0wX3EkxGk0fpbWhmB7g==",
+ "license": "MIT"
+ },
+ "node_modules/@types/d3-time-format": {
+ "version": "4.0.3",
+ "resolved": "https://registry.npmjs.org/@types/d3-time-format/-/d3-time-format-4.0.3.tgz",
+ "integrity": "sha512-5xg9rC+wWL8kdDj153qZcsJ0FWiFt0J5RB6LYUNZjwSnesfblqrI/bJ1wBdJ8OQfncgbJG5+2F+qfqnqyzYxyg==",
+ "license": "MIT"
+ },
+ "node_modules/@types/d3-timer": {
+ "version": "3.0.2",
+ "resolved": "https://registry.npmjs.org/@types/d3-timer/-/d3-timer-3.0.2.tgz",
+ "integrity": "sha512-Ps3T8E8dZDam6fUyNiMkekK3XUsaUEik+idO9/YjPtfj2qruF8tFBXS7XhtE4iIXBLxhmLjP3SXpLhVf21I9Lw==",
+ "license": "MIT"
+ },
+ "node_modules/@types/d3-transition": {
+ "version": "3.0.9",
+ "resolved": "https://registry.npmjs.org/@types/d3-transition/-/d3-transition-3.0.9.tgz",
+ "integrity": "sha512-uZS5shfxzO3rGlu0cC3bjmMFKsXv+SmZZcgp0KD22ts4uGXp5EVYGzu/0YdwZeKmddhcAccYtREJKkPfXkZuCg==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/d3-selection": "*"
+ }
+ },
+ "node_modules/@types/d3-zoom": {
+ "version": "3.0.8",
+ "resolved": "https://registry.npmjs.org/@types/d3-zoom/-/d3-zoom-3.0.8.tgz",
+ "integrity": "sha512-iqMC4/YlFCSlO8+2Ii1GGGliCAY4XdeG748w5vQUbevlbDu0zSjH/+jojorQVBK/se0j6DUFNPBGSqD3YWYnDw==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/d3-interpolate": "*",
+ "@types/d3-selection": "*"
+ }
+ },
+ "node_modules/@types/debug": {
+ "version": "4.1.12",
+ "resolved": "https://registry.npmmirror.com/@types/debug/-/debug-4.1.12.tgz",
+ "integrity": "sha512-vIChWdVG3LG1SMxEvI/AK+FWJthlrqlTu7fbrlywTkkaONwk/UAGaULXRlf8vkzFBLVm0zkMdCquhL5aOjhXPQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/ms": "*"
+ }
+ },
+ "node_modules/@types/estree": {
+ "version": "1.0.8",
+ "resolved": "https://registry.npmmirror.com/@types/estree/-/estree-1.0.8.tgz",
+ "integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==",
+ "license": "MIT"
+ },
+ "node_modules/@types/estree-jsx": {
+ "version": "1.0.5",
+ "resolved": "https://registry.npmmirror.com/@types/estree-jsx/-/estree-jsx-1.0.5.tgz",
+ "integrity": "sha512-52CcUVNFyfb1A2ALocQw/Dd1BQFNmSdkuC3BkZ6iqhdMfQz7JWOFRuJFloOzjk+6WijU56m9oKXFAXc7o3Towg==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/estree": "*"
+ }
+ },
+ "node_modules/@types/geojson": {
+ "version": "7946.0.16",
+ "resolved": "https://registry.npmjs.org/@types/geojson/-/geojson-7946.0.16.tgz",
+ "integrity": "sha512-6C8nqWur3j98U6+lXDfTUWIfgvZU+EumvpHKcYjujKH7woYyLj2sUmff0tRhrqM7BohUw7Pz3ZB1jj2gW9Fvmg==",
+ "license": "MIT"
+ },
+ "node_modules/@types/hast": {
+ "version": "3.0.4",
+ "resolved": "https://registry.npmmirror.com/@types/hast/-/hast-3.0.4.tgz",
+ "integrity": "sha512-WPs+bbQw5aCj+x6laNGWLH3wviHtoCv/P3+otBhbOhJgG8qtpdAMlTCxLtsTWA7LH1Oh/bFCHsBn0TPS5m30EQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/unist": "*"
+ }
+ },
+ "node_modules/@types/json5": {
+ "version": "0.0.29",
+ "resolved": "https://registry.npmmirror.com/@types/json5/-/json5-0.0.29.tgz",
+ "integrity": "sha512-dRLjCWHYg4oaA77cxO64oO+7JwCwnIzkZPdrrC71jQmQtlhM556pwKo5bUzqvZndkVbeFLIIi+9TC40JNF5hNQ==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/katex": {
+ "version": "0.16.7",
+ "resolved": "https://registry.npmmirror.com/@types/katex/-/katex-0.16.7.tgz",
+ "integrity": "sha512-HMwFiRujE5PjrgwHQ25+bsLJgowjGjm5Z8FVSf0N6PwgJrwxH0QxzHYDcKsTfV3wva0vzrpqMTJS2jXPr5BMEQ==",
+ "license": "MIT"
+ },
+ "node_modules/@types/mdast": {
+ "version": "4.0.4",
+ "resolved": "https://registry.npmmirror.com/@types/mdast/-/mdast-4.0.4.tgz",
+ "integrity": "sha512-kGaNbPh1k7AFzgpud/gMdvIm5xuECykRR+JnWKQno9TAXVa6WIVCGTPvYGekIDL4uwCZQSYbUxNBSb1aUo79oA==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/unist": "*"
+ }
+ },
+ "node_modules/@types/ms": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmmirror.com/@types/ms/-/ms-2.1.0.tgz",
+ "integrity": "sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA==",
+ "license": "MIT"
+ },
+ "node_modules/@types/node": {
+ "version": "20.19.25",
+ "resolved": "https://registry.npmmirror.com/@types/node/-/node-20.19.25.tgz",
+ "integrity": "sha512-ZsJzA5thDQMSQO788d7IocwwQbI8B5OPzmqNvpf3NY/+MHDAS759Wo0gd2WQeXYt5AAAQjzcrTVC6SKCuYgoCQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "undici-types": "~6.21.0"
+ }
+ },
+ "node_modules/@types/prop-types": {
+ "version": "15.7.15",
+ "resolved": "https://registry.npmmirror.com/@types/prop-types/-/prop-types-15.7.15.tgz",
+ "integrity": "sha512-F6bEyamV9jKGAFBEmlQnesRPGOQqS2+Uwi0Em15xenOxHaf2hv6L8YCVn3rPdPJOiJfPiCnLIRyvwVaqMY3MIw==",
+ "license": "MIT"
+ },
+ "node_modules/@types/raf": {
+ "version": "3.4.3",
+ "resolved": "https://registry.npmmirror.com/@types/raf/-/raf-3.4.3.tgz",
+ "integrity": "sha512-c4YAvMedbPZ5tEyxzQdMoOhhJ4RD3rngZIdwC2/qDN3d7JpEhB6fiBRKVY1lg5B7Wk+uPBjn5f39j1/2MY1oOw==",
+ "license": "MIT",
+ "optional": true
+ },
+ "node_modules/@types/react": {
+ "version": "18.3.27",
+ "resolved": "https://registry.npmmirror.com/@types/react/-/react-18.3.27.tgz",
+ "integrity": "sha512-cisd7gxkzjBKU2GgdYrTdtQx1SORymWyaAFhaxQPK9bYO9ot3Y5OikQRvY0VYQtvwjeQnizCINJAenh/V7MK2w==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/prop-types": "*",
+ "csstype": "^3.2.2"
+ }
+ },
+ "node_modules/@types/react-dom": {
+ "version": "18.3.7",
+ "resolved": "https://registry.npmmirror.com/@types/react-dom/-/react-dom-18.3.7.tgz",
+ "integrity": "sha512-MEe3UeoENYVFXzoXEWsvcpg6ZvlrFNlOQ7EOsvhI3CfAXwzPfO8Qwuxd40nepsYKqyyVQnTdEfv68q91yLcKrQ==",
+ "dev": true,
+ "license": "MIT",
+ "peerDependencies": {
+ "@types/react": "^18.0.0"
+ }
+ },
+ "node_modules/@types/trusted-types": {
+ "version": "2.0.7",
+ "resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz",
+ "integrity": "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==",
+ "license": "MIT",
+ "optional": true
+ },
+ "node_modules/@types/unist": {
+ "version": "3.0.3",
+ "resolved": "https://registry.npmmirror.com/@types/unist/-/unist-3.0.3.tgz",
+ "integrity": "sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q==",
+ "license": "MIT"
+ },
+ "node_modules/@typescript-eslint/parser": {
+ "version": "6.21.0",
+ "resolved": "https://registry.npmmirror.com/@typescript-eslint/parser/-/parser-6.21.0.tgz",
+ "integrity": "sha512-tbsV1jPne5CkFQCgPBcDOt30ItF7aJoZL997JSF7MhGQqOeT3svWRYxiqlfA5RUdlHN6Fi+EI9bxqbdyAUZjYQ==",
+ "dev": true,
+ "license": "BSD-2-Clause",
+ "dependencies": {
+ "@typescript-eslint/scope-manager": "6.21.0",
+ "@typescript-eslint/types": "6.21.0",
+ "@typescript-eslint/typescript-estree": "6.21.0",
+ "@typescript-eslint/visitor-keys": "6.21.0",
+ "debug": "^4.3.4"
+ },
+ "engines": {
+ "node": "^16.0.0 || >=18.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/typescript-eslint"
+ },
+ "peerDependencies": {
+ "eslint": "^7.0.0 || ^8.0.0"
+ },
+ "peerDependenciesMeta": {
+ "typescript": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@typescript-eslint/scope-manager": {
+ "version": "6.21.0",
+ "resolved": "https://registry.npmmirror.com/@typescript-eslint/scope-manager/-/scope-manager-6.21.0.tgz",
+ "integrity": "sha512-OwLUIWZJry80O99zvqXVEioyniJMa+d2GrqpUTqi5/v5D5rOrppJVBPa0yKCblcigC0/aYAzxxqQ1B+DS2RYsg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@typescript-eslint/types": "6.21.0",
+ "@typescript-eslint/visitor-keys": "6.21.0"
+ },
+ "engines": {
+ "node": "^16.0.0 || >=18.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/typescript-eslint"
+ }
+ },
+ "node_modules/@typescript-eslint/types": {
+ "version": "6.21.0",
+ "resolved": "https://registry.npmmirror.com/@typescript-eslint/types/-/types-6.21.0.tgz",
+ "integrity": "sha512-1kFmZ1rOm5epu9NZEZm1kckCDGj5UJEf7P1kliH4LKu/RkwpsfqqGmY2OOcUs18lSlQBKLDYBOGxRVtrMN5lpg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": "^16.0.0 || >=18.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/typescript-eslint"
+ }
+ },
+ "node_modules/@typescript-eslint/typescript-estree": {
+ "version": "6.21.0",
+ "resolved": "https://registry.npmmirror.com/@typescript-eslint/typescript-estree/-/typescript-estree-6.21.0.tgz",
+ "integrity": "sha512-6npJTkZcO+y2/kr+z0hc4HwNfrrP4kNYh57ek7yCNlrBjWQ1Y0OS7jiZTkgumrvkX5HkEKXFZkkdFNkaW2wmUQ==",
+ "dev": true,
+ "license": "BSD-2-Clause",
+ "dependencies": {
+ "@typescript-eslint/types": "6.21.0",
+ "@typescript-eslint/visitor-keys": "6.21.0",
+ "debug": "^4.3.4",
+ "globby": "^11.1.0",
+ "is-glob": "^4.0.3",
+ "minimatch": "9.0.3",
+ "semver": "^7.5.4",
+ "ts-api-utils": "^1.0.1"
+ },
+ "engines": {
+ "node": "^16.0.0 || >=18.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/typescript-eslint"
+ },
+ "peerDependenciesMeta": {
+ "typescript": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@typescript-eslint/typescript-estree/node_modules/brace-expansion": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmmirror.com/brace-expansion/-/brace-expansion-2.0.2.tgz",
+ "integrity": "sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "balanced-match": "^1.0.0"
+ }
+ },
+ "node_modules/@typescript-eslint/typescript-estree/node_modules/minimatch": {
+ "version": "9.0.3",
+ "resolved": "https://registry.npmmirror.com/minimatch/-/minimatch-9.0.3.tgz",
+ "integrity": "sha512-RHiac9mvaRw0x3AYRgDC1CxAP7HTcNrrECeA8YYJeWnpo+2Q5CegtZjaotWTWxDG3UeGA1coE05iH1mPjT/2mg==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "brace-expansion": "^2.0.1"
+ },
+ "engines": {
+ "node": ">=16 || 14 >=14.17"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/isaacs"
+ }
+ },
+ "node_modules/@typescript-eslint/visitor-keys": {
+ "version": "6.21.0",
+ "resolved": "https://registry.npmmirror.com/@typescript-eslint/visitor-keys/-/visitor-keys-6.21.0.tgz",
+ "integrity": "sha512-JJtkDduxLi9bivAB+cYOVMtbkqdPOhZ+ZI5LC47MIRrDV4Yn2o+ZnW10Nkmr28xRpSpdJ6Sm42Hjf2+REYXm0A==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@typescript-eslint/types": "6.21.0",
+ "eslint-visitor-keys": "^3.4.1"
+ },
+ "engines": {
+ "node": "^16.0.0 || >=18.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/typescript-eslint"
+ }
+ },
+ "node_modules/@ungap/structured-clone": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmmirror.com/@ungap/structured-clone/-/structured-clone-1.3.0.tgz",
+ "integrity": "sha512-WmoN8qaIAo7WTYWbAZuG8PYEhn5fkz7dZrqTBZ7dtt//lL2Gwms1IcnQ5yHqjDfX8Ft5j4YzDM23f87zBfDe9g==",
+ "license": "ISC"
+ },
+ "node_modules/@unrs/resolver-binding-android-arm-eabi": {
+ "version": "1.11.1",
+ "resolved": "https://registry.npmmirror.com/@unrs/resolver-binding-android-arm-eabi/-/resolver-binding-android-arm-eabi-1.11.1.tgz",
+ "integrity": "sha512-ppLRUgHVaGRWUx0R0Ut06Mjo9gBaBkg3v/8AxusGLhsIotbBLuRk51rAzqLC8gq6NyyAojEXglNjzf6R948DNw==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ]
+ },
+ "node_modules/@unrs/resolver-binding-android-arm64": {
+ "version": "1.11.1",
+ "resolved": "https://registry.npmmirror.com/@unrs/resolver-binding-android-arm64/-/resolver-binding-android-arm64-1.11.1.tgz",
+ "integrity": "sha512-lCxkVtb4wp1v+EoN+HjIG9cIIzPkX5OtM03pQYkG+U5O/wL53LC4QbIeazgiKqluGeVEeBlZahHalCaBvU1a2g==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ]
+ },
+ "node_modules/@unrs/resolver-binding-darwin-arm64": {
+ "version": "1.11.1",
+ "resolved": "https://registry.npmmirror.com/@unrs/resolver-binding-darwin-arm64/-/resolver-binding-darwin-arm64-1.11.1.tgz",
+ "integrity": "sha512-gPVA1UjRu1Y/IsB/dQEsp2V1pm44Of6+LWvbLc9SDk1c2KhhDRDBUkQCYVWe6f26uJb3fOK8saWMgtX8IrMk3g==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ]
+ },
+ "node_modules/@unrs/resolver-binding-darwin-x64": {
+ "version": "1.11.1",
+ "resolved": "https://registry.npmmirror.com/@unrs/resolver-binding-darwin-x64/-/resolver-binding-darwin-x64-1.11.1.tgz",
+ "integrity": "sha512-cFzP7rWKd3lZaCsDze07QX1SC24lO8mPty9vdP+YVa3MGdVgPmFc59317b2ioXtgCMKGiCLxJ4HQs62oz6GfRQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ]
+ },
+ "node_modules/@unrs/resolver-binding-freebsd-x64": {
+ "version": "1.11.1",
+ "resolved": "https://registry.npmmirror.com/@unrs/resolver-binding-freebsd-x64/-/resolver-binding-freebsd-x64-1.11.1.tgz",
+ "integrity": "sha512-fqtGgak3zX4DCB6PFpsH5+Kmt/8CIi4Bry4rb1ho6Av2QHTREM+47y282Uqiu3ZRF5IQioJQ5qWRV6jduA+iGw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ]
+ },
+ "node_modules/@unrs/resolver-binding-linux-arm-gnueabihf": {
+ "version": "1.11.1",
+ "resolved": "https://registry.npmmirror.com/@unrs/resolver-binding-linux-arm-gnueabihf/-/resolver-binding-linux-arm-gnueabihf-1.11.1.tgz",
+ "integrity": "sha512-u92mvlcYtp9MRKmP+ZvMmtPN34+/3lMHlyMj7wXJDeXxuM0Vgzz0+PPJNsro1m3IZPYChIkn944wW8TYgGKFHw==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@unrs/resolver-binding-linux-arm-musleabihf": {
+ "version": "1.11.1",
+ "resolved": "https://registry.npmmirror.com/@unrs/resolver-binding-linux-arm-musleabihf/-/resolver-binding-linux-arm-musleabihf-1.11.1.tgz",
+ "integrity": "sha512-cINaoY2z7LVCrfHkIcmvj7osTOtm6VVT16b5oQdS4beibX2SYBwgYLmqhBjA1t51CarSaBuX5YNsWLjsqfW5Cw==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@unrs/resolver-binding-linux-arm64-gnu": {
+ "version": "1.11.1",
+ "resolved": "https://registry.npmmirror.com/@unrs/resolver-binding-linux-arm64-gnu/-/resolver-binding-linux-arm64-gnu-1.11.1.tgz",
+ "integrity": "sha512-34gw7PjDGB9JgePJEmhEqBhWvCiiWCuXsL9hYphDF7crW7UgI05gyBAi6MF58uGcMOiOqSJ2ybEeCvHcq0BCmQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@unrs/resolver-binding-linux-arm64-musl": {
+ "version": "1.11.1",
+ "resolved": "https://registry.npmmirror.com/@unrs/resolver-binding-linux-arm64-musl/-/resolver-binding-linux-arm64-musl-1.11.1.tgz",
+ "integrity": "sha512-RyMIx6Uf53hhOtJDIamSbTskA99sPHS96wxVE/bJtePJJtpdKGXO1wY90oRdXuYOGOTuqjT8ACccMc4K6QmT3w==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@unrs/resolver-binding-linux-ppc64-gnu": {
+ "version": "1.11.1",
+ "resolved": "https://registry.npmmirror.com/@unrs/resolver-binding-linux-ppc64-gnu/-/resolver-binding-linux-ppc64-gnu-1.11.1.tgz",
+ "integrity": "sha512-D8Vae74A4/a+mZH0FbOkFJL9DSK2R6TFPC9M+jCWYia/q2einCubX10pecpDiTmkJVUH+y8K3BZClycD8nCShA==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@unrs/resolver-binding-linux-riscv64-gnu": {
+ "version": "1.11.1",
+ "resolved": "https://registry.npmmirror.com/@unrs/resolver-binding-linux-riscv64-gnu/-/resolver-binding-linux-riscv64-gnu-1.11.1.tgz",
+ "integrity": "sha512-frxL4OrzOWVVsOc96+V3aqTIQl1O2TjgExV4EKgRY09AJ9leZpEg8Ak9phadbuX0BA4k8U5qtvMSQQGGmaJqcQ==",
+ "cpu": [
+ "riscv64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@unrs/resolver-binding-linux-riscv64-musl": {
+ "version": "1.11.1",
+ "resolved": "https://registry.npmmirror.com/@unrs/resolver-binding-linux-riscv64-musl/-/resolver-binding-linux-riscv64-musl-1.11.1.tgz",
+ "integrity": "sha512-mJ5vuDaIZ+l/acv01sHoXfpnyrNKOk/3aDoEdLO/Xtn9HuZlDD6jKxHlkN8ZhWyLJsRBxfv9GYM2utQ1SChKew==",
+ "cpu": [
+ "riscv64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@unrs/resolver-binding-linux-s390x-gnu": {
+ "version": "1.11.1",
+ "resolved": "https://registry.npmmirror.com/@unrs/resolver-binding-linux-s390x-gnu/-/resolver-binding-linux-s390x-gnu-1.11.1.tgz",
+ "integrity": "sha512-kELo8ebBVtb9sA7rMe1Cph4QHreByhaZ2QEADd9NzIQsYNQpt9UkM9iqr2lhGr5afh885d/cB5QeTXSbZHTYPg==",
+ "cpu": [
+ "s390x"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@unrs/resolver-binding-linux-x64-gnu": {
+ "version": "1.11.1",
+ "resolved": "https://registry.npmmirror.com/@unrs/resolver-binding-linux-x64-gnu/-/resolver-binding-linux-x64-gnu-1.11.1.tgz",
+ "integrity": "sha512-C3ZAHugKgovV5YvAMsxhq0gtXuwESUKc5MhEtjBpLoHPLYM+iuwSj3lflFwK3DPm68660rZ7G8BMcwSro7hD5w==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@unrs/resolver-binding-linux-x64-musl": {
+ "version": "1.11.1",
+ "resolved": "https://registry.npmmirror.com/@unrs/resolver-binding-linux-x64-musl/-/resolver-binding-linux-x64-musl-1.11.1.tgz",
+ "integrity": "sha512-rV0YSoyhK2nZ4vEswT/QwqzqQXw5I6CjoaYMOX0TqBlWhojUf8P94mvI7nuJTeaCkkds3QE4+zS8Ko+GdXuZtA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@unrs/resolver-binding-wasm32-wasi": {
+ "version": "1.11.1",
+ "resolved": "https://registry.npmmirror.com/@unrs/resolver-binding-wasm32-wasi/-/resolver-binding-wasm32-wasi-1.11.1.tgz",
+ "integrity": "sha512-5u4RkfxJm+Ng7IWgkzi3qrFOvLvQYnPBmjmZQ8+szTK/b31fQCnleNl1GgEt7nIsZRIf5PLhPwT0WM+q45x/UQ==",
+ "cpu": [
+ "wasm32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "@napi-rs/wasm-runtime": "^0.2.11"
+ },
+ "engines": {
+ "node": ">=14.0.0"
+ }
+ },
+ "node_modules/@unrs/resolver-binding-win32-arm64-msvc": {
+ "version": "1.11.1",
+ "resolved": "https://registry.npmmirror.com/@unrs/resolver-binding-win32-arm64-msvc/-/resolver-binding-win32-arm64-msvc-1.11.1.tgz",
+ "integrity": "sha512-nRcz5Il4ln0kMhfL8S3hLkxI85BXs3o8EYoattsJNdsX4YUU89iOkVn7g0VHSRxFuVMdM4Q1jEpIId1Ihim/Uw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ]
+ },
+ "node_modules/@unrs/resolver-binding-win32-ia32-msvc": {
+ "version": "1.11.1",
+ "resolved": "https://registry.npmmirror.com/@unrs/resolver-binding-win32-ia32-msvc/-/resolver-binding-win32-ia32-msvc-1.11.1.tgz",
+ "integrity": "sha512-DCEI6t5i1NmAZp6pFonpD5m7i6aFrpofcp4LA2i8IIq60Jyo28hamKBxNrZcyOwVOZkgsRp9O2sXWBWP8MnvIQ==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ]
+ },
+ "node_modules/@unrs/resolver-binding-win32-x64-msvc": {
+ "version": "1.11.1",
+ "resolved": "https://registry.npmmirror.com/@unrs/resolver-binding-win32-x64-msvc/-/resolver-binding-win32-x64-msvc-1.11.1.tgz",
+ "integrity": "sha512-lrW200hZdbfRtztbygyaq/6jP6AKE8qQN2KvPcJ+x7wiD038YtnYtZ82IMNJ69GJibV7bwL3y9FgK+5w/pYt6g==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ]
+ },
+ "node_modules/acorn": {
+ "version": "8.15.0",
+ "resolved": "https://registry.npmmirror.com/acorn/-/acorn-8.15.0.tgz",
+ "integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==",
+ "license": "MIT",
+ "bin": {
+ "acorn": "bin/acorn"
+ },
+ "engines": {
+ "node": ">=0.4.0"
+ }
+ },
+ "node_modules/acorn-jsx": {
+ "version": "5.3.2",
+ "resolved": "https://registry.npmmirror.com/acorn-jsx/-/acorn-jsx-5.3.2.tgz",
+ "integrity": "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==",
+ "dev": true,
+ "license": "MIT",
+ "peerDependencies": {
+ "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0"
+ }
+ },
+ "node_modules/ajv": {
+ "version": "6.12.6",
+ "resolved": "https://registry.npmmirror.com/ajv/-/ajv-6.12.6.tgz",
+ "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "fast-deep-equal": "^3.1.1",
+ "fast-json-stable-stringify": "^2.0.0",
+ "json-schema-traverse": "^0.4.1",
+ "uri-js": "^4.2.2"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/epoberezkin"
+ }
+ },
+ "node_modules/ansi-regex": {
+ "version": "5.0.1",
+ "resolved": "https://registry.npmmirror.com/ansi-regex/-/ansi-regex-5.0.1.tgz",
+ "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/ansi-styles": {
+ "version": "4.3.0",
+ "resolved": "https://registry.npmmirror.com/ansi-styles/-/ansi-styles-4.3.0.tgz",
+ "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "color-convert": "^2.0.1"
+ },
+ "engines": {
+ "node": ">=8"
+ },
+ "funding": {
+ "url": "https://github.com/chalk/ansi-styles?sponsor=1"
+ }
+ },
+ "node_modules/any-promise": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmmirror.com/any-promise/-/any-promise-1.3.0.tgz",
+ "integrity": "sha512-7UvmKalWRt1wgjL1RrGxoSJW/0QZFIegpeGvZG9kjp8vrRu55XTHbwnqq2GpXm9uLbcuhxm3IqX9OB4MZR1b2A==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/anymatch": {
+ "version": "3.1.3",
+ "resolved": "https://registry.npmmirror.com/anymatch/-/anymatch-3.1.3.tgz",
+ "integrity": "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "normalize-path": "^3.0.0",
+ "picomatch": "^2.0.4"
+ },
+ "engines": {
+ "node": ">= 8"
+ }
+ },
+ "node_modules/arg": {
+ "version": "5.0.2",
+ "resolved": "https://registry.npmmirror.com/arg/-/arg-5.0.2.tgz",
+ "integrity": "sha512-PYjyFOLKQ9y57JvQ6QLo8dAgNqswh8M1RMJYdQduT6xbWSgK36P/Z/v+p888pM69jMMfS8Xd8F6I1kQ/I9HUGg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/argparse": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmmirror.com/argparse/-/argparse-2.0.1.tgz",
+ "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==",
+ "dev": true,
+ "license": "Python-2.0"
+ },
+ "node_modules/aria-query": {
+ "version": "5.3.2",
+ "resolved": "https://registry.npmmirror.com/aria-query/-/aria-query-5.3.2.tgz",
+ "integrity": "sha512-COROpnaoap1E2F000S62r6A60uHZnmlvomhfyT2DlTcrY1OrBKn2UhH7qn5wTC9zMvD0AY7csdPSNwKP+7WiQw==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/array-buffer-byte-length": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmmirror.com/array-buffer-byte-length/-/array-buffer-byte-length-1.0.2.tgz",
+ "integrity": "sha512-LHE+8BuR7RYGDKvnrmcuSq3tDcKv9OFEXQt/HpbZhY7V6h0zlUXutnAD82GiFx9rdieCMjkvtcsPqBwgUl1Iiw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bound": "^1.0.3",
+ "is-array-buffer": "^3.0.5"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/array-includes": {
+ "version": "3.1.9",
+ "resolved": "https://registry.npmmirror.com/array-includes/-/array-includes-3.1.9.tgz",
+ "integrity": "sha512-FmeCCAenzH0KH381SPT5FZmiA/TmpndpcaShhfgEN9eCVjnFBqq3l1xrI42y8+PPLI6hypzou4GXw00WHmPBLQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bind": "^1.0.8",
+ "call-bound": "^1.0.4",
+ "define-properties": "^1.2.1",
+ "es-abstract": "^1.24.0",
+ "es-object-atoms": "^1.1.1",
+ "get-intrinsic": "^1.3.0",
+ "is-string": "^1.1.1",
+ "math-intrinsics": "^1.1.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/array-union": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmmirror.com/array-union/-/array-union-2.1.0.tgz",
+ "integrity": "sha512-HGyxoOTYUyCM6stUe6EJgnd4EoewAI7zMdfqO+kGjnlZmBDz/cR5pf8r/cR4Wq60sL/p0IkcjUEEPwS3GFrIyw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/array.prototype.findlast": {
+ "version": "1.2.5",
+ "resolved": "https://registry.npmmirror.com/array.prototype.findlast/-/array.prototype.findlast-1.2.5.tgz",
+ "integrity": "sha512-CVvd6FHg1Z3POpBLxO6E6zr+rSKEQ9L6rZHAaY7lLfhKsWYUBBOuMs0e9o24oopj6H+geRCX0YJ+TJLBK2eHyQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bind": "^1.0.7",
+ "define-properties": "^1.2.1",
+ "es-abstract": "^1.23.2",
+ "es-errors": "^1.3.0",
+ "es-object-atoms": "^1.0.0",
+ "es-shim-unscopables": "^1.0.2"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/array.prototype.findlastindex": {
+ "version": "1.2.6",
+ "resolved": "https://registry.npmmirror.com/array.prototype.findlastindex/-/array.prototype.findlastindex-1.2.6.tgz",
+ "integrity": "sha512-F/TKATkzseUExPlfvmwQKGITM3DGTK+vkAsCZoDc5daVygbJBnjEUCbgkAvVFsgfXfX4YIqZ/27G3k3tdXrTxQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bind": "^1.0.8",
+ "call-bound": "^1.0.4",
+ "define-properties": "^1.2.1",
+ "es-abstract": "^1.23.9",
+ "es-errors": "^1.3.0",
+ "es-object-atoms": "^1.1.1",
+ "es-shim-unscopables": "^1.1.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/array.prototype.flat": {
+ "version": "1.3.3",
+ "resolved": "https://registry.npmmirror.com/array.prototype.flat/-/array.prototype.flat-1.3.3.tgz",
+ "integrity": "sha512-rwG/ja1neyLqCuGZ5YYrznA62D4mZXg0i1cIskIUKSiqF3Cje9/wXAls9B9s1Wa2fomMsIv8czB8jZcPmxCXFg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bind": "^1.0.8",
+ "define-properties": "^1.2.1",
+ "es-abstract": "^1.23.5",
+ "es-shim-unscopables": "^1.0.2"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/array.prototype.flatmap": {
+ "version": "1.3.3",
+ "resolved": "https://registry.npmmirror.com/array.prototype.flatmap/-/array.prototype.flatmap-1.3.3.tgz",
+ "integrity": "sha512-Y7Wt51eKJSyi80hFrJCePGGNo5ktJCslFuboqJsbf57CCPcm5zztluPlc4/aD8sWsKvlwatezpV4U1efk8kpjg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bind": "^1.0.8",
+ "define-properties": "^1.2.1",
+ "es-abstract": "^1.23.5",
+ "es-shim-unscopables": "^1.0.2"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/array.prototype.tosorted": {
+ "version": "1.1.4",
+ "resolved": "https://registry.npmmirror.com/array.prototype.tosorted/-/array.prototype.tosorted-1.1.4.tgz",
+ "integrity": "sha512-p6Fx8B7b7ZhL/gmUsAy0D15WhvDccw3mnGNbZpi3pmeJdxtWsj2jEaI4Y6oo3XiHfzuSgPwKc04MYt6KgvC/wA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bind": "^1.0.7",
+ "define-properties": "^1.2.1",
+ "es-abstract": "^1.23.3",
+ "es-errors": "^1.3.0",
+ "es-shim-unscopables": "^1.0.2"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/arraybuffer.prototype.slice": {
+ "version": "1.0.4",
+ "resolved": "https://registry.npmmirror.com/arraybuffer.prototype.slice/-/arraybuffer.prototype.slice-1.0.4.tgz",
+ "integrity": "sha512-BNoCY6SXXPQ7gF2opIP4GBE+Xw7U+pHMYKuzjgCN3GwiaIR09UUeKfheyIry77QtrCBlC0KK0q5/TER/tYh3PQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "array-buffer-byte-length": "^1.0.1",
+ "call-bind": "^1.0.8",
+ "define-properties": "^1.2.1",
+ "es-abstract": "^1.23.5",
+ "es-errors": "^1.3.0",
+ "get-intrinsic": "^1.2.6",
+ "is-array-buffer": "^3.0.4"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/ast-types-flow": {
+ "version": "0.0.8",
+ "resolved": "https://registry.npmmirror.com/ast-types-flow/-/ast-types-flow-0.0.8.tgz",
+ "integrity": "sha512-OH/2E5Fg20h2aPrbe+QL8JZQFko0YZaF+j4mnQ7BGhfavO7OpSLa8a0y9sBwomHdSbkhTS8TQNayBfnW5DwbvQ==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/async-function": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmmirror.com/async-function/-/async-function-1.0.0.tgz",
+ "integrity": "sha512-hsU18Ae8CDTR6Kgu9DYf0EbCr/a5iGL0rytQDobUcdpYOKokk8LEjVphnXkDkgpi0wYVsqrXuP0bZxJaTqdgoA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/atob": {
+ "version": "2.1.2",
+ "resolved": "https://registry.npmmirror.com/atob/-/atob-2.1.2.tgz",
+ "integrity": "sha512-Wm6ukoaOGJi/73p/cl2GvLjTI5JM1k/O14isD73YML8StrH/7/lRFgmg8nICZgD3bZZvjwCGxtMOD3wWNAu8cg==",
+ "license": "(MIT OR Apache-2.0)",
+ "bin": {
+ "atob": "bin/atob.js"
+ },
+ "engines": {
+ "node": ">= 4.5.0"
+ }
+ },
+ "node_modules/autoprefixer": {
+ "version": "10.4.22",
+ "resolved": "https://registry.npmmirror.com/autoprefixer/-/autoprefixer-10.4.22.tgz",
+ "integrity": "sha512-ARe0v/t9gO28Bznv6GgqARmVqcWOV3mfgUPn9becPHMiD3o9BwlRgaeccZnwTpZ7Zwqrm+c1sUSsMxIzQzc8Xg==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/postcss/"
+ },
+ {
+ "type": "tidelift",
+ "url": "https://tidelift.com/funding/github/npm/autoprefixer"
+ },
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "browserslist": "^4.27.0",
+ "caniuse-lite": "^1.0.30001754",
+ "fraction.js": "^5.3.4",
+ "normalize-range": "^0.1.2",
+ "picocolors": "^1.1.1",
+ "postcss-value-parser": "^4.2.0"
+ },
+ "bin": {
+ "autoprefixer": "bin/autoprefixer"
+ },
+ "engines": {
+ "node": "^10 || ^12 || >=14"
+ },
+ "peerDependencies": {
+ "postcss": "^8.1.0"
+ }
+ },
+ "node_modules/available-typed-arrays": {
+ "version": "1.0.7",
+ "resolved": "https://registry.npmmirror.com/available-typed-arrays/-/available-typed-arrays-1.0.7.tgz",
+ "integrity": "sha512-wvUjBtSGN7+7SjNpq/9M2Tg350UZD3q62IFZLbRAR1bSMlCo1ZaeW+BJ+D090e4hIIZLBcTDWe4Mh4jvUDajzQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "possible-typed-array-names": "^1.0.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/axe-core": {
+ "version": "4.11.0",
+ "resolved": "https://registry.npmmirror.com/axe-core/-/axe-core-4.11.0.tgz",
+ "integrity": "sha512-ilYanEU8vxxBexpJd8cWM4ElSQq4QctCLKih0TSfjIfCQTeyH/6zVrmIJfLPrKTKJRbiG+cfnZbQIjAlJmF1jQ==",
+ "dev": true,
+ "license": "MPL-2.0",
+ "engines": {
+ "node": ">=4"
+ }
+ },
+ "node_modules/axobject-query": {
+ "version": "4.1.0",
+ "resolved": "https://registry.npmmirror.com/axobject-query/-/axobject-query-4.1.0.tgz",
+ "integrity": "sha512-qIj0G9wZbMGNLjLmg1PT6v2mE9AH2zlnADJD/2tC6E00hgmhUOfEB6greHPAfLRSufHqROIUTkw6E+M3lH0PTQ==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/bail": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmmirror.com/bail/-/bail-2.0.2.tgz",
+ "integrity": "sha512-0xO6mYd7JB2YesxDKplafRpsiOzPt9V02ddPCLbY1xYGPOX24NTyN50qnUxgCPcSoYMhKpAuBTjQoRZCAkUDRw==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
+ "node_modules/balanced-match": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmmirror.com/balanced-match/-/balanced-match-1.0.2.tgz",
+ "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/base64-arraybuffer": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmmirror.com/base64-arraybuffer/-/base64-arraybuffer-1.0.2.tgz",
+ "integrity": "sha512-I3yl4r9QB5ZRY3XuJVEPfc2XhZO6YweFPI+UovAzn+8/hb3oJ6lnysaFcjVpkCPfVWFUDvoZ8kmVDP7WyRtYtQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.6.0"
+ }
+ },
+ "node_modules/baseline-browser-mapping": {
+ "version": "2.8.29",
+ "resolved": "https://registry.npmmirror.com/baseline-browser-mapping/-/baseline-browser-mapping-2.8.29.tgz",
+ "integrity": "sha512-sXdt2elaVnhpDNRDz+1BDx1JQoJRuNk7oVlAlbGiFkLikHCAQiccexF/9e91zVi6RCgqspl04aP+6Cnl9zRLrA==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "bin": {
+ "baseline-browser-mapping": "dist/cli.js"
+ }
+ },
+ "node_modules/binary-extensions": {
+ "version": "2.3.0",
+ "resolved": "https://registry.npmmirror.com/binary-extensions/-/binary-extensions-2.3.0.tgz",
+ "integrity": "sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=8"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/brace-expansion": {
+ "version": "1.1.12",
+ "resolved": "https://registry.npmmirror.com/brace-expansion/-/brace-expansion-1.1.12.tgz",
+ "integrity": "sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "balanced-match": "^1.0.0",
+ "concat-map": "0.0.1"
+ }
+ },
+ "node_modules/braces": {
+ "version": "3.0.3",
+ "resolved": "https://registry.npmmirror.com/braces/-/braces-3.0.3.tgz",
+ "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "fill-range": "^7.1.1"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/browserslist": {
+ "version": "4.28.0",
+ "resolved": "https://registry.npmmirror.com/browserslist/-/browserslist-4.28.0.tgz",
+ "integrity": "sha512-tbydkR/CxfMwelN0vwdP/pLkDwyAASZ+VfWm4EOwlB6SWhx1sYnWLqo8N5j0rAzPfzfRaxt0mM/4wPU/Su84RQ==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/browserslist"
+ },
+ {
+ "type": "tidelift",
+ "url": "https://tidelift.com/funding/github/npm/browserslist"
+ },
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "baseline-browser-mapping": "^2.8.25",
+ "caniuse-lite": "^1.0.30001754",
+ "electron-to-chromium": "^1.5.249",
+ "node-releases": "^2.0.27",
+ "update-browserslist-db": "^1.1.4"
+ },
+ "bin": {
+ "browserslist": "cli.js"
+ },
+ "engines": {
+ "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7"
+ }
+ },
+ "node_modules/btoa": {
+ "version": "1.2.1",
+ "resolved": "https://registry.npmmirror.com/btoa/-/btoa-1.2.1.tgz",
+ "integrity": "sha512-SB4/MIGlsiVkMcHmT+pSmIPoNDoHg+7cMzmt3Uxt628MTz2487DKSqK/fuhFBrkuqrYv5UCEnACpF4dTFNKc/g==",
+ "license": "(MIT OR Apache-2.0)",
+ "bin": {
+ "btoa": "bin/btoa.js"
+ },
+ "engines": {
+ "node": ">= 0.4.0"
+ }
+ },
+ "node_modules/busboy": {
+ "version": "1.6.0",
+ "resolved": "https://registry.npmmirror.com/busboy/-/busboy-1.6.0.tgz",
+ "integrity": "sha512-8SFQbg/0hQ9xy3UNTB0YEnsNBbWfhf7RtnzpL7TkBiTBRfrQ9Fxcnz7VJsleJpyp6rVLvXiuORqjlHi5q+PYuA==",
+ "dependencies": {
+ "streamsearch": "^1.1.0"
+ },
+ "engines": {
+ "node": ">=10.16.0"
+ }
+ },
+ "node_modules/call-bind": {
+ "version": "1.0.8",
+ "resolved": "https://registry.npmmirror.com/call-bind/-/call-bind-1.0.8.tgz",
+ "integrity": "sha512-oKlSFMcMwpUg2ednkhQ454wfWiU/ul3CkJe/PEHcTKuiX6RpbehUiFMXu13HalGZxfUwCQzZG747YXBn1im9ww==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bind-apply-helpers": "^1.0.0",
+ "es-define-property": "^1.0.0",
+ "get-intrinsic": "^1.2.4",
+ "set-function-length": "^1.2.2"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/call-bind-apply-helpers": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmmirror.com/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz",
+ "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "es-errors": "^1.3.0",
+ "function-bind": "^1.1.2"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/call-bound": {
+ "version": "1.0.4",
+ "resolved": "https://registry.npmmirror.com/call-bound/-/call-bound-1.0.4.tgz",
+ "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bind-apply-helpers": "^1.0.2",
+ "get-intrinsic": "^1.3.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/callsites": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmmirror.com/callsites/-/callsites-3.1.0.tgz",
+ "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "node_modules/camelcase-css": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmmirror.com/camelcase-css/-/camelcase-css-2.0.1.tgz",
+ "integrity": "sha512-QOSvevhslijgYwRx6Rv7zKdMF8lbRmx+uQGx2+vDc+KI/eBnsy9kit5aj23AgGu3pa4t9AgwbnXWqS+iOY+2aA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 6"
+ }
+ },
+ "node_modules/caniuse-lite": {
+ "version": "1.0.30001756",
+ "resolved": "https://registry.npmmirror.com/caniuse-lite/-/caniuse-lite-1.0.30001756.tgz",
+ "integrity": "sha512-4HnCNKbMLkLdhJz3TToeVWHSnfJvPaq6vu/eRP0Ahub/07n484XHhBF5AJoSGHdVrS8tKFauUQz8Bp9P7LVx7A==",
+ "funding": [
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/browserslist"
+ },
+ {
+ "type": "tidelift",
+ "url": "https://tidelift.com/funding/github/npm/caniuse-lite"
+ },
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "CC-BY-4.0"
+ },
+ "node_modules/canvg": {
+ "version": "3.0.11",
+ "resolved": "https://registry.npmmirror.com/canvg/-/canvg-3.0.11.tgz",
+ "integrity": "sha512-5ON+q7jCTgMp9cjpu4Jo6XbvfYwSB2Ow3kzHKfIyJfaCAOHLbdKPQqGKgfED/R5B+3TFFfe8pegYA+b423SRyA==",
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "@babel/runtime": "^7.12.5",
+ "@types/raf": "^3.4.0",
+ "core-js": "^3.8.3",
+ "raf": "^3.4.1",
+ "regenerator-runtime": "^0.13.7",
+ "rgbcolor": "^1.0.1",
+ "stackblur-canvas": "^2.0.0",
+ "svg-pathdata": "^6.0.3"
+ },
+ "engines": {
+ "node": ">=10.0.0"
+ }
+ },
+ "node_modules/ccount": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmmirror.com/ccount/-/ccount-2.0.1.tgz",
+ "integrity": "sha512-eyrF0jiFpY+3drT6383f1qhkbGsLSifNAjA61IUjZjmLCWjItY6LB9ft9YhoDgwfmclB2zhu51Lc7+95b8NRAg==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
+ "node_modules/chalk": {
+ "version": "4.1.2",
+ "resolved": "https://registry.npmmirror.com/chalk/-/chalk-4.1.2.tgz",
+ "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "ansi-styles": "^4.1.0",
+ "supports-color": "^7.1.0"
+ },
+ "engines": {
+ "node": ">=10"
+ },
+ "funding": {
+ "url": "https://github.com/chalk/chalk?sponsor=1"
+ }
+ },
+ "node_modules/character-entities": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmmirror.com/character-entities/-/character-entities-2.0.2.tgz",
+ "integrity": "sha512-shx7oQ0Awen/BRIdkjkvz54PnEEI/EjwXDSIZp86/KKdbafHh1Df/RYGBhn4hbe2+uKC9FnT5UCEdyPz3ai9hQ==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
+ "node_modules/character-entities-html4": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmmirror.com/character-entities-html4/-/character-entities-html4-2.1.0.tgz",
+ "integrity": "sha512-1v7fgQRj6hnSwFpq1Eu0ynr/CDEw0rXo2B61qXrLNdHZmPKgb7fqS1a2JwF0rISo9q77jDI8VMEHoApn8qDoZA==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
+ "node_modules/character-entities-legacy": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmmirror.com/character-entities-legacy/-/character-entities-legacy-3.0.0.tgz",
+ "integrity": "sha512-RpPp0asT/6ufRm//AJVwpViZbGM/MkjQFxJccQRHmISF/22NBtsHqAWmL+/pmkPWoIUJdWyeVleTl1wydHATVQ==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
+ "node_modules/character-reference-invalid": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmmirror.com/character-reference-invalid/-/character-reference-invalid-2.0.1.tgz",
+ "integrity": "sha512-iBZ4F4wRbyORVsu0jPV7gXkOsGYjGHPmAyv+HiHG8gi5PtC9KI2j1+v8/tlibRvjoWX027ypmG/n0HtO5t7unw==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
+ "node_modules/chevrotain": {
+ "version": "11.0.3",
+ "resolved": "https://registry.npmjs.org/chevrotain/-/chevrotain-11.0.3.tgz",
+ "integrity": "sha512-ci2iJH6LeIkvP9eJW6gpueU8cnZhv85ELY8w8WiFtNjMHA5ad6pQLaJo9mEly/9qUyCpvqX8/POVUTf18/HFdw==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@chevrotain/cst-dts-gen": "11.0.3",
+ "@chevrotain/gast": "11.0.3",
+ "@chevrotain/regexp-to-ast": "11.0.3",
+ "@chevrotain/types": "11.0.3",
+ "@chevrotain/utils": "11.0.3",
+ "lodash-es": "4.17.21"
+ }
+ },
+ "node_modules/chevrotain-allstar": {
+ "version": "0.3.1",
+ "resolved": "https://registry.npmjs.org/chevrotain-allstar/-/chevrotain-allstar-0.3.1.tgz",
+ "integrity": "sha512-b7g+y9A0v4mxCW1qUhf3BSVPg+/NvGErk/dOkrDaHA0nQIQGAtrOjlX//9OQtRlSCy+x9rfB5N8yC71lH1nvMw==",
+ "license": "MIT",
+ "dependencies": {
+ "lodash-es": "^4.17.21"
+ },
+ "peerDependencies": {
+ "chevrotain": "^11.0.0"
+ }
+ },
+ "node_modules/chokidar": {
+ "version": "3.6.0",
+ "resolved": "https://registry.npmmirror.com/chokidar/-/chokidar-3.6.0.tgz",
+ "integrity": "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "anymatch": "~3.1.2",
+ "braces": "~3.0.2",
+ "glob-parent": "~5.1.2",
+ "is-binary-path": "~2.1.0",
+ "is-glob": "~4.0.1",
+ "normalize-path": "~3.0.0",
+ "readdirp": "~3.6.0"
+ },
+ "engines": {
+ "node": ">= 8.10.0"
+ },
+ "funding": {
+ "url": "https://paulmillr.com/funding/"
+ },
+ "optionalDependencies": {
+ "fsevents": "~2.3.2"
+ }
+ },
+ "node_modules/chokidar/node_modules/glob-parent": {
+ "version": "5.1.2",
+ "resolved": "https://registry.npmmirror.com/glob-parent/-/glob-parent-5.1.2.tgz",
+ "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "is-glob": "^4.0.1"
+ },
+ "engines": {
+ "node": ">= 6"
+ }
+ },
+ "node_modules/client-only": {
+ "version": "0.0.1",
+ "resolved": "https://registry.npmmirror.com/client-only/-/client-only-0.0.1.tgz",
+ "integrity": "sha512-IV3Ou0jSMzZrd3pZ48nLkT9DA7Ag1pnPzaiQhpW7c3RbcqqzvzzVu+L8gfqMp/8IM2MQtSiqaCxrrcfu8I8rMA==",
+ "license": "MIT"
+ },
+ "node_modules/clsx": {
+ "version": "2.1.1",
+ "resolved": "https://registry.npmmirror.com/clsx/-/clsx-2.1.1.tgz",
+ "integrity": "sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "node_modules/color-convert": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmmirror.com/color-convert/-/color-convert-2.0.1.tgz",
+ "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "color-name": "~1.1.4"
+ },
+ "engines": {
+ "node": ">=7.0.0"
+ }
+ },
+ "node_modules/color-name": {
+ "version": "1.1.4",
+ "resolved": "https://registry.npmmirror.com/color-name/-/color-name-1.1.4.tgz",
+ "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/comma-separated-tokens": {
+ "version": "2.0.3",
+ "resolved": "https://registry.npmmirror.com/comma-separated-tokens/-/comma-separated-tokens-2.0.3.tgz",
+ "integrity": "sha512-Fu4hJdvzeylCfQPp9SGWidpzrMs7tTrlu6Vb8XGaRGck8QSNZJJp538Wrb60Lax4fPwR64ViY468OIUTbRlGZg==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
+ "node_modules/commander": {
+ "version": "8.3.0",
+ "resolved": "https://registry.npmmirror.com/commander/-/commander-8.3.0.tgz",
+ "integrity": "sha512-OkTL9umf+He2DZkUq8f8J9of7yL6RJKI24dVITBmNfZBmri9zYZQrKkuXiKhyfPSu8tUhnVBB1iKXevvnlR4Ww==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 12"
+ }
+ },
+ "node_modules/concat-map": {
+ "version": "0.0.1",
+ "resolved": "https://registry.npmmirror.com/concat-map/-/concat-map-0.0.1.tgz",
+ "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/confbox": {
+ "version": "0.1.8",
+ "resolved": "https://registry.npmjs.org/confbox/-/confbox-0.1.8.tgz",
+ "integrity": "sha512-RMtmw0iFkeR4YV+fUOSucriAQNb9g8zFR52MWCtl+cCZOFRNL6zeB395vPzFhEjjn4fMxXudmELnl/KF/WrK6w==",
+ "license": "MIT"
+ },
+ "node_modules/core-js": {
+ "version": "3.47.0",
+ "resolved": "https://registry.npmmirror.com/core-js/-/core-js-3.47.0.tgz",
+ "integrity": "sha512-c3Q2VVkGAUyupsjRnaNX6u8Dq2vAdzm9iuPj5FW0fRxzlxgq9Q39MDq10IvmQSpLgHQNyQzQmOo6bgGHmH3NNg==",
+ "hasInstallScript": true,
+ "license": "MIT",
+ "optional": true,
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/core-js"
+ }
+ },
+ "node_modules/cose-base": {
+ "version": "1.0.3",
+ "resolved": "https://registry.npmjs.org/cose-base/-/cose-base-1.0.3.tgz",
+ "integrity": "sha512-s9whTXInMSgAp/NVXVNuVxVKzGH2qck3aQlVHxDCdAEPgtMKwc4Wq6/QKhgdEdgbLSi9rBTAcPoRa6JpiG4ksg==",
+ "license": "MIT",
+ "dependencies": {
+ "layout-base": "^1.0.0"
+ }
+ },
+ "node_modules/cross-spawn": {
+ "version": "7.0.6",
+ "resolved": "https://registry.npmmirror.com/cross-spawn/-/cross-spawn-7.0.6.tgz",
+ "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "path-key": "^3.1.0",
+ "shebang-command": "^2.0.0",
+ "which": "^2.0.1"
+ },
+ "engines": {
+ "node": ">= 8"
+ }
+ },
+ "node_modules/css-line-break": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmmirror.com/css-line-break/-/css-line-break-2.1.0.tgz",
+ "integrity": "sha512-FHcKFCZcAha3LwfVBhCQbW2nCNbkZXn7KVUJcsT5/P8YmfsVja0FMPJr0B903j/E69HUphKiV9iQArX8SDYA4w==",
+ "license": "MIT",
+ "dependencies": {
+ "utrie": "^1.0.2"
+ }
+ },
+ "node_modules/cssesc": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmmirror.com/cssesc/-/cssesc-3.0.0.tgz",
+ "integrity": "sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg==",
+ "dev": true,
+ "license": "MIT",
+ "bin": {
+ "cssesc": "bin/cssesc"
+ },
+ "engines": {
+ "node": ">=4"
+ }
+ },
+ "node_modules/csstype": {
+ "version": "3.2.3",
+ "resolved": "https://registry.npmmirror.com/csstype/-/csstype-3.2.3.tgz",
+ "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==",
+ "license": "MIT"
+ },
+ "node_modules/cytoscape": {
+ "version": "3.33.1",
+ "resolved": "https://registry.npmjs.org/cytoscape/-/cytoscape-3.33.1.tgz",
+ "integrity": "sha512-iJc4TwyANnOGR1OmWhsS9ayRS3s+XQ185FmuHObThD+5AeJCakAAbWv8KimMTt08xCCLNgneQwFp+JRJOr9qGQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.10"
+ }
+ },
+ "node_modules/cytoscape-cose-bilkent": {
+ "version": "4.1.0",
+ "resolved": "https://registry.npmjs.org/cytoscape-cose-bilkent/-/cytoscape-cose-bilkent-4.1.0.tgz",
+ "integrity": "sha512-wgQlVIUJF13Quxiv5e1gstZ08rnZj2XaLHGoFMYXz7SkNfCDOOteKBE6SYRfA9WxxI/iBc3ajfDoc6hb/MRAHQ==",
+ "license": "MIT",
+ "dependencies": {
+ "cose-base": "^1.0.0"
+ },
+ "peerDependencies": {
+ "cytoscape": "^3.2.0"
+ }
+ },
+ "node_modules/cytoscape-fcose": {
+ "version": "2.2.0",
+ "resolved": "https://registry.npmjs.org/cytoscape-fcose/-/cytoscape-fcose-2.2.0.tgz",
+ "integrity": "sha512-ki1/VuRIHFCzxWNrsshHYPs6L7TvLu3DL+TyIGEsRcvVERmxokbf5Gdk7mFxZnTdiGtnA4cfSmjZJMviqSuZrQ==",
+ "license": "MIT",
+ "dependencies": {
+ "cose-base": "^2.2.0"
+ },
+ "peerDependencies": {
+ "cytoscape": "^3.2.0"
+ }
+ },
+ "node_modules/cytoscape-fcose/node_modules/cose-base": {
+ "version": "2.2.0",
+ "resolved": "https://registry.npmjs.org/cose-base/-/cose-base-2.2.0.tgz",
+ "integrity": "sha512-AzlgcsCbUMymkADOJtQm3wO9S3ltPfYOFD5033keQn9NJzIbtnZj+UdBJe7DYml/8TdbtHJW3j58SOnKhWY/5g==",
+ "license": "MIT",
+ "dependencies": {
+ "layout-base": "^2.0.0"
+ }
+ },
+ "node_modules/cytoscape-fcose/node_modules/layout-base": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/layout-base/-/layout-base-2.0.1.tgz",
+ "integrity": "sha512-dp3s92+uNI1hWIpPGH3jK2kxE2lMjdXdr+DH8ynZHpd6PUlH6x6cbuXnoMmiNumznqaNO31xu9e79F0uuZ0JFg==",
+ "license": "MIT"
+ },
+ "node_modules/d3": {
+ "version": "7.9.0",
+ "resolved": "https://registry.npmjs.org/d3/-/d3-7.9.0.tgz",
+ "integrity": "sha512-e1U46jVP+w7Iut8Jt8ri1YsPOvFpg46k+K8TpCb0P+zjCkjkPnV7WzfDJzMHy1LnA+wj5pLT1wjO901gLXeEhA==",
+ "license": "ISC",
+ "dependencies": {
+ "d3-array": "3",
+ "d3-axis": "3",
+ "d3-brush": "3",
+ "d3-chord": "3",
+ "d3-color": "3",
+ "d3-contour": "4",
+ "d3-delaunay": "6",
+ "d3-dispatch": "3",
+ "d3-drag": "3",
+ "d3-dsv": "3",
+ "d3-ease": "3",
+ "d3-fetch": "3",
+ "d3-force": "3",
+ "d3-format": "3",
+ "d3-geo": "3",
+ "d3-hierarchy": "3",
+ "d3-interpolate": "3",
+ "d3-path": "3",
+ "d3-polygon": "3",
+ "d3-quadtree": "3",
+ "d3-random": "3",
+ "d3-scale": "4",
+ "d3-scale-chromatic": "3",
+ "d3-selection": "3",
+ "d3-shape": "3",
+ "d3-time": "3",
+ "d3-time-format": "4",
+ "d3-timer": "3",
+ "d3-transition": "3",
+ "d3-zoom": "3"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-array": {
+ "version": "3.2.4",
+ "resolved": "https://registry.npmjs.org/d3-array/-/d3-array-3.2.4.tgz",
+ "integrity": "sha512-tdQAmyA18i4J7wprpYq8ClcxZy3SC31QMeByyCFyRt7BVHdREQZ5lpzoe5mFEYZUWe+oq8HBvk9JjpibyEV4Jg==",
+ "license": "ISC",
+ "dependencies": {
+ "internmap": "1 - 2"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-axis": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/d3-axis/-/d3-axis-3.0.0.tgz",
+ "integrity": "sha512-IH5tgjV4jE/GhHkRV0HiVYPDtvfjHQlQfJHs0usq7M30XcSBvOotpmH1IgkcXsO/5gEQZD43B//fc7SRT5S+xw==",
+ "license": "ISC",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-brush": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/d3-brush/-/d3-brush-3.0.0.tgz",
+ "integrity": "sha512-ALnjWlVYkXsVIGlOsuWH1+3udkYFI48Ljihfnh8FZPF2QS9o+PzGLBslO0PjzVoHLZ2KCVgAM8NVkXPJB2aNnQ==",
+ "license": "ISC",
+ "dependencies": {
+ "d3-dispatch": "1 - 3",
+ "d3-drag": "2 - 3",
+ "d3-interpolate": "1 - 3",
+ "d3-selection": "3",
+ "d3-transition": "3"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-chord": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/d3-chord/-/d3-chord-3.0.1.tgz",
+ "integrity": "sha512-VE5S6TNa+j8msksl7HwjxMHDM2yNK3XCkusIlpX5kwauBfXuyLAtNg9jCp/iHH61tgI4sb6R/EIMWCqEIdjT/g==",
+ "license": "ISC",
+ "dependencies": {
+ "d3-path": "1 - 3"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-color": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/d3-color/-/d3-color-3.1.0.tgz",
+ "integrity": "sha512-zg/chbXyeBtMQ1LbD/WSoW2DpC3I0mpmPdW+ynRTj/x2DAWYrIY7qeZIHidozwV24m4iavr15lNwIwLxRmOxhA==",
+ "license": "ISC",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-contour": {
+ "version": "4.0.2",
+ "resolved": "https://registry.npmjs.org/d3-contour/-/d3-contour-4.0.2.tgz",
+ "integrity": "sha512-4EzFTRIikzs47RGmdxbeUvLWtGedDUNkTcmzoeyg4sP/dvCexO47AaQL7VKy/gul85TOxw+IBgA8US2xwbToNA==",
+ "license": "ISC",
+ "dependencies": {
+ "d3-array": "^3.2.0"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-delaunay": {
+ "version": "6.0.4",
+ "resolved": "https://registry.npmjs.org/d3-delaunay/-/d3-delaunay-6.0.4.tgz",
+ "integrity": "sha512-mdjtIZ1XLAM8bm/hx3WwjfHt6Sggek7qH043O8KEjDXN40xi3vx/6pYSVTwLjEgiXQTbvaouWKynLBiUZ6SK6A==",
+ "license": "ISC",
+ "dependencies": {
+ "delaunator": "5"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-dispatch": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/d3-dispatch/-/d3-dispatch-3.0.1.tgz",
+ "integrity": "sha512-rzUyPU/S7rwUflMyLc1ETDeBj0NRuHKKAcvukozwhshr6g6c5d8zh4c2gQjY2bZ0dXeGLWc1PF174P2tVvKhfg==",
+ "license": "ISC",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-drag": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/d3-drag/-/d3-drag-3.0.0.tgz",
+ "integrity": "sha512-pWbUJLdETVA8lQNJecMxoXfH6x+mO2UQo8rSmZ+QqxcbyA3hfeprFgIT//HW2nlHChWeIIMwS2Fq+gEARkhTkg==",
+ "license": "ISC",
+ "dependencies": {
+ "d3-dispatch": "1 - 3",
+ "d3-selection": "3"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-dsv": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/d3-dsv/-/d3-dsv-3.0.1.tgz",
+ "integrity": "sha512-UG6OvdI5afDIFP9w4G0mNq50dSOsXHJaRE8arAS5o9ApWnIElp8GZw1Dun8vP8OyHOZ/QJUKUJwxiiCCnUwm+Q==",
+ "license": "ISC",
+ "dependencies": {
+ "commander": "7",
+ "iconv-lite": "0.6",
+ "rw": "1"
+ },
+ "bin": {
+ "csv2json": "bin/dsv2json.js",
+ "csv2tsv": "bin/dsv2dsv.js",
+ "dsv2dsv": "bin/dsv2dsv.js",
+ "dsv2json": "bin/dsv2json.js",
+ "json2csv": "bin/json2dsv.js",
+ "json2dsv": "bin/json2dsv.js",
+ "json2tsv": "bin/json2dsv.js",
+ "tsv2csv": "bin/dsv2dsv.js",
+ "tsv2json": "bin/dsv2json.js"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-dsv/node_modules/commander": {
+ "version": "7.2.0",
+ "resolved": "https://registry.npmjs.org/commander/-/commander-7.2.0.tgz",
+ "integrity": "sha512-QrWXB+ZQSVPmIWIhtEO9H+gwHaMGYiF5ChvoJ+K9ZGHG/sVsa6yiesAD1GC/x46sET00Xlwo1u49RVVVzvcSkw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 10"
+ }
+ },
+ "node_modules/d3-ease": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/d3-ease/-/d3-ease-3.0.1.tgz",
+ "integrity": "sha512-wR/XK3D3XcLIZwpbvQwQ5fK+8Ykds1ip7A2Txe0yxncXSdq1L9skcG7blcedkOX+ZcgxGAmLX1FrRGbADwzi0w==",
+ "license": "BSD-3-Clause",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-fetch": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/d3-fetch/-/d3-fetch-3.0.1.tgz",
+ "integrity": "sha512-kpkQIM20n3oLVBKGg6oHrUchHM3xODkTzjMoj7aWQFq5QEM+R6E4WkzT5+tojDY7yjez8KgCBRoj4aEr99Fdqw==",
+ "license": "ISC",
+ "dependencies": {
+ "d3-dsv": "1 - 3"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-force": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/d3-force/-/d3-force-3.0.0.tgz",
+ "integrity": "sha512-zxV/SsA+U4yte8051P4ECydjD/S+qeYtnaIyAs9tgHCqfguma/aAQDjo85A9Z6EKhBirHRJHXIgJUlffT4wdLg==",
+ "license": "ISC",
+ "dependencies": {
+ "d3-dispatch": "1 - 3",
+ "d3-quadtree": "1 - 3",
+ "d3-timer": "1 - 3"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-format": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/d3-format/-/d3-format-3.1.0.tgz",
+ "integrity": "sha512-YyUI6AEuY/Wpt8KWLgZHsIU86atmikuoOmCfommt0LYHiQSPjvX2AcFc38PX0CBpr2RCyZhjex+NS/LPOv6YqA==",
+ "license": "ISC",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-geo": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/d3-geo/-/d3-geo-3.1.1.tgz",
+ "integrity": "sha512-637ln3gXKXOwhalDzinUgY83KzNWZRKbYubaG+fGVuc/dxO64RRljtCTnf5ecMyE1RIdtqpkVcq0IbtU2S8j2Q==",
+ "license": "ISC",
+ "dependencies": {
+ "d3-array": "2.5.0 - 3"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-hierarchy": {
+ "version": "3.1.2",
+ "resolved": "https://registry.npmjs.org/d3-hierarchy/-/d3-hierarchy-3.1.2.tgz",
+ "integrity": "sha512-FX/9frcub54beBdugHjDCdikxThEqjnR93Qt7PvQTOHxyiNCAlvMrHhclk3cD5VeAaq9fxmfRp+CnWw9rEMBuA==",
+ "license": "ISC",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-interpolate": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/d3-interpolate/-/d3-interpolate-3.0.1.tgz",
+ "integrity": "sha512-3bYs1rOD33uo8aqJfKP3JWPAibgw8Zm2+L9vBKEHJ2Rg+viTR7o5Mmv5mZcieN+FRYaAOWX5SJATX6k1PWz72g==",
+ "license": "ISC",
+ "dependencies": {
+ "d3-color": "1 - 3"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-path": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/d3-path/-/d3-path-3.1.0.tgz",
+ "integrity": "sha512-p3KP5HCf/bvjBSSKuXid6Zqijx7wIfNW+J/maPs+iwR35at5JCbLUT0LzF1cnjbCHWhqzQTIN2Jpe8pRebIEFQ==",
+ "license": "ISC",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-polygon": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/d3-polygon/-/d3-polygon-3.0.1.tgz",
+ "integrity": "sha512-3vbA7vXYwfe1SYhED++fPUQlWSYTTGmFmQiany/gdbiWgU/iEyQzyymwL9SkJjFFuCS4902BSzewVGsHHmHtXg==",
+ "license": "ISC",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-quadtree": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/d3-quadtree/-/d3-quadtree-3.0.1.tgz",
+ "integrity": "sha512-04xDrxQTDTCFwP5H6hRhsRcb9xxv2RzkcsygFzmkSIOJy3PeRJP7sNk3VRIbKXcog561P9oU0/rVH6vDROAgUw==",
+ "license": "ISC",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-random": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/d3-random/-/d3-random-3.0.1.tgz",
+ "integrity": "sha512-FXMe9GfxTxqd5D6jFsQ+DJ8BJS4E/fT5mqqdjovykEB2oFbTMDVdg1MGFxfQW+FBOGoB++k8swBrgwSHT1cUXQ==",
+ "license": "ISC",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-sankey": {
+ "version": "0.12.3",
+ "resolved": "https://registry.npmjs.org/d3-sankey/-/d3-sankey-0.12.3.tgz",
+ "integrity": "sha512-nQhsBRmM19Ax5xEIPLMY9ZmJ/cDvd1BG3UVvt5h3WRxKg5zGRbvnteTyWAbzeSvlh3tW7ZEmq4VwR5mB3tutmQ==",
+ "license": "BSD-3-Clause",
+ "dependencies": {
+ "d3-array": "1 - 2",
+ "d3-shape": "^1.2.0"
+ }
+ },
+ "node_modules/d3-sankey/node_modules/d3-array": {
+ "version": "2.12.1",
+ "resolved": "https://registry.npmjs.org/d3-array/-/d3-array-2.12.1.tgz",
+ "integrity": "sha512-B0ErZK/66mHtEsR1TkPEEkwdy+WDesimkM5gpZr5Dsg54BiTA5RXtYW5qTLIAcekaS9xfZrzBLF/OAkB3Qn1YQ==",
+ "license": "BSD-3-Clause",
+ "dependencies": {
+ "internmap": "^1.0.0"
+ }
+ },
+ "node_modules/d3-sankey/node_modules/d3-path": {
+ "version": "1.0.9",
+ "resolved": "https://registry.npmjs.org/d3-path/-/d3-path-1.0.9.tgz",
+ "integrity": "sha512-VLaYcn81dtHVTjEHd8B+pbe9yHWpXKZUC87PzoFmsFrJqgFwDe/qxfp5MlfsfM1V5E/iVt0MmEbWQ7FVIXh/bg==",
+ "license": "BSD-3-Clause"
+ },
+ "node_modules/d3-sankey/node_modules/d3-shape": {
+ "version": "1.3.7",
+ "resolved": "https://registry.npmjs.org/d3-shape/-/d3-shape-1.3.7.tgz",
+ "integrity": "sha512-EUkvKjqPFUAZyOlhY5gzCxCeI0Aep04LwIRpsZ/mLFelJiUfnK56jo5JMDSE7yyP2kLSb6LtF+S5chMk7uqPqw==",
+ "license": "BSD-3-Clause",
+ "dependencies": {
+ "d3-path": "1"
+ }
+ },
+ "node_modules/d3-sankey/node_modules/internmap": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/internmap/-/internmap-1.0.1.tgz",
+ "integrity": "sha512-lDB5YccMydFBtasVtxnZ3MRBHuaoE8GKsppq+EchKL2U4nK/DmEpPHNH8MZe5HkMtpSiTSOZwfN0tzYjO/lJEw==",
+ "license": "ISC"
+ },
+ "node_modules/d3-scale": {
+ "version": "4.0.2",
+ "resolved": "https://registry.npmjs.org/d3-scale/-/d3-scale-4.0.2.tgz",
+ "integrity": "sha512-GZW464g1SH7ag3Y7hXjf8RoUuAFIqklOAq3MRl4OaWabTFJY9PN/E1YklhXLh+OQ3fM9yS2nOkCoS+WLZ6kvxQ==",
+ "license": "ISC",
+ "dependencies": {
+ "d3-array": "2.10.0 - 3",
+ "d3-format": "1 - 3",
+ "d3-interpolate": "1.2.0 - 3",
+ "d3-time": "2.1.1 - 3",
+ "d3-time-format": "2 - 4"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-scale-chromatic": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/d3-scale-chromatic/-/d3-scale-chromatic-3.1.0.tgz",
+ "integrity": "sha512-A3s5PWiZ9YCXFye1o246KoscMWqf8BsD9eRiJ3He7C9OBaxKhAd5TFCdEx/7VbKtxxTsu//1mMJFrEt572cEyQ==",
+ "license": "ISC",
+ "dependencies": {
+ "d3-color": "1 - 3",
+ "d3-interpolate": "1 - 3"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-selection": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/d3-selection/-/d3-selection-3.0.0.tgz",
+ "integrity": "sha512-fmTRWbNMmsmWq6xJV8D19U/gw/bwrHfNXxrIN+HfZgnzqTHp9jOmKMhsTUjXOJnZOdZY9Q28y4yebKzqDKlxlQ==",
+ "license": "ISC",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-shape": {
+ "version": "3.2.0",
+ "resolved": "https://registry.npmjs.org/d3-shape/-/d3-shape-3.2.0.tgz",
+ "integrity": "sha512-SaLBuwGm3MOViRq2ABk3eLoxwZELpH6zhl3FbAoJ7Vm1gofKx6El1Ib5z23NUEhF9AsGl7y+dzLe5Cw2AArGTA==",
+ "license": "ISC",
+ "dependencies": {
+ "d3-path": "^3.1.0"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-time": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/d3-time/-/d3-time-3.1.0.tgz",
+ "integrity": "sha512-VqKjzBLejbSMT4IgbmVgDjpkYrNWUYJnbCGo874u7MMKIWsILRX+OpX/gTk8MqjpT1A/c6HY2dCA77ZN0lkQ2Q==",
+ "license": "ISC",
+ "dependencies": {
+ "d3-array": "2 - 3"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-time-format": {
+ "version": "4.1.0",
+ "resolved": "https://registry.npmjs.org/d3-time-format/-/d3-time-format-4.1.0.tgz",
+ "integrity": "sha512-dJxPBlzC7NugB2PDLwo9Q8JiTR3M3e4/XANkreKSUxF8vvXKqm1Yfq4Q5dl8budlunRVlUUaDUgFt7eA8D6NLg==",
+ "license": "ISC",
+ "dependencies": {
+ "d3-time": "1 - 3"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-timer": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/d3-timer/-/d3-timer-3.0.1.tgz",
+ "integrity": "sha512-ndfJ/JxxMd3nw31uyKoY2naivF+r29V+Lc0svZxe1JvvIRmi8hUsrMvdOwgS1o6uBHmiz91geQ0ylPP0aj1VUA==",
+ "license": "ISC",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-transition": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/d3-transition/-/d3-transition-3.0.1.tgz",
+ "integrity": "sha512-ApKvfjsSR6tg06xrL434C0WydLr7JewBB3V+/39RMHsaXTOG0zmt/OAXeng5M5LBm0ojmxJrpomQVZ1aPvBL4w==",
+ "license": "ISC",
+ "dependencies": {
+ "d3-color": "1 - 3",
+ "d3-dispatch": "1 - 3",
+ "d3-ease": "1 - 3",
+ "d3-interpolate": "1 - 3",
+ "d3-timer": "1 - 3"
+ },
+ "engines": {
+ "node": ">=12"
+ },
+ "peerDependencies": {
+ "d3-selection": "2 - 3"
+ }
+ },
+ "node_modules/d3-zoom": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/d3-zoom/-/d3-zoom-3.0.0.tgz",
+ "integrity": "sha512-b8AmV3kfQaqWAuacbPuNbL6vahnOJflOhexLzMMNLga62+/nh0JzvJ0aO/5a5MVgUFGS7Hu1P9P03o3fJkDCyw==",
+ "license": "ISC",
+ "dependencies": {
+ "d3-dispatch": "1 - 3",
+ "d3-drag": "2 - 3",
+ "d3-interpolate": "1 - 3",
+ "d3-selection": "2 - 3",
+ "d3-transition": "2 - 3"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/dagre-d3-es": {
+ "version": "7.0.13",
+ "resolved": "https://registry.npmjs.org/dagre-d3-es/-/dagre-d3-es-7.0.13.tgz",
+ "integrity": "sha512-efEhnxpSuwpYOKRm/L5KbqoZmNNukHa/Flty4Wp62JRvgH2ojwVgPgdYyr4twpieZnyRDdIH7PY2mopX26+j2Q==",
+ "license": "MIT",
+ "dependencies": {
+ "d3": "^7.9.0",
+ "lodash-es": "^4.17.21"
+ }
+ },
+ "node_modules/damerau-levenshtein": {
+ "version": "1.0.8",
+ "resolved": "https://registry.npmmirror.com/damerau-levenshtein/-/damerau-levenshtein-1.0.8.tgz",
+ "integrity": "sha512-sdQSFB7+llfUcQHUQO3+B8ERRj0Oa4w9POWMI/puGtuf7gFywGmkaLCElnudfTiKZV+NvHqL0ifzdrI8Ro7ESA==",
+ "dev": true,
+ "license": "BSD-2-Clause"
+ },
+ "node_modules/data-view-buffer": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmmirror.com/data-view-buffer/-/data-view-buffer-1.0.2.tgz",
+ "integrity": "sha512-EmKO5V3OLXh1rtK2wgXRansaK1/mtVdTUEiEI0W8RkvgT05kfxaH29PliLnpLP73yYO6142Q72QNa8Wx/A5CqQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bound": "^1.0.3",
+ "es-errors": "^1.3.0",
+ "is-data-view": "^1.0.2"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/data-view-byte-length": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmmirror.com/data-view-byte-length/-/data-view-byte-length-1.0.2.tgz",
+ "integrity": "sha512-tuhGbE6CfTM9+5ANGf+oQb72Ky/0+s3xKUpHvShfiz2RxMFgFPjsXuRLBVMtvMs15awe45SRb83D6wH4ew6wlQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bound": "^1.0.3",
+ "es-errors": "^1.3.0",
+ "is-data-view": "^1.0.2"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/inspect-js"
+ }
+ },
+ "node_modules/data-view-byte-offset": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmmirror.com/data-view-byte-offset/-/data-view-byte-offset-1.0.1.tgz",
+ "integrity": "sha512-BS8PfmtDGnrgYdOonGZQdLZslWIeCGFP9tpan0hi1Co2Zr2NKADsvGYA8XxuG/4UWgJ6Cjtv+YJnB6MM69QGlQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bound": "^1.0.2",
+ "es-errors": "^1.3.0",
+ "is-data-view": "^1.0.1"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/dayjs": {
+ "version": "1.11.19",
+ "resolved": "https://registry.npmjs.org/dayjs/-/dayjs-1.11.19.tgz",
+ "integrity": "sha512-t5EcLVS6QPBNqM2z8fakk/NKel+Xzshgt8FFKAn+qwlD1pzZWxh0nVCrvFK7ZDb6XucZeF9z8C7CBWTRIVApAw==",
+ "license": "MIT"
+ },
+ "node_modules/debug": {
+ "version": "4.4.3",
+ "resolved": "https://registry.npmmirror.com/debug/-/debug-4.4.3.tgz",
+ "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
+ "license": "MIT",
+ "dependencies": {
+ "ms": "^2.1.3"
+ },
+ "engines": {
+ "node": ">=6.0"
+ },
+ "peerDependenciesMeta": {
+ "supports-color": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/decode-named-character-reference": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmmirror.com/decode-named-character-reference/-/decode-named-character-reference-1.2.0.tgz",
+ "integrity": "sha512-c6fcElNV6ShtZXmsgNgFFV5tVX2PaV4g+MOAkb8eXHvn6sryJBrZa9r0zV6+dtTyoCKxtDy5tyQ5ZwQuidtd+Q==",
+ "license": "MIT",
+ "dependencies": {
+ "character-entities": "^2.0.0"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
+ "node_modules/deep-is": {
+ "version": "0.1.4",
+ "resolved": "https://registry.npmmirror.com/deep-is/-/deep-is-0.1.4.tgz",
+ "integrity": "sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/define-data-property": {
+ "version": "1.1.4",
+ "resolved": "https://registry.npmmirror.com/define-data-property/-/define-data-property-1.1.4.tgz",
+ "integrity": "sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "es-define-property": "^1.0.0",
+ "es-errors": "^1.3.0",
+ "gopd": "^1.0.1"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/define-properties": {
+ "version": "1.2.1",
+ "resolved": "https://registry.npmmirror.com/define-properties/-/define-properties-1.2.1.tgz",
+ "integrity": "sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "define-data-property": "^1.0.1",
+ "has-property-descriptors": "^1.0.0",
+ "object-keys": "^1.1.1"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/delaunator": {
+ "version": "5.0.1",
+ "resolved": "https://registry.npmjs.org/delaunator/-/delaunator-5.0.1.tgz",
+ "integrity": "sha512-8nvh+XBe96aCESrGOqMp/84b13H9cdKbG5P2ejQCh4d4sK9RL4371qou9drQjMhvnPmhWl5hnmqbEE0fXr9Xnw==",
+ "license": "ISC",
+ "dependencies": {
+ "robust-predicates": "^3.0.2"
+ }
+ },
+ "node_modules/dequal": {
+ "version": "2.0.3",
+ "resolved": "https://registry.npmmirror.com/dequal/-/dequal-2.0.3.tgz",
+ "integrity": "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "node_modules/devlop": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmmirror.com/devlop/-/devlop-1.1.0.tgz",
+ "integrity": "sha512-RWmIqhcFf1lRYBvNmr7qTNuyCt/7/ns2jbpp1+PalgE/rDQcBT0fioSMUpJ93irlUhC5hrg4cYqe6U+0ImW0rA==",
+ "license": "MIT",
+ "dependencies": {
+ "dequal": "^2.0.0"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
+ "node_modules/didyoumean": {
+ "version": "1.2.2",
+ "resolved": "https://registry.npmmirror.com/didyoumean/-/didyoumean-1.2.2.tgz",
+ "integrity": "sha512-gxtyfqMg7GKyhQmb056K7M3xszy/myH8w+B4RT+QXBQsvAOdc3XymqDDPHx1BgPgsdAA5SIifona89YtRATDzw==",
+ "dev": true,
+ "license": "Apache-2.0"
+ },
+ "node_modules/dir-glob": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmmirror.com/dir-glob/-/dir-glob-3.0.1.tgz",
+ "integrity": "sha512-WkrWp9GR4KXfKGYzOLmTuGVi1UWFfws377n9cc55/tb6DuqyF6pcQ5AbiHEshaDpY9v6oaSr2XCDidGmMwdzIA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "path-type": "^4.0.0"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/dlv": {
+ "version": "1.1.3",
+ "resolved": "https://registry.npmmirror.com/dlv/-/dlv-1.1.3.tgz",
+ "integrity": "sha512-+HlytyjlPKnIG8XuRG8WvmBP8xs8P71y+SKKS6ZXWoEgLuePxtDoUEiH7WkdePWrQ5JBpE6aoVqfZfJUQkjXwA==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/doctrine": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmmirror.com/doctrine/-/doctrine-3.0.0.tgz",
+ "integrity": "sha512-yS+Q5i3hBf7GBkd4KG8a7eBNNWNGLTaEwwYWUijIYM7zrlYDM0BFXHjjPWlWZ1Rg7UaddZeIDmi9jF3HmqiQ2w==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "dependencies": {
+ "esutils": "^2.0.2"
+ },
+ "engines": {
+ "node": ">=6.0.0"
+ }
+ },
+ "node_modules/dompurify": {
+ "version": "2.5.8",
+ "resolved": "https://registry.npmmirror.com/dompurify/-/dompurify-2.5.8.tgz",
+ "integrity": "sha512-o1vSNgrmYMQObbSSvF/1brBYEQPHhV1+gsmrusO7/GXtp1T9rCS8cXFqVxK/9crT1jA6Ccv+5MTSjBNqr7Sovw==",
+ "license": "(MPL-2.0 OR Apache-2.0)",
+ "optional": true
+ },
+ "node_modules/dunder-proto": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmmirror.com/dunder-proto/-/dunder-proto-1.0.1.tgz",
+ "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bind-apply-helpers": "^1.0.1",
+ "es-errors": "^1.3.0",
+ "gopd": "^1.2.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/electron-to-chromium": {
+ "version": "1.5.256",
+ "resolved": "https://registry.npmmirror.com/electron-to-chromium/-/electron-to-chromium-1.5.256.tgz",
+ "integrity": "sha512-uqYq1IQhpXXLX+HgiXdyOZml7spy4xfy42yPxcCCRjswp0fYM2X+JwCON07lqnpLEGVCj739B7Yr+FngmHBMEQ==",
+ "dev": true,
+ "license": "ISC"
+ },
+ "node_modules/emoji-regex": {
+ "version": "9.2.2",
+ "resolved": "https://registry.npmmirror.com/emoji-regex/-/emoji-regex-9.2.2.tgz",
+ "integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/entities": {
+ "version": "6.0.1",
+ "resolved": "https://registry.npmmirror.com/entities/-/entities-6.0.1.tgz",
+ "integrity": "sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g==",
+ "license": "BSD-2-Clause",
+ "engines": {
+ "node": ">=0.12"
+ },
+ "funding": {
+ "url": "https://github.com/fb55/entities?sponsor=1"
+ }
+ },
+ "node_modules/es-abstract": {
+ "version": "1.24.0",
+ "resolved": "https://registry.npmmirror.com/es-abstract/-/es-abstract-1.24.0.tgz",
+ "integrity": "sha512-WSzPgsdLtTcQwm4CROfS5ju2Wa1QQcVeT37jFjYzdFz1r9ahadC8B8/a4qxJxM+09F18iumCdRmlr96ZYkQvEg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "array-buffer-byte-length": "^1.0.2",
+ "arraybuffer.prototype.slice": "^1.0.4",
+ "available-typed-arrays": "^1.0.7",
+ "call-bind": "^1.0.8",
+ "call-bound": "^1.0.4",
+ "data-view-buffer": "^1.0.2",
+ "data-view-byte-length": "^1.0.2",
+ "data-view-byte-offset": "^1.0.1",
+ "es-define-property": "^1.0.1",
+ "es-errors": "^1.3.0",
+ "es-object-atoms": "^1.1.1",
+ "es-set-tostringtag": "^2.1.0",
+ "es-to-primitive": "^1.3.0",
+ "function.prototype.name": "^1.1.8",
+ "get-intrinsic": "^1.3.0",
+ "get-proto": "^1.0.1",
+ "get-symbol-description": "^1.1.0",
+ "globalthis": "^1.0.4",
+ "gopd": "^1.2.0",
+ "has-property-descriptors": "^1.0.2",
+ "has-proto": "^1.2.0",
+ "has-symbols": "^1.1.0",
+ "hasown": "^2.0.2",
+ "internal-slot": "^1.1.0",
+ "is-array-buffer": "^3.0.5",
+ "is-callable": "^1.2.7",
+ "is-data-view": "^1.0.2",
+ "is-negative-zero": "^2.0.3",
+ "is-regex": "^1.2.1",
+ "is-set": "^2.0.3",
+ "is-shared-array-buffer": "^1.0.4",
+ "is-string": "^1.1.1",
+ "is-typed-array": "^1.1.15",
+ "is-weakref": "^1.1.1",
+ "math-intrinsics": "^1.1.0",
+ "object-inspect": "^1.13.4",
+ "object-keys": "^1.1.1",
+ "object.assign": "^4.1.7",
+ "own-keys": "^1.0.1",
+ "regexp.prototype.flags": "^1.5.4",
+ "safe-array-concat": "^1.1.3",
+ "safe-push-apply": "^1.0.0",
+ "safe-regex-test": "^1.1.0",
+ "set-proto": "^1.0.0",
+ "stop-iteration-iterator": "^1.1.0",
+ "string.prototype.trim": "^1.2.10",
+ "string.prototype.trimend": "^1.0.9",
+ "string.prototype.trimstart": "^1.0.8",
+ "typed-array-buffer": "^1.0.3",
+ "typed-array-byte-length": "^1.0.3",
+ "typed-array-byte-offset": "^1.0.4",
+ "typed-array-length": "^1.0.7",
+ "unbox-primitive": "^1.1.0",
+ "which-typed-array": "^1.1.19"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/es-define-property": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmmirror.com/es-define-property/-/es-define-property-1.0.1.tgz",
+ "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/es-errors": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmmirror.com/es-errors/-/es-errors-1.3.0.tgz",
+ "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/es-iterator-helpers": {
+ "version": "1.2.1",
+ "resolved": "https://registry.npmmirror.com/es-iterator-helpers/-/es-iterator-helpers-1.2.1.tgz",
+ "integrity": "sha512-uDn+FE1yrDzyC0pCo961B2IHbdM8y/ACZsKD4dG6WqrjV53BADjwa7D+1aom2rsNVfLyDgU/eigvlJGJ08OQ4w==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bind": "^1.0.8",
+ "call-bound": "^1.0.3",
+ "define-properties": "^1.2.1",
+ "es-abstract": "^1.23.6",
+ "es-errors": "^1.3.0",
+ "es-set-tostringtag": "^2.0.3",
+ "function-bind": "^1.1.2",
+ "get-intrinsic": "^1.2.6",
+ "globalthis": "^1.0.4",
+ "gopd": "^1.2.0",
+ "has-property-descriptors": "^1.0.2",
+ "has-proto": "^1.2.0",
+ "has-symbols": "^1.1.0",
+ "internal-slot": "^1.1.0",
+ "iterator.prototype": "^1.1.4",
+ "safe-array-concat": "^1.1.3"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/es-object-atoms": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmmirror.com/es-object-atoms/-/es-object-atoms-1.1.1.tgz",
+ "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "es-errors": "^1.3.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/es-set-tostringtag": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmmirror.com/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz",
+ "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "es-errors": "^1.3.0",
+ "get-intrinsic": "^1.2.6",
+ "has-tostringtag": "^1.0.2",
+ "hasown": "^2.0.2"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/es-shim-unscopables": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmmirror.com/es-shim-unscopables/-/es-shim-unscopables-1.1.0.tgz",
+ "integrity": "sha512-d9T8ucsEhh8Bi1woXCf+TIKDIROLG5WCkxg8geBCbvk22kzwC5G2OnXVMO6FUsvQlgUUXQ2itephWDLqDzbeCw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "hasown": "^2.0.2"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/es-to-primitive": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmmirror.com/es-to-primitive/-/es-to-primitive-1.3.0.tgz",
+ "integrity": "sha512-w+5mJ3GuFL+NjVtJlvydShqE1eN3h3PbI7/5LAsYJP/2qtuMXjfL2LpHSRqo4b4eSF5K/DH1JXKUAHSB2UW50g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "is-callable": "^1.2.7",
+ "is-date-object": "^1.0.5",
+ "is-symbol": "^1.0.4"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/escalade": {
+ "version": "3.2.0",
+ "resolved": "https://registry.npmmirror.com/escalade/-/escalade-3.2.0.tgz",
+ "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "node_modules/escape-string-regexp": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmmirror.com/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz",
+ "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=10"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/eslint": {
+ "version": "8.57.1",
+ "resolved": "https://registry.npmmirror.com/eslint/-/eslint-8.57.1.tgz",
+ "integrity": "sha512-ypowyDxpVSYpkXr9WPv2PAZCtNip1Mv5KTW0SCurXv/9iOpcrH9PaqUElksqEB6pChqHGDRCFTyrZlGhnLNGiA==",
+ "deprecated": "This version is no longer supported. Please see https://eslint.org/version-support for other options.",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@eslint-community/eslint-utils": "^4.2.0",
+ "@eslint-community/regexpp": "^4.6.1",
+ "@eslint/eslintrc": "^2.1.4",
+ "@eslint/js": "8.57.1",
+ "@humanwhocodes/config-array": "^0.13.0",
+ "@humanwhocodes/module-importer": "^1.0.1",
+ "@nodelib/fs.walk": "^1.2.8",
+ "@ungap/structured-clone": "^1.2.0",
+ "ajv": "^6.12.4",
+ "chalk": "^4.0.0",
+ "cross-spawn": "^7.0.2",
+ "debug": "^4.3.2",
+ "doctrine": "^3.0.0",
+ "escape-string-regexp": "^4.0.0",
+ "eslint-scope": "^7.2.2",
+ "eslint-visitor-keys": "^3.4.3",
+ "espree": "^9.6.1",
+ "esquery": "^1.4.2",
+ "esutils": "^2.0.2",
+ "fast-deep-equal": "^3.1.3",
+ "file-entry-cache": "^6.0.1",
+ "find-up": "^5.0.0",
+ "glob-parent": "^6.0.2",
+ "globals": "^13.19.0",
+ "graphemer": "^1.4.0",
+ "ignore": "^5.2.0",
+ "imurmurhash": "^0.1.4",
+ "is-glob": "^4.0.0",
+ "is-path-inside": "^3.0.3",
+ "js-yaml": "^4.1.0",
+ "json-stable-stringify-without-jsonify": "^1.0.1",
+ "levn": "^0.4.1",
+ "lodash.merge": "^4.6.2",
+ "minimatch": "^3.1.2",
+ "natural-compare": "^1.4.0",
+ "optionator": "^0.9.3",
+ "strip-ansi": "^6.0.1",
+ "text-table": "^0.2.0"
+ },
+ "bin": {
+ "eslint": "bin/eslint.js"
+ },
+ "engines": {
+ "node": "^12.22.0 || ^14.17.0 || >=16.0.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/eslint"
+ }
+ },
+ "node_modules/eslint-config-next": {
+ "version": "14.0.3",
+ "resolved": "https://registry.npmmirror.com/eslint-config-next/-/eslint-config-next-14.0.3.tgz",
+ "integrity": "sha512-IKPhpLdpSUyKofmsXUfrvBC49JMUTdeaD8ZIH4v9Vk0sC1X6URTuTJCLtA0Vwuj7V/CQh0oISuSTvNn5//Buew==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@next/eslint-plugin-next": "14.0.3",
+ "@rushstack/eslint-patch": "^1.3.3",
+ "@typescript-eslint/parser": "^5.4.2 || ^6.0.0",
+ "eslint-import-resolver-node": "^0.3.6",
+ "eslint-import-resolver-typescript": "^3.5.2",
+ "eslint-plugin-import": "^2.28.1",
+ "eslint-plugin-jsx-a11y": "^6.7.1",
+ "eslint-plugin-react": "^7.33.2",
+ "eslint-plugin-react-hooks": "^4.5.0 || 5.0.0-canary-7118f5dd7-20230705"
+ },
+ "peerDependencies": {
+ "eslint": "^7.23.0 || ^8.0.0",
+ "typescript": ">=3.3.1"
+ },
+ "peerDependenciesMeta": {
+ "typescript": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/eslint-import-resolver-node": {
+ "version": "0.3.9",
+ "resolved": "https://registry.npmmirror.com/eslint-import-resolver-node/-/eslint-import-resolver-node-0.3.9.tgz",
+ "integrity": "sha512-WFj2isz22JahUv+B788TlO3N6zL3nNJGU8CcZbPZvVEkBPaJdCV4vy5wyghty5ROFbCRnm132v8BScu5/1BQ8g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "debug": "^3.2.7",
+ "is-core-module": "^2.13.0",
+ "resolve": "^1.22.4"
+ }
+ },
+ "node_modules/eslint-import-resolver-node/node_modules/debug": {
+ "version": "3.2.7",
+ "resolved": "https://registry.npmmirror.com/debug/-/debug-3.2.7.tgz",
+ "integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "ms": "^2.1.1"
+ }
+ },
+ "node_modules/eslint-import-resolver-typescript": {
+ "version": "3.10.1",
+ "resolved": "https://registry.npmmirror.com/eslint-import-resolver-typescript/-/eslint-import-resolver-typescript-3.10.1.tgz",
+ "integrity": "sha512-A1rHYb06zjMGAxdLSkN2fXPBwuSaQ0iO5M/hdyS0Ajj1VBaRp0sPD3dn1FhME3c/JluGFbwSxyCfqdSbtQLAHQ==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "@nolyfill/is-core-module": "1.0.39",
+ "debug": "^4.4.0",
+ "get-tsconfig": "^4.10.0",
+ "is-bun-module": "^2.0.0",
+ "stable-hash": "^0.0.5",
+ "tinyglobby": "^0.2.13",
+ "unrs-resolver": "^1.6.2"
+ },
+ "engines": {
+ "node": "^14.18.0 || >=16.0.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/eslint-import-resolver-typescript"
+ },
+ "peerDependencies": {
+ "eslint": "*",
+ "eslint-plugin-import": "*",
+ "eslint-plugin-import-x": "*"
+ },
+ "peerDependenciesMeta": {
+ "eslint-plugin-import": {
+ "optional": true
+ },
+ "eslint-plugin-import-x": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/eslint-module-utils": {
+ "version": "2.12.1",
+ "resolved": "https://registry.npmmirror.com/eslint-module-utils/-/eslint-module-utils-2.12.1.tgz",
+ "integrity": "sha512-L8jSWTze7K2mTg0vos/RuLRS5soomksDPoJLXIslC7c8Wmut3bx7CPpJijDcBZtxQ5lrbUdM+s0OlNbz0DCDNw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "debug": "^3.2.7"
+ },
+ "engines": {
+ "node": ">=4"
+ },
+ "peerDependenciesMeta": {
+ "eslint": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/eslint-module-utils/node_modules/debug": {
+ "version": "3.2.7",
+ "resolved": "https://registry.npmmirror.com/debug/-/debug-3.2.7.tgz",
+ "integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "ms": "^2.1.1"
+ }
+ },
+ "node_modules/eslint-plugin-import": {
+ "version": "2.32.0",
+ "resolved": "https://registry.npmmirror.com/eslint-plugin-import/-/eslint-plugin-import-2.32.0.tgz",
+ "integrity": "sha512-whOE1HFo/qJDyX4SnXzP4N6zOWn79WhnCUY/iDR0mPfQZO8wcYE4JClzI2oZrhBnnMUCBCHZhO6VQyoBU95mZA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@rtsao/scc": "^1.1.0",
+ "array-includes": "^3.1.9",
+ "array.prototype.findlastindex": "^1.2.6",
+ "array.prototype.flat": "^1.3.3",
+ "array.prototype.flatmap": "^1.3.3",
+ "debug": "^3.2.7",
+ "doctrine": "^2.1.0",
+ "eslint-import-resolver-node": "^0.3.9",
+ "eslint-module-utils": "^2.12.1",
+ "hasown": "^2.0.2",
+ "is-core-module": "^2.16.1",
+ "is-glob": "^4.0.3",
+ "minimatch": "^3.1.2",
+ "object.fromentries": "^2.0.8",
+ "object.groupby": "^1.0.3",
+ "object.values": "^1.2.1",
+ "semver": "^6.3.1",
+ "string.prototype.trimend": "^1.0.9",
+ "tsconfig-paths": "^3.15.0"
+ },
+ "engines": {
+ "node": ">=4"
+ },
+ "peerDependencies": {
+ "eslint": "^2 || ^3 || ^4 || ^5 || ^6 || ^7.2.0 || ^8 || ^9"
+ }
+ },
+ "node_modules/eslint-plugin-import/node_modules/debug": {
+ "version": "3.2.7",
+ "resolved": "https://registry.npmmirror.com/debug/-/debug-3.2.7.tgz",
+ "integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "ms": "^2.1.1"
+ }
+ },
+ "node_modules/eslint-plugin-import/node_modules/doctrine": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmmirror.com/doctrine/-/doctrine-2.1.0.tgz",
+ "integrity": "sha512-35mSku4ZXK0vfCuHEDAwt55dg2jNajHZ1odvF+8SSr82EsZY4QmXfuWso8oEd8zRhVObSN18aM0CjSdoBX7zIw==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "dependencies": {
+ "esutils": "^2.0.2"
+ },
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/eslint-plugin-import/node_modules/semver": {
+ "version": "6.3.1",
+ "resolved": "https://registry.npmmirror.com/semver/-/semver-6.3.1.tgz",
+ "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==",
+ "dev": true,
+ "license": "ISC",
+ "bin": {
+ "semver": "bin/semver.js"
+ }
+ },
+ "node_modules/eslint-plugin-jsx-a11y": {
+ "version": "6.10.2",
+ "resolved": "https://registry.npmmirror.com/eslint-plugin-jsx-a11y/-/eslint-plugin-jsx-a11y-6.10.2.tgz",
+ "integrity": "sha512-scB3nz4WmG75pV8+3eRUQOHZlNSUhFNq37xnpgRkCCELU3XMvXAxLk1eqWWyE22Ki4Q01Fnsw9BA3cJHDPgn2Q==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "aria-query": "^5.3.2",
+ "array-includes": "^3.1.8",
+ "array.prototype.flatmap": "^1.3.2",
+ "ast-types-flow": "^0.0.8",
+ "axe-core": "^4.10.0",
+ "axobject-query": "^4.1.0",
+ "damerau-levenshtein": "^1.0.8",
+ "emoji-regex": "^9.2.2",
+ "hasown": "^2.0.2",
+ "jsx-ast-utils": "^3.3.5",
+ "language-tags": "^1.0.9",
+ "minimatch": "^3.1.2",
+ "object.fromentries": "^2.0.8",
+ "safe-regex-test": "^1.0.3",
+ "string.prototype.includes": "^2.0.1"
+ },
+ "engines": {
+ "node": ">=4.0"
+ },
+ "peerDependencies": {
+ "eslint": "^3 || ^4 || ^5 || ^6 || ^7 || ^8 || ^9"
+ }
+ },
+ "node_modules/eslint-plugin-react": {
+ "version": "7.37.5",
+ "resolved": "https://registry.npmmirror.com/eslint-plugin-react/-/eslint-plugin-react-7.37.5.tgz",
+ "integrity": "sha512-Qteup0SqU15kdocexFNAJMvCJEfa2xUKNV4CC1xsVMrIIqEy3SQ/rqyxCWNzfrd3/ldy6HMlD2e0JDVpDg2qIA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "array-includes": "^3.1.8",
+ "array.prototype.findlast": "^1.2.5",
+ "array.prototype.flatmap": "^1.3.3",
+ "array.prototype.tosorted": "^1.1.4",
+ "doctrine": "^2.1.0",
+ "es-iterator-helpers": "^1.2.1",
+ "estraverse": "^5.3.0",
+ "hasown": "^2.0.2",
+ "jsx-ast-utils": "^2.4.1 || ^3.0.0",
+ "minimatch": "^3.1.2",
+ "object.entries": "^1.1.9",
+ "object.fromentries": "^2.0.8",
+ "object.values": "^1.2.1",
+ "prop-types": "^15.8.1",
+ "resolve": "^2.0.0-next.5",
+ "semver": "^6.3.1",
+ "string.prototype.matchall": "^4.0.12",
+ "string.prototype.repeat": "^1.0.0"
+ },
+ "engines": {
+ "node": ">=4"
+ },
+ "peerDependencies": {
+ "eslint": "^3 || ^4 || ^5 || ^6 || ^7 || ^8 || ^9.7"
+ }
+ },
+ "node_modules/eslint-plugin-react-hooks": {
+ "version": "5.0.0-canary-7118f5dd7-20230705",
+ "resolved": "https://registry.npmmirror.com/eslint-plugin-react-hooks/-/eslint-plugin-react-hooks-5.0.0-canary-7118f5dd7-20230705.tgz",
+ "integrity": "sha512-AZYbMo/NW9chdL7vk6HQzQhT+PvTAEVqWk9ziruUoW2kAOcN5qNyelv70e0F1VNQAbvutOC9oc+xfWycI9FxDw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=10"
+ },
+ "peerDependencies": {
+ "eslint": "^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0-0"
+ }
+ },
+ "node_modules/eslint-plugin-react/node_modules/doctrine": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmmirror.com/doctrine/-/doctrine-2.1.0.tgz",
+ "integrity": "sha512-35mSku4ZXK0vfCuHEDAwt55dg2jNajHZ1odvF+8SSr82EsZY4QmXfuWso8oEd8zRhVObSN18aM0CjSdoBX7zIw==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "dependencies": {
+ "esutils": "^2.0.2"
+ },
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/eslint-plugin-react/node_modules/resolve": {
+ "version": "2.0.0-next.5",
+ "resolved": "https://registry.npmmirror.com/resolve/-/resolve-2.0.0-next.5.tgz",
+ "integrity": "sha512-U7WjGVG9sH8tvjW5SmGbQuui75FiyjAX72HX15DwBBwF9dNiQZRQAg9nnPhYy+TUnE0+VcrttuvNI8oSxZcocA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "is-core-module": "^2.13.0",
+ "path-parse": "^1.0.7",
+ "supports-preserve-symlinks-flag": "^1.0.0"
+ },
+ "bin": {
+ "resolve": "bin/resolve"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/eslint-plugin-react/node_modules/semver": {
+ "version": "6.3.1",
+ "resolved": "https://registry.npmmirror.com/semver/-/semver-6.3.1.tgz",
+ "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==",
+ "dev": true,
+ "license": "ISC",
+ "bin": {
+ "semver": "bin/semver.js"
+ }
+ },
+ "node_modules/eslint-scope": {
+ "version": "7.2.2",
+ "resolved": "https://registry.npmmirror.com/eslint-scope/-/eslint-scope-7.2.2.tgz",
+ "integrity": "sha512-dOt21O7lTMhDM+X9mB4GX+DZrZtCUJPL/wlcTqxyrx5IvO0IYtILdtrQGQp+8n5S0gwSVmOf9NQrjMOgfQZlIg==",
+ "dev": true,
+ "license": "BSD-2-Clause",
+ "dependencies": {
+ "esrecurse": "^4.3.0",
+ "estraverse": "^5.2.0"
+ },
+ "engines": {
+ "node": "^12.22.0 || ^14.17.0 || >=16.0.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/eslint"
+ }
+ },
+ "node_modules/eslint-visitor-keys": {
+ "version": "3.4.3",
+ "resolved": "https://registry.npmmirror.com/eslint-visitor-keys/-/eslint-visitor-keys-3.4.3.tgz",
+ "integrity": "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "engines": {
+ "node": "^12.22.0 || ^14.17.0 || >=16.0.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/eslint"
+ }
+ },
+ "node_modules/espree": {
+ "version": "9.6.1",
+ "resolved": "https://registry.npmmirror.com/espree/-/espree-9.6.1.tgz",
+ "integrity": "sha512-oruZaFkjorTpF32kDSI5/75ViwGeZginGGy2NoOSg3Q9bnwlnmDm4HLnkl0RE3n+njDXR037aY1+x58Z/zFdwQ==",
+ "dev": true,
+ "license": "BSD-2-Clause",
+ "dependencies": {
+ "acorn": "^8.9.0",
+ "acorn-jsx": "^5.3.2",
+ "eslint-visitor-keys": "^3.4.1"
+ },
+ "engines": {
+ "node": "^12.22.0 || ^14.17.0 || >=16.0.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/eslint"
+ }
+ },
+ "node_modules/esquery": {
+ "version": "1.6.0",
+ "resolved": "https://registry.npmmirror.com/esquery/-/esquery-1.6.0.tgz",
+ "integrity": "sha512-ca9pw9fomFcKPvFLXhBKUK90ZvGibiGOvRJNbjljY7s7uq/5YO4BOzcYtJqExdx99rF6aAcnRxHmcUHcz6sQsg==",
+ "dev": true,
+ "license": "BSD-3-Clause",
+ "dependencies": {
+ "estraverse": "^5.1.0"
+ },
+ "engines": {
+ "node": ">=0.10"
+ }
+ },
+ "node_modules/esrecurse": {
+ "version": "4.3.0",
+ "resolved": "https://registry.npmmirror.com/esrecurse/-/esrecurse-4.3.0.tgz",
+ "integrity": "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==",
+ "dev": true,
+ "license": "BSD-2-Clause",
+ "dependencies": {
+ "estraverse": "^5.2.0"
+ },
+ "engines": {
+ "node": ">=4.0"
+ }
+ },
+ "node_modules/estraverse": {
+ "version": "5.3.0",
+ "resolved": "https://registry.npmmirror.com/estraverse/-/estraverse-5.3.0.tgz",
+ "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==",
+ "dev": true,
+ "license": "BSD-2-Clause",
+ "engines": {
+ "node": ">=4.0"
+ }
+ },
+ "node_modules/estree-util-is-identifier-name": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmmirror.com/estree-util-is-identifier-name/-/estree-util-is-identifier-name-3.0.0.tgz",
+ "integrity": "sha512-hFtqIDZTIUZ9BXLb8y4pYGyk6+wekIivNVTcmvk8NoOh+VeRn5y6cEHzbURrWbfp1fIqdVipilzj+lfaadNZmg==",
+ "license": "MIT",
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/esutils": {
+ "version": "2.0.3",
+ "resolved": "https://registry.npmmirror.com/esutils/-/esutils-2.0.3.tgz",
+ "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==",
+ "dev": true,
+ "license": "BSD-2-Clause",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/extend": {
+ "version": "3.0.2",
+ "resolved": "https://registry.npmmirror.com/extend/-/extend-3.0.2.tgz",
+ "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==",
+ "license": "MIT"
+ },
+ "node_modules/fast-deep-equal": {
+ "version": "3.1.3",
+ "resolved": "https://registry.npmmirror.com/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",
+ "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/fast-glob": {
+ "version": "3.3.3",
+ "resolved": "https://registry.npmmirror.com/fast-glob/-/fast-glob-3.3.3.tgz",
+ "integrity": "sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@nodelib/fs.stat": "^2.0.2",
+ "@nodelib/fs.walk": "^1.2.3",
+ "glob-parent": "^5.1.2",
+ "merge2": "^1.3.0",
+ "micromatch": "^4.0.8"
+ },
+ "engines": {
+ "node": ">=8.6.0"
+ }
+ },
+ "node_modules/fast-glob/node_modules/glob-parent": {
+ "version": "5.1.2",
+ "resolved": "https://registry.npmmirror.com/glob-parent/-/glob-parent-5.1.2.tgz",
+ "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "is-glob": "^4.0.1"
+ },
+ "engines": {
+ "node": ">= 6"
+ }
+ },
+ "node_modules/fast-json-stable-stringify": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmmirror.com/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz",
+ "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/fast-levenshtein": {
+ "version": "2.0.6",
+ "resolved": "https://registry.npmmirror.com/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz",
+ "integrity": "sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/fastq": {
+ "version": "1.19.1",
+ "resolved": "https://registry.npmmirror.com/fastq/-/fastq-1.19.1.tgz",
+ "integrity": "sha512-GwLTyxkCXjXbxqIhTsMI2Nui8huMPtnxg7krajPJAjnEG/iiOS7i+zCtWGZR9G0NBKbXKh6X9m9UIsYX/N6vvQ==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "reusify": "^1.0.4"
+ }
+ },
+ "node_modules/fflate": {
+ "version": "0.8.2",
+ "resolved": "https://registry.npmmirror.com/fflate/-/fflate-0.8.2.tgz",
+ "integrity": "sha512-cPJU47OaAoCbg0pBvzsgpTPhmhqI5eJjh/JIu8tPj5q+T7iLvW/JAYUqmE7KOB4R1ZyEhzBaIQpQpardBF5z8A==",
+ "license": "MIT"
+ },
+ "node_modules/file-entry-cache": {
+ "version": "6.0.1",
+ "resolved": "https://registry.npmmirror.com/file-entry-cache/-/file-entry-cache-6.0.1.tgz",
+ "integrity": "sha512-7Gps/XWymbLk2QLYK4NzpMOrYjMhdIxXuIvy2QBsLE6ljuodKvdkWs/cpyJJ3CVIVpH0Oi1Hvg1ovbMzLdFBBg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "flat-cache": "^3.0.4"
+ },
+ "engines": {
+ "node": "^10.12.0 || >=12.0.0"
+ }
+ },
+ "node_modules/fill-range": {
+ "version": "7.1.1",
+ "resolved": "https://registry.npmmirror.com/fill-range/-/fill-range-7.1.1.tgz",
+ "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "to-regex-range": "^5.0.1"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/find-up": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmmirror.com/find-up/-/find-up-5.0.0.tgz",
+ "integrity": "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "locate-path": "^6.0.0",
+ "path-exists": "^4.0.0"
+ },
+ "engines": {
+ "node": ">=10"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/flat-cache": {
+ "version": "3.2.0",
+ "resolved": "https://registry.npmmirror.com/flat-cache/-/flat-cache-3.2.0.tgz",
+ "integrity": "sha512-CYcENa+FtcUKLmhhqyctpclsq7QF38pKjZHsGNiSQF5r4FtoKDWabFDl3hzaEQMvT1LHEysw5twgLvpYYb4vbw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "flatted": "^3.2.9",
+ "keyv": "^4.5.3",
+ "rimraf": "^3.0.2"
+ },
+ "engines": {
+ "node": "^10.12.0 || >=12.0.0"
+ }
+ },
+ "node_modules/flatted": {
+ "version": "3.3.3",
+ "resolved": "https://registry.npmmirror.com/flatted/-/flatted-3.3.3.tgz",
+ "integrity": "sha512-GX+ysw4PBCz0PzosHDepZGANEuFCMLrnRTiEy9McGjmkCQYwRq4A/X786G/fjM/+OjsWSU1ZrY5qyARZmO/uwg==",
+ "dev": true,
+ "license": "ISC"
+ },
+ "node_modules/for-each": {
+ "version": "0.3.5",
+ "resolved": "https://registry.npmmirror.com/for-each/-/for-each-0.3.5.tgz",
+ "integrity": "sha512-dKx12eRCVIzqCxFGplyFKJMPvLEWgmNtUrpTiJIR5u97zEhRG8ySrtboPHZXx7daLxQVrl643cTzbab2tkQjxg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "is-callable": "^1.2.7"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/fraction.js": {
+ "version": "5.3.4",
+ "resolved": "https://registry.npmmirror.com/fraction.js/-/fraction.js-5.3.4.tgz",
+ "integrity": "sha512-1X1NTtiJphryn/uLQz3whtY6jK3fTqoE3ohKs0tT+Ujr1W59oopxmoEh7Lu5p6vBaPbgoM0bzveAW4Qi5RyWDQ==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": "*"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/rawify"
+ }
+ },
+ "node_modules/framer-motion": {
+ "version": "10.18.0",
+ "resolved": "https://registry.npmmirror.com/framer-motion/-/framer-motion-10.18.0.tgz",
+ "integrity": "sha512-oGlDh1Q1XqYPksuTD/usb0I70hq95OUzmL9+6Zd+Hs4XV0oaISBa/UUMSjYiq6m8EUF32132mOJ8xVZS+I0S6w==",
+ "license": "MIT",
+ "dependencies": {
+ "tslib": "^2.4.0"
+ },
+ "optionalDependencies": {
+ "@emotion/is-prop-valid": "^0.8.2"
+ },
+ "peerDependencies": {
+ "react": "^18.0.0",
+ "react-dom": "^18.0.0"
+ },
+ "peerDependenciesMeta": {
+ "react": {
+ "optional": true
+ },
+ "react-dom": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/fs.realpath": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmmirror.com/fs.realpath/-/fs.realpath-1.0.0.tgz",
+ "integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==",
+ "dev": true,
+ "license": "ISC"
+ },
+ "node_modules/fsevents": {
+ "version": "2.3.3",
+ "resolved": "https://registry.npmmirror.com/fsevents/-/fsevents-2.3.3.tgz",
+ "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",
+ "dev": true,
+ "hasInstallScript": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": "^8.16.0 || ^10.6.0 || >=11.0.0"
+ }
+ },
+ "node_modules/function-bind": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmmirror.com/function-bind/-/function-bind-1.1.2.tgz",
+ "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==",
+ "dev": true,
+ "license": "MIT",
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/function.prototype.name": {
+ "version": "1.1.8",
+ "resolved": "https://registry.npmmirror.com/function.prototype.name/-/function.prototype.name-1.1.8.tgz",
+ "integrity": "sha512-e5iwyodOHhbMr/yNrc7fDYG4qlbIvI5gajyzPnb5TCwyhjApznQh1BMFou9b30SevY43gCJKXycoCBjMbsuW0Q==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bind": "^1.0.8",
+ "call-bound": "^1.0.3",
+ "define-properties": "^1.2.1",
+ "functions-have-names": "^1.2.3",
+ "hasown": "^2.0.2",
+ "is-callable": "^1.2.7"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/functions-have-names": {
+ "version": "1.2.3",
+ "resolved": "https://registry.npmmirror.com/functions-have-names/-/functions-have-names-1.2.3.tgz",
+ "integrity": "sha512-xckBUXyTIqT97tq2x2AMb+g163b5JFysYk0x4qxNFwbfQkmNZoiRHb6sPzI9/QV33WeuvVYBUIiD4NzNIyqaRQ==",
+ "dev": true,
+ "license": "MIT",
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/generator-function": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmmirror.com/generator-function/-/generator-function-2.0.1.tgz",
+ "integrity": "sha512-SFdFmIJi+ybC0vjlHN0ZGVGHc3lgE0DxPAT0djjVg+kjOnSqclqmj0KQ7ykTOLP6YxoqOvuAODGdcHJn+43q3g==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/get-intrinsic": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmmirror.com/get-intrinsic/-/get-intrinsic-1.3.0.tgz",
+ "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bind-apply-helpers": "^1.0.2",
+ "es-define-property": "^1.0.1",
+ "es-errors": "^1.3.0",
+ "es-object-atoms": "^1.1.1",
+ "function-bind": "^1.1.2",
+ "get-proto": "^1.0.1",
+ "gopd": "^1.2.0",
+ "has-symbols": "^1.1.0",
+ "hasown": "^2.0.2",
+ "math-intrinsics": "^1.1.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/get-proto": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmmirror.com/get-proto/-/get-proto-1.0.1.tgz",
+ "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "dunder-proto": "^1.0.1",
+ "es-object-atoms": "^1.0.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/get-symbol-description": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmmirror.com/get-symbol-description/-/get-symbol-description-1.1.0.tgz",
+ "integrity": "sha512-w9UMqWwJxHNOvoNzSJ2oPF5wvYcvP7jUvYzhp67yEhTi17ZDBBC1z9pTdGuzjD+EFIqLSYRweZjqfiPzQ06Ebg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bound": "^1.0.3",
+ "es-errors": "^1.3.0",
+ "get-intrinsic": "^1.2.6"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/get-tsconfig": {
+ "version": "4.13.0",
+ "resolved": "https://registry.npmmirror.com/get-tsconfig/-/get-tsconfig-4.13.0.tgz",
+ "integrity": "sha512-1VKTZJCwBrvbd+Wn3AOgQP/2Av+TfTCOlE4AcRJE72W1ksZXbAx8PPBR9RzgTeSPzlPMHrbANMH3LbltH73wxQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "resolve-pkg-maps": "^1.0.0"
+ },
+ "funding": {
+ "url": "https://github.com/privatenumber/get-tsconfig?sponsor=1"
+ }
+ },
+ "node_modules/glob": {
+ "version": "7.1.7",
+ "resolved": "https://registry.npmmirror.com/glob/-/glob-7.1.7.tgz",
+ "integrity": "sha512-OvD9ENzPLbegENnYP5UUfJIirTg4+XwMWGaQfQTY0JenxNvvIKP3U3/tAQSPIu/lHxXYSZmpXlUHeqAIdKzBLQ==",
+ "deprecated": "Glob versions prior to v9 are no longer supported",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "fs.realpath": "^1.0.0",
+ "inflight": "^1.0.4",
+ "inherits": "2",
+ "minimatch": "^3.0.4",
+ "once": "^1.3.0",
+ "path-is-absolute": "^1.0.0"
+ },
+ "engines": {
+ "node": "*"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/isaacs"
+ }
+ },
+ "node_modules/glob-parent": {
+ "version": "6.0.2",
+ "resolved": "https://registry.npmmirror.com/glob-parent/-/glob-parent-6.0.2.tgz",
+ "integrity": "sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "is-glob": "^4.0.3"
+ },
+ "engines": {
+ "node": ">=10.13.0"
+ }
+ },
+ "node_modules/glob-to-regexp": {
+ "version": "0.4.1",
+ "resolved": "https://registry.npmmirror.com/glob-to-regexp/-/glob-to-regexp-0.4.1.tgz",
+ "integrity": "sha512-lkX1HJXwyMcprw/5YUZc2s7DrpAiHB21/V+E1rHUrVNokkvB6bqMzT0VfV6/86ZNabt1k14YOIaT7nDvOX3Iiw==",
+ "license": "BSD-2-Clause"
+ },
+ "node_modules/globals": {
+ "version": "13.24.0",
+ "resolved": "https://registry.npmmirror.com/globals/-/globals-13.24.0.tgz",
+ "integrity": "sha512-AhO5QUcj8llrbG09iWhPU2B204J1xnPeL8kQmVorSsy+Sjj1sk8gIyh6cUocGmH4L0UuhAJy+hJMRA4mgA4mFQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "type-fest": "^0.20.2"
+ },
+ "engines": {
+ "node": ">=8"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/globalthis": {
+ "version": "1.0.4",
+ "resolved": "https://registry.npmmirror.com/globalthis/-/globalthis-1.0.4.tgz",
+ "integrity": "sha512-DpLKbNU4WylpxJykQujfCcwYWiV/Jhm50Goo0wrVILAv5jOr9d+H+UR3PhSCD2rCCEIg0uc+G+muBTwD54JhDQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "define-properties": "^1.2.1",
+ "gopd": "^1.0.1"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/globby": {
+ "version": "11.1.0",
+ "resolved": "https://registry.npmmirror.com/globby/-/globby-11.1.0.tgz",
+ "integrity": "sha512-jhIXaOzy1sb8IyocaruWSn1TjmnBVs8Ayhcy83rmxNJ8q2uWKCAj3CnJY+KpGSXCueAPc0i05kVvVKtP1t9S3g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "array-union": "^2.1.0",
+ "dir-glob": "^3.0.1",
+ "fast-glob": "^3.2.9",
+ "ignore": "^5.2.0",
+ "merge2": "^1.4.1",
+ "slash": "^3.0.0"
+ },
+ "engines": {
+ "node": ">=10"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/gopd": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmmirror.com/gopd/-/gopd-1.2.0.tgz",
+ "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/graceful-fs": {
+ "version": "4.2.11",
+ "resolved": "https://registry.npmmirror.com/graceful-fs/-/graceful-fs-4.2.11.tgz",
+ "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==",
+ "license": "ISC"
+ },
+ "node_modules/graphemer": {
+ "version": "1.4.0",
+ "resolved": "https://registry.npmmirror.com/graphemer/-/graphemer-1.4.0.tgz",
+ "integrity": "sha512-EtKwoO6kxCL9WO5xipiHTZlSzBm7WLT627TqC/uVRd0HKmq8NXyebnNYxDoBi7wt8eTWrUrKXCOVaFq9x1kgag==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/hachure-fill": {
+ "version": "0.5.2",
+ "resolved": "https://registry.npmjs.org/hachure-fill/-/hachure-fill-0.5.2.tgz",
+ "integrity": "sha512-3GKBOn+m2LX9iq+JC1064cSFprJY4jL1jCXTcpnfER5HYE2l/4EfWSGzkPa/ZDBmYI0ZOEj5VHV/eKnPGkHuOg==",
+ "license": "MIT"
+ },
+ "node_modules/has-bigints": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmmirror.com/has-bigints/-/has-bigints-1.1.0.tgz",
+ "integrity": "sha512-R3pbpkcIqv2Pm3dUwgjclDRVmWpTJW2DcMzcIhEXEx1oh/CEMObMm3KLmRJOdvhM7o4uQBnwr8pzRK2sJWIqfg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/has-flag": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmmirror.com/has-flag/-/has-flag-4.0.0.tgz",
+ "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/has-property-descriptors": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmmirror.com/has-property-descriptors/-/has-property-descriptors-1.0.2.tgz",
+ "integrity": "sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "es-define-property": "^1.0.0"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/has-proto": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmmirror.com/has-proto/-/has-proto-1.2.0.tgz",
+ "integrity": "sha512-KIL7eQPfHQRC8+XluaIw7BHUwwqL19bQn4hzNgdr+1wXoU0KKj6rufu47lhY7KbJR2C6T6+PfyN0Ea7wkSS+qQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "dunder-proto": "^1.0.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/has-symbols": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmmirror.com/has-symbols/-/has-symbols-1.1.0.tgz",
+ "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/has-tostringtag": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmmirror.com/has-tostringtag/-/has-tostringtag-1.0.2.tgz",
+ "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "has-symbols": "^1.0.3"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/hasown": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmmirror.com/hasown/-/hasown-2.0.2.tgz",
+ "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "function-bind": "^1.1.2"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/hast-util-from-dom": {
+ "version": "5.0.1",
+ "resolved": "https://registry.npmmirror.com/hast-util-from-dom/-/hast-util-from-dom-5.0.1.tgz",
+ "integrity": "sha512-N+LqofjR2zuzTjCPzyDUdSshy4Ma6li7p/c3pA78uTwzFgENbgbUrm2ugwsOdcjI1muO+o6Dgzp9p8WHtn/39Q==",
+ "license": "ISC",
+ "dependencies": {
+ "@types/hast": "^3.0.0",
+ "hastscript": "^9.0.0",
+ "web-namespaces": "^2.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/hast-util-from-html": {
+ "version": "2.0.3",
+ "resolved": "https://registry.npmmirror.com/hast-util-from-html/-/hast-util-from-html-2.0.3.tgz",
+ "integrity": "sha512-CUSRHXyKjzHov8yKsQjGOElXy/3EKpyX56ELnkHH34vDVw1N1XSQ1ZcAvTyAPtGqLTuKP/uxM+aLkSPqF/EtMw==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/hast": "^3.0.0",
+ "devlop": "^1.1.0",
+ "hast-util-from-parse5": "^8.0.0",
+ "parse5": "^7.0.0",
+ "vfile": "^6.0.0",
+ "vfile-message": "^4.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/hast-util-from-html-isomorphic": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmmirror.com/hast-util-from-html-isomorphic/-/hast-util-from-html-isomorphic-2.0.0.tgz",
+ "integrity": "sha512-zJfpXq44yff2hmE0XmwEOzdWin5xwH+QIhMLOScpX91e/NSGPsAzNCvLQDIEPyO2TXi+lBmU6hjLIhV8MwP2kw==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/hast": "^3.0.0",
+ "hast-util-from-dom": "^5.0.0",
+ "hast-util-from-html": "^2.0.0",
+ "unist-util-remove-position": "^5.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/hast-util-from-parse5": {
+ "version": "8.0.3",
+ "resolved": "https://registry.npmmirror.com/hast-util-from-parse5/-/hast-util-from-parse5-8.0.3.tgz",
+ "integrity": "sha512-3kxEVkEKt0zvcZ3hCRYI8rqrgwtlIOFMWkbclACvjlDw8Li9S2hk/d51OI0nr/gIpdMHNepwgOKqZ/sy0Clpyg==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/hast": "^3.0.0",
+ "@types/unist": "^3.0.0",
+ "devlop": "^1.0.0",
+ "hastscript": "^9.0.0",
+ "property-information": "^7.0.0",
+ "vfile": "^6.0.0",
+ "vfile-location": "^5.0.0",
+ "web-namespaces": "^2.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/hast-util-is-element": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmmirror.com/hast-util-is-element/-/hast-util-is-element-3.0.0.tgz",
+ "integrity": "sha512-Val9mnv2IWpLbNPqc/pUem+a7Ipj2aHacCwgNfTiK0vJKl0LF+4Ba4+v1oPHFpf3bLYmreq0/l3Gud9S5OH42g==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/hast": "^3.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/hast-util-parse-selector": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmmirror.com/hast-util-parse-selector/-/hast-util-parse-selector-4.0.0.tgz",
+ "integrity": "sha512-wkQCkSYoOGCRKERFWcxMVMOcYE2K1AaNLU8DXS9arxnLOUEWbOXKXiJUNzEpqZ3JOKpnha3jkFrumEjVliDe7A==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/hast": "^3.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/hast-util-raw": {
+ "version": "9.1.0",
+ "resolved": "https://registry.npmmirror.com/hast-util-raw/-/hast-util-raw-9.1.0.tgz",
+ "integrity": "sha512-Y8/SBAHkZGoNkpzqqfCldijcuUKh7/su31kEBp67cFY09Wy0mTRgtsLYsiIxMJxlu0f6AA5SUTbDR8K0rxnbUw==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/hast": "^3.0.0",
+ "@types/unist": "^3.0.0",
+ "@ungap/structured-clone": "^1.0.0",
+ "hast-util-from-parse5": "^8.0.0",
+ "hast-util-to-parse5": "^8.0.0",
+ "html-void-elements": "^3.0.0",
+ "mdast-util-to-hast": "^13.0.0",
+ "parse5": "^7.0.0",
+ "unist-util-position": "^5.0.0",
+ "unist-util-visit": "^5.0.0",
+ "vfile": "^6.0.0",
+ "web-namespaces": "^2.0.0",
+ "zwitch": "^2.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/hast-util-to-jsx-runtime": {
+ "version": "2.3.6",
+ "resolved": "https://registry.npmmirror.com/hast-util-to-jsx-runtime/-/hast-util-to-jsx-runtime-2.3.6.tgz",
+ "integrity": "sha512-zl6s8LwNyo1P9uw+XJGvZtdFF1GdAkOg8ujOw+4Pyb76874fLps4ueHXDhXWdk6YHQ6OgUtinliG7RsYvCbbBg==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/estree": "^1.0.0",
+ "@types/hast": "^3.0.0",
+ "@types/unist": "^3.0.0",
+ "comma-separated-tokens": "^2.0.0",
+ "devlop": "^1.0.0",
+ "estree-util-is-identifier-name": "^3.0.0",
+ "hast-util-whitespace": "^3.0.0",
+ "mdast-util-mdx-expression": "^2.0.0",
+ "mdast-util-mdx-jsx": "^3.0.0",
+ "mdast-util-mdxjs-esm": "^2.0.0",
+ "property-information": "^7.0.0",
+ "space-separated-tokens": "^2.0.0",
+ "style-to-js": "^1.0.0",
+ "unist-util-position": "^5.0.0",
+ "vfile-message": "^4.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/hast-util-to-parse5": {
+ "version": "8.0.0",
+ "resolved": "https://registry.npmmirror.com/hast-util-to-parse5/-/hast-util-to-parse5-8.0.0.tgz",
+ "integrity": "sha512-3KKrV5ZVI8if87DVSi1vDeByYrkGzg4mEfeu4alwgmmIeARiBLKCZS2uw5Gb6nU9x9Yufyj3iudm6i7nl52PFw==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/hast": "^3.0.0",
+ "comma-separated-tokens": "^2.0.0",
+ "devlop": "^1.0.0",
+ "property-information": "^6.0.0",
+ "space-separated-tokens": "^2.0.0",
+ "web-namespaces": "^2.0.0",
+ "zwitch": "^2.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/hast-util-to-parse5/node_modules/property-information": {
+ "version": "6.5.0",
+ "resolved": "https://registry.npmmirror.com/property-information/-/property-information-6.5.0.tgz",
+ "integrity": "sha512-PgTgs/BlvHxOu8QuEN7wi5A0OmXaBcHpmCSTehcs6Uuu9IkDIEo13Hy7n898RHfrQ49vKCoGeWZSaAK01nwVig==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
+ "node_modules/hast-util-to-text": {
+ "version": "4.0.2",
+ "resolved": "https://registry.npmmirror.com/hast-util-to-text/-/hast-util-to-text-4.0.2.tgz",
+ "integrity": "sha512-KK6y/BN8lbaq654j7JgBydev7wuNMcID54lkRav1P0CaE1e47P72AWWPiGKXTJU271ooYzcvTAn/Zt0REnvc7A==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/hast": "^3.0.0",
+ "@types/unist": "^3.0.0",
+ "hast-util-is-element": "^3.0.0",
+ "unist-util-find-after": "^5.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/hast-util-whitespace": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmmirror.com/hast-util-whitespace/-/hast-util-whitespace-3.0.0.tgz",
+ "integrity": "sha512-88JUN06ipLwsnv+dVn+OIYOvAuvBMy/Qoi6O7mQHxdPXpjy+Cd6xRkWwux7DKO+4sYILtLBRIKgsdpS2gQc7qw==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/hast": "^3.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/hastscript": {
+ "version": "9.0.1",
+ "resolved": "https://registry.npmmirror.com/hastscript/-/hastscript-9.0.1.tgz",
+ "integrity": "sha512-g7df9rMFX/SPi34tyGCyUBREQoKkapwdY/T04Qn9TDWfHhAYt4/I0gMVirzK5wEzeUqIjEB+LXC/ypb7Aqno5w==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/hast": "^3.0.0",
+ "comma-separated-tokens": "^2.0.0",
+ "hast-util-parse-selector": "^4.0.0",
+ "property-information": "^7.0.0",
+ "space-separated-tokens": "^2.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/html-url-attributes": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmmirror.com/html-url-attributes/-/html-url-attributes-3.0.1.tgz",
+ "integrity": "sha512-ol6UPyBWqsrO6EJySPz2O7ZSr856WDrEzM5zMqp+FJJLGMW35cLYmmZnl0vztAZxRUoNZJFTCohfjuIJ8I4QBQ==",
+ "license": "MIT",
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/html-void-elements": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmmirror.com/html-void-elements/-/html-void-elements-3.0.0.tgz",
+ "integrity": "sha512-bEqo66MRXsUGxWHV5IP0PUiAWwoEjba4VCzg0LjFJBpchPaTfyfCKTG6bc5F8ucKec3q5y6qOdGyYTSBEvhCrg==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
+ "node_modules/html2canvas": {
+ "version": "1.4.1",
+ "resolved": "https://registry.npmmirror.com/html2canvas/-/html2canvas-1.4.1.tgz",
+ "integrity": "sha512-fPU6BHNpsyIhr8yyMpTLLxAbkaK8ArIBcmZIRiBLiDhjeqvXolaEmDGmELFuX9I4xDcaKKcJl+TKZLqruBbmWA==",
+ "license": "MIT",
+ "dependencies": {
+ "css-line-break": "^2.1.0",
+ "text-segmentation": "^1.0.3"
+ },
+ "engines": {
+ "node": ">=8.0.0"
+ }
+ },
+ "node_modules/iconv-lite": {
+ "version": "0.6.3",
+ "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz",
+ "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==",
+ "license": "MIT",
+ "dependencies": {
+ "safer-buffer": ">= 2.1.2 < 3.0.0"
+ },
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/ignore": {
+ "version": "5.3.2",
+ "resolved": "https://registry.npmmirror.com/ignore/-/ignore-5.3.2.tgz",
+ "integrity": "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 4"
+ }
+ },
+ "node_modules/import-fresh": {
+ "version": "3.3.1",
+ "resolved": "https://registry.npmmirror.com/import-fresh/-/import-fresh-3.3.1.tgz",
+ "integrity": "sha512-TR3KfrTZTYLPB6jUjfx6MF9WcWrHL9su5TObK4ZkYgBdWKPOFoSoQIdEuTuR82pmtxH2spWG9h6etwfr1pLBqQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "parent-module": "^1.0.0",
+ "resolve-from": "^4.0.0"
+ },
+ "engines": {
+ "node": ">=6"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/imurmurhash": {
+ "version": "0.1.4",
+ "resolved": "https://registry.npmmirror.com/imurmurhash/-/imurmurhash-0.1.4.tgz",
+ "integrity": "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.8.19"
+ }
+ },
+ "node_modules/inflight": {
+ "version": "1.0.6",
+ "resolved": "https://registry.npmmirror.com/inflight/-/inflight-1.0.6.tgz",
+ "integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==",
+ "deprecated": "This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "once": "^1.3.0",
+ "wrappy": "1"
+ }
+ },
+ "node_modules/inherits": {
+ "version": "2.0.4",
+ "resolved": "https://registry.npmmirror.com/inherits/-/inherits-2.0.4.tgz",
+ "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",
+ "dev": true,
+ "license": "ISC"
+ },
+ "node_modules/inline-style-parser": {
+ "version": "0.2.7",
+ "resolved": "https://registry.npmmirror.com/inline-style-parser/-/inline-style-parser-0.2.7.tgz",
+ "integrity": "sha512-Nb2ctOyNR8DqQoR0OwRG95uNWIC0C1lCgf5Naz5H6Ji72KZ8OcFZLz2P5sNgwlyoJ8Yif11oMuYs5pBQa86csA==",
+ "license": "MIT"
+ },
+ "node_modules/internal-slot": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmmirror.com/internal-slot/-/internal-slot-1.1.0.tgz",
+ "integrity": "sha512-4gd7VpWNQNB4UKKCFFVcp1AVv+FMOgs9NKzjHKusc8jTMhd5eL1NqQqOpE0KzMds804/yHlglp3uxgluOqAPLw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "es-errors": "^1.3.0",
+ "hasown": "^2.0.2",
+ "side-channel": "^1.1.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/internmap": {
+ "version": "2.0.3",
+ "resolved": "https://registry.npmjs.org/internmap/-/internmap-2.0.3.tgz",
+ "integrity": "sha512-5Hh7Y1wQbvY5ooGgPbDaL5iYLAPzMTUrjMulskHLH6wnv/A+1q5rgEaiuqEjB+oxGXIVZs1FF+R/KPN3ZSQYYg==",
+ "license": "ISC",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/is-alphabetical": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmmirror.com/is-alphabetical/-/is-alphabetical-2.0.1.tgz",
+ "integrity": "sha512-FWyyY60MeTNyeSRpkM2Iry0G9hpr7/9kD40mD/cGQEuilcZYS4okz8SN2Q6rLCJ8gbCt6fN+rC+6tMGS99LaxQ==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
+ "node_modules/is-alphanumerical": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmmirror.com/is-alphanumerical/-/is-alphanumerical-2.0.1.tgz",
+ "integrity": "sha512-hmbYhX/9MUMF5uh7tOXyK/n0ZvWpad5caBA17GsC6vyuCqaWliRG5K1qS9inmUhEMaOBIW7/whAnSwveW/LtZw==",
+ "license": "MIT",
+ "dependencies": {
+ "is-alphabetical": "^2.0.0",
+ "is-decimal": "^2.0.0"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
+ "node_modules/is-array-buffer": {
+ "version": "3.0.5",
+ "resolved": "https://registry.npmmirror.com/is-array-buffer/-/is-array-buffer-3.0.5.tgz",
+ "integrity": "sha512-DDfANUiiG2wC1qawP66qlTugJeL5HyzMpfr8lLK+jMQirGzNod0B12cFB/9q838Ru27sBwfw78/rdoU7RERz6A==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bind": "^1.0.8",
+ "call-bound": "^1.0.3",
+ "get-intrinsic": "^1.2.6"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/is-async-function": {
+ "version": "2.1.1",
+ "resolved": "https://registry.npmmirror.com/is-async-function/-/is-async-function-2.1.1.tgz",
+ "integrity": "sha512-9dgM/cZBnNvjzaMYHVoxxfPj2QXt22Ev7SuuPrs+xav0ukGB0S6d4ydZdEiM48kLx5kDV+QBPrpVnFyefL8kkQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "async-function": "^1.0.0",
+ "call-bound": "^1.0.3",
+ "get-proto": "^1.0.1",
+ "has-tostringtag": "^1.0.2",
+ "safe-regex-test": "^1.1.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/is-bigint": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmmirror.com/is-bigint/-/is-bigint-1.1.0.tgz",
+ "integrity": "sha512-n4ZT37wG78iz03xPRKJrHTdZbe3IicyucEtdRsV5yglwc3GyUfbAfpSeD0FJ41NbUNSt5wbhqfp1fS+BgnvDFQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "has-bigints": "^1.0.2"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/is-binary-path": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmmirror.com/is-binary-path/-/is-binary-path-2.1.0.tgz",
+ "integrity": "sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "binary-extensions": "^2.0.0"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/is-boolean-object": {
+ "version": "1.2.2",
+ "resolved": "https://registry.npmmirror.com/is-boolean-object/-/is-boolean-object-1.2.2.tgz",
+ "integrity": "sha512-wa56o2/ElJMYqjCjGkXri7it5FbebW5usLw/nPmCMs5DeZ7eziSYZhSmPRn0txqeW4LnAmQQU7FgqLpsEFKM4A==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bound": "^1.0.3",
+ "has-tostringtag": "^1.0.2"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/is-bun-module": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmmirror.com/is-bun-module/-/is-bun-module-2.0.0.tgz",
+ "integrity": "sha512-gNCGbnnnnFAUGKeZ9PdbyeGYJqewpmc2aKHUEMO5nQPWU9lOmv7jcmQIv+qHD8fXW6W7qfuCwX4rY9LNRjXrkQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "semver": "^7.7.1"
+ }
+ },
+ "node_modules/is-callable": {
+ "version": "1.2.7",
+ "resolved": "https://registry.npmmirror.com/is-callable/-/is-callable-1.2.7.tgz",
+ "integrity": "sha512-1BC0BVFhS/p0qtw6enp8e+8OD0UrK0oFLztSjNzhcKA3WDuJxxAPXzPuPtKkjEY9UUoEWlX/8fgKeu2S8i9JTA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/is-core-module": {
+ "version": "2.16.1",
+ "resolved": "https://registry.npmmirror.com/is-core-module/-/is-core-module-2.16.1.tgz",
+ "integrity": "sha512-UfoeMA6fIJ8wTYFEUjelnaGI67v6+N7qXJEvQuIGa99l4xsCruSYOVSQ0uPANn4dAzm8lkYPaKLrrijLq7x23w==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "hasown": "^2.0.2"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/is-data-view": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmmirror.com/is-data-view/-/is-data-view-1.0.2.tgz",
+ "integrity": "sha512-RKtWF8pGmS87i2D6gqQu/l7EYRlVdfzemCJN/P3UOs//x1QE7mfhvzHIApBTRf7axvT6DMGwSwBXYCT0nfB9xw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bound": "^1.0.2",
+ "get-intrinsic": "^1.2.6",
+ "is-typed-array": "^1.1.13"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/is-date-object": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmmirror.com/is-date-object/-/is-date-object-1.1.0.tgz",
+ "integrity": "sha512-PwwhEakHVKTdRNVOw+/Gyh0+MzlCl4R6qKvkhuvLtPMggI1WAHt9sOwZxQLSGpUaDnrdyDsomoRgNnCfKNSXXg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bound": "^1.0.2",
+ "has-tostringtag": "^1.0.2"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/is-decimal": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmmirror.com/is-decimal/-/is-decimal-2.0.1.tgz",
+ "integrity": "sha512-AAB9hiomQs5DXWcRB1rqsxGUstbRroFOPPVAomNk/3XHR5JyEZChOyTWe2oayKnsSsr/kcGqF+z6yuH6HHpN0A==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
+ "node_modules/is-extglob": {
+ "version": "2.1.1",
+ "resolved": "https://registry.npmmirror.com/is-extglob/-/is-extglob-2.1.1.tgz",
+ "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/is-finalizationregistry": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmmirror.com/is-finalizationregistry/-/is-finalizationregistry-1.1.1.tgz",
+ "integrity": "sha512-1pC6N8qWJbWoPtEjgcL2xyhQOP491EQjeUo3qTKcmV8YSDDJrOepfG8pcC7h/QgnQHYSv0mJ3Z/ZWxmatVrysg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bound": "^1.0.3"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/is-generator-function": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmmirror.com/is-generator-function/-/is-generator-function-1.1.2.tgz",
+ "integrity": "sha512-upqt1SkGkODW9tsGNG5mtXTXtECizwtS2kA161M+gJPc1xdb/Ax629af6YrTwcOeQHbewrPNlE5Dx7kzvXTizA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bound": "^1.0.4",
+ "generator-function": "^2.0.0",
+ "get-proto": "^1.0.1",
+ "has-tostringtag": "^1.0.2",
+ "safe-regex-test": "^1.1.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/is-glob": {
+ "version": "4.0.3",
+ "resolved": "https://registry.npmmirror.com/is-glob/-/is-glob-4.0.3.tgz",
+ "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "is-extglob": "^2.1.1"
+ },
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/is-hexadecimal": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmmirror.com/is-hexadecimal/-/is-hexadecimal-2.0.1.tgz",
+ "integrity": "sha512-DgZQp241c8oO6cA1SbTEWiXeoxV42vlcJxgH+B3hi1AiqqKruZR3ZGF8In3fj4+/y/7rHvlOZLZtgJ/4ttYGZg==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
+ "node_modules/is-map": {
+ "version": "2.0.3",
+ "resolved": "https://registry.npmmirror.com/is-map/-/is-map-2.0.3.tgz",
+ "integrity": "sha512-1Qed0/Hr2m+YqxnM09CjA2d/i6YZNfF6R2oRAOj36eUdS6qIV/huPJNSEpKbupewFs+ZsJlxsjjPbc0/afW6Lw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/is-negative-zero": {
+ "version": "2.0.3",
+ "resolved": "https://registry.npmmirror.com/is-negative-zero/-/is-negative-zero-2.0.3.tgz",
+ "integrity": "sha512-5KoIu2Ngpyek75jXodFvnafB6DJgr3u8uuK0LEZJjrU19DrMD3EVERaR8sjz8CCGgpZvxPl9SuE1GMVPFHx1mw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/is-number": {
+ "version": "7.0.0",
+ "resolved": "https://registry.npmmirror.com/is-number/-/is-number-7.0.0.tgz",
+ "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.12.0"
+ }
+ },
+ "node_modules/is-number-object": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmmirror.com/is-number-object/-/is-number-object-1.1.1.tgz",
+ "integrity": "sha512-lZhclumE1G6VYD8VHe35wFaIif+CTy5SJIi5+3y4psDgWu4wPDoBhF8NxUOinEc7pHgiTsT6MaBb92rKhhD+Xw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bound": "^1.0.3",
+ "has-tostringtag": "^1.0.2"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/is-path-inside": {
+ "version": "3.0.3",
+ "resolved": "https://registry.npmmirror.com/is-path-inside/-/is-path-inside-3.0.3.tgz",
+ "integrity": "sha512-Fd4gABb+ycGAmKou8eMftCupSir5lRxqf4aD/vd0cD2qc4HL07OjCeuHMr8Ro4CoMaeCKDB0/ECBOVWjTwUvPQ==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/is-plain-obj": {
+ "version": "4.1.0",
+ "resolved": "https://registry.npmmirror.com/is-plain-obj/-/is-plain-obj-4.1.0.tgz",
+ "integrity": "sha512-+Pgi+vMuUNkJyExiMBt5IlFoMyKnr5zhJ4Uspz58WOhBF5QoIZkFyNHIbBAtHwzVAgk5RtndVNsDRN61/mmDqg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=12"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/is-regex": {
+ "version": "1.2.1",
+ "resolved": "https://registry.npmmirror.com/is-regex/-/is-regex-1.2.1.tgz",
+ "integrity": "sha512-MjYsKHO5O7mCsmRGxWcLWheFqN9DJ/2TmngvjKXihe6efViPqc274+Fx/4fYj/r03+ESvBdTXK0V6tA3rgez1g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bound": "^1.0.2",
+ "gopd": "^1.2.0",
+ "has-tostringtag": "^1.0.2",
+ "hasown": "^2.0.2"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/is-set": {
+ "version": "2.0.3",
+ "resolved": "https://registry.npmmirror.com/is-set/-/is-set-2.0.3.tgz",
+ "integrity": "sha512-iPAjerrse27/ygGLxw+EBR9agv9Y6uLeYVJMu+QNCoouJ1/1ri0mGrcWpfCqFZuzzx3WjtwxG098X+n4OuRkPg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/is-shared-array-buffer": {
+ "version": "1.0.4",
+ "resolved": "https://registry.npmmirror.com/is-shared-array-buffer/-/is-shared-array-buffer-1.0.4.tgz",
+ "integrity": "sha512-ISWac8drv4ZGfwKl5slpHG9OwPNty4jOWPRIhBpxOoD+hqITiwuipOQ2bNthAzwA3B4fIjO4Nln74N0S9byq8A==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bound": "^1.0.3"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/is-string": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmmirror.com/is-string/-/is-string-1.1.1.tgz",
+ "integrity": "sha512-BtEeSsoaQjlSPBemMQIrY1MY0uM6vnS1g5fmufYOtnxLGUZM2178PKbhsk7Ffv58IX+ZtcvoGwccYsh0PglkAA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bound": "^1.0.3",
+ "has-tostringtag": "^1.0.2"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/is-symbol": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmmirror.com/is-symbol/-/is-symbol-1.1.1.tgz",
+ "integrity": "sha512-9gGx6GTtCQM73BgmHQXfDmLtfjjTUDSyoxTCbp5WtoixAhfgsDirWIcVQ/IHpvI5Vgd5i/J5F7B9cN/WlVbC/w==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bound": "^1.0.2",
+ "has-symbols": "^1.1.0",
+ "safe-regex-test": "^1.1.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/is-typed-array": {
+ "version": "1.1.15",
+ "resolved": "https://registry.npmmirror.com/is-typed-array/-/is-typed-array-1.1.15.tgz",
+ "integrity": "sha512-p3EcsicXjit7SaskXHs1hA91QxgTw46Fv6EFKKGS5DRFLD8yKnohjF3hxoju94b/OcMZoQukzpPpBE9uLVKzgQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "which-typed-array": "^1.1.16"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/is-weakmap": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmmirror.com/is-weakmap/-/is-weakmap-2.0.2.tgz",
+ "integrity": "sha512-K5pXYOm9wqY1RgjpL3YTkF39tni1XajUIkawTLUo9EZEVUFga5gSQJF8nNS7ZwJQ02y+1YCNYcMh+HIf1ZqE+w==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/is-weakref": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmmirror.com/is-weakref/-/is-weakref-1.1.1.tgz",
+ "integrity": "sha512-6i9mGWSlqzNMEqpCp93KwRS1uUOodk2OJ6b+sq7ZPDSy2WuI5NFIxp/254TytR8ftefexkWn5xNiHUNpPOfSew==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bound": "^1.0.3"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/is-weakset": {
+ "version": "2.0.4",
+ "resolved": "https://registry.npmmirror.com/is-weakset/-/is-weakset-2.0.4.tgz",
+ "integrity": "sha512-mfcwb6IzQyOKTs84CQMrOwW4gQcaTOAWJ0zzJCl2WSPDrWk/OzDaImWFH3djXhb24g4eudZfLRozAvPGw4d9hQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bound": "^1.0.3",
+ "get-intrinsic": "^1.2.6"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/isarray": {
+ "version": "2.0.5",
+ "resolved": "https://registry.npmmirror.com/isarray/-/isarray-2.0.5.tgz",
+ "integrity": "sha512-xHjhDr3cNBK0BzdUJSPXZntQUx/mwMS5Rw4A7lPJ90XGAO6ISP/ePDNuo0vhqOZU+UD5JoodwCAAoZQd3FeAKw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/isexe": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmmirror.com/isexe/-/isexe-2.0.0.tgz",
+ "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==",
+ "dev": true,
+ "license": "ISC"
+ },
+ "node_modules/iterator.prototype": {
+ "version": "1.1.5",
+ "resolved": "https://registry.npmmirror.com/iterator.prototype/-/iterator.prototype-1.1.5.tgz",
+ "integrity": "sha512-H0dkQoCa3b2VEeKQBOxFph+JAbcrQdE7KC0UkqwpLmv2EC4P41QXP+rqo9wYodACiG5/WM5s9oDApTU8utwj9g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "define-data-property": "^1.1.4",
+ "es-object-atoms": "^1.0.0",
+ "get-intrinsic": "^1.2.6",
+ "get-proto": "^1.0.0",
+ "has-symbols": "^1.1.0",
+ "set-function-name": "^2.0.2"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/jiti": {
+ "version": "1.21.7",
+ "resolved": "https://registry.npmmirror.com/jiti/-/jiti-1.21.7.tgz",
+ "integrity": "sha512-/imKNG4EbWNrVjoNC/1H5/9GFy+tqjGBHCaSsN+P2RnPqjsLmv6UD3Ej+Kj8nBWaRAwyk7kK5ZUc+OEatnTR3A==",
+ "dev": true,
+ "license": "MIT",
+ "bin": {
+ "jiti": "bin/jiti.js"
+ }
+ },
+ "node_modules/js-tokens": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmmirror.com/js-tokens/-/js-tokens-4.0.0.tgz",
+ "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==",
+ "license": "MIT"
+ },
+ "node_modules/js-yaml": {
+ "version": "4.1.1",
+ "resolved": "https://registry.npmmirror.com/js-yaml/-/js-yaml-4.1.1.tgz",
+ "integrity": "sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "argparse": "^2.0.1"
+ },
+ "bin": {
+ "js-yaml": "bin/js-yaml.js"
+ }
+ },
+ "node_modules/json-buffer": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmmirror.com/json-buffer/-/json-buffer-3.0.1.tgz",
+ "integrity": "sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/json-schema-traverse": {
+ "version": "0.4.1",
+ "resolved": "https://registry.npmmirror.com/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz",
+ "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/json-stable-stringify-without-jsonify": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmmirror.com/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz",
+ "integrity": "sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/json5": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmmirror.com/json5/-/json5-1.0.2.tgz",
+ "integrity": "sha512-g1MWMLBiz8FKi1e4w0UyVL3w+iJceWAFBAaBnnGKOpNa5f8TLktkbre1+s6oICydWAm+HRUGTmI+//xv2hvXYA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "minimist": "^1.2.0"
+ },
+ "bin": {
+ "json5": "lib/cli.js"
+ }
+ },
+ "node_modules/jspdf": {
+ "version": "2.5.2",
+ "resolved": "https://registry.npmmirror.com/jspdf/-/jspdf-2.5.2.tgz",
+ "integrity": "sha512-myeX9c+p7znDWPk0eTrujCzNjT+CXdXyk7YmJq5nD5V7uLLKmSXnlQ/Jn/kuo3X09Op70Apm0rQSnFWyGK8uEQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@babel/runtime": "^7.23.2",
+ "atob": "^2.1.2",
+ "btoa": "^1.2.1",
+ "fflate": "^0.8.1"
+ },
+ "optionalDependencies": {
+ "canvg": "^3.0.6",
+ "core-js": "^3.6.0",
+ "dompurify": "^2.5.4",
+ "html2canvas": "^1.0.0-rc.5"
+ }
+ },
+ "node_modules/jsx-ast-utils": {
+ "version": "3.3.5",
+ "resolved": "https://registry.npmmirror.com/jsx-ast-utils/-/jsx-ast-utils-3.3.5.tgz",
+ "integrity": "sha512-ZZow9HBI5O6EPgSJLUb8n2NKgmVWTwCvHGwFuJlMjvLFqlGG6pjirPhtdsseaLZjSibD8eegzmYpUZwoIlj2cQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "array-includes": "^3.1.6",
+ "array.prototype.flat": "^1.3.1",
+ "object.assign": "^4.1.4",
+ "object.values": "^1.1.6"
+ },
+ "engines": {
+ "node": ">=4.0"
+ }
+ },
+ "node_modules/katex": {
+ "version": "0.16.25",
+ "resolved": "https://registry.npmmirror.com/katex/-/katex-0.16.25.tgz",
+ "integrity": "sha512-woHRUZ/iF23GBP1dkDQMh1QBad9dmr8/PAwNA54VrSOVYgI12MAcE14TqnDdQOdzyEonGzMepYnqBMYdsoAr8Q==",
+ "funding": [
+ "https://opencollective.com/katex",
+ "https://github.com/sponsors/katex"
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "commander": "^8.3.0"
+ },
+ "bin": {
+ "katex": "cli.js"
+ }
+ },
+ "node_modules/keyv": {
+ "version": "4.5.4",
+ "resolved": "https://registry.npmmirror.com/keyv/-/keyv-4.5.4.tgz",
+ "integrity": "sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "json-buffer": "3.0.1"
+ }
+ },
+ "node_modules/khroma": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/khroma/-/khroma-2.1.0.tgz",
+ "integrity": "sha512-Ls993zuzfayK269Svk9hzpeGUKob/sIgZzyHYdjQoAdQetRKpOLj+k/QQQ/6Qi0Yz65mlROrfd+Ev+1+7dz9Kw=="
+ },
+ "node_modules/langium": {
+ "version": "3.3.1",
+ "resolved": "https://registry.npmjs.org/langium/-/langium-3.3.1.tgz",
+ "integrity": "sha512-QJv/h939gDpvT+9SiLVlY7tZC3xB2qK57v0J04Sh9wpMb6MP1q8gB21L3WIo8T5P1MSMg3Ep14L7KkDCFG3y4w==",
+ "license": "MIT",
+ "dependencies": {
+ "chevrotain": "~11.0.3",
+ "chevrotain-allstar": "~0.3.0",
+ "vscode-languageserver": "~9.0.1",
+ "vscode-languageserver-textdocument": "~1.0.11",
+ "vscode-uri": "~3.0.8"
+ },
+ "engines": {
+ "node": ">=16.0.0"
+ }
+ },
+ "node_modules/language-subtag-registry": {
+ "version": "0.3.23",
+ "resolved": "https://registry.npmmirror.com/language-subtag-registry/-/language-subtag-registry-0.3.23.tgz",
+ "integrity": "sha512-0K65Lea881pHotoGEa5gDlMxt3pctLi2RplBb7Ezh4rRdLEOtgi7n4EwK9lamnUCkKBqaeKRVebTq6BAxSkpXQ==",
+ "dev": true,
+ "license": "CC0-1.0"
+ },
+ "node_modules/language-tags": {
+ "version": "1.0.9",
+ "resolved": "https://registry.npmmirror.com/language-tags/-/language-tags-1.0.9.tgz",
+ "integrity": "sha512-MbjN408fEndfiQXbFQ1vnd+1NoLDsnQW41410oQBXiyXDMYH5z505juWa4KUE1LqxRC7DgOgZDbKLxHIwm27hA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "language-subtag-registry": "^0.3.20"
+ },
+ "engines": {
+ "node": ">=0.10"
+ }
+ },
+ "node_modules/layout-base": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/layout-base/-/layout-base-1.0.2.tgz",
+ "integrity": "sha512-8h2oVEZNktL4BH2JCOI90iD1yXwL6iNW7KcCKT2QZgQJR2vbqDsldCTPRU9NifTCqHZci57XvQQ15YTu+sTYPg==",
+ "license": "MIT"
+ },
+ "node_modules/levn": {
+ "version": "0.4.1",
+ "resolved": "https://registry.npmmirror.com/levn/-/levn-0.4.1.tgz",
+ "integrity": "sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "prelude-ls": "^1.2.1",
+ "type-check": "~0.4.0"
+ },
+ "engines": {
+ "node": ">= 0.8.0"
+ }
+ },
+ "node_modules/lilconfig": {
+ "version": "3.1.3",
+ "resolved": "https://registry.npmmirror.com/lilconfig/-/lilconfig-3.1.3.tgz",
+ "integrity": "sha512-/vlFKAoH5Cgt3Ie+JLhRbwOsCQePABiU3tJ1egGvyQ+33R/vcwM2Zl2QR/LzjsBeItPt3oSVXapn+m4nQDvpzw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=14"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/antonk52"
+ }
+ },
+ "node_modules/lines-and-columns": {
+ "version": "1.2.4",
+ "resolved": "https://registry.npmmirror.com/lines-and-columns/-/lines-and-columns-1.2.4.tgz",
+ "integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/locate-path": {
+ "version": "6.0.0",
+ "resolved": "https://registry.npmmirror.com/locate-path/-/locate-path-6.0.0.tgz",
+ "integrity": "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "p-locate": "^5.0.0"
+ },
+ "engines": {
+ "node": ">=10"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/lodash-es": {
+ "version": "4.17.21",
+ "resolved": "https://registry.npmjs.org/lodash-es/-/lodash-es-4.17.21.tgz",
+ "integrity": "sha512-mKnC+QJ9pWVzv+C4/U3rRsHapFfHvQFoFB92e52xeyGMcX6/OlIl78je1u8vePzYZSkkogMPJ2yjxxsb89cxyw==",
+ "license": "MIT"
+ },
+ "node_modules/lodash.merge": {
+ "version": "4.6.2",
+ "resolved": "https://registry.npmmirror.com/lodash.merge/-/lodash.merge-4.6.2.tgz",
+ "integrity": "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/longest-streak": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmmirror.com/longest-streak/-/longest-streak-3.1.0.tgz",
+ "integrity": "sha512-9Ri+o0JYgehTaVBBDoMqIl8GXtbWg711O3srftcHhZ0dqnETqLaoIK0x17fUw9rFSlK/0NlsKe0Ahhyl5pXE2g==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
+ "node_modules/loose-envify": {
+ "version": "1.4.0",
+ "resolved": "https://registry.npmmirror.com/loose-envify/-/loose-envify-1.4.0.tgz",
+ "integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==",
+ "license": "MIT",
+ "dependencies": {
+ "js-tokens": "^3.0.0 || ^4.0.0"
+ },
+ "bin": {
+ "loose-envify": "cli.js"
+ }
+ },
+ "node_modules/lucide-react": {
+ "version": "0.294.0",
+ "resolved": "https://registry.npmmirror.com/lucide-react/-/lucide-react-0.294.0.tgz",
+ "integrity": "sha512-V7o0/VECSGbLHn3/1O67FUgBwWB+hmzshrgDVRJQhMh8uj5D3HBuIvhuAmQTtlupILSplwIZg5FTc4tTKMA2SA==",
+ "license": "ISC",
+ "peerDependencies": {
+ "react": "^16.5.1 || ^17.0.0 || ^18.0.0"
+ }
+ },
+ "node_modules/markdown-table": {
+ "version": "3.0.4",
+ "resolved": "https://registry.npmmirror.com/markdown-table/-/markdown-table-3.0.4.tgz",
+ "integrity": "sha512-wiYz4+JrLyb/DqW2hkFJxP7Vd7JuTDm77fvbM8VfEQdmSMqcImWeeRbHwZjBjIFki/VaMK2BhFi7oUUZeM5bqw==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
+ "node_modules/marked": {
+ "version": "16.4.2",
+ "resolved": "https://registry.npmjs.org/marked/-/marked-16.4.2.tgz",
+ "integrity": "sha512-TI3V8YYWvkVf3KJe1dRkpnjs68JUPyEa5vjKrp1XEEJUAOaQc+Qj+L1qWbPd0SJuAdQkFU0h73sXXqwDYxsiDA==",
+ "license": "MIT",
+ "bin": {
+ "marked": "bin/marked.js"
+ },
+ "engines": {
+ "node": ">= 20"
+ }
+ },
+ "node_modules/math-intrinsics": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmmirror.com/math-intrinsics/-/math-intrinsics-1.1.0.tgz",
+ "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/mdast-util-find-and-replace": {
+ "version": "3.0.2",
+ "resolved": "https://registry.npmmirror.com/mdast-util-find-and-replace/-/mdast-util-find-and-replace-3.0.2.tgz",
+ "integrity": "sha512-Tmd1Vg/m3Xz43afeNxDIhWRtFZgM2VLyaf4vSTYwudTyeuTneoL3qtWMA5jeLyz/O1vDJmmV4QuScFCA2tBPwg==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/mdast": "^4.0.0",
+ "escape-string-regexp": "^5.0.0",
+ "unist-util-is": "^6.0.0",
+ "unist-util-visit-parents": "^6.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/mdast-util-find-and-replace/node_modules/escape-string-regexp": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmmirror.com/escape-string-regexp/-/escape-string-regexp-5.0.0.tgz",
+ "integrity": "sha512-/veY75JbMK4j1yjvuUxuVsiS/hr/4iHs9FTT6cgTexxdE0Ly/glccBAkloH/DofkjRbZU3bnoj38mOmhkZ0lHw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=12"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/mdast-util-from-markdown": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmmirror.com/mdast-util-from-markdown/-/mdast-util-from-markdown-2.0.2.tgz",
+ "integrity": "sha512-uZhTV/8NBuw0WHkPTrCqDOl0zVe1BIng5ZtHoDk49ME1qqcjYmmLmOf0gELgcRMxN4w2iuIeVso5/6QymSrgmA==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/mdast": "^4.0.0",
+ "@types/unist": "^3.0.0",
+ "decode-named-character-reference": "^1.0.0",
+ "devlop": "^1.0.0",
+ "mdast-util-to-string": "^4.0.0",
+ "micromark": "^4.0.0",
+ "micromark-util-decode-numeric-character-reference": "^2.0.0",
+ "micromark-util-decode-string": "^2.0.0",
+ "micromark-util-normalize-identifier": "^2.0.0",
+ "micromark-util-symbol": "^2.0.0",
+ "micromark-util-types": "^2.0.0",
+ "unist-util-stringify-position": "^4.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/mdast-util-gfm": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmmirror.com/mdast-util-gfm/-/mdast-util-gfm-3.1.0.tgz",
+ "integrity": "sha512-0ulfdQOM3ysHhCJ1p06l0b0VKlhU0wuQs3thxZQagjcjPrlFRqY215uZGHHJan9GEAXd9MbfPjFJz+qMkVR6zQ==",
+ "license": "MIT",
+ "dependencies": {
+ "mdast-util-from-markdown": "^2.0.0",
+ "mdast-util-gfm-autolink-literal": "^2.0.0",
+ "mdast-util-gfm-footnote": "^2.0.0",
+ "mdast-util-gfm-strikethrough": "^2.0.0",
+ "mdast-util-gfm-table": "^2.0.0",
+ "mdast-util-gfm-task-list-item": "^2.0.0",
+ "mdast-util-to-markdown": "^2.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/mdast-util-gfm-autolink-literal": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmmirror.com/mdast-util-gfm-autolink-literal/-/mdast-util-gfm-autolink-literal-2.0.1.tgz",
+ "integrity": "sha512-5HVP2MKaP6L+G6YaxPNjuL0BPrq9orG3TsrZ9YXbA3vDw/ACI4MEsnoDpn6ZNm7GnZgtAcONJyPhOP8tNJQavQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/mdast": "^4.0.0",
+ "ccount": "^2.0.0",
+ "devlop": "^1.0.0",
+ "mdast-util-find-and-replace": "^3.0.0",
+ "micromark-util-character": "^2.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/mdast-util-gfm-footnote": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmmirror.com/mdast-util-gfm-footnote/-/mdast-util-gfm-footnote-2.1.0.tgz",
+ "integrity": "sha512-sqpDWlsHn7Ac9GNZQMeUzPQSMzR6Wv0WKRNvQRg0KqHh02fpTz69Qc1QSseNX29bhz1ROIyNyxExfawVKTm1GQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/mdast": "^4.0.0",
+ "devlop": "^1.1.0",
+ "mdast-util-from-markdown": "^2.0.0",
+ "mdast-util-to-markdown": "^2.0.0",
+ "micromark-util-normalize-identifier": "^2.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/mdast-util-gfm-strikethrough": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmmirror.com/mdast-util-gfm-strikethrough/-/mdast-util-gfm-strikethrough-2.0.0.tgz",
+ "integrity": "sha512-mKKb915TF+OC5ptj5bJ7WFRPdYtuHv0yTRxK2tJvi+BDqbkiG7h7u/9SI89nRAYcmap2xHQL9D+QG/6wSrTtXg==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/mdast": "^4.0.0",
+ "mdast-util-from-markdown": "^2.0.0",
+ "mdast-util-to-markdown": "^2.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/mdast-util-gfm-table": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmmirror.com/mdast-util-gfm-table/-/mdast-util-gfm-table-2.0.0.tgz",
+ "integrity": "sha512-78UEvebzz/rJIxLvE7ZtDd/vIQ0RHv+3Mh5DR96p7cS7HsBhYIICDBCu8csTNWNO6tBWfqXPWekRuj2FNOGOZg==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/mdast": "^4.0.0",
+ "devlop": "^1.0.0",
+ "markdown-table": "^3.0.0",
+ "mdast-util-from-markdown": "^2.0.0",
+ "mdast-util-to-markdown": "^2.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/mdast-util-gfm-task-list-item": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmmirror.com/mdast-util-gfm-task-list-item/-/mdast-util-gfm-task-list-item-2.0.0.tgz",
+ "integrity": "sha512-IrtvNvjxC1o06taBAVJznEnkiHxLFTzgonUdy8hzFVeDun0uTjxxrRGVaNFqkU1wJR3RBPEfsxmU6jDWPofrTQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/mdast": "^4.0.0",
+ "devlop": "^1.0.0",
+ "mdast-util-from-markdown": "^2.0.0",
+ "mdast-util-to-markdown": "^2.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/mdast-util-math": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmmirror.com/mdast-util-math/-/mdast-util-math-3.0.0.tgz",
+ "integrity": "sha512-Tl9GBNeG/AhJnQM221bJR2HPvLOSnLE/T9cJI9tlc6zwQk2nPk/4f0cHkOdEixQPC/j8UtKDdITswvLAy1OZ1w==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/hast": "^3.0.0",
+ "@types/mdast": "^4.0.0",
+ "devlop": "^1.0.0",
+ "longest-streak": "^3.0.0",
+ "mdast-util-from-markdown": "^2.0.0",
+ "mdast-util-to-markdown": "^2.1.0",
+ "unist-util-remove-position": "^5.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/mdast-util-mdx-expression": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmmirror.com/mdast-util-mdx-expression/-/mdast-util-mdx-expression-2.0.1.tgz",
+ "integrity": "sha512-J6f+9hUp+ldTZqKRSg7Vw5V6MqjATc+3E4gf3CFNcuZNWD8XdyI6zQ8GqH7f8169MM6P7hMBRDVGnn7oHB9kXQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/estree-jsx": "^1.0.0",
+ "@types/hast": "^3.0.0",
+ "@types/mdast": "^4.0.0",
+ "devlop": "^1.0.0",
+ "mdast-util-from-markdown": "^2.0.0",
+ "mdast-util-to-markdown": "^2.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/mdast-util-mdx-jsx": {
+ "version": "3.2.0",
+ "resolved": "https://registry.npmmirror.com/mdast-util-mdx-jsx/-/mdast-util-mdx-jsx-3.2.0.tgz",
+ "integrity": "sha512-lj/z8v0r6ZtsN/cGNNtemmmfoLAFZnjMbNyLzBafjzikOM+glrjNHPlf6lQDOTccj9n5b0PPihEBbhneMyGs1Q==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/estree-jsx": "^1.0.0",
+ "@types/hast": "^3.0.0",
+ "@types/mdast": "^4.0.0",
+ "@types/unist": "^3.0.0",
+ "ccount": "^2.0.0",
+ "devlop": "^1.1.0",
+ "mdast-util-from-markdown": "^2.0.0",
+ "mdast-util-to-markdown": "^2.0.0",
+ "parse-entities": "^4.0.0",
+ "stringify-entities": "^4.0.0",
+ "unist-util-stringify-position": "^4.0.0",
+ "vfile-message": "^4.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/mdast-util-mdxjs-esm": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmmirror.com/mdast-util-mdxjs-esm/-/mdast-util-mdxjs-esm-2.0.1.tgz",
+ "integrity": "sha512-EcmOpxsZ96CvlP03NghtH1EsLtr0n9Tm4lPUJUBccV9RwUOneqSycg19n5HGzCf+10LozMRSObtVr3ee1WoHtg==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/estree-jsx": "^1.0.0",
+ "@types/hast": "^3.0.0",
+ "@types/mdast": "^4.0.0",
+ "devlop": "^1.0.0",
+ "mdast-util-from-markdown": "^2.0.0",
+ "mdast-util-to-markdown": "^2.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/mdast-util-phrasing": {
+ "version": "4.1.0",
+ "resolved": "https://registry.npmmirror.com/mdast-util-phrasing/-/mdast-util-phrasing-4.1.0.tgz",
+ "integrity": "sha512-TqICwyvJJpBwvGAMZjj4J2n0X8QWp21b9l0o7eXyVJ25YNWYbJDVIyD1bZXE6WtV6RmKJVYmQAKWa0zWOABz2w==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/mdast": "^4.0.0",
+ "unist-util-is": "^6.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/mdast-util-to-hast": {
+ "version": "13.2.0",
+ "resolved": "https://registry.npmmirror.com/mdast-util-to-hast/-/mdast-util-to-hast-13.2.0.tgz",
+ "integrity": "sha512-QGYKEuUsYT9ykKBCMOEDLsU5JRObWQusAolFMeko/tYPufNkRffBAQjIE+99jbA87xv6FgmjLtwjh9wBWajwAA==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/hast": "^3.0.0",
+ "@types/mdast": "^4.0.0",
+ "@ungap/structured-clone": "^1.0.0",
+ "devlop": "^1.0.0",
+ "micromark-util-sanitize-uri": "^2.0.0",
+ "trim-lines": "^3.0.0",
+ "unist-util-position": "^5.0.0",
+ "unist-util-visit": "^5.0.0",
+ "vfile": "^6.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/mdast-util-to-markdown": {
+ "version": "2.1.2",
+ "resolved": "https://registry.npmmirror.com/mdast-util-to-markdown/-/mdast-util-to-markdown-2.1.2.tgz",
+ "integrity": "sha512-xj68wMTvGXVOKonmog6LwyJKrYXZPvlwabaryTjLh9LuvovB/KAH+kvi8Gjj+7rJjsFi23nkUxRQv1KqSroMqA==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/mdast": "^4.0.0",
+ "@types/unist": "^3.0.0",
+ "longest-streak": "^3.0.0",
+ "mdast-util-phrasing": "^4.0.0",
+ "mdast-util-to-string": "^4.0.0",
+ "micromark-util-classify-character": "^2.0.0",
+ "micromark-util-decode-string": "^2.0.0",
+ "unist-util-visit": "^5.0.0",
+ "zwitch": "^2.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/mdast-util-to-string": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmmirror.com/mdast-util-to-string/-/mdast-util-to-string-4.0.0.tgz",
+ "integrity": "sha512-0H44vDimn51F0YwvxSJSm0eCDOJTRlmN0R1yBh4HLj9wiV1Dn0QoXGbvFAWj2hSItVTlCmBF1hqKlIyUBVFLPg==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/mdast": "^4.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/merge2": {
+ "version": "1.4.1",
+ "resolved": "https://registry.npmmirror.com/merge2/-/merge2-1.4.1.tgz",
+ "integrity": "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 8"
+ }
+ },
+ "node_modules/mermaid": {
+ "version": "11.12.2",
+ "resolved": "https://registry.npmjs.org/mermaid/-/mermaid-11.12.2.tgz",
+ "integrity": "sha512-n34QPDPEKmaeCG4WDMGy0OT6PSyxKCfy2pJgShP+Qow2KLrvWjclwbc3yXfSIf4BanqWEhQEpngWwNp/XhZt6w==",
+ "license": "MIT",
+ "dependencies": {
+ "@braintree/sanitize-url": "^7.1.1",
+ "@iconify/utils": "^3.0.1",
+ "@mermaid-js/parser": "^0.6.3",
+ "@types/d3": "^7.4.3",
+ "cytoscape": "^3.29.3",
+ "cytoscape-cose-bilkent": "^4.1.0",
+ "cytoscape-fcose": "^2.2.0",
+ "d3": "^7.9.0",
+ "d3-sankey": "^0.12.3",
+ "dagre-d3-es": "7.0.13",
+ "dayjs": "^1.11.18",
+ "dompurify": "^3.2.5",
+ "katex": "^0.16.22",
+ "khroma": "^2.1.0",
+ "lodash-es": "^4.17.21",
+ "marked": "^16.2.1",
+ "roughjs": "^4.6.6",
+ "stylis": "^4.3.6",
+ "ts-dedent": "^2.2.0",
+ "uuid": "^11.1.0"
+ }
+ },
+ "node_modules/mermaid/node_modules/dompurify": {
+ "version": "3.3.1",
+ "resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.3.1.tgz",
+ "integrity": "sha512-qkdCKzLNtrgPFP1Vo+98FRzJnBRGe4ffyCea9IwHB1fyxPOeNTHpLKYGd4Uk9xvNoH0ZoOjwZxNptyMwqrId1Q==",
+ "license": "(MPL-2.0 OR Apache-2.0)",
+ "optionalDependencies": {
+ "@types/trusted-types": "^2.0.7"
+ }
+ },
+ "node_modules/micromark": {
+ "version": "4.0.2",
+ "resolved": "https://registry.npmmirror.com/micromark/-/micromark-4.0.2.tgz",
+ "integrity": "sha512-zpe98Q6kvavpCr1NPVSCMebCKfD7CA2NqZ+rykeNhONIJBpc1tFKt9hucLGwha3jNTNI8lHpctWJWoimVF4PfA==",
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "@types/debug": "^4.0.0",
+ "debug": "^4.0.0",
+ "decode-named-character-reference": "^1.0.0",
+ "devlop": "^1.0.0",
+ "micromark-core-commonmark": "^2.0.0",
+ "micromark-factory-space": "^2.0.0",
+ "micromark-util-character": "^2.0.0",
+ "micromark-util-chunked": "^2.0.0",
+ "micromark-util-combine-extensions": "^2.0.0",
+ "micromark-util-decode-numeric-character-reference": "^2.0.0",
+ "micromark-util-encode": "^2.0.0",
+ "micromark-util-normalize-identifier": "^2.0.0",
+ "micromark-util-resolve-all": "^2.0.0",
+ "micromark-util-sanitize-uri": "^2.0.0",
+ "micromark-util-subtokenize": "^2.0.0",
+ "micromark-util-symbol": "^2.0.0",
+ "micromark-util-types": "^2.0.0"
+ }
+ },
+ "node_modules/micromark-core-commonmark": {
+ "version": "2.0.3",
+ "resolved": "https://registry.npmmirror.com/micromark-core-commonmark/-/micromark-core-commonmark-2.0.3.tgz",
+ "integrity": "sha512-RDBrHEMSxVFLg6xvnXmb1Ayr2WzLAWjeSATAoxwKYJV94TeNavgoIdA0a9ytzDSVzBy2YKFK+emCPOEibLeCrg==",
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "decode-named-character-reference": "^1.0.0",
+ "devlop": "^1.0.0",
+ "micromark-factory-destination": "^2.0.0",
+ "micromark-factory-label": "^2.0.0",
+ "micromark-factory-space": "^2.0.0",
+ "micromark-factory-title": "^2.0.0",
+ "micromark-factory-whitespace": "^2.0.0",
+ "micromark-util-character": "^2.0.0",
+ "micromark-util-chunked": "^2.0.0",
+ "micromark-util-classify-character": "^2.0.0",
+ "micromark-util-html-tag-name": "^2.0.0",
+ "micromark-util-normalize-identifier": "^2.0.0",
+ "micromark-util-resolve-all": "^2.0.0",
+ "micromark-util-subtokenize": "^2.0.0",
+ "micromark-util-symbol": "^2.0.0",
+ "micromark-util-types": "^2.0.0"
+ }
+ },
+ "node_modules/micromark-extension-gfm": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmmirror.com/micromark-extension-gfm/-/micromark-extension-gfm-3.0.0.tgz",
+ "integrity": "sha512-vsKArQsicm7t0z2GugkCKtZehqUm31oeGBV/KVSorWSy8ZlNAv7ytjFhvaryUiCUJYqs+NoE6AFhpQvBTM6Q4w==",
+ "license": "MIT",
+ "dependencies": {
+ "micromark-extension-gfm-autolink-literal": "^2.0.0",
+ "micromark-extension-gfm-footnote": "^2.0.0",
+ "micromark-extension-gfm-strikethrough": "^2.0.0",
+ "micromark-extension-gfm-table": "^2.0.0",
+ "micromark-extension-gfm-tagfilter": "^2.0.0",
+ "micromark-extension-gfm-task-list-item": "^2.0.0",
+ "micromark-util-combine-extensions": "^2.0.0",
+ "micromark-util-types": "^2.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/micromark-extension-gfm-autolink-literal": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmmirror.com/micromark-extension-gfm-autolink-literal/-/micromark-extension-gfm-autolink-literal-2.1.0.tgz",
+ "integrity": "sha512-oOg7knzhicgQ3t4QCjCWgTmfNhvQbDDnJeVu9v81r7NltNCVmhPy1fJRX27pISafdjL+SVc4d3l48Gb6pbRypw==",
+ "license": "MIT",
+ "dependencies": {
+ "micromark-util-character": "^2.0.0",
+ "micromark-util-sanitize-uri": "^2.0.0",
+ "micromark-util-symbol": "^2.0.0",
+ "micromark-util-types": "^2.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/micromark-extension-gfm-footnote": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmmirror.com/micromark-extension-gfm-footnote/-/micromark-extension-gfm-footnote-2.1.0.tgz",
+ "integrity": "sha512-/yPhxI1ntnDNsiHtzLKYnE3vf9JZ6cAisqVDauhp4CEHxlb4uoOTxOCJ+9s51bIB8U1N1FJ1RXOKTIlD5B/gqw==",
+ "license": "MIT",
+ "dependencies": {
+ "devlop": "^1.0.0",
+ "micromark-core-commonmark": "^2.0.0",
+ "micromark-factory-space": "^2.0.0",
+ "micromark-util-character": "^2.0.0",
+ "micromark-util-normalize-identifier": "^2.0.0",
+ "micromark-util-sanitize-uri": "^2.0.0",
+ "micromark-util-symbol": "^2.0.0",
+ "micromark-util-types": "^2.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/micromark-extension-gfm-strikethrough": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmmirror.com/micromark-extension-gfm-strikethrough/-/micromark-extension-gfm-strikethrough-2.1.0.tgz",
+ "integrity": "sha512-ADVjpOOkjz1hhkZLlBiYA9cR2Anf8F4HqZUO6e5eDcPQd0Txw5fxLzzxnEkSkfnD0wziSGiv7sYhk/ktvbf1uw==",
+ "license": "MIT",
+ "dependencies": {
+ "devlop": "^1.0.0",
+ "micromark-util-chunked": "^2.0.0",
+ "micromark-util-classify-character": "^2.0.0",
+ "micromark-util-resolve-all": "^2.0.0",
+ "micromark-util-symbol": "^2.0.0",
+ "micromark-util-types": "^2.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/micromark-extension-gfm-table": {
+ "version": "2.1.1",
+ "resolved": "https://registry.npmmirror.com/micromark-extension-gfm-table/-/micromark-extension-gfm-table-2.1.1.tgz",
+ "integrity": "sha512-t2OU/dXXioARrC6yWfJ4hqB7rct14e8f7m0cbI5hUmDyyIlwv5vEtooptH8INkbLzOatzKuVbQmAYcbWoyz6Dg==",
+ "license": "MIT",
+ "dependencies": {
+ "devlop": "^1.0.0",
+ "micromark-factory-space": "^2.0.0",
+ "micromark-util-character": "^2.0.0",
+ "micromark-util-symbol": "^2.0.0",
+ "micromark-util-types": "^2.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/micromark-extension-gfm-tagfilter": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmmirror.com/micromark-extension-gfm-tagfilter/-/micromark-extension-gfm-tagfilter-2.0.0.tgz",
+ "integrity": "sha512-xHlTOmuCSotIA8TW1mDIM6X2O1SiX5P9IuDtqGonFhEK0qgRI4yeC6vMxEV2dgyr2TiD+2PQ10o+cOhdVAcwfg==",
+ "license": "MIT",
+ "dependencies": {
+ "micromark-util-types": "^2.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/micromark-extension-gfm-task-list-item": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmmirror.com/micromark-extension-gfm-task-list-item/-/micromark-extension-gfm-task-list-item-2.1.0.tgz",
+ "integrity": "sha512-qIBZhqxqI6fjLDYFTBIa4eivDMnP+OZqsNwmQ3xNLE4Cxwc+zfQEfbs6tzAo2Hjq+bh6q5F+Z8/cksrLFYWQQw==",
+ "license": "MIT",
+ "dependencies": {
+ "devlop": "^1.0.0",
+ "micromark-factory-space": "^2.0.0",
+ "micromark-util-character": "^2.0.0",
+ "micromark-util-symbol": "^2.0.0",
+ "micromark-util-types": "^2.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/micromark-extension-math": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmmirror.com/micromark-extension-math/-/micromark-extension-math-3.1.0.tgz",
+ "integrity": "sha512-lvEqd+fHjATVs+2v/8kg9i5Q0AP2k85H0WUOwpIVvUML8BapsMvh1XAogmQjOCsLpoKRCVQqEkQBB3NhVBcsOg==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/katex": "^0.16.0",
+ "devlop": "^1.0.0",
+ "katex": "^0.16.0",
+ "micromark-factory-space": "^2.0.0",
+ "micromark-util-character": "^2.0.0",
+ "micromark-util-symbol": "^2.0.0",
+ "micromark-util-types": "^2.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/micromark-factory-destination": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmmirror.com/micromark-factory-destination/-/micromark-factory-destination-2.0.1.tgz",
+ "integrity": "sha512-Xe6rDdJlkmbFRExpTOmRj9N3MaWmbAgdpSrBQvCFqhezUn4AHqJHbaEnfbVYYiexVSs//tqOdY/DxhjdCiJnIA==",
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "micromark-util-character": "^2.0.0",
+ "micromark-util-symbol": "^2.0.0",
+ "micromark-util-types": "^2.0.0"
+ }
+ },
+ "node_modules/micromark-factory-label": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmmirror.com/micromark-factory-label/-/micromark-factory-label-2.0.1.tgz",
+ "integrity": "sha512-VFMekyQExqIW7xIChcXn4ok29YE3rnuyveW3wZQWWqF4Nv9Wk5rgJ99KzPvHjkmPXF93FXIbBp6YdW3t71/7Vg==",
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "devlop": "^1.0.0",
+ "micromark-util-character": "^2.0.0",
+ "micromark-util-symbol": "^2.0.0",
+ "micromark-util-types": "^2.0.0"
+ }
+ },
+ "node_modules/micromark-factory-space": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmmirror.com/micromark-factory-space/-/micromark-factory-space-2.0.1.tgz",
+ "integrity": "sha512-zRkxjtBxxLd2Sc0d+fbnEunsTj46SWXgXciZmHq0kDYGnck/ZSGj9/wULTV95uoeYiK5hRXP2mJ98Uo4cq/LQg==",
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "micromark-util-character": "^2.0.0",
+ "micromark-util-types": "^2.0.0"
+ }
+ },
+ "node_modules/micromark-factory-title": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmmirror.com/micromark-factory-title/-/micromark-factory-title-2.0.1.tgz",
+ "integrity": "sha512-5bZ+3CjhAd9eChYTHsjy6TGxpOFSKgKKJPJxr293jTbfry2KDoWkhBb6TcPVB4NmzaPhMs1Frm9AZH7OD4Cjzw==",
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "micromark-factory-space": "^2.0.0",
+ "micromark-util-character": "^2.0.0",
+ "micromark-util-symbol": "^2.0.0",
+ "micromark-util-types": "^2.0.0"
+ }
+ },
+ "node_modules/micromark-factory-whitespace": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmmirror.com/micromark-factory-whitespace/-/micromark-factory-whitespace-2.0.1.tgz",
+ "integrity": "sha512-Ob0nuZ3PKt/n0hORHyvoD9uZhr+Za8sFoP+OnMcnWK5lngSzALgQYKMr9RJVOWLqQYuyn6ulqGWSXdwf6F80lQ==",
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "micromark-factory-space": "^2.0.0",
+ "micromark-util-character": "^2.0.0",
+ "micromark-util-symbol": "^2.0.0",
+ "micromark-util-types": "^2.0.0"
+ }
+ },
+ "node_modules/micromark-util-character": {
+ "version": "2.1.1",
+ "resolved": "https://registry.npmmirror.com/micromark-util-character/-/micromark-util-character-2.1.1.tgz",
+ "integrity": "sha512-wv8tdUTJ3thSFFFJKtpYKOYiGP2+v96Hvk4Tu8KpCAsTMs6yi+nVmGh1syvSCsaxz45J6Jbw+9DD6g97+NV67Q==",
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "micromark-util-symbol": "^2.0.0",
+ "micromark-util-types": "^2.0.0"
+ }
+ },
+ "node_modules/micromark-util-chunked": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmmirror.com/micromark-util-chunked/-/micromark-util-chunked-2.0.1.tgz",
+ "integrity": "sha512-QUNFEOPELfmvv+4xiNg2sRYeS/P84pTW0TCgP5zc9FpXetHY0ab7SxKyAQCNCc1eK0459uoLI1y5oO5Vc1dbhA==",
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "micromark-util-symbol": "^2.0.0"
+ }
+ },
+ "node_modules/micromark-util-classify-character": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmmirror.com/micromark-util-classify-character/-/micromark-util-classify-character-2.0.1.tgz",
+ "integrity": "sha512-K0kHzM6afW/MbeWYWLjoHQv1sgg2Q9EccHEDzSkxiP/EaagNzCm7T/WMKZ3rjMbvIpvBiZgwR3dKMygtA4mG1Q==",
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "micromark-util-character": "^2.0.0",
+ "micromark-util-symbol": "^2.0.0",
+ "micromark-util-types": "^2.0.0"
+ }
+ },
+ "node_modules/micromark-util-combine-extensions": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmmirror.com/micromark-util-combine-extensions/-/micromark-util-combine-extensions-2.0.1.tgz",
+ "integrity": "sha512-OnAnH8Ujmy59JcyZw8JSbK9cGpdVY44NKgSM7E9Eh7DiLS2E9RNQf0dONaGDzEG9yjEl5hcqeIsj4hfRkLH/Bg==",
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "micromark-util-chunked": "^2.0.0",
+ "micromark-util-types": "^2.0.0"
+ }
+ },
+ "node_modules/micromark-util-decode-numeric-character-reference": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmmirror.com/micromark-util-decode-numeric-character-reference/-/micromark-util-decode-numeric-character-reference-2.0.2.tgz",
+ "integrity": "sha512-ccUbYk6CwVdkmCQMyr64dXz42EfHGkPQlBj5p7YVGzq8I7CtjXZJrubAYezf7Rp+bjPseiROqe7G6foFd+lEuw==",
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "micromark-util-symbol": "^2.0.0"
+ }
+ },
+ "node_modules/micromark-util-decode-string": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmmirror.com/micromark-util-decode-string/-/micromark-util-decode-string-2.0.1.tgz",
+ "integrity": "sha512-nDV/77Fj6eH1ynwscYTOsbK7rR//Uj0bZXBwJZRfaLEJ1iGBR6kIfNmlNqaqJf649EP0F3NWNdeJi03elllNUQ==",
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "decode-named-character-reference": "^1.0.0",
+ "micromark-util-character": "^2.0.0",
+ "micromark-util-decode-numeric-character-reference": "^2.0.0",
+ "micromark-util-symbol": "^2.0.0"
+ }
+ },
+ "node_modules/micromark-util-encode": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmmirror.com/micromark-util-encode/-/micromark-util-encode-2.0.1.tgz",
+ "integrity": "sha512-c3cVx2y4KqUnwopcO9b/SCdo2O67LwJJ/UyqGfbigahfegL9myoEFoDYZgkT7f36T0bLrM9hZTAaAyH+PCAXjw==",
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT"
+ },
+ "node_modules/micromark-util-html-tag-name": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmmirror.com/micromark-util-html-tag-name/-/micromark-util-html-tag-name-2.0.1.tgz",
+ "integrity": "sha512-2cNEiYDhCWKI+Gs9T0Tiysk136SnR13hhO8yW6BGNyhOC4qYFnwF1nKfD3HFAIXA5c45RrIG1ub11GiXeYd1xA==",
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT"
+ },
+ "node_modules/micromark-util-normalize-identifier": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmmirror.com/micromark-util-normalize-identifier/-/micromark-util-normalize-identifier-2.0.1.tgz",
+ "integrity": "sha512-sxPqmo70LyARJs0w2UclACPUUEqltCkJ6PhKdMIDuJ3gSf/Q+/GIe3WKl0Ijb/GyH9lOpUkRAO2wp0GVkLvS9Q==",
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "micromark-util-symbol": "^2.0.0"
+ }
+ },
+ "node_modules/micromark-util-resolve-all": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmmirror.com/micromark-util-resolve-all/-/micromark-util-resolve-all-2.0.1.tgz",
+ "integrity": "sha512-VdQyxFWFT2/FGJgwQnJYbe1jjQoNTS4RjglmSjTUlpUMa95Htx9NHeYW4rGDJzbjvCsl9eLjMQwGeElsqmzcHg==",
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "micromark-util-types": "^2.0.0"
+ }
+ },
+ "node_modules/micromark-util-sanitize-uri": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmmirror.com/micromark-util-sanitize-uri/-/micromark-util-sanitize-uri-2.0.1.tgz",
+ "integrity": "sha512-9N9IomZ/YuGGZZmQec1MbgxtlgougxTodVwDzzEouPKo3qFWvymFHWcnDi2vzV1ff6kas9ucW+o3yzJK9YB1AQ==",
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "micromark-util-character": "^2.0.0",
+ "micromark-util-encode": "^2.0.0",
+ "micromark-util-symbol": "^2.0.0"
+ }
+ },
+ "node_modules/micromark-util-subtokenize": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmmirror.com/micromark-util-subtokenize/-/micromark-util-subtokenize-2.1.0.tgz",
+ "integrity": "sha512-XQLu552iSctvnEcgXw6+Sx75GflAPNED1qx7eBJ+wydBb2KCbRZe+NwvIEEMM83uml1+2WSXpBAcp9IUCgCYWA==",
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "devlop": "^1.0.0",
+ "micromark-util-chunked": "^2.0.0",
+ "micromark-util-symbol": "^2.0.0",
+ "micromark-util-types": "^2.0.0"
+ }
+ },
+ "node_modules/micromark-util-symbol": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmmirror.com/micromark-util-symbol/-/micromark-util-symbol-2.0.1.tgz",
+ "integrity": "sha512-vs5t8Apaud9N28kgCrRUdEed4UJ+wWNvicHLPxCa9ENlYuAY31M0ETy5y1vA33YoNPDFTghEbnh6efaE8h4x0Q==",
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT"
+ },
+ "node_modules/micromark-util-types": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmmirror.com/micromark-util-types/-/micromark-util-types-2.0.2.tgz",
+ "integrity": "sha512-Yw0ECSpJoViF1qTU4DC6NwtC4aWGt1EkzaQB8KPPyCRR8z9TWeV0HbEFGTO+ZY1wB22zmxnJqhPyTpOVCpeHTA==",
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT"
+ },
+ "node_modules/micromatch": {
+ "version": "4.0.8",
+ "resolved": "https://registry.npmmirror.com/micromatch/-/micromatch-4.0.8.tgz",
+ "integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "braces": "^3.0.3",
+ "picomatch": "^2.3.1"
+ },
+ "engines": {
+ "node": ">=8.6"
+ }
+ },
+ "node_modules/minimatch": {
+ "version": "3.1.2",
+ "resolved": "https://registry.npmmirror.com/minimatch/-/minimatch-3.1.2.tgz",
+ "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "brace-expansion": "^1.1.7"
+ },
+ "engines": {
+ "node": "*"
+ }
+ },
+ "node_modules/minimist": {
+ "version": "1.2.8",
+ "resolved": "https://registry.npmmirror.com/minimist/-/minimist-1.2.8.tgz",
+ "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==",
+ "dev": true,
+ "license": "MIT",
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/mlly": {
+ "version": "1.8.0",
+ "resolved": "https://registry.npmjs.org/mlly/-/mlly-1.8.0.tgz",
+ "integrity": "sha512-l8D9ODSRWLe2KHJSifWGwBqpTZXIXTeo8mlKjY+E2HAakaTeNpqAyBZ8GSqLzHgw4XmHmC8whvpjJNMbFZN7/g==",
+ "license": "MIT",
+ "dependencies": {
+ "acorn": "^8.15.0",
+ "pathe": "^2.0.3",
+ "pkg-types": "^1.3.1",
+ "ufo": "^1.6.1"
+ }
+ },
+ "node_modules/ms": {
+ "version": "2.1.3",
+ "resolved": "https://registry.npmmirror.com/ms/-/ms-2.1.3.tgz",
+ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
+ "license": "MIT"
+ },
+ "node_modules/mz": {
+ "version": "2.7.0",
+ "resolved": "https://registry.npmmirror.com/mz/-/mz-2.7.0.tgz",
+ "integrity": "sha512-z81GNO7nnYMEhrGh9LeymoE4+Yr0Wn5McHIZMK5cfQCl+NDX08sCZgUc9/6MHni9IWuFLm1Z3HTCXu2z9fN62Q==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "any-promise": "^1.0.0",
+ "object-assign": "^4.0.1",
+ "thenify-all": "^1.0.0"
+ }
+ },
+ "node_modules/nanoid": {
+ "version": "3.3.11",
+ "resolved": "https://registry.npmmirror.com/nanoid/-/nanoid-3.3.11.tgz",
+ "integrity": "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "MIT",
+ "bin": {
+ "nanoid": "bin/nanoid.cjs"
+ },
+ "engines": {
+ "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
+ }
+ },
+ "node_modules/napi-postinstall": {
+ "version": "0.3.4",
+ "resolved": "https://registry.npmmirror.com/napi-postinstall/-/napi-postinstall-0.3.4.tgz",
+ "integrity": "sha512-PHI5f1O0EP5xJ9gQmFGMS6IZcrVvTjpXjz7Na41gTE7eE2hK11lg04CECCYEEjdc17EV4DO+fkGEtt7TpTaTiQ==",
+ "dev": true,
+ "license": "MIT",
+ "bin": {
+ "napi-postinstall": "lib/cli.js"
+ },
+ "engines": {
+ "node": "^12.20.0 || ^14.18.0 || >=16.0.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/napi-postinstall"
+ }
+ },
+ "node_modules/natural-compare": {
+ "version": "1.4.0",
+ "resolved": "https://registry.npmmirror.com/natural-compare/-/natural-compare-1.4.0.tgz",
+ "integrity": "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/next": {
+ "version": "14.0.3",
+ "resolved": "https://registry.npmmirror.com/next/-/next-14.0.3.tgz",
+ "integrity": "sha512-AbYdRNfImBr3XGtvnwOxq8ekVCwbFTv/UJoLwmaX89nk9i051AEY4/HAWzU0YpaTDw8IofUpmuIlvzWF13jxIw==",
+ "license": "MIT",
+ "dependencies": {
+ "@next/env": "14.0.3",
+ "@swc/helpers": "0.5.2",
+ "busboy": "1.6.0",
+ "caniuse-lite": "^1.0.30001406",
+ "postcss": "8.4.31",
+ "styled-jsx": "5.1.1",
+ "watchpack": "2.4.0"
+ },
+ "bin": {
+ "next": "dist/bin/next"
+ },
+ "engines": {
+ "node": ">=18.17.0"
+ },
+ "optionalDependencies": {
+ "@next/swc-darwin-arm64": "14.0.3",
+ "@next/swc-darwin-x64": "14.0.3",
+ "@next/swc-linux-arm64-gnu": "14.0.3",
+ "@next/swc-linux-arm64-musl": "14.0.3",
+ "@next/swc-linux-x64-gnu": "14.0.3",
+ "@next/swc-linux-x64-musl": "14.0.3",
+ "@next/swc-win32-arm64-msvc": "14.0.3",
+ "@next/swc-win32-ia32-msvc": "14.0.3",
+ "@next/swc-win32-x64-msvc": "14.0.3"
+ },
+ "peerDependencies": {
+ "@opentelemetry/api": "^1.1.0",
+ "react": "^18.2.0",
+ "react-dom": "^18.2.0",
+ "sass": "^1.3.0"
+ },
+ "peerDependenciesMeta": {
+ "@opentelemetry/api": {
+ "optional": true
+ },
+ "sass": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/next/node_modules/postcss": {
+ "version": "8.4.31",
+ "resolved": "https://registry.npmmirror.com/postcss/-/postcss-8.4.31.tgz",
+ "integrity": "sha512-PS08Iboia9mts/2ygV3eLpY5ghnUcfLV/EXTOW1E2qYxJKGGBUtNjN76FYHnMs36RmARn41bC0AZmn+rR0OVpQ==",
+ "funding": [
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/postcss/"
+ },
+ {
+ "type": "tidelift",
+ "url": "https://tidelift.com/funding/github/npm/postcss"
+ },
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "nanoid": "^3.3.6",
+ "picocolors": "^1.0.0",
+ "source-map-js": "^1.0.2"
+ },
+ "engines": {
+ "node": "^10 || ^12 || >=14"
+ }
+ },
+ "node_modules/node-releases": {
+ "version": "2.0.27",
+ "resolved": "https://registry.npmmirror.com/node-releases/-/node-releases-2.0.27.tgz",
+ "integrity": "sha512-nmh3lCkYZ3grZvqcCH+fjmQ7X+H0OeZgP40OierEaAptX4XofMh5kwNbWh7lBduUzCcV/8kZ+NDLCwm2iorIlA==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/normalize-path": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmmirror.com/normalize-path/-/normalize-path-3.0.0.tgz",
+ "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/normalize-range": {
+ "version": "0.1.2",
+ "resolved": "https://registry.npmmirror.com/normalize-range/-/normalize-range-0.1.2.tgz",
+ "integrity": "sha512-bdok/XvKII3nUpklnV6P2hxtMNrCboOjAcyBuQnWEhO665FwrSNRxU+AqpsyvO6LgGYPspN+lu5CLtw4jPRKNA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/object-assign": {
+ "version": "4.1.1",
+ "resolved": "https://registry.npmmirror.com/object-assign/-/object-assign-4.1.1.tgz",
+ "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/object-hash": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmmirror.com/object-hash/-/object-hash-3.0.0.tgz",
+ "integrity": "sha512-RSn9F68PjH9HqtltsSnqYC1XXoWe9Bju5+213R98cNGttag9q9yAOTzdbsqvIa7aNm5WffBZFpWYr2aWrklWAw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 6"
+ }
+ },
+ "node_modules/object-inspect": {
+ "version": "1.13.4",
+ "resolved": "https://registry.npmmirror.com/object-inspect/-/object-inspect-1.13.4.tgz",
+ "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/object-keys": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmmirror.com/object-keys/-/object-keys-1.1.1.tgz",
+ "integrity": "sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/object.assign": {
+ "version": "4.1.7",
+ "resolved": "https://registry.npmmirror.com/object.assign/-/object.assign-4.1.7.tgz",
+ "integrity": "sha512-nK28WOo+QIjBkDduTINE4JkF/UJJKyf2EJxvJKfblDpyg0Q+pkOHNTL0Qwy6NP6FhE/EnzV73BxxqcJaXY9anw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bind": "^1.0.8",
+ "call-bound": "^1.0.3",
+ "define-properties": "^1.2.1",
+ "es-object-atoms": "^1.0.0",
+ "has-symbols": "^1.1.0",
+ "object-keys": "^1.1.1"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/object.entries": {
+ "version": "1.1.9",
+ "resolved": "https://registry.npmmirror.com/object.entries/-/object.entries-1.1.9.tgz",
+ "integrity": "sha512-8u/hfXFRBD1O0hPUjioLhoWFHRmt6tKA4/vZPyckBr18l1KE9uHrFaFaUi8MDRTpi4uak2goyPTSNJLXX2k2Hw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bind": "^1.0.8",
+ "call-bound": "^1.0.4",
+ "define-properties": "^1.2.1",
+ "es-object-atoms": "^1.1.1"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/object.fromentries": {
+ "version": "2.0.8",
+ "resolved": "https://registry.npmmirror.com/object.fromentries/-/object.fromentries-2.0.8.tgz",
+ "integrity": "sha512-k6E21FzySsSK5a21KRADBd/NGneRegFO5pLHfdQLpRDETUNJueLXs3WCzyQ3tFRDYgbq3KHGXfTbi2bs8WQ6rQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bind": "^1.0.7",
+ "define-properties": "^1.2.1",
+ "es-abstract": "^1.23.2",
+ "es-object-atoms": "^1.0.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/object.groupby": {
+ "version": "1.0.3",
+ "resolved": "https://registry.npmmirror.com/object.groupby/-/object.groupby-1.0.3.tgz",
+ "integrity": "sha512-+Lhy3TQTuzXI5hevh8sBGqbmurHbbIjAi0Z4S63nthVLmLxfbj4T54a4CfZrXIrt9iP4mVAPYMo/v99taj3wjQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bind": "^1.0.7",
+ "define-properties": "^1.2.1",
+ "es-abstract": "^1.23.2"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/object.values": {
+ "version": "1.2.1",
+ "resolved": "https://registry.npmmirror.com/object.values/-/object.values-1.2.1.tgz",
+ "integrity": "sha512-gXah6aZrcUxjWg2zR2MwouP2eHlCBzdV4pygudehaKXSGW4v2AsRQUK+lwwXhii6KFZcunEnmSUoYp5CXibxtA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bind": "^1.0.8",
+ "call-bound": "^1.0.3",
+ "define-properties": "^1.2.1",
+ "es-object-atoms": "^1.0.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/once": {
+ "version": "1.4.0",
+ "resolved": "https://registry.npmmirror.com/once/-/once-1.4.0.tgz",
+ "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "wrappy": "1"
+ }
+ },
+ "node_modules/optionator": {
+ "version": "0.9.4",
+ "resolved": "https://registry.npmmirror.com/optionator/-/optionator-0.9.4.tgz",
+ "integrity": "sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "deep-is": "^0.1.3",
+ "fast-levenshtein": "^2.0.6",
+ "levn": "^0.4.1",
+ "prelude-ls": "^1.2.1",
+ "type-check": "^0.4.0",
+ "word-wrap": "^1.2.5"
+ },
+ "engines": {
+ "node": ">= 0.8.0"
+ }
+ },
+ "node_modules/own-keys": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmmirror.com/own-keys/-/own-keys-1.0.1.tgz",
+ "integrity": "sha512-qFOyK5PjiWZd+QQIh+1jhdb9LpxTF0qs7Pm8o5QHYZ0M3vKqSqzsZaEB6oWlxZ+q2sJBMI/Ktgd2N5ZwQoRHfg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "get-intrinsic": "^1.2.6",
+ "object-keys": "^1.1.1",
+ "safe-push-apply": "^1.0.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/p-limit": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmmirror.com/p-limit/-/p-limit-3.1.0.tgz",
+ "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "yocto-queue": "^0.1.0"
+ },
+ "engines": {
+ "node": ">=10"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/p-locate": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmmirror.com/p-locate/-/p-locate-5.0.0.tgz",
+ "integrity": "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "p-limit": "^3.0.2"
+ },
+ "engines": {
+ "node": ">=10"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/package-manager-detector": {
+ "version": "1.6.0",
+ "resolved": "https://registry.npmjs.org/package-manager-detector/-/package-manager-detector-1.6.0.tgz",
+ "integrity": "sha512-61A5ThoTiDG/C8s8UMZwSorAGwMJ0ERVGj2OjoW5pAalsNOg15+iQiPzrLJ4jhZ1HJzmC2PIHT2oEiH3R5fzNA==",
+ "license": "MIT"
+ },
+ "node_modules/parent-module": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmmirror.com/parent-module/-/parent-module-1.0.1.tgz",
+ "integrity": "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "callsites": "^3.0.0"
+ },
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "node_modules/parse-entities": {
+ "version": "4.0.2",
+ "resolved": "https://registry.npmmirror.com/parse-entities/-/parse-entities-4.0.2.tgz",
+ "integrity": "sha512-GG2AQYWoLgL877gQIKeRPGO1xF9+eG1ujIb5soS5gPvLQ1y2o8FL90w2QWNdf9I361Mpp7726c+lj3U0qK1uGw==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/unist": "^2.0.0",
+ "character-entities-legacy": "^3.0.0",
+ "character-reference-invalid": "^2.0.0",
+ "decode-named-character-reference": "^1.0.0",
+ "is-alphanumerical": "^2.0.0",
+ "is-decimal": "^2.0.0",
+ "is-hexadecimal": "^2.0.0"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
+ "node_modules/parse-entities/node_modules/@types/unist": {
+ "version": "2.0.11",
+ "resolved": "https://registry.npmmirror.com/@types/unist/-/unist-2.0.11.tgz",
+ "integrity": "sha512-CmBKiL6NNo/OqgmMn95Fk9Whlp2mtvIv+KNpQKN2F4SjvrEesubTRWGYSg+BnWZOnlCaSTU1sMpsBOzgbYhnsA==",
+ "license": "MIT"
+ },
+ "node_modules/parse5": {
+ "version": "7.3.0",
+ "resolved": "https://registry.npmmirror.com/parse5/-/parse5-7.3.0.tgz",
+ "integrity": "sha512-IInvU7fabl34qmi9gY8XOVxhYyMyuH2xUNpb2q8/Y+7552KlejkRvqvD19nMoUW/uQGGbqNpA6Tufu5FL5BZgw==",
+ "license": "MIT",
+ "dependencies": {
+ "entities": "^6.0.0"
+ },
+ "funding": {
+ "url": "https://github.com/inikulin/parse5?sponsor=1"
+ }
+ },
+ "node_modules/path-data-parser": {
+ "version": "0.1.0",
+ "resolved": "https://registry.npmjs.org/path-data-parser/-/path-data-parser-0.1.0.tgz",
+ "integrity": "sha512-NOnmBpt5Y2RWbuv0LMzsayp3lVylAHLPUTut412ZA3l+C4uw4ZVkQbjShYCQ8TCpUMdPapr4YjUqLYD6v68j+w==",
+ "license": "MIT"
+ },
+ "node_modules/path-exists": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmmirror.com/path-exists/-/path-exists-4.0.0.tgz",
+ "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/path-is-absolute": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmmirror.com/path-is-absolute/-/path-is-absolute-1.0.1.tgz",
+ "integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/path-key": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmmirror.com/path-key/-/path-key-3.1.1.tgz",
+ "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/path-parse": {
+ "version": "1.0.7",
+ "resolved": "https://registry.npmmirror.com/path-parse/-/path-parse-1.0.7.tgz",
+ "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/path-type": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmmirror.com/path-type/-/path-type-4.0.0.tgz",
+ "integrity": "sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/pathe": {
+ "version": "2.0.3",
+ "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz",
+ "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==",
+ "license": "MIT"
+ },
+ "node_modules/performance-now": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmmirror.com/performance-now/-/performance-now-2.1.0.tgz",
+ "integrity": "sha512-7EAHlyLHI56VEIdK57uwHdHKIaAGbnXPiw0yWbarQZOKaKpvUIgW0jWRVLiatnM+XXlSwsanIBH/hzGMJulMow==",
+ "license": "MIT",
+ "optional": true
+ },
+ "node_modules/picocolors": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmmirror.com/picocolors/-/picocolors-1.1.1.tgz",
+ "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",
+ "license": "ISC"
+ },
+ "node_modules/picomatch": {
+ "version": "2.3.1",
+ "resolved": "https://registry.npmmirror.com/picomatch/-/picomatch-2.3.1.tgz",
+ "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=8.6"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/jonschlinkert"
+ }
+ },
+ "node_modules/pify": {
+ "version": "2.3.0",
+ "resolved": "https://registry.npmmirror.com/pify/-/pify-2.3.0.tgz",
+ "integrity": "sha512-udgsAY+fTnvv7kI7aaxbqwWNb0AHiB0qBO89PZKPkoTmGOgdbrHDKD+0B2X4uTfJ/FT1R09r9gTsjUjNJotuog==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/pirates": {
+ "version": "4.0.7",
+ "resolved": "https://registry.npmmirror.com/pirates/-/pirates-4.0.7.tgz",
+ "integrity": "sha512-TfySrs/5nm8fQJDcBDuUng3VOUKsd7S+zqvbOTiGXHfxX4wK31ard+hoNuvkicM/2YFzlpDgABOevKSsB4G/FA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 6"
+ }
+ },
+ "node_modules/pkg-types": {
+ "version": "1.3.1",
+ "resolved": "https://registry.npmjs.org/pkg-types/-/pkg-types-1.3.1.tgz",
+ "integrity": "sha512-/Jm5M4RvtBFVkKWRu2BLUTNP8/M2a+UwuAX+ae4770q1qVGtfjG+WTCupoZixokjmHiry8uI+dlY8KXYV5HVVQ==",
+ "license": "MIT",
+ "dependencies": {
+ "confbox": "^0.1.8",
+ "mlly": "^1.7.4",
+ "pathe": "^2.0.1"
+ }
+ },
+ "node_modules/points-on-curve": {
+ "version": "0.2.0",
+ "resolved": "https://registry.npmjs.org/points-on-curve/-/points-on-curve-0.2.0.tgz",
+ "integrity": "sha512-0mYKnYYe9ZcqMCWhUjItv/oHjvgEsfKvnUTg8sAtnHr3GVy7rGkXCb6d5cSyqrWqL4k81b9CPg3urd+T7aop3A==",
+ "license": "MIT"
+ },
+ "node_modules/points-on-path": {
+ "version": "0.2.1",
+ "resolved": "https://registry.npmjs.org/points-on-path/-/points-on-path-0.2.1.tgz",
+ "integrity": "sha512-25ClnWWuw7JbWZcgqY/gJ4FQWadKxGWk+3kR/7kD0tCaDtPPMj7oHu2ToLaVhfpnHrZzYby2w6tUA0eOIuUg8g==",
+ "license": "MIT",
+ "dependencies": {
+ "path-data-parser": "0.1.0",
+ "points-on-curve": "0.2.0"
+ }
+ },
+ "node_modules/possible-typed-array-names": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmmirror.com/possible-typed-array-names/-/possible-typed-array-names-1.1.0.tgz",
+ "integrity": "sha512-/+5VFTchJDoVj3bhoqi6UeymcD00DAwb1nJwamzPvHEszJ4FpF6SNNbUbOS8yI56qHzdV8eK0qEfOSiodkTdxg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/postcss": {
+ "version": "8.5.6",
+ "resolved": "https://registry.npmmirror.com/postcss/-/postcss-8.5.6.tgz",
+ "integrity": "sha512-3Ybi1tAuwAP9s0r1UQ2J4n5Y0G05bJkpUIO0/bI9MhwmD70S5aTWbXGBwxHrelT+XM1k6dM0pk+SwNkpTRN7Pg==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/postcss/"
+ },
+ {
+ "type": "tidelift",
+ "url": "https://tidelift.com/funding/github/npm/postcss"
+ },
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "nanoid": "^3.3.11",
+ "picocolors": "^1.1.1",
+ "source-map-js": "^1.2.1"
+ },
+ "engines": {
+ "node": "^10 || ^12 || >=14"
+ }
+ },
+ "node_modules/postcss-import": {
+ "version": "15.1.0",
+ "resolved": "https://registry.npmmirror.com/postcss-import/-/postcss-import-15.1.0.tgz",
+ "integrity": "sha512-hpr+J05B2FVYUAXHeK1YyI267J/dDDhMU6B6civm8hSY1jYJnBXxzKDKDswzJmtLHryrjhnDjqqp/49t8FALew==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "postcss-value-parser": "^4.0.0",
+ "read-cache": "^1.0.0",
+ "resolve": "^1.1.7"
+ },
+ "engines": {
+ "node": ">=14.0.0"
+ },
+ "peerDependencies": {
+ "postcss": "^8.0.0"
+ }
+ },
+ "node_modules/postcss-js": {
+ "version": "4.1.0",
+ "resolved": "https://registry.npmmirror.com/postcss-js/-/postcss-js-4.1.0.tgz",
+ "integrity": "sha512-oIAOTqgIo7q2EOwbhb8UalYePMvYoIeRY2YKntdpFQXNosSu3vLrniGgmH9OKs/qAkfoj5oB3le/7mINW1LCfw==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/postcss/"
+ },
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "camelcase-css": "^2.0.1"
+ },
+ "engines": {
+ "node": "^12 || ^14 || >= 16"
+ },
+ "peerDependencies": {
+ "postcss": "^8.4.21"
+ }
+ },
+ "node_modules/postcss-load-config": {
+ "version": "6.0.1",
+ "resolved": "https://registry.npmmirror.com/postcss-load-config/-/postcss-load-config-6.0.1.tgz",
+ "integrity": "sha512-oPtTM4oerL+UXmx+93ytZVN82RrlY/wPUV8IeDxFrzIjXOLF1pN+EmKPLbubvKHT2HC20xXsCAH2Z+CKV6Oz/g==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/postcss/"
+ },
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "lilconfig": "^3.1.1"
+ },
+ "engines": {
+ "node": ">= 18"
+ },
+ "peerDependencies": {
+ "jiti": ">=1.21.0",
+ "postcss": ">=8.0.9",
+ "tsx": "^4.8.1",
+ "yaml": "^2.4.2"
+ },
+ "peerDependenciesMeta": {
+ "jiti": {
+ "optional": true
+ },
+ "postcss": {
+ "optional": true
+ },
+ "tsx": {
+ "optional": true
+ },
+ "yaml": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/postcss-nested": {
+ "version": "6.2.0",
+ "resolved": "https://registry.npmmirror.com/postcss-nested/-/postcss-nested-6.2.0.tgz",
+ "integrity": "sha512-HQbt28KulC5AJzG+cZtj9kvKB93CFCdLvog1WFLf1D+xmMvPGlBstkpTEZfK5+AN9hfJocyBFCNiqyS48bpgzQ==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/postcss/"
+ },
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "postcss-selector-parser": "^6.1.1"
+ },
+ "engines": {
+ "node": ">=12.0"
+ },
+ "peerDependencies": {
+ "postcss": "^8.2.14"
+ }
+ },
+ "node_modules/postcss-selector-parser": {
+ "version": "6.1.2",
+ "resolved": "https://registry.npmmirror.com/postcss-selector-parser/-/postcss-selector-parser-6.1.2.tgz",
+ "integrity": "sha512-Q8qQfPiZ+THO/3ZrOrO0cJJKfpYCagtMUkXbnEfmgUjwXg6z/WBeOyS9APBBPCTSiDV+s4SwQGu8yFsiMRIudg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "cssesc": "^3.0.0",
+ "util-deprecate": "^1.0.2"
+ },
+ "engines": {
+ "node": ">=4"
+ }
+ },
+ "node_modules/postcss-value-parser": {
+ "version": "4.2.0",
+ "resolved": "https://registry.npmmirror.com/postcss-value-parser/-/postcss-value-parser-4.2.0.tgz",
+ "integrity": "sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/prelude-ls": {
+ "version": "1.2.1",
+ "resolved": "https://registry.npmmirror.com/prelude-ls/-/prelude-ls-1.2.1.tgz",
+ "integrity": "sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.8.0"
+ }
+ },
+ "node_modules/prop-types": {
+ "version": "15.8.1",
+ "resolved": "https://registry.npmmirror.com/prop-types/-/prop-types-15.8.1.tgz",
+ "integrity": "sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "loose-envify": "^1.4.0",
+ "object-assign": "^4.1.1",
+ "react-is": "^16.13.1"
+ }
+ },
+ "node_modules/property-information": {
+ "version": "7.1.0",
+ "resolved": "https://registry.npmmirror.com/property-information/-/property-information-7.1.0.tgz",
+ "integrity": "sha512-TwEZ+X+yCJmYfL7TPUOcvBZ4QfoT5YenQiJuX//0th53DE6w0xxLEtfK3iyryQFddXuvkIk51EEgrJQ0WJkOmQ==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
+ "node_modules/punycode": {
+ "version": "2.3.1",
+ "resolved": "https://registry.npmmirror.com/punycode/-/punycode-2.3.1.tgz",
+ "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "node_modules/queue-microtask": {
+ "version": "1.2.3",
+ "resolved": "https://registry.npmmirror.com/queue-microtask/-/queue-microtask-1.2.3.tgz",
+ "integrity": "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
+ "license": "MIT"
+ },
+ "node_modules/raf": {
+ "version": "3.4.1",
+ "resolved": "https://registry.npmmirror.com/raf/-/raf-3.4.1.tgz",
+ "integrity": "sha512-Sq4CW4QhwOHE8ucn6J34MqtZCeWFP2aQSmrlroYgqAV1PjStIhJXxYuTgUIfkEk7zTLjmIjLmU5q+fbD1NnOJA==",
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "performance-now": "^2.1.0"
+ }
+ },
+ "node_modules/react": {
+ "version": "18.3.1",
+ "resolved": "https://registry.npmmirror.com/react/-/react-18.3.1.tgz",
+ "integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==",
+ "license": "MIT",
+ "dependencies": {
+ "loose-envify": "^1.1.0"
+ },
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/react-dom": {
+ "version": "18.3.1",
+ "resolved": "https://registry.npmmirror.com/react-dom/-/react-dom-18.3.1.tgz",
+ "integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==",
+ "license": "MIT",
+ "dependencies": {
+ "loose-envify": "^1.1.0",
+ "scheduler": "^0.23.2"
+ },
+ "peerDependencies": {
+ "react": "^18.3.1"
+ }
+ },
+ "node_modules/react-is": {
+ "version": "16.13.1",
+ "resolved": "https://registry.npmmirror.com/react-is/-/react-is-16.13.1.tgz",
+ "integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/react-markdown": {
+ "version": "9.1.0",
+ "resolved": "https://registry.npmmirror.com/react-markdown/-/react-markdown-9.1.0.tgz",
+ "integrity": "sha512-xaijuJB0kzGiUdG7nc2MOMDUDBWPyGAjZtUrow9XxUeua8IqeP+VlIfAZ3bphpcLTnSZXz6z9jcVC/TCwbfgdw==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/hast": "^3.0.0",
+ "@types/mdast": "^4.0.0",
+ "devlop": "^1.0.0",
+ "hast-util-to-jsx-runtime": "^2.0.0",
+ "html-url-attributes": "^3.0.0",
+ "mdast-util-to-hast": "^13.0.0",
+ "remark-parse": "^11.0.0",
+ "remark-rehype": "^11.0.0",
+ "unified": "^11.0.0",
+ "unist-util-visit": "^5.0.0",
+ "vfile": "^6.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ },
+ "peerDependencies": {
+ "@types/react": ">=18",
+ "react": ">=18"
+ }
+ },
+ "node_modules/read-cache": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmmirror.com/read-cache/-/read-cache-1.0.0.tgz",
+ "integrity": "sha512-Owdv/Ft7IjOgm/i0xvNDZ1LrRANRfew4b2prF3OWMQLxLfu3bS8FVhCsrSCMK4lR56Y9ya+AThoTpDCTxCmpRA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "pify": "^2.3.0"
+ }
+ },
+ "node_modules/readdirp": {
+ "version": "3.6.0",
+ "resolved": "https://registry.npmmirror.com/readdirp/-/readdirp-3.6.0.tgz",
+ "integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "picomatch": "^2.2.1"
+ },
+ "engines": {
+ "node": ">=8.10.0"
+ }
+ },
+ "node_modules/reflect.getprototypeof": {
+ "version": "1.0.10",
+ "resolved": "https://registry.npmmirror.com/reflect.getprototypeof/-/reflect.getprototypeof-1.0.10.tgz",
+ "integrity": "sha512-00o4I+DVrefhv+nX0ulyi3biSHCPDe+yLv5o/p6d/UVlirijB8E16FtfwSAi4g3tcqrQ4lRAqQSoFEZJehYEcw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bind": "^1.0.8",
+ "define-properties": "^1.2.1",
+ "es-abstract": "^1.23.9",
+ "es-errors": "^1.3.0",
+ "es-object-atoms": "^1.0.0",
+ "get-intrinsic": "^1.2.7",
+ "get-proto": "^1.0.1",
+ "which-builtin-type": "^1.2.1"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/regenerator-runtime": {
+ "version": "0.13.11",
+ "resolved": "https://registry.npmmirror.com/regenerator-runtime/-/regenerator-runtime-0.13.11.tgz",
+ "integrity": "sha512-kY1AZVr2Ra+t+piVaJ4gxaFaReZVH40AKNo7UCX6W+dEwBo/2oZJzqfuN1qLq1oL45o56cPaTXELwrTh8Fpggg==",
+ "license": "MIT",
+ "optional": true
+ },
+ "node_modules/regexp.prototype.flags": {
+ "version": "1.5.4",
+ "resolved": "https://registry.npmmirror.com/regexp.prototype.flags/-/regexp.prototype.flags-1.5.4.tgz",
+ "integrity": "sha512-dYqgNSZbDwkaJ2ceRd9ojCGjBq+mOm9LmtXnAnEGyHhN/5R7iDW2TRw3h+o/jCFxus3P2LfWIIiwowAjANm7IA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bind": "^1.0.8",
+ "define-properties": "^1.2.1",
+ "es-errors": "^1.3.0",
+ "get-proto": "^1.0.1",
+ "gopd": "^1.2.0",
+ "set-function-name": "^2.0.2"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/rehype-katex": {
+ "version": "7.0.1",
+ "resolved": "https://registry.npmmirror.com/rehype-katex/-/rehype-katex-7.0.1.tgz",
+ "integrity": "sha512-OiM2wrZ/wuhKkigASodFoo8wimG3H12LWQaH8qSPVJn9apWKFSH3YOCtbKpBorTVw/eI7cuT21XBbvwEswbIOA==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/hast": "^3.0.0",
+ "@types/katex": "^0.16.0",
+ "hast-util-from-html-isomorphic": "^2.0.0",
+ "hast-util-to-text": "^4.0.0",
+ "katex": "^0.16.0",
+ "unist-util-visit-parents": "^6.0.0",
+ "vfile": "^6.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/rehype-raw": {
+ "version": "7.0.0",
+ "resolved": "https://registry.npmmirror.com/rehype-raw/-/rehype-raw-7.0.0.tgz",
+ "integrity": "sha512-/aE8hCfKlQeA8LmyeyQvQF3eBiLRGNlfBJEvWH7ivp9sBqs7TNqBL5X3v157rM4IFETqDnIOO+z5M/biZbo9Ww==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/hast": "^3.0.0",
+ "hast-util-raw": "^9.0.0",
+ "vfile": "^6.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/remark-gfm": {
+ "version": "4.0.1",
+ "resolved": "https://registry.npmmirror.com/remark-gfm/-/remark-gfm-4.0.1.tgz",
+ "integrity": "sha512-1quofZ2RQ9EWdeN34S79+KExV1764+wCUGop5CPL1WGdD0ocPpu91lzPGbwWMECpEpd42kJGQwzRfyov9j4yNg==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/mdast": "^4.0.0",
+ "mdast-util-gfm": "^3.0.0",
+ "micromark-extension-gfm": "^3.0.0",
+ "remark-parse": "^11.0.0",
+ "remark-stringify": "^11.0.0",
+ "unified": "^11.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/remark-math": {
+ "version": "6.0.0",
+ "resolved": "https://registry.npmmirror.com/remark-math/-/remark-math-6.0.0.tgz",
+ "integrity": "sha512-MMqgnP74Igy+S3WwnhQ7kqGlEerTETXMvJhrUzDikVZ2/uogJCb+WHUg97hK9/jcfc0dkD73s3LN8zU49cTEtA==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/mdast": "^4.0.0",
+ "mdast-util-math": "^3.0.0",
+ "micromark-extension-math": "^3.0.0",
+ "unified": "^11.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/remark-parse": {
+ "version": "11.0.0",
+ "resolved": "https://registry.npmmirror.com/remark-parse/-/remark-parse-11.0.0.tgz",
+ "integrity": "sha512-FCxlKLNGknS5ba/1lmpYijMUzX2esxW5xQqjWxw2eHFfS2MSdaHVINFmhjo+qN1WhZhNimq0dZATN9pH0IDrpA==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/mdast": "^4.0.0",
+ "mdast-util-from-markdown": "^2.0.0",
+ "micromark-util-types": "^2.0.0",
+ "unified": "^11.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/remark-rehype": {
+ "version": "11.1.2",
+ "resolved": "https://registry.npmmirror.com/remark-rehype/-/remark-rehype-11.1.2.tgz",
+ "integrity": "sha512-Dh7l57ianaEoIpzbp0PC9UKAdCSVklD8E5Rpw7ETfbTl3FqcOOgq5q2LVDhgGCkaBv7p24JXikPdvhhmHvKMsw==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/hast": "^3.0.0",
+ "@types/mdast": "^4.0.0",
+ "mdast-util-to-hast": "^13.0.0",
+ "unified": "^11.0.0",
+ "vfile": "^6.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/remark-stringify": {
+ "version": "11.0.0",
+ "resolved": "https://registry.npmmirror.com/remark-stringify/-/remark-stringify-11.0.0.tgz",
+ "integrity": "sha512-1OSmLd3awB/t8qdoEOMazZkNsfVTeY4fTsgzcQFdXNq8ToTN4ZGwrMnlda4K6smTFKD+GRV6O48i6Z4iKgPPpw==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/mdast": "^4.0.0",
+ "mdast-util-to-markdown": "^2.0.0",
+ "unified": "^11.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/resolve": {
+ "version": "1.22.11",
+ "resolved": "https://registry.npmmirror.com/resolve/-/resolve-1.22.11.tgz",
+ "integrity": "sha512-RfqAvLnMl313r7c9oclB1HhUEAezcpLjz95wFH4LVuhk9JF/r22qmVP9AMmOU4vMX7Q8pN8jwNg/CSpdFnMjTQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "is-core-module": "^2.16.1",
+ "path-parse": "^1.0.7",
+ "supports-preserve-symlinks-flag": "^1.0.0"
+ },
+ "bin": {
+ "resolve": "bin/resolve"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/resolve-from": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmmirror.com/resolve-from/-/resolve-from-4.0.0.tgz",
+ "integrity": "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=4"
+ }
+ },
+ "node_modules/resolve-pkg-maps": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmmirror.com/resolve-pkg-maps/-/resolve-pkg-maps-1.0.0.tgz",
+ "integrity": "sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw==",
+ "dev": true,
+ "license": "MIT",
+ "funding": {
+ "url": "https://github.com/privatenumber/resolve-pkg-maps?sponsor=1"
+ }
+ },
+ "node_modules/reusify": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmmirror.com/reusify/-/reusify-1.1.0.tgz",
+ "integrity": "sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "iojs": ">=1.0.0",
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/rgbcolor": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmmirror.com/rgbcolor/-/rgbcolor-1.0.1.tgz",
+ "integrity": "sha512-9aZLIrhRaD97sgVhtJOW6ckOEh6/GnvQtdVNfdZ6s67+3/XwLS9lBcQYzEEhYVeUowN7pRzMLsyGhK2i/xvWbw==",
+ "license": "MIT OR SEE LICENSE IN FEEL-FREE.md",
+ "optional": true,
+ "engines": {
+ "node": ">= 0.8.15"
+ }
+ },
+ "node_modules/rimraf": {
+ "version": "3.0.2",
+ "resolved": "https://registry.npmmirror.com/rimraf/-/rimraf-3.0.2.tgz",
+ "integrity": "sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==",
+ "deprecated": "Rimraf versions prior to v4 are no longer supported",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "glob": "^7.1.3"
+ },
+ "bin": {
+ "rimraf": "bin.js"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/isaacs"
+ }
+ },
+ "node_modules/robust-predicates": {
+ "version": "3.0.2",
+ "resolved": "https://registry.npmjs.org/robust-predicates/-/robust-predicates-3.0.2.tgz",
+ "integrity": "sha512-IXgzBWvWQwE6PrDI05OvmXUIruQTcoMDzRsOd5CDvHCVLcLHMTSYvOK5Cm46kWqlV3yAbuSpBZdJ5oP5OUoStg==",
+ "license": "Unlicense"
+ },
+ "node_modules/roughjs": {
+ "version": "4.6.6",
+ "resolved": "https://registry.npmjs.org/roughjs/-/roughjs-4.6.6.tgz",
+ "integrity": "sha512-ZUz/69+SYpFN/g/lUlo2FXcIjRkSu3nDarreVdGGndHEBJ6cXPdKguS8JGxwj5HA5xIbVKSmLgr5b3AWxtRfvQ==",
+ "license": "MIT",
+ "dependencies": {
+ "hachure-fill": "^0.5.2",
+ "path-data-parser": "^0.1.0",
+ "points-on-curve": "^0.2.0",
+ "points-on-path": "^0.2.1"
+ }
+ },
+ "node_modules/run-parallel": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmmirror.com/run-parallel/-/run-parallel-1.2.0.tgz",
+ "integrity": "sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "queue-microtask": "^1.2.2"
+ }
+ },
+ "node_modules/rw": {
+ "version": "1.3.3",
+ "resolved": "https://registry.npmjs.org/rw/-/rw-1.3.3.tgz",
+ "integrity": "sha512-PdhdWy89SiZogBLaw42zdeqtRJ//zFd2PgQavcICDUgJT5oW10QCRKbJ6bg4r0/UY2M6BWd5tkxuGFRvCkgfHQ==",
+ "license": "BSD-3-Clause"
+ },
+ "node_modules/safe-array-concat": {
+ "version": "1.1.3",
+ "resolved": "https://registry.npmmirror.com/safe-array-concat/-/safe-array-concat-1.1.3.tgz",
+ "integrity": "sha512-AURm5f0jYEOydBj7VQlVvDrjeFgthDdEF5H1dP+6mNpoXOMo1quQqJ4wvJDyRZ9+pO3kGWoOdmV08cSv2aJV6Q==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bind": "^1.0.8",
+ "call-bound": "^1.0.2",
+ "get-intrinsic": "^1.2.6",
+ "has-symbols": "^1.1.0",
+ "isarray": "^2.0.5"
+ },
+ "engines": {
+ "node": ">=0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/safe-push-apply": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmmirror.com/safe-push-apply/-/safe-push-apply-1.0.0.tgz",
+ "integrity": "sha512-iKE9w/Z7xCzUMIZqdBsp6pEQvwuEebH4vdpjcDWnyzaI6yl6O9FHvVpmGelvEHNsoY6wGblkxR6Zty/h00WiSA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "es-errors": "^1.3.0",
+ "isarray": "^2.0.5"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/safe-regex-test": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmmirror.com/safe-regex-test/-/safe-regex-test-1.1.0.tgz",
+ "integrity": "sha512-x/+Cz4YrimQxQccJf5mKEbIa1NzeCRNI5Ecl/ekmlYaampdNLPalVyIcCZNNH3MvmqBugV5TMYZXv0ljslUlaw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bound": "^1.0.2",
+ "es-errors": "^1.3.0",
+ "is-regex": "^1.2.1"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/safer-buffer": {
+ "version": "2.1.2",
+ "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
+ "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",
+ "license": "MIT"
+ },
+ "node_modules/scheduler": {
+ "version": "0.23.2",
+ "resolved": "https://registry.npmmirror.com/scheduler/-/scheduler-0.23.2.tgz",
+ "integrity": "sha512-UOShsPwz7NrMUqhR6t0hWjFduvOzbtv7toDH1/hIrfRNIDBnnBWd0CwJTGvTpngVlmwGCdP9/Zl/tVrDqcuYzQ==",
+ "license": "MIT",
+ "dependencies": {
+ "loose-envify": "^1.1.0"
+ }
+ },
+ "node_modules/semver": {
+ "version": "7.7.3",
+ "resolved": "https://registry.npmmirror.com/semver/-/semver-7.7.3.tgz",
+ "integrity": "sha512-SdsKMrI9TdgjdweUSR9MweHA4EJ8YxHn8DFaDisvhVlUOe4BF1tLD7GAj0lIqWVl+dPb/rExr0Btby5loQm20Q==",
+ "dev": true,
+ "license": "ISC",
+ "bin": {
+ "semver": "bin/semver.js"
+ },
+ "engines": {
+ "node": ">=10"
+ }
+ },
+ "node_modules/set-function-length": {
+ "version": "1.2.2",
+ "resolved": "https://registry.npmmirror.com/set-function-length/-/set-function-length-1.2.2.tgz",
+ "integrity": "sha512-pgRc4hJ4/sNjWCSS9AmnS40x3bNMDTknHgL5UaMBTMyJnU90EgWh1Rz+MC9eFu4BuN/UwZjKQuY/1v3rM7HMfg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "define-data-property": "^1.1.4",
+ "es-errors": "^1.3.0",
+ "function-bind": "^1.1.2",
+ "get-intrinsic": "^1.2.4",
+ "gopd": "^1.0.1",
+ "has-property-descriptors": "^1.0.2"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/set-function-name": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmmirror.com/set-function-name/-/set-function-name-2.0.2.tgz",
+ "integrity": "sha512-7PGFlmtwsEADb0WYyvCMa1t+yke6daIG4Wirafur5kcf+MhUnPms1UeR0CKQdTZD81yESwMHbtn+TR+dMviakQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "define-data-property": "^1.1.4",
+ "es-errors": "^1.3.0",
+ "functions-have-names": "^1.2.3",
+ "has-property-descriptors": "^1.0.2"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/set-proto": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmmirror.com/set-proto/-/set-proto-1.0.0.tgz",
+ "integrity": "sha512-RJRdvCo6IAnPdsvP/7m6bsQqNnn1FCBX5ZNtFL98MmFF/4xAIJTIg1YbHW5DC2W5SKZanrC6i4HsJqlajw/dZw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "dunder-proto": "^1.0.1",
+ "es-errors": "^1.3.0",
+ "es-object-atoms": "^1.0.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/shebang-command": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmmirror.com/shebang-command/-/shebang-command-2.0.0.tgz",
+ "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "shebang-regex": "^3.0.0"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/shebang-regex": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmmirror.com/shebang-regex/-/shebang-regex-3.0.0.tgz",
+ "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/side-channel": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmmirror.com/side-channel/-/side-channel-1.1.0.tgz",
+ "integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "es-errors": "^1.3.0",
+ "object-inspect": "^1.13.3",
+ "side-channel-list": "^1.0.0",
+ "side-channel-map": "^1.0.1",
+ "side-channel-weakmap": "^1.0.2"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/side-channel-list": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmmirror.com/side-channel-list/-/side-channel-list-1.0.0.tgz",
+ "integrity": "sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "es-errors": "^1.3.0",
+ "object-inspect": "^1.13.3"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/side-channel-map": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmmirror.com/side-channel-map/-/side-channel-map-1.0.1.tgz",
+ "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bound": "^1.0.2",
+ "es-errors": "^1.3.0",
+ "get-intrinsic": "^1.2.5",
+ "object-inspect": "^1.13.3"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/side-channel-weakmap": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmmirror.com/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz",
+ "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bound": "^1.0.2",
+ "es-errors": "^1.3.0",
+ "get-intrinsic": "^1.2.5",
+ "object-inspect": "^1.13.3",
+ "side-channel-map": "^1.0.1"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/slash": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmmirror.com/slash/-/slash-3.0.0.tgz",
+ "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/source-map-js": {
+ "version": "1.2.1",
+ "resolved": "https://registry.npmmirror.com/source-map-js/-/source-map-js-1.2.1.tgz",
+ "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==",
+ "license": "BSD-3-Clause",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/space-separated-tokens": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmmirror.com/space-separated-tokens/-/space-separated-tokens-2.0.2.tgz",
+ "integrity": "sha512-PEGlAwrG8yXGXRjW32fGbg66JAlOAwbObuqVoJpv/mRgoWDQfgH1wDPvtzWyUSNAXBGSk8h755YDbbcEy3SH2Q==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
+ "node_modules/stable-hash": {
+ "version": "0.0.5",
+ "resolved": "https://registry.npmmirror.com/stable-hash/-/stable-hash-0.0.5.tgz",
+ "integrity": "sha512-+L3ccpzibovGXFK+Ap/f8LOS0ahMrHTf3xu7mMLSpEGU0EO9ucaysSylKo9eRDFNhWve/y275iPmIZ4z39a9iA==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/stackblur-canvas": {
+ "version": "2.7.0",
+ "resolved": "https://registry.npmmirror.com/stackblur-canvas/-/stackblur-canvas-2.7.0.tgz",
+ "integrity": "sha512-yf7OENo23AGJhBriGx0QivY5JP6Y1HbrrDI6WLt6C5auYZXlQrheoY8hD4ibekFKz1HOfE48Ww8kMWMnJD/zcQ==",
+ "license": "MIT",
+ "optional": true,
+ "engines": {
+ "node": ">=0.1.14"
+ }
+ },
+ "node_modules/stop-iteration-iterator": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmmirror.com/stop-iteration-iterator/-/stop-iteration-iterator-1.1.0.tgz",
+ "integrity": "sha512-eLoXW/DHyl62zxY4SCaIgnRhuMr6ri4juEYARS8E6sCEqzKpOiE521Ucofdx+KnDZl5xmvGYaaKCk5FEOxJCoQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "es-errors": "^1.3.0",
+ "internal-slot": "^1.1.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/streamsearch": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmmirror.com/streamsearch/-/streamsearch-1.1.0.tgz",
+ "integrity": "sha512-Mcc5wHehp9aXz1ax6bZUyY5afg9u2rv5cqQI3mRrYkGC8rW2hM02jWuwjtL++LS5qinSyhj2QfLyNsuc+VsExg==",
+ "engines": {
+ "node": ">=10.0.0"
+ }
+ },
+ "node_modules/string.prototype.includes": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmmirror.com/string.prototype.includes/-/string.prototype.includes-2.0.1.tgz",
+ "integrity": "sha512-o7+c9bW6zpAdJHTtujeePODAhkuicdAryFsfVKwA+wGw89wJ4GTY484WTucM9hLtDEOpOvI+aHnzqnC5lHp4Rg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bind": "^1.0.7",
+ "define-properties": "^1.2.1",
+ "es-abstract": "^1.23.3"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/string.prototype.matchall": {
+ "version": "4.0.12",
+ "resolved": "https://registry.npmmirror.com/string.prototype.matchall/-/string.prototype.matchall-4.0.12.tgz",
+ "integrity": "sha512-6CC9uyBL+/48dYizRf7H7VAYCMCNTBeM78x/VTUe9bFEaxBepPJDa1Ow99LqI/1yF7kuy7Q3cQsYMrcjGUcskA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bind": "^1.0.8",
+ "call-bound": "^1.0.3",
+ "define-properties": "^1.2.1",
+ "es-abstract": "^1.23.6",
+ "es-errors": "^1.3.0",
+ "es-object-atoms": "^1.0.0",
+ "get-intrinsic": "^1.2.6",
+ "gopd": "^1.2.0",
+ "has-symbols": "^1.1.0",
+ "internal-slot": "^1.1.0",
+ "regexp.prototype.flags": "^1.5.3",
+ "set-function-name": "^2.0.2",
+ "side-channel": "^1.1.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/string.prototype.repeat": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmmirror.com/string.prototype.repeat/-/string.prototype.repeat-1.0.0.tgz",
+ "integrity": "sha512-0u/TldDbKD8bFCQ/4f5+mNRrXwZ8hg2w7ZR8wa16e8z9XpePWl3eGEcUD0OXpEH/VJH/2G3gjUtR3ZOiBe2S/w==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "define-properties": "^1.1.3",
+ "es-abstract": "^1.17.5"
+ }
+ },
+ "node_modules/string.prototype.trim": {
+ "version": "1.2.10",
+ "resolved": "https://registry.npmmirror.com/string.prototype.trim/-/string.prototype.trim-1.2.10.tgz",
+ "integrity": "sha512-Rs66F0P/1kedk5lyYyH9uBzuiI/kNRmwJAR9quK6VOtIpZ2G+hMZd+HQbbv25MgCA6gEffoMZYxlTod4WcdrKA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bind": "^1.0.8",
+ "call-bound": "^1.0.2",
+ "define-data-property": "^1.1.4",
+ "define-properties": "^1.2.1",
+ "es-abstract": "^1.23.5",
+ "es-object-atoms": "^1.0.0",
+ "has-property-descriptors": "^1.0.2"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/string.prototype.trimend": {
+ "version": "1.0.9",
+ "resolved": "https://registry.npmmirror.com/string.prototype.trimend/-/string.prototype.trimend-1.0.9.tgz",
+ "integrity": "sha512-G7Ok5C6E/j4SGfyLCloXTrngQIQU3PWtXGst3yM7Bea9FRURf1S42ZHlZZtsNque2FN2PoUhfZXYLNWwEr4dLQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bind": "^1.0.8",
+ "call-bound": "^1.0.2",
+ "define-properties": "^1.2.1",
+ "es-object-atoms": "^1.0.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/string.prototype.trimstart": {
+ "version": "1.0.8",
+ "resolved": "https://registry.npmmirror.com/string.prototype.trimstart/-/string.prototype.trimstart-1.0.8.tgz",
+ "integrity": "sha512-UXSH262CSZY1tfu3G3Secr6uGLCFVPMhIqHjlgCUtCCcgihYc/xKs9djMTMUOb2j1mVSeU8EU6NWc/iQKU6Gfg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bind": "^1.0.7",
+ "define-properties": "^1.2.1",
+ "es-object-atoms": "^1.0.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/stringify-entities": {
+ "version": "4.0.4",
+ "resolved": "https://registry.npmmirror.com/stringify-entities/-/stringify-entities-4.0.4.tgz",
+ "integrity": "sha512-IwfBptatlO+QCJUo19AqvrPNqlVMpW9YEL2LIVY+Rpv2qsjCGxaDLNRgeGsQWJhfItebuJhsGSLjaBbNSQ+ieg==",
+ "license": "MIT",
+ "dependencies": {
+ "character-entities-html4": "^2.0.0",
+ "character-entities-legacy": "^3.0.0"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
+ "node_modules/strip-ansi": {
+ "version": "6.0.1",
+ "resolved": "https://registry.npmmirror.com/strip-ansi/-/strip-ansi-6.0.1.tgz",
+ "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "ansi-regex": "^5.0.1"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/strip-bom": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmmirror.com/strip-bom/-/strip-bom-3.0.0.tgz",
+ "integrity": "sha512-vavAMRXOgBVNF6nyEEmL3DBK19iRpDcoIwW+swQ+CbGiu7lju6t+JklA1MHweoWtadgt4ISVUsXLyDq34ddcwA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=4"
+ }
+ },
+ "node_modules/strip-json-comments": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmmirror.com/strip-json-comments/-/strip-json-comments-3.1.1.tgz",
+ "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=8"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/style-to-js": {
+ "version": "1.1.21",
+ "resolved": "https://registry.npmmirror.com/style-to-js/-/style-to-js-1.1.21.tgz",
+ "integrity": "sha512-RjQetxJrrUJLQPHbLku6U/ocGtzyjbJMP9lCNK7Ag0CNh690nSH8woqWH9u16nMjYBAok+i7JO1NP2pOy8IsPQ==",
+ "license": "MIT",
+ "dependencies": {
+ "style-to-object": "1.0.14"
+ }
+ },
+ "node_modules/style-to-object": {
+ "version": "1.0.14",
+ "resolved": "https://registry.npmmirror.com/style-to-object/-/style-to-object-1.0.14.tgz",
+ "integrity": "sha512-LIN7rULI0jBscWQYaSswptyderlarFkjQ+t79nzty8tcIAceVomEVlLzH5VP4Cmsv6MtKhs7qaAiwlcp+Mgaxw==",
+ "license": "MIT",
+ "dependencies": {
+ "inline-style-parser": "0.2.7"
+ }
+ },
+ "node_modules/styled-jsx": {
+ "version": "5.1.1",
+ "resolved": "https://registry.npmmirror.com/styled-jsx/-/styled-jsx-5.1.1.tgz",
+ "integrity": "sha512-pW7uC1l4mBZ8ugbiZrcIsiIvVx1UmTfw7UkC3Um2tmfUq9Bhk8IiyEIPl6F8agHgjzku6j0xQEZbfA5uSgSaCw==",
+ "license": "MIT",
+ "dependencies": {
+ "client-only": "0.0.1"
+ },
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "peerDependencies": {
+ "react": ">= 16.8.0 || 17.x.x || ^18.0.0-0"
+ },
+ "peerDependenciesMeta": {
+ "@babel/core": {
+ "optional": true
+ },
+ "babel-plugin-macros": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/stylis": {
+ "version": "4.3.6",
+ "resolved": "https://registry.npmjs.org/stylis/-/stylis-4.3.6.tgz",
+ "integrity": "sha512-yQ3rwFWRfwNUY7H5vpU0wfdkNSnvnJinhF9830Swlaxl03zsOjCfmX0ugac+3LtK0lYSgwL/KXc8oYL3mG4YFQ==",
+ "license": "MIT"
+ },
+ "node_modules/sucrase": {
+ "version": "3.35.1",
+ "resolved": "https://registry.npmmirror.com/sucrase/-/sucrase-3.35.1.tgz",
+ "integrity": "sha512-DhuTmvZWux4H1UOnWMB3sk0sbaCVOoQZjv8u1rDoTV0HTdGem9hkAZtl4JZy8P2z4Bg0nT+YMeOFyVr4zcG5Tw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@jridgewell/gen-mapping": "^0.3.2",
+ "commander": "^4.0.0",
+ "lines-and-columns": "^1.1.6",
+ "mz": "^2.7.0",
+ "pirates": "^4.0.1",
+ "tinyglobby": "^0.2.11",
+ "ts-interface-checker": "^0.1.9"
+ },
+ "bin": {
+ "sucrase": "bin/sucrase",
+ "sucrase-node": "bin/sucrase-node"
+ },
+ "engines": {
+ "node": ">=16 || 14 >=14.17"
+ }
+ },
+ "node_modules/sucrase/node_modules/commander": {
+ "version": "4.1.1",
+ "resolved": "https://registry.npmmirror.com/commander/-/commander-4.1.1.tgz",
+ "integrity": "sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 6"
+ }
+ },
+ "node_modules/supports-color": {
+ "version": "7.2.0",
+ "resolved": "https://registry.npmmirror.com/supports-color/-/supports-color-7.2.0.tgz",
+ "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "has-flag": "^4.0.0"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/supports-preserve-symlinks-flag": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmmirror.com/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz",
+ "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/svg-pathdata": {
+ "version": "6.0.3",
+ "resolved": "https://registry.npmmirror.com/svg-pathdata/-/svg-pathdata-6.0.3.tgz",
+ "integrity": "sha512-qsjeeq5YjBZ5eMdFuUa4ZosMLxgr5RZ+F+Y1OrDhuOCEInRMA3x74XdBtggJcj9kOeInz0WE+LgCPDkZFlBYJw==",
+ "license": "MIT",
+ "optional": true,
+ "engines": {
+ "node": ">=12.0.0"
+ }
+ },
+ "node_modules/tailwind-merge": {
+ "version": "2.6.0",
+ "resolved": "https://registry.npmmirror.com/tailwind-merge/-/tailwind-merge-2.6.0.tgz",
+ "integrity": "sha512-P+Vu1qXfzediirmHOC3xKGAYeZtPcV9g76X+xg2FD4tYgR71ewMA35Y3sCz3zhiN/dwefRpJX0yBcgwi1fXNQA==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/dcastil"
+ }
+ },
+ "node_modules/tailwindcss": {
+ "version": "3.4.18",
+ "resolved": "https://registry.npmmirror.com/tailwindcss/-/tailwindcss-3.4.18.tgz",
+ "integrity": "sha512-6A2rnmW5xZMdw11LYjhcI5846rt9pbLSabY5XPxo+XWdxwZaFEn47Go4NzFiHu9sNNmr/kXivP1vStfvMaK1GQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@alloc/quick-lru": "^5.2.0",
+ "arg": "^5.0.2",
+ "chokidar": "^3.6.0",
+ "didyoumean": "^1.2.2",
+ "dlv": "^1.1.3",
+ "fast-glob": "^3.3.2",
+ "glob-parent": "^6.0.2",
+ "is-glob": "^4.0.3",
+ "jiti": "^1.21.7",
+ "lilconfig": "^3.1.3",
+ "micromatch": "^4.0.8",
+ "normalize-path": "^3.0.0",
+ "object-hash": "^3.0.0",
+ "picocolors": "^1.1.1",
+ "postcss": "^8.4.47",
+ "postcss-import": "^15.1.0",
+ "postcss-js": "^4.0.1",
+ "postcss-load-config": "^4.0.2 || ^5.0 || ^6.0",
+ "postcss-nested": "^6.2.0",
+ "postcss-selector-parser": "^6.1.2",
+ "resolve": "^1.22.8",
+ "sucrase": "^3.35.0"
+ },
+ "bin": {
+ "tailwind": "lib/cli.js",
+ "tailwindcss": "lib/cli.js"
+ },
+ "engines": {
+ "node": ">=14.0.0"
+ }
+ },
+ "node_modules/text-segmentation": {
+ "version": "1.0.3",
+ "resolved": "https://registry.npmmirror.com/text-segmentation/-/text-segmentation-1.0.3.tgz",
+ "integrity": "sha512-iOiPUo/BGnZ6+54OsWxZidGCsdU8YbE4PSpdPinp7DeMtUJNJBoJ/ouUSTJjHkh1KntHaltHl/gDs2FC4i5+Nw==",
+ "license": "MIT",
+ "dependencies": {
+ "utrie": "^1.0.2"
+ }
+ },
+ "node_modules/text-table": {
+ "version": "0.2.0",
+ "resolved": "https://registry.npmmirror.com/text-table/-/text-table-0.2.0.tgz",
+ "integrity": "sha512-N+8UisAXDGk8PFXP4HAzVR9nbfmVJ3zYLAWiTIoqC5v5isinhr+r5uaO8+7r3BMfuNIufIsA7RdpVgacC2cSpw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/thenify": {
+ "version": "3.3.1",
+ "resolved": "https://registry.npmmirror.com/thenify/-/thenify-3.3.1.tgz",
+ "integrity": "sha512-RVZSIV5IG10Hk3enotrhvz0T9em6cyHBLkH/YAZuKqd8hRkKhSfCGIcP2KUY0EPxndzANBmNllzWPwak+bheSw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "any-promise": "^1.0.0"
+ }
+ },
+ "node_modules/thenify-all": {
+ "version": "1.6.0",
+ "resolved": "https://registry.npmmirror.com/thenify-all/-/thenify-all-1.6.0.tgz",
+ "integrity": "sha512-RNxQH/qI8/t3thXJDwcstUO4zeqo64+Uy/+sNVRBx4Xn2OX+OZ9oP+iJnNFqplFra2ZUVeKCSa2oVWi3T4uVmA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "thenify": ">= 3.1.0 < 4"
+ },
+ "engines": {
+ "node": ">=0.8"
+ }
+ },
+ "node_modules/tinyexec": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.0.2.tgz",
+ "integrity": "sha512-W/KYk+NFhkmsYpuHq5JykngiOCnxeVL8v8dFnqxSD8qEEdRfXk1SDM6JzNqcERbcGYj9tMrDQBYV9cjgnunFIg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/tinyglobby": {
+ "version": "0.2.15",
+ "resolved": "https://registry.npmmirror.com/tinyglobby/-/tinyglobby-0.2.15.tgz",
+ "integrity": "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "fdir": "^6.5.0",
+ "picomatch": "^4.0.3"
+ },
+ "engines": {
+ "node": ">=12.0.0"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/SuperchupuDev"
+ }
+ },
+ "node_modules/tinyglobby/node_modules/fdir": {
+ "version": "6.5.0",
+ "resolved": "https://registry.npmmirror.com/fdir/-/fdir-6.5.0.tgz",
+ "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=12.0.0"
+ },
+ "peerDependencies": {
+ "picomatch": "^3 || ^4"
+ },
+ "peerDependenciesMeta": {
+ "picomatch": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/tinyglobby/node_modules/picomatch": {
+ "version": "4.0.3",
+ "resolved": "https://registry.npmmirror.com/picomatch/-/picomatch-4.0.3.tgz",
+ "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=12"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/jonschlinkert"
+ }
+ },
+ "node_modules/to-regex-range": {
+ "version": "5.0.1",
+ "resolved": "https://registry.npmmirror.com/to-regex-range/-/to-regex-range-5.0.1.tgz",
+ "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "is-number": "^7.0.0"
+ },
+ "engines": {
+ "node": ">=8.0"
+ }
+ },
+ "node_modules/trim-lines": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmmirror.com/trim-lines/-/trim-lines-3.0.1.tgz",
+ "integrity": "sha512-kRj8B+YHZCc9kQYdWfJB2/oUl9rA99qbowYYBtr4ui4mZyAQ2JpvVBd/6U2YloATfqBhBTSMhTpgBHtU0Mf3Rg==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
+ "node_modules/trough": {
+ "version": "2.2.0",
+ "resolved": "https://registry.npmmirror.com/trough/-/trough-2.2.0.tgz",
+ "integrity": "sha512-tmMpK00BjZiUyVyvrBK7knerNgmgvcV/KLVyuma/SC+TQN167GrMRciANTz09+k3zW8L8t60jWO1GpfkZdjTaw==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
+ "node_modules/ts-api-utils": {
+ "version": "1.4.3",
+ "resolved": "https://registry.npmmirror.com/ts-api-utils/-/ts-api-utils-1.4.3.tgz",
+ "integrity": "sha512-i3eMG77UTMD0hZhgRS562pv83RC6ukSAC2GMNWc+9dieh/+jDM5u5YG+NHX6VNDRHQcHwmsTHctP9LhbC3WxVw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=16"
+ },
+ "peerDependencies": {
+ "typescript": ">=4.2.0"
+ }
+ },
+ "node_modules/ts-dedent": {
+ "version": "2.2.0",
+ "resolved": "https://registry.npmjs.org/ts-dedent/-/ts-dedent-2.2.0.tgz",
+ "integrity": "sha512-q5W7tVM71e2xjHZTlgfTDoPF/SmqKG5hddq9SzR49CH2hayqRKJtQ4mtRlSxKaJlR/+9rEM+mnBHf7I2/BQcpQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=6.10"
+ }
+ },
+ "node_modules/ts-interface-checker": {
+ "version": "0.1.13",
+ "resolved": "https://registry.npmmirror.com/ts-interface-checker/-/ts-interface-checker-0.1.13.tgz",
+ "integrity": "sha512-Y/arvbn+rrz3JCKl9C4kVNfTfSm2/mEp5FSz5EsZSANGPSlQrpRI5M4PKF+mJnE52jOO90PnPSc3Ur3bTQw0gA==",
+ "dev": true,
+ "license": "Apache-2.0"
+ },
+ "node_modules/tsconfig-paths": {
+ "version": "3.15.0",
+ "resolved": "https://registry.npmmirror.com/tsconfig-paths/-/tsconfig-paths-3.15.0.tgz",
+ "integrity": "sha512-2Ac2RgzDe/cn48GvOe3M+o82pEFewD3UPbyoUHHdKasHwJKjds4fLXWf/Ux5kATBKN20oaFGu+jbElp1pos0mg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/json5": "^0.0.29",
+ "json5": "^1.0.2",
+ "minimist": "^1.2.6",
+ "strip-bom": "^3.0.0"
+ }
+ },
+ "node_modules/tslib": {
+ "version": "2.8.1",
+ "resolved": "https://registry.npmmirror.com/tslib/-/tslib-2.8.1.tgz",
+ "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
+ "license": "0BSD"
+ },
+ "node_modules/type-check": {
+ "version": "0.4.0",
+ "resolved": "https://registry.npmmirror.com/type-check/-/type-check-0.4.0.tgz",
+ "integrity": "sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "prelude-ls": "^1.2.1"
+ },
+ "engines": {
+ "node": ">= 0.8.0"
+ }
+ },
+ "node_modules/type-fest": {
+ "version": "0.20.2",
+ "resolved": "https://registry.npmmirror.com/type-fest/-/type-fest-0.20.2.tgz",
+ "integrity": "sha512-Ne+eE4r0/iWnpAxD852z3A+N0Bt5RN//NjJwRd2VFHEmrywxf5vsZlh4R6lixl6B+wz/8d+maTSAkN1FIkI3LQ==",
+ "dev": true,
+ "license": "(MIT OR CC0-1.0)",
+ "engines": {
+ "node": ">=10"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/typed-array-buffer": {
+ "version": "1.0.3",
+ "resolved": "https://registry.npmmirror.com/typed-array-buffer/-/typed-array-buffer-1.0.3.tgz",
+ "integrity": "sha512-nAYYwfY3qnzX30IkA6AQZjVbtK6duGontcQm1WSG1MD94YLqK0515GNApXkoxKOWMusVssAHWLh9SeaoefYFGw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bound": "^1.0.3",
+ "es-errors": "^1.3.0",
+ "is-typed-array": "^1.1.14"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/typed-array-byte-length": {
+ "version": "1.0.3",
+ "resolved": "https://registry.npmmirror.com/typed-array-byte-length/-/typed-array-byte-length-1.0.3.tgz",
+ "integrity": "sha512-BaXgOuIxz8n8pIq3e7Atg/7s+DpiYrxn4vdot3w9KbnBhcRQq6o3xemQdIfynqSeXeDrF32x+WvfzmOjPiY9lg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bind": "^1.0.8",
+ "for-each": "^0.3.3",
+ "gopd": "^1.2.0",
+ "has-proto": "^1.2.0",
+ "is-typed-array": "^1.1.14"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/typed-array-byte-offset": {
+ "version": "1.0.4",
+ "resolved": "https://registry.npmmirror.com/typed-array-byte-offset/-/typed-array-byte-offset-1.0.4.tgz",
+ "integrity": "sha512-bTlAFB/FBYMcuX81gbL4OcpH5PmlFHqlCCpAl8AlEzMz5k53oNDvN8p1PNOWLEmI2x4orp3raOFB51tv9X+MFQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "available-typed-arrays": "^1.0.7",
+ "call-bind": "^1.0.8",
+ "for-each": "^0.3.3",
+ "gopd": "^1.2.0",
+ "has-proto": "^1.2.0",
+ "is-typed-array": "^1.1.15",
+ "reflect.getprototypeof": "^1.0.9"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/typed-array-length": {
+ "version": "1.0.7",
+ "resolved": "https://registry.npmmirror.com/typed-array-length/-/typed-array-length-1.0.7.tgz",
+ "integrity": "sha512-3KS2b+kL7fsuk/eJZ7EQdnEmQoaho/r6KUef7hxvltNA5DR8NAUM+8wJMbJyZ4G9/7i3v5zPBIMN5aybAh2/Jg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bind": "^1.0.7",
+ "for-each": "^0.3.3",
+ "gopd": "^1.0.1",
+ "is-typed-array": "^1.1.13",
+ "possible-typed-array-names": "^1.0.0",
+ "reflect.getprototypeof": "^1.0.6"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/typescript": {
+ "version": "5.9.3",
+ "resolved": "https://registry.npmmirror.com/typescript/-/typescript-5.9.3.tgz",
+ "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "bin": {
+ "tsc": "bin/tsc",
+ "tsserver": "bin/tsserver"
+ },
+ "engines": {
+ "node": ">=14.17"
+ }
+ },
+ "node_modules/ufo": {
+ "version": "1.6.1",
+ "resolved": "https://registry.npmjs.org/ufo/-/ufo-1.6.1.tgz",
+ "integrity": "sha512-9a4/uxlTWJ4+a5i0ooc1rU7C7YOw3wT+UGqdeNNHWnOF9qcMBgLRS+4IYUqbczewFx4mLEig6gawh7X6mFlEkA==",
+ "license": "MIT"
+ },
+ "node_modules/unbox-primitive": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmmirror.com/unbox-primitive/-/unbox-primitive-1.1.0.tgz",
+ "integrity": "sha512-nWJ91DjeOkej/TA8pXQ3myruKpKEYgqvpw9lz4OPHj/NWFNluYrjbz9j01CJ8yKQd2g4jFoOkINCTW2I5LEEyw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bound": "^1.0.3",
+ "has-bigints": "^1.0.2",
+ "has-symbols": "^1.1.0",
+ "which-boxed-primitive": "^1.1.1"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/undici-types": {
+ "version": "6.21.0",
+ "resolved": "https://registry.npmmirror.com/undici-types/-/undici-types-6.21.0.tgz",
+ "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/unified": {
+ "version": "11.0.5",
+ "resolved": "https://registry.npmmirror.com/unified/-/unified-11.0.5.tgz",
+ "integrity": "sha512-xKvGhPWw3k84Qjh8bI3ZeJjqnyadK+GEFtazSfZv/rKeTkTjOJho6mFqh2SM96iIcZokxiOpg78GazTSg8+KHA==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/unist": "^3.0.0",
+ "bail": "^2.0.0",
+ "devlop": "^1.0.0",
+ "extend": "^3.0.0",
+ "is-plain-obj": "^4.0.0",
+ "trough": "^2.0.0",
+ "vfile": "^6.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/unist-util-find-after": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmmirror.com/unist-util-find-after/-/unist-util-find-after-5.0.0.tgz",
+ "integrity": "sha512-amQa0Ep2m6hE2g72AugUItjbuM8X8cGQnFoHk0pGfrFeT9GZhzN5SW8nRsiGKK7Aif4CrACPENkA6P/Lw6fHGQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/unist": "^3.0.0",
+ "unist-util-is": "^6.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/unist-util-is": {
+ "version": "6.0.1",
+ "resolved": "https://registry.npmmirror.com/unist-util-is/-/unist-util-is-6.0.1.tgz",
+ "integrity": "sha512-LsiILbtBETkDz8I9p1dQ0uyRUWuaQzd/cuEeS1hoRSyW5E5XGmTzlwY1OrNzzakGowI9Dr/I8HVaw4hTtnxy8g==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/unist": "^3.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/unist-util-position": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmmirror.com/unist-util-position/-/unist-util-position-5.0.0.tgz",
+ "integrity": "sha512-fucsC7HjXvkB5R3kTCO7kUjRdrS0BJt3M/FPxmHMBOm8JQi2BsHAHFsy27E0EolP8rp0NzXsJ+jNPyDWvOJZPA==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/unist": "^3.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/unist-util-remove-position": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmmirror.com/unist-util-remove-position/-/unist-util-remove-position-5.0.0.tgz",
+ "integrity": "sha512-Hp5Kh3wLxv0PHj9m2yZhhLt58KzPtEYKQQ4yxfYFEO7EvHwzyDYnduhHnY1mDxoqr7VUwVuHXk9RXKIiYS1N8Q==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/unist": "^3.0.0",
+ "unist-util-visit": "^5.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/unist-util-stringify-position": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmmirror.com/unist-util-stringify-position/-/unist-util-stringify-position-4.0.0.tgz",
+ "integrity": "sha512-0ASV06AAoKCDkS2+xw5RXJywruurpbC4JZSm7nr7MOt1ojAzvyyaO+UxZf18j8FCF6kmzCZKcAgN/yu2gm2XgQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/unist": "^3.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/unist-util-visit": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmmirror.com/unist-util-visit/-/unist-util-visit-5.0.0.tgz",
+ "integrity": "sha512-MR04uvD+07cwl/yhVuVWAtw+3GOR/knlL55Nd/wAdblk27GCVt3lqpTivy/tkJcZoNPzTwS1Y+KMojlLDhoTzg==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/unist": "^3.0.0",
+ "unist-util-is": "^6.0.0",
+ "unist-util-visit-parents": "^6.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/unist-util-visit-parents": {
+ "version": "6.0.2",
+ "resolved": "https://registry.npmmirror.com/unist-util-visit-parents/-/unist-util-visit-parents-6.0.2.tgz",
+ "integrity": "sha512-goh1s1TBrqSqukSc8wrjwWhL0hiJxgA8m4kFxGlQ+8FYQ3C/m11FcTs4YYem7V664AhHVvgoQLk890Ssdsr2IQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/unist": "^3.0.0",
+ "unist-util-is": "^6.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/unrs-resolver": {
+ "version": "1.11.1",
+ "resolved": "https://registry.npmmirror.com/unrs-resolver/-/unrs-resolver-1.11.1.tgz",
+ "integrity": "sha512-bSjt9pjaEBnNiGgc9rUiHGKv5l4/TGzDmYw3RhnkJGtLhbnnA/5qJj7x3dNDCRx/PJxu774LlH8lCOlB4hEfKg==",
+ "dev": true,
+ "hasInstallScript": true,
+ "license": "MIT",
+ "dependencies": {
+ "napi-postinstall": "^0.3.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/unrs-resolver"
+ },
+ "optionalDependencies": {
+ "@unrs/resolver-binding-android-arm-eabi": "1.11.1",
+ "@unrs/resolver-binding-android-arm64": "1.11.1",
+ "@unrs/resolver-binding-darwin-arm64": "1.11.1",
+ "@unrs/resolver-binding-darwin-x64": "1.11.1",
+ "@unrs/resolver-binding-freebsd-x64": "1.11.1",
+ "@unrs/resolver-binding-linux-arm-gnueabihf": "1.11.1",
+ "@unrs/resolver-binding-linux-arm-musleabihf": "1.11.1",
+ "@unrs/resolver-binding-linux-arm64-gnu": "1.11.1",
+ "@unrs/resolver-binding-linux-arm64-musl": "1.11.1",
+ "@unrs/resolver-binding-linux-ppc64-gnu": "1.11.1",
+ "@unrs/resolver-binding-linux-riscv64-gnu": "1.11.1",
+ "@unrs/resolver-binding-linux-riscv64-musl": "1.11.1",
+ "@unrs/resolver-binding-linux-s390x-gnu": "1.11.1",
+ "@unrs/resolver-binding-linux-x64-gnu": "1.11.1",
+ "@unrs/resolver-binding-linux-x64-musl": "1.11.1",
+ "@unrs/resolver-binding-wasm32-wasi": "1.11.1",
+ "@unrs/resolver-binding-win32-arm64-msvc": "1.11.1",
+ "@unrs/resolver-binding-win32-ia32-msvc": "1.11.1",
+ "@unrs/resolver-binding-win32-x64-msvc": "1.11.1"
+ }
+ },
+ "node_modules/update-browserslist-db": {
+ "version": "1.1.4",
+ "resolved": "https://registry.npmmirror.com/update-browserslist-db/-/update-browserslist-db-1.1.4.tgz",
+ "integrity": "sha512-q0SPT4xyU84saUX+tomz1WLkxUbuaJnR1xWt17M7fJtEJigJeWUNGUqrauFXsHnqev9y9JTRGwk13tFBuKby4A==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/browserslist"
+ },
+ {
+ "type": "tidelift",
+ "url": "https://tidelift.com/funding/github/npm/browserslist"
+ },
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "escalade": "^3.2.0",
+ "picocolors": "^1.1.1"
+ },
+ "bin": {
+ "update-browserslist-db": "cli.js"
+ },
+ "peerDependencies": {
+ "browserslist": ">= 4.21.0"
+ }
+ },
+ "node_modules/uri-js": {
+ "version": "4.4.1",
+ "resolved": "https://registry.npmmirror.com/uri-js/-/uri-js-4.4.1.tgz",
+ "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==",
+ "dev": true,
+ "license": "BSD-2-Clause",
+ "dependencies": {
+ "punycode": "^2.1.0"
+ }
+ },
+ "node_modules/util-deprecate": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmmirror.com/util-deprecate/-/util-deprecate-1.0.2.tgz",
+ "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/utrie": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmmirror.com/utrie/-/utrie-1.0.2.tgz",
+ "integrity": "sha512-1MLa5ouZiOmQzUbjbu9VmjLzn1QLXBhwpUa7kdLUQK+KQ5KA9I1vk5U4YHe/X2Ch7PYnJfWuWT+VbuxbGwljhw==",
+ "license": "MIT",
+ "dependencies": {
+ "base64-arraybuffer": "^1.0.2"
+ }
+ },
+ "node_modules/uuid": {
+ "version": "11.1.0",
+ "resolved": "https://registry.npmjs.org/uuid/-/uuid-11.1.0.tgz",
+ "integrity": "sha512-0/A9rDy9P7cJ+8w1c9WD9V//9Wj15Ce2MPz8Ri6032usz+NfePxx5AcN3bN+r6ZL6jEo066/yNYB3tn4pQEx+A==",
+ "funding": [
+ "https://github.com/sponsors/broofa",
+ "https://github.com/sponsors/ctavan"
+ ],
+ "license": "MIT",
+ "bin": {
+ "uuid": "dist/esm/bin/uuid"
+ }
+ },
+ "node_modules/vfile": {
+ "version": "6.0.3",
+ "resolved": "https://registry.npmmirror.com/vfile/-/vfile-6.0.3.tgz",
+ "integrity": "sha512-KzIbH/9tXat2u30jf+smMwFCsno4wHVdNmzFyL+T/L3UGqqk6JKfVqOFOZEpZSHADH1k40ab6NUIXZq422ov3Q==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/unist": "^3.0.0",
+ "vfile-message": "^4.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/vfile-location": {
+ "version": "5.0.3",
+ "resolved": "https://registry.npmmirror.com/vfile-location/-/vfile-location-5.0.3.tgz",
+ "integrity": "sha512-5yXvWDEgqeiYiBe1lbxYF7UMAIm/IcopxMHrMQDq3nvKcjPKIhZklUKL+AE7J7uApI4kwe2snsK+eI6UTj9EHg==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/unist": "^3.0.0",
+ "vfile": "^6.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/vfile-message": {
+ "version": "4.0.3",
+ "resolved": "https://registry.npmmirror.com/vfile-message/-/vfile-message-4.0.3.tgz",
+ "integrity": "sha512-QTHzsGd1EhbZs4AsQ20JX1rC3cOlt/IWJruk893DfLRr57lcnOeMaWG4K0JrRta4mIJZKth2Au3mM3u03/JWKw==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/unist": "^3.0.0",
+ "unist-util-stringify-position": "^4.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/vscode-jsonrpc": {
+ "version": "8.2.0",
+ "resolved": "https://registry.npmjs.org/vscode-jsonrpc/-/vscode-jsonrpc-8.2.0.tgz",
+ "integrity": "sha512-C+r0eKJUIfiDIfwJhria30+TYWPtuHJXHtI7J0YlOmKAo7ogxP20T0zxB7HZQIFhIyvoBPwWskjxrvAtfjyZfA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=14.0.0"
+ }
+ },
+ "node_modules/vscode-languageserver": {
+ "version": "9.0.1",
+ "resolved": "https://registry.npmjs.org/vscode-languageserver/-/vscode-languageserver-9.0.1.tgz",
+ "integrity": "sha512-woByF3PDpkHFUreUa7Hos7+pUWdeWMXRd26+ZX2A8cFx6v/JPTtd4/uN0/jB6XQHYaOlHbio03NTHCqrgG5n7g==",
+ "license": "MIT",
+ "dependencies": {
+ "vscode-languageserver-protocol": "3.17.5"
+ },
+ "bin": {
+ "installServerIntoExtension": "bin/installServerIntoExtension"
+ }
+ },
+ "node_modules/vscode-languageserver-protocol": {
+ "version": "3.17.5",
+ "resolved": "https://registry.npmjs.org/vscode-languageserver-protocol/-/vscode-languageserver-protocol-3.17.5.tgz",
+ "integrity": "sha512-mb1bvRJN8SVznADSGWM9u/b07H7Ecg0I3OgXDuLdn307rl/J3A9YD6/eYOssqhecL27hK1IPZAsaqh00i/Jljg==",
+ "license": "MIT",
+ "dependencies": {
+ "vscode-jsonrpc": "8.2.0",
+ "vscode-languageserver-types": "3.17.5"
+ }
+ },
+ "node_modules/vscode-languageserver-textdocument": {
+ "version": "1.0.12",
+ "resolved": "https://registry.npmjs.org/vscode-languageserver-textdocument/-/vscode-languageserver-textdocument-1.0.12.tgz",
+ "integrity": "sha512-cxWNPesCnQCcMPeenjKKsOCKQZ/L6Tv19DTRIGuLWe32lyzWhihGVJ/rcckZXJxfdKCFvRLS3fpBIsV/ZGX4zA==",
+ "license": "MIT"
+ },
+ "node_modules/vscode-languageserver-types": {
+ "version": "3.17.5",
+ "resolved": "https://registry.npmjs.org/vscode-languageserver-types/-/vscode-languageserver-types-3.17.5.tgz",
+ "integrity": "sha512-Ld1VelNuX9pdF39h2Hgaeb5hEZM2Z3jUrrMgWQAu82jMtZp7p3vJT3BzToKtZI7NgQssZje5o0zryOrhQvzQAg==",
+ "license": "MIT"
+ },
+ "node_modules/vscode-uri": {
+ "version": "3.0.8",
+ "resolved": "https://registry.npmjs.org/vscode-uri/-/vscode-uri-3.0.8.tgz",
+ "integrity": "sha512-AyFQ0EVmsOZOlAnxoFOGOq1SQDWAB7C6aqMGS23svWAllfOaxbuFvcT8D1i8z3Gyn8fraVeZNNmN6e9bxxXkKw==",
+ "license": "MIT"
+ },
+ "node_modules/watchpack": {
+ "version": "2.4.0",
+ "resolved": "https://registry.npmmirror.com/watchpack/-/watchpack-2.4.0.tgz",
+ "integrity": "sha512-Lcvm7MGST/4fup+ifyKi2hjyIAwcdI4HRgtvTpIUxBRhB+RFtUh8XtDOxUfctVCnhVi+QQj49i91OyvzkJl6cg==",
+ "license": "MIT",
+ "dependencies": {
+ "glob-to-regexp": "^0.4.1",
+ "graceful-fs": "^4.1.2"
+ },
+ "engines": {
+ "node": ">=10.13.0"
+ }
+ },
+ "node_modules/web-namespaces": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmmirror.com/web-namespaces/-/web-namespaces-2.0.1.tgz",
+ "integrity": "sha512-bKr1DkiNa2krS7qxNtdrtHAmzuYGFQLiQ13TsorsdT6ULTkPLKuu5+GsFpDlg6JFjUTwX2DyhMPG2be8uPrqsQ==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
+ "node_modules/which": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmmirror.com/which/-/which-2.0.2.tgz",
+ "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "isexe": "^2.0.0"
+ },
+ "bin": {
+ "node-which": "bin/node-which"
+ },
+ "engines": {
+ "node": ">= 8"
+ }
+ },
+ "node_modules/which-boxed-primitive": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmmirror.com/which-boxed-primitive/-/which-boxed-primitive-1.1.1.tgz",
+ "integrity": "sha512-TbX3mj8n0odCBFVlY8AxkqcHASw3L60jIuF8jFP78az3C2YhmGvqbHBpAjTRH2/xqYunrJ9g1jSyjCjpoWzIAA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "is-bigint": "^1.1.0",
+ "is-boolean-object": "^1.2.1",
+ "is-number-object": "^1.1.1",
+ "is-string": "^1.1.1",
+ "is-symbol": "^1.1.1"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/which-builtin-type": {
+ "version": "1.2.1",
+ "resolved": "https://registry.npmmirror.com/which-builtin-type/-/which-builtin-type-1.2.1.tgz",
+ "integrity": "sha512-6iBczoX+kDQ7a3+YJBnh3T+KZRxM/iYNPXicqk66/Qfm1b93iu+yOImkg0zHbj5LNOcNv1TEADiZ0xa34B4q6Q==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bound": "^1.0.2",
+ "function.prototype.name": "^1.1.6",
+ "has-tostringtag": "^1.0.2",
+ "is-async-function": "^2.0.0",
+ "is-date-object": "^1.1.0",
+ "is-finalizationregistry": "^1.1.0",
+ "is-generator-function": "^1.0.10",
+ "is-regex": "^1.2.1",
+ "is-weakref": "^1.0.2",
+ "isarray": "^2.0.5",
+ "which-boxed-primitive": "^1.1.0",
+ "which-collection": "^1.0.2",
+ "which-typed-array": "^1.1.16"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/which-collection": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmmirror.com/which-collection/-/which-collection-1.0.2.tgz",
+ "integrity": "sha512-K4jVyjnBdgvc86Y6BkaLZEN933SwYOuBFkdmBu9ZfkcAbdVbpITnDmjvZ/aQjRXQrv5EPkTnD1s39GiiqbngCw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "is-map": "^2.0.3",
+ "is-set": "^2.0.3",
+ "is-weakmap": "^2.0.2",
+ "is-weakset": "^2.0.3"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/which-typed-array": {
+ "version": "1.1.19",
+ "resolved": "https://registry.npmmirror.com/which-typed-array/-/which-typed-array-1.1.19.tgz",
+ "integrity": "sha512-rEvr90Bck4WZt9HHFC4DJMsjvu7x+r6bImz0/BrbWb7A2djJ8hnZMrWnHo9F8ssv0OMErasDhftrfROTyqSDrw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "available-typed-arrays": "^1.0.7",
+ "call-bind": "^1.0.8",
+ "call-bound": "^1.0.4",
+ "for-each": "^0.3.5",
+ "get-proto": "^1.0.1",
+ "gopd": "^1.2.0",
+ "has-tostringtag": "^1.0.2"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/word-wrap": {
+ "version": "1.2.5",
+ "resolved": "https://registry.npmmirror.com/word-wrap/-/word-wrap-1.2.5.tgz",
+ "integrity": "sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/wrappy": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmmirror.com/wrappy/-/wrappy-1.0.2.tgz",
+ "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==",
+ "dev": true,
+ "license": "ISC"
+ },
+ "node_modules/yocto-queue": {
+ "version": "0.1.0",
+ "resolved": "https://registry.npmmirror.com/yocto-queue/-/yocto-queue-0.1.0.tgz",
+ "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=10"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/zwitch": {
+ "version": "2.0.4",
+ "resolved": "https://registry.npmmirror.com/zwitch/-/zwitch-2.0.4.tgz",
+ "integrity": "sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ }
+ }
+}
diff --git a/web/package.json b/web/package.json
new file mode 100644
index 000000000..d899423f2
--- /dev/null
+++ b/web/package.json
@@ -0,0 +1,40 @@
+{
+ "name": "opentutor-web",
+ "version": "0.1.0",
+ "private": true,
+ "scripts": {
+ "dev": "next dev",
+ "build": "next build",
+ "start": "next start",
+ "lint": "next lint"
+ },
+ "dependencies": {
+ "clsx": "^2.0.0",
+ "cytoscape": "^3.33.1",
+ "framer-motion": "^10.16.4",
+ "html2canvas": "^1.4.1",
+ "jspdf": "^2.5.1",
+ "lucide-react": "^0.294.0",
+ "mermaid": "^11.12.2",
+ "next": "14.0.3",
+ "react": "^18",
+ "react-dom": "^18",
+ "react-markdown": "^9.0.1",
+ "rehype-katex": "^7.0.0",
+ "rehype-raw": "^7.0.0",
+ "remark-gfm": "^4.0.0",
+ "remark-math": "^6.0.0",
+ "tailwind-merge": "^2.0.0"
+ },
+ "devDependencies": {
+ "@types/node": "^20",
+ "@types/react": "^18",
+ "@types/react-dom": "^18",
+ "autoprefixer": "^10.0.1",
+ "eslint": "^8",
+ "eslint-config-next": "14.0.3",
+ "postcss": "^8",
+ "tailwindcss": "^3.3.0",
+ "typescript": "^5"
+ }
+}
diff --git a/web/postcss.config.js b/web/postcss.config.js
new file mode 100644
index 000000000..12a703d90
--- /dev/null
+++ b/web/postcss.config.js
@@ -0,0 +1,6 @@
+module.exports = {
+ plugins: {
+ tailwindcss: {},
+ autoprefixer: {},
+ },
+};
diff --git a/web/public/logo.png b/web/public/logo.png
new file mode 100644
index 000000000..856aee98b
Binary files /dev/null and b/web/public/logo.png differ
diff --git a/web/tailwind.config.js b/web/tailwind.config.js
new file mode 100644
index 000000000..fb5ed7e62
--- /dev/null
+++ b/web/tailwind.config.js
@@ -0,0 +1,54 @@
+/** @type {import('tailwindcss').Config} */
+module.exports = {
+ darkMode: "class",
+ content: [
+ "./pages/**/*.{js,ts,jsx,tsx,mdx}",
+ "./components/**/*.{js,ts,jsx,tsx,mdx}",
+ "./app/**/*.{js,ts,jsx,tsx,mdx}",
+ ],
+ theme: {
+ extend: {
+ colors: {
+ border: "hsl(var(--border))",
+ input: "hsl(var(--input))",
+ ring: "hsl(var(--ring))",
+ background: "hsl(var(--background))",
+ foreground: "hsl(var(--foreground))",
+ primary: {
+ DEFAULT: "hsl(var(--primary))",
+ foreground: "hsl(var(--primary-foreground))",
+ },
+ secondary: {
+ DEFAULT: "hsl(var(--secondary))",
+ foreground: "hsl(var(--secondary-foreground))",
+ },
+ destructive: {
+ DEFAULT: "hsl(var(--destructive))",
+ foreground: "hsl(var(--destructive-foreground))",
+ },
+ muted: {
+ DEFAULT: "hsl(var(--muted))",
+ foreground: "hsl(var(--muted-foreground))",
+ },
+ accent: {
+ DEFAULT: "hsl(var(--accent))",
+ foreground: "hsl(var(--accent-foreground))",
+ },
+ popover: {
+ DEFAULT: "hsl(var(--popover))",
+ foreground: "hsl(var(--popover-foreground))",
+ },
+ card: {
+ DEFAULT: "hsl(var(--card))",
+ foreground: "hsl(var(--card-foreground))",
+ },
+ },
+ backgroundImage: {
+ "gradient-radial": "radial-gradient(var(--tw-gradient-stops))",
+ "gradient-conic":
+ "conic-gradient(from 180deg at 50% 50%, var(--tw-gradient-stops))",
+ },
+ },
+ },
+ plugins: [],
+};
diff --git a/web/tsconfig.json b/web/tsconfig.json
new file mode 100644
index 000000000..c71469637
--- /dev/null
+++ b/web/tsconfig.json
@@ -0,0 +1,27 @@
+{
+ "compilerOptions": {
+ "target": "es5",
+ "lib": ["dom", "dom.iterable", "esnext"],
+ "allowJs": true,
+ "skipLibCheck": true,
+ "strict": true,
+ "noEmit": true,
+ "esModuleInterop": true,
+ "module": "esnext",
+ "moduleResolution": "bundler",
+ "resolveJsonModule": true,
+ "isolatedModules": true,
+ "jsx": "preserve",
+ "incremental": true,
+ "plugins": [
+ {
+ "name": "next"
+ }
+ ],
+ "paths": {
+ "@/*": ["./*"]
+ }
+ },
+ "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
+ "exclude": ["node_modules"]
+}
diff --git a/web/types/question.ts b/web/types/question.ts
new file mode 100644
index 000000000..8fe1bb949
--- /dev/null
+++ b/web/types/question.ts
@@ -0,0 +1,262 @@
+// Question generation types for the Dashboard UI
+
+export interface QuestionFocus {
+ id: string;
+ focus: string;
+ scenario_hint?: string;
+}
+
+export interface QuestionValidation {
+ decision?:
+ | "approve"
+ | "request_modification"
+ | "request_regeneration"
+ | "extended";
+ issues?: string[];
+ suggestions?: string[];
+ reasoning?: string;
+ // Extension analysis fields (for extended questions)
+ kb_connection?: string;
+ extended_aspect?: string;
+ // Relevance analysis fields (for custom mode)
+ relevance?: "high" | "partial";
+ kb_coverage?: string;
+ extension_points?: string;
+}
+
+// Question Plan (for custom mode)
+export interface QuestionPlan {
+ knowledge_point: string;
+ difficulty: string;
+ question_type: string;
+ num_questions: number;
+ focuses: QuestionFocus[];
+}
+
+export interface GeneratedQuestion {
+ question_type?: string;
+ type?: string;
+ question: string;
+ options?: Record<string, string>;
+ correct_answer: string;
+ explanation: string;
+ knowledge_point?: string;
+}
+
+export interface QuestionResult {
+ success: boolean;
+ question_id: string;
+ question: GeneratedQuestion;
+ validation: QuestionValidation;
+ rounds: number;
+ focus?: QuestionFocus;
+ // Extended question indicator
+ extended?: boolean;
+}
+
+export interface QuestionFailure {
+ question_id: string;
+ error: string;
+ reason?: string;
+}
+
+export interface QuestionTask {
+ id: string;
+ focus: string;
+ scenarioHint?: string;
+ status:
+ | "pending"
+ | "generating"
+ | "analyzing"
+ | "validating"
+ | "done"
+ | "error";
+ round?: number;
+ maxRounds?: number;
+ result?: QuestionResult;
+ error?: string;
+ extended?: boolean; // Whether this is an extended question
+ lastUpdate: number;
+}
+
+export interface QuestionProgress {
+ stage:
+ | "idle"
+ | "planning"
+ | "researching"
+ | "generating"
+ | "complete"
+ // Mimic mode stages
+ | "uploading"
+ | "parsing"
+ | "extracting";
+ status?: string;
+ message?: string; // Progress message for display
+ // Planning
+ queries?: string[];
+ // Generating
+ current?: number;
+ total?: number;
+ round?: number;
+ maxRounds?: number;
+ // Focuses
+ focuses?: QuestionFocus[];
+ // Mimic mode - reference questions info
+ referenceQuestions?: Array<{
+ number: string;
+ preview: string;
+ }>;
+}
+
+export interface QuestionState {
+ // Global state
+ global: {
+ stage:
+ | "idle"
+ | "planning"
+ | "researching"
+ | "generating"
+ | "complete"
+ // Mimic mode stages
+ | "uploading"
+ | "parsing"
+ | "extracting";
+ startTime: number;
+ totalQuestions: number;
+ completedQuestions: number;
+ failedQuestions: number;
+ extendedQuestions: number; // Count of extended questions
+ topic?: string;
+ // Mimic mode specific
+ mode?: "custom" | "mimic";
+ referenceQuestions?: Array<{
+ number: string;
+ preview: string;
+ }>;
+ };
+ // Planning stage
+ planning: {
+ topic: string;
+ difficulty: string;
+ questionType: string;
+ queries: string[];
+ progress: string;
+ };
+ // Question tasks
+ tasks: Record<string, QuestionTask>;
+ activeTaskIds: string[];
+ // Results
+ results: QuestionResult[];
+ failures: QuestionFailure[];
+ // Shared context summary (truncated for display)
+ sharedContextPreview?: string;
+ // Sub-focuses assigned to each question
+ subFocuses: QuestionFocus[];
+ // Logs
+ logs: QuestionLogEntry[];
+}
+
+export interface QuestionLogEntry {
+ id: string;
+ timestamp: number;
+ type: "info" | "success" | "warning" | "error" | "system";
+ content: string;
+}
+
+// WebSocket Event Types
+export type QuestionEventType =
+ // Progress events
+ | "progress"
+ | "question_update"
+ | "question_result"
+ | "question_error"
+ | "batch_summary"
+ // Custom mode events
+ | "knowledge_saved"
+ | "plan_ready"
+ // Mimic mode events
+ | "summary" // Mimic mode final summary
+ // Status events
+ | "status"
+ | "agent_status"
+ | "token_stats"
+ // Result events
+ | "result"
+ | "complete"
+ | "error"
+ | "log";
+
+export interface QuestionEvent {
+ type: QuestionEventType;
+ // Progress fields
+ stage?: string;
+ status?: string;
+ message?: string; // Progress message for display
+ // Question-specific
+ question_id?: string;
+ question?: GeneratedQuestion;
+ validation?: QuestionValidation;
+ rounds?: number;
+ focus?: QuestionFocus;
+ // Batch fields
+ requested?: number;
+ completed?: number;
+ failed?: number;
+ total?: number;
+ current?: number;
+ sub_focuses?: QuestionFocus[];
+ focuses?: QuestionFocus[];
+ queries?: string[];
+ // Custom mode fields
+ plan?: QuestionPlan;
+ // Mimic mode fields
+ reference_question?: string;
+ reference_number?: string;
+ reference_preview?: string;
+ reference_questions?: Array<{
+ number: string;
+ preview: string;
+ }>;
+ total_questions?: number;
+ successful?: number;
+ total_reference?: number;
+ output_file?: string;
+ // Generic
+ content?: string;
+ index?: number;
+ success?: boolean;
+ error?: string;
+ [key: string]: any;
+}
+
+// Token stats
+export interface QuestionTokenStats {
+ model: string;
+ calls: number;
+ tokens: number;
+ input_tokens: number;
+ output_tokens: number;
+ cost: number;
+}
+
+// Agent status
+export interface QuestionAgentStatus {
+ [key: string]: "pending" | "running" | "done" | "error";
+}
+
+// Config for question generation
+export interface QuestionConfig {
+ topic: string;
+ difficulty: "easy" | "medium" | "hard";
+ type: "choice" | "written";
+ count: number;
+ selectedKb: string;
+}
+
+// Mimic mode config
+export interface MimicConfig {
+ uploadedFile: File | null;
+ paperPath: string;
+ selectedKb: string;
+ maxQuestions?: number;
+}
diff --git a/web/types/research.ts b/web/types/research.ts
new file mode 100644
index 000000000..7655815f8
--- /dev/null
+++ b/web/types/research.ts
@@ -0,0 +1,161 @@
+export interface TopicBlock {
+ block_id: string;
+ sub_topic: string;
+ overview: string;
+ status: "pending" | "researching" | "completed" | "failed";
+ tool_traces: ToolTrace[];
+ iteration_count: number;
+ created_at: string;
+ updated_at: string;
+ metadata?: Record<string, any>;
+}
+
+export interface ToolTrace {
+ tool_id?: string; // Optional as it might not be populated in all contexts
+ citation_id?: string;
+ tool_type: string;
+ query: string;
+ raw_answer: string;
+ summary: string;
+ timestamp?: string;
+ raw_answer_truncated?: boolean;
+ raw_answer_original_size?: number;
+}
+
+export interface ThoughtEntry {
+ type: "sufficiency" | "plan" | "tool_call" | "note" | "error";
+ content: string;
+ metadata?: Record<string, any>;
+ timestamp: number;
+}
+
+export interface TaskState {
+ id: string;
+ topic: string;
+ status: "pending" | "running" | "completed" | "failed";
+ iteration: number;
+ maxIterations: number;
+ currentAction: string; // e.g. "Searching web for..."
+ toolsUsed: string[];
+ thoughts: ThoughtEntry[]; // Record chain of thought (Sufficiency -> Query -> Tool)
+ lastUpdate: number;
+ // Specific fields for parallel mode display
+ currentTool?: string;
+ currentQuery?: string;
+}
+
+export interface OutlineSubsection {
+ title: string;
+ instruction: string;
+}
+
+export interface OutlineSection {
+ title: string;
+ instruction: string;
+ block_id?: string;
+ subsections?: OutlineSubsection[];
+}
+
+export interface ReportOutline {
+ title: string;
+ introduction: string;
+ introduction_instruction?: string;
+ sections: OutlineSection[];
+ conclusion: string;
+ conclusion_instruction?: string;
+}
+
+export interface LogEntry {
+ id: string;
+ timestamp: number;
+ type: "info" | "success" | "warning" | "error";
+ message: string;
+ details?: any;
+}
+
+export interface ResearchState {
+ global: {
+ stage: "idle" | "planning" | "researching" | "reporting" | "completed";
+ startTime: number;
+ totalBlocks: number;
+ completedBlocks: number;
+ topic?: string; // Main topic
+ };
+ // Planning stage data
+ planning: {
+ originalTopic: string;
+ optimizedTopic: string;
+ subTopics: TopicBlock[];
+ progress: string; // Current planning step description
+ };
+ // Research stage data (Core)
+ tasks: Record<string, TaskState>; // block_id -> detailed state
+ activeTaskIds: string[]; // IDs of tasks currently running in parallel
+ executionMode: "series" | "parallel";
+
+ // Reporting stage data
+ reporting: {
+ outline: ReportOutline | null;
+ progress: string; // Current reporting step description
+ generatedReport?: string;
+ wordCount?: number;
+ sectionCount?: number;
+ citationCount?: number;
+ // Current writing progress
+ currentSection?: string;
+ sectionIndex?: number;
+ totalSections?: number;
+ };
+ logs: LogEntry[]; // Global log stream
+}
+
+// WebSocket Event Types
+export type ResearchEventType =
+ // Planning
+ | "planning_started"
+ | "rephrase_completed"
+ | "decompose_started"
+ | "decompose_completed"
+ | "queue_seeded"
+ | "planning_completed"
+
+ // Researching - Pipeline
+ | "researching_started"
+ | "parallel_status_update"
+ | "block_started"
+ | "block_completed"
+ | "block_failed"
+ | "researching_completed"
+
+ // Researching - Agent
+ | "iteration_started"
+ | "checking_sufficiency"
+ | "knowledge_sufficient"
+ | "generating_query"
+ | "tool_calling"
+ | "tool_completed"
+ | "processing_notes"
+ | "iteration_completed"
+ | "new_topic_added"
+
+ // Reporting
+ | "reporting_started"
+ | "deduplicate_completed"
+ | "outline_completed"
+ | "writing_section"
+ | "writing_completed"
+ | "reporting_completed"
+
+ // System
+ | "log"
+ | "error"
+ | "status";
+
+export interface ResearchEvent {
+ type: ResearchEventType;
+ stage?: string;
+ status?: string;
+ timestamp?: string;
+ research_id?: string;
+ [key: string]: any; // Payload
+}