Showing preview only (2,171K chars total). Download the full file or copy to clipboard to get everything.
Repository: HKUDS/DeepCode
Branch: main
Commit: b5c741ab572a
Files: 255
Total size: 2.0 MB
Directory structure:
gitextract_3wtguj4a/
├── .dockerignore
├── .gitattributes
├── .github/
│ ├── ISSUE_TEMPLATE/
│ │ ├── bug_report.yml
│ │ ├── config.yml
│ │ ├── feature_request.yml
│ │ └── question.yml
│ ├── dependabot.yml
│ ├── pull_request_template.md
│ └── workflows/
│ ├── linting.yaml
│ └── pypi-publish.yml
├── .gitignore
├── .pre-commit-config.yaml
├── CHANGELOG.md
├── LICENSE
├── MANIFEST.in
├── README.md
├── README_ZH.md
├── __init__.py
├── cli/
│ ├── __init__.py
│ ├── cli_app.py
│ ├── cli_interface.py
│ ├── cli_launcher.py
│ ├── main_cli.py
│ └── workflows/
│ ├── __init__.py
│ └── cli_workflow_adapter.py
├── config/
│ ├── mcp_tool_definitions.py
│ └── mcp_tool_definitions_index.py
├── deepcode.py
├── deepcode_docker/
│ ├── .dockerignore
│ ├── Dockerfile
│ ├── docker-compose.yml
│ ├── docker-entrypoint.sh
│ └── run_docker.sh
├── mcp_agent.config.yaml
├── mcp_agent.secrets.yaml.example
├── nanobot/
│ ├── .dockerignore
│ ├── .gitignore
│ ├── COMMUNICATION.md
│ ├── Dockerfile
│ ├── LICENSE
│ ├── README.md
│ ├── SECURITY.md
│ ├── bridge/
│ │ ├── package.json
│ │ ├── src/
│ │ │ ├── index.ts
│ │ │ ├── server.ts
│ │ │ ├── types.d.ts
│ │ │ └── whatsapp.ts
│ │ └── tsconfig.json
│ ├── core_agent_lines.sh
│ ├── nanobot/
│ │ ├── __init__.py
│ │ ├── __main__.py
│ │ ├── agent/
│ │ │ ├── __init__.py
│ │ │ ├── context.py
│ │ │ ├── loop.py
│ │ │ ├── memory.py
│ │ │ ├── skills.py
│ │ │ ├── subagent.py
│ │ │ └── tools/
│ │ │ ├── __init__.py
│ │ │ ├── base.py
│ │ │ ├── cron.py
│ │ │ ├── deepcode.py
│ │ │ ├── filesystem.py
│ │ │ ├── message.py
│ │ │ ├── registry.py
│ │ │ ├── shell.py
│ │ │ ├── spawn.py
│ │ │ └── web.py
│ │ ├── bus/
│ │ │ ├── __init__.py
│ │ │ ├── events.py
│ │ │ └── queue.py
│ │ ├── channels/
│ │ │ ├── __init__.py
│ │ │ ├── base.py
│ │ │ ├── dingtalk.py
│ │ │ ├── discord.py
│ │ │ ├── email.py
│ │ │ ├── feishu.py
│ │ │ ├── manager.py
│ │ │ ├── qq.py
│ │ │ ├── slack.py
│ │ │ ├── telegram.py
│ │ │ └── whatsapp.py
│ │ ├── cli/
│ │ │ ├── __init__.py
│ │ │ └── commands.py
│ │ ├── config/
│ │ │ ├── __init__.py
│ │ │ ├── loader.py
│ │ │ └── schema.py
│ │ ├── cron/
│ │ │ ├── __init__.py
│ │ │ ├── service.py
│ │ │ └── types.py
│ │ ├── heartbeat/
│ │ │ ├── __init__.py
│ │ │ └── service.py
│ │ ├── providers/
│ │ │ ├── __init__.py
│ │ │ ├── base.py
│ │ │ ├── litellm_provider.py
│ │ │ ├── registry.py
│ │ │ └── transcription.py
│ │ ├── session/
│ │ │ ├── __init__.py
│ │ │ └── manager.py
│ │ ├── skills/
│ │ │ ├── README.md
│ │ │ ├── cron/
│ │ │ │ └── SKILL.md
│ │ │ ├── deepcode/
│ │ │ │ └── SKILL.md
│ │ │ ├── github/
│ │ │ │ └── SKILL.md
│ │ │ ├── skill-creator/
│ │ │ │ └── SKILL.md
│ │ │ ├── summarize/
│ │ │ │ └── SKILL.md
│ │ │ ├── tmux/
│ │ │ │ ├── SKILL.md
│ │ │ │ └── scripts/
│ │ │ │ ├── find-sessions.sh
│ │ │ │ └── wait-for-text.sh
│ │ │ └── weather/
│ │ │ └── SKILL.md
│ │ └── utils/
│ │ ├── __init__.py
│ │ └── helpers.py
│ ├── pyproject.toml
│ ├── run_nanobot.sh
│ └── workspace/
│ ├── AGENTS.md
│ ├── HEARTBEAT.md
│ ├── SOUL.md
│ ├── TOOLS.md
│ ├── USER.md
│ └── memory/
│ └── MEMORY.md
├── nanobot_config.json.example
├── new_ui/
│ ├── README.md
│ ├── backend/
│ │ ├── __init__.py
│ │ ├── api/
│ │ │ ├── __init__.py
│ │ │ ├── routes/
│ │ │ │ ├── __init__.py
│ │ │ │ ├── config.py
│ │ │ │ ├── files.py
│ │ │ │ ├── requirements.py
│ │ │ │ └── workflows.py
│ │ │ └── websockets/
│ │ │ ├── __init__.py
│ │ │ ├── code_stream_ws.py
│ │ │ ├── logs_ws.py
│ │ │ └── workflow_ws.py
│ │ ├── app_utils/
│ │ │ └── __init__.py
│ │ ├── main.py
│ │ ├── models/
│ │ │ ├── __init__.py
│ │ │ ├── requests.py
│ │ │ └── responses.py
│ │ ├── services/
│ │ │ ├── __init__.py
│ │ │ ├── requirement_service.py
│ │ │ ├── session_service.py
│ │ │ └── workflow_service.py
│ │ └── settings.py
│ ├── frontend/
│ │ ├── index.html
│ │ ├── package.json
│ │ ├── postcss.config.js
│ │ ├── src/
│ │ │ ├── App.tsx
│ │ │ ├── components/
│ │ │ │ ├── common/
│ │ │ │ │ ├── Button.tsx
│ │ │ │ │ ├── Card.tsx
│ │ │ │ │ ├── ConfirmDialog.tsx
│ │ │ │ │ ├── GuardedLink.tsx
│ │ │ │ │ ├── TaskRecoveryBanner.tsx
│ │ │ │ │ ├── Toaster.tsx
│ │ │ │ │ └── index.ts
│ │ │ │ ├── input/
│ │ │ │ │ ├── ChatInput.tsx
│ │ │ │ │ ├── FileUploader.tsx
│ │ │ │ │ ├── UrlInput.tsx
│ │ │ │ │ └── index.ts
│ │ │ │ ├── interaction/
│ │ │ │ │ ├── InlineChatInteraction.tsx
│ │ │ │ │ ├── InteractionPanel.tsx
│ │ │ │ │ └── index.ts
│ │ │ │ ├── layout/
│ │ │ │ │ ├── Header.tsx
│ │ │ │ │ ├── Layout.tsx
│ │ │ │ │ ├── Sidebar.tsx
│ │ │ │ │ └── index.ts
│ │ │ │ ├── results/
│ │ │ │ │ ├── CodePreview.tsx
│ │ │ │ │ ├── FileTree.tsx
│ │ │ │ │ └── index.ts
│ │ │ │ ├── streaming/
│ │ │ │ │ ├── ActivityLogViewer.tsx
│ │ │ │ │ ├── CodeStreamViewer.tsx
│ │ │ │ │ ├── LogViewer.tsx
│ │ │ │ │ ├── ProgressTracker.tsx
│ │ │ │ │ └── index.ts
│ │ │ │ └── workflow/
│ │ │ │ ├── WorkflowCanvas.tsx
│ │ │ │ ├── WorkflowNode.tsx
│ │ │ │ └── index.ts
│ │ │ ├── hooks/
│ │ │ │ ├── index.ts
│ │ │ │ ├── useAdaptiveLayout.ts
│ │ │ │ ├── useNavigationGuard.ts
│ │ │ │ ├── useStreaming.ts
│ │ │ │ ├── useTaskRecovery.ts
│ │ │ │ └── useWebSocket.ts
│ │ │ ├── index.css
│ │ │ ├── main.tsx
│ │ │ ├── pages/
│ │ │ │ ├── ChatPlanningPage.tsx
│ │ │ │ ├── HomePage.tsx
│ │ │ │ ├── PaperToCodePage.tsx
│ │ │ │ ├── SettingsPage.tsx
│ │ │ │ ├── WorkflowEditorPage.tsx
│ │ │ │ └── index.ts
│ │ │ ├── services/
│ │ │ │ └── api.ts
│ │ │ ├── stores/
│ │ │ │ ├── index.ts
│ │ │ │ ├── sessionStore.ts
│ │ │ │ └── workflowStore.ts
│ │ │ └── types/
│ │ │ ├── api.ts
│ │ │ ├── common.ts
│ │ │ ├── index.ts
│ │ │ └── workflow.ts
│ │ ├── tailwind.config.js
│ │ ├── tsconfig.json
│ │ ├── tsconfig.node.json
│ │ └── vite.config.ts
│ └── scripts/
│ ├── build.sh
│ └── start_dev.sh
├── prompts/
│ └── code_prompts.py
├── requirements.txt
├── run.bat
├── run.sh
├── schema/
│ └── mcp-agent.config.schema.json
├── setup.py
├── tools/
│ ├── __init__.py
│ ├── bocha_search_server.py
│ ├── code_implementation_server.py
│ ├── code_indexer.py
│ ├── code_reference_indexer.py
│ ├── command_executor.py
│ ├── document_segmentation_server.py
│ ├── git_command.py
│ ├── indexer_config.yaml
│ ├── pdf_converter.py
│ ├── pdf_downloader.py
│ └── pdf_utils.py
├── ui/
│ ├── __init__.py
│ ├── app.py
│ ├── components.py
│ ├── handlers.py
│ ├── layout.py
│ ├── sidebar_feed.py
│ ├── streamlit_app.py
│ └── styles.py
├── utils/
│ ├── __init__.py
│ ├── cli_interface.py
│ ├── cross_platform_file_handler.py
│ ├── dialogue_logger.py
│ ├── file_processor.py
│ ├── llm_utils.py
│ ├── loop_detector.py
│ ├── model_limits.py
│ └── simple_llm_logger.py
└── workflows/
├── __init__.py
├── agent_orchestration_engine.py
├── agents/
│ ├── __init__.py
│ ├── code_implementation_agent.py
│ ├── document_segmentation_agent.py
│ ├── memory_agent_concise.py
│ ├── memory_agent_concise_index.py
│ ├── memory_agent_concise_multi.py
│ └── requirement_analysis_agent.py
├── code_implementation_workflow.py
├── code_implementation_workflow_index.py
├── codebase_index_workflow.py
└── plugins/
├── USAGE.md
├── __init__.py
├── base.py
├── integration.py
├── plan_review.py
└── requirement_analysis.py
================================================
FILE CONTENTS
================================================
================================================
FILE: .dockerignore
================================================
# Git
.git
.gitignore
# Node
new_ui/frontend/node_modules
new_ui/frontend/dist
# Python
__pycache__
*.pyc
*.pyo
*.egg-info
.eggs
dist
build
# Virtual environments
.venv
venv
env
# IDE
.vscode
.idea
.cursor
*.swp
*.swo
# Runtime data
deepcode_lab
uploads
logs
*.log
# Docker
deepcode_docker/Dockerfile
deepcode_docker/docker-compose.yml
deepcode_docker/.dockerignore
deepcode_docker/run_docker.sh
# Documentation
assets
*.md
LICENSE
================================================
FILE: .gitattributes
================================================
# Force LF line endings for shell scripts (prevents CRLF issues in Docker)
*.sh text eol=lf
docker-entrypoint.sh text eol=lf
================================================
FILE: .github/ISSUE_TEMPLATE/bug_report.yml
================================================
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: How can we replicate the issue?
- 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: textarea
id: configused
attributes:
label: DeepCode Config Used
description: The DeepCode configuration used for the run.
placeholder: The settings content or DeepCode configuration
value: |
# Paste your config here
- 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: |
- DeepCode Version: e.g., v0.1.1
- Operating System: e.g., Windows 10, Ubuntu 20.04
- Python Version: e.g., 3.8
- Related Issues: e.g., #1
- Any other relevant information.
value: |
- DeepCode Version:
- Operating System:
- Python Version:
- Related Issues:
================================================
FILE: .github/ISSUE_TEMPLATE/config.yml
================================================
blank_issues_enabled: false
================================================
FILE: .github/ISSUE_TEMPLATE/feature_request.yml
================================================
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 this feature request add more or improve?
- 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
================================================
FILE: .github/ISSUE_TEMPLATE/question.yml
================================================
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 question 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: 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
================================================
FILE: .github/dependabot.yml
================================================
# To get started with Dependabot version updates, you'll need to specify which
# package ecosystems to update and where the package manifests are located.
# Please see the documentation for all configuration options:
# https://docs.github.com/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file
version: 2
updates:
- package-ecosystem: "pip" # See documentation for possible values
directory: "/" # Location of package manifests
schedule:
interval: "weekly"
================================================
FILE: .github/pull_request_template.md
================================================
<!--
Thanks for contributing to DeepCode!
Please ensure your pull request is ready for review before submitting.
About this template
This template helps contributors provide 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.]
## Changes Made
[List the specific changes made in this pull request.]
## Checklist
- [ ] Changes tested locally
- [ ] Code reviewed
- [ ] Documentation updated (if necessary)
- [ ] Unit tests added (if applicable)
## Additional Notes
[Add any additional notes or context for the reviewer(s).]
================================================
FILE: .github/workflows/linting.yaml
================================================
name: Linting and Formatting
on:
push:
branches:
- main
pull_request:
branches:
- main
jobs:
lint-and-format:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v2
- name: Set up Python
uses: actions/setup-python@v2
with:
python-version: '3.x'
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install pre-commit
- name: Run pre-commit
run: pre-commit run --all-files --show-diff-on-failure
================================================
FILE: .github/workflows/pypi-publish.yml
================================================
name: Upload DeepCode Package
on:
release:
types: [published]
permissions:
contents: read
jobs:
release-build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.x"
- name: Build release distributions
run: |
python -m pip install build
python -m build
- name: Upload distributions
uses: actions/upload-artifact@v4
with:
name: release-dists
path: dist/
pypi-publish:
runs-on: ubuntu-latest
needs:
- release-build
permissions:
id-token: write
environment:
name: pypi
steps:
- name: Retrieve release distributions
uses: actions/download-artifact@v4
with:
name: release-dists
path: dist/
- name: Publish release distributions to PyPI
uses: pypa/gh-action-pypi-publish@release/v1
with:
packages-dir: dist/
================================================
FILE: .gitignore
================================================
# Python-related files
__pycache__/
*.py[cod]
*.egg-info/
.eggs/
*.tgz
*.tar.gz
*.ini
# Virtual Environment
.venv/
env/
venv/
*.env*
.env_example
# Build / Distribution
dist/
build/
site/
# Logs / Reports
*.log
*.log.*
*.logfire
*.coverage/
log/
logs/
# Node
node_modules/
# Caches
.cache/
.mypy_cache/
.pytest_cache/
.ruff_cache/
.gradio/
.history/
temp/
# IDE / Editor Files
.idea/
.vscode/
.vscode/settings.json
# Framework-specific files
local_neo4jWorkDir/
neo4jWorkDir/
# Data & Storage
inputs/
rag_storage/
examples/input/
examples/output/
deepcode-mcp/agent_folders
# Miscellaneous
.DS_Store
TODO.md
ignore_this.txt
*.ignore.*
# unit-test files
test_*
run_indexer_with_filtering.py
# Cline files
memory-bank/
# project files
deepcode_lab/
# secrets (use .env or environment variables instead)
mcp_agent.secrets.yaml
nanobot_config.json
================================================
FILE: .pre-commit-config.yaml
================================================
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v5.0.0
hooks:
- id: trailing-whitespace
- id: end-of-file-fixer
- id: requirements-txt-fixer
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.6.4
hooks:
- id: ruff-format
- id: ruff
args: [--fix, --ignore=E402]
- repo: https://github.com/mgedmin/check-manifest
rev: "0.49"
hooks:
- id: check-manifest
stages: [manual]
================================================
FILE: CHANGELOG.md
================================================
# Changelog
All notable changes to DeepCode will be documented in this file.
## [1.0.6-jm] - 2025-10-19
### Added
- **Dynamic Model Limit Detection**: New `utils/model_limits.py` module that automatically detects and adapts to any LLM model's token limits and pricing
- **Loop Detection System**: `utils/loop_detector.py` prevents infinite loops by detecting repeated tool calls, timeouts, and progress stalls
- **Progress Tracking**: 8-phase progress tracking (5% → 100%) with file-level progress indicators in both UI and terminal
- **Abort Mechanism**: "Stop Processing" button in UI with global abort flag for clean process termination
- **Cache Cleanup Scripts**: `start_clean.bat` and `start_clean.ps1` to clear Python cache before starting
- **Enhanced Error Display**: Real-time error messages in both UI and terminal with timestamps
- **File Progress Tracking**: Shows files completed/total with estimated time remaining
### Fixed
- **Critical: False Error Detection**: Fixed overly aggressive error detection that was marking successful operations as failures, causing premature abort and empty file generation
- **Critical: Empty File Generation**: Files now contain actual code instead of being empty (2-byte files)
- **Unique Folder Naming**: Each project run now creates `paper_{timestamp}` folders instead of reusing `pdf_output`
- **PDF Save Location**: PDFs now save to `deepcode_lab/papers/` instead of system temp directory
- **Duplicate Folder Prevention**: Added session state caching to prevent duplicate folder creation on UI reruns
- **Token Limit Compliance**: Fixed `max_tokens` to respect model limits dynamically (e.g., gpt-4o-mini's 16,384 token limit)
- **Empty Plan Detection**: System now fails early with clear error messages when initial plan is empty or invalid
- **Process Hanging**: Fixed infinite loops and hanging on errors - process now exits cleanly
- **Token Cost Tracking**: Restored accurate token usage and cost display (was showing $0.0000)
- **PDF to Markdown Conversion**: Fixed automatic conversion and file location handling
- **Document Segmentation**: Properly uses configured 50K character threshold from `mcp_agent.config.yaml`
- **Error Propagation**: Abort mechanism now properly stops process after 10 consecutive real errors
### Changed
- **Model-Aware Token Management**: Token limits now adapt automatically based on configured model instead of hardcoded values
- **Cost Calculation**: Dynamic pricing based on actual model rates (OpenAI, Anthropic)
- **Retry Logic**: Token limits for retries now respect model maximum (87.5% → 95% → 98% of max)
- **Segmentation Workflow**: Better integration with code implementation phase
- **Error Handling**: Enhanced error propagation - errors no longer reported as "success"
- **UI Display**: Shows project folder name after PDF conversion for better visibility
- **Terminal Logging**: Added timestamps to all progress messages
### Technical Improvements
- Added document-segmentation server to code implementation workflow for better token management
- Improved error handling in agent orchestration engine with proper cleanup
- Enhanced subprocess handling on Windows (hide console windows, prevent hanging)
- Better LibreOffice detection on Windows using direct path checking
- Fixed input data format consistency (JSON with `paper_path` key)
- Added comprehensive logging throughout the pipeline
- Improved resource cleanup on errors and process termination
### Documentation
- Translated Chinese comments to English in core workflow files
- Added inline documentation for new utility modules
- Created startup scripts with clear usage instructions
### Breaking Changes
- None - all changes are backward compatible
### Known Issues
- Terminal may show trailing "Calling Tool..." line after completion (cosmetic display artifact - process completes successfully)
- Some Chinese comments remain in non-critical files (cli, tools) - translation in progress
- tiktoken package optional warning (doesn't affect functionality)
### Success Metrics
- ✅ Complete end-to-end workflow: DOCX upload → PDF conversion → Markdown → Segmentation → Planning → Code generation
- ✅ Files generated with actual code content (15+ files with proper implementation)
- ✅ Single folder per project run (no duplicates)
- ✅ Dynamic token management working across different models
- ✅ Accurate cost tracking per model
- ✅ Clean process termination with proper error handling
---
## [1.0.5] - Previous Release
See previous releases for earlier changes.
================================================
FILE: LICENSE
================================================
MIT License
Copyright (c) 2025 ✨Data Intelligence Lab@HKU✨
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
================================================
FILE: MANIFEST.in
================================================
include README.md
include LICENSE
include requirements.txt
include __init__.py
include *.png
include *.yaml
recursive-include config *.yaml
recursive-include prompts *
recursive-include schema *
recursive-include ui *.py
recursive-include cli *.py
recursive-include utils *.py
recursive-include tools *.py
recursive-include workflows *.py
global-exclude *.pyc
global-exclude .git*
global-exclude .history*
global-exclude .ruff_cache*
global-exclude __pycache__*
================================================
FILE: README.md
================================================
<div align="center">
<table style="border: none; margin: 0 auto; padding: 0; border-collapse: collapse;">
<tr>
<td align="center" style="vertical-align: middle; padding: 10px; border: none; width: 250px;">
<img src="assets/logo.png" alt="DeepCode Logo" width="200" style="margin: 0; padding: 0; display: block;"/>
</td>
<td align="left" style="vertical-align: middle; padding: 10px 0 10px 30px; border: none;">
<pre style="font-family: 'Courier New', monospace; font-size: 16px; color: #0EA5E9; margin: 0; padding: 0; text-shadow: 0 0 10px #0EA5E9, 0 0 20px rgba(14,165,233,0.5); line-height: 1.2; transform: skew(-1deg, 0deg); display: block;"> ██████╗ ███████╗███████╗██████╗ ██████╗ ██████╗ ██████╗ ███████╗
██╔══██╗██╔════╝██╔════╝██╔══██╗██╔════╝██╔═══██╗██╔══██╗██╔════╝
██║ ██║█████╗ █████╗ ██████╔╝██║ ██║ ██║██║ ██║█████╗
██║ ██║██╔══╝ ██╔══╝ ██╔═══╝ ██║ ██║ ██║██║ ██║██╔══╝
██████╔╝███████╗███████╗██║ ╚██████╗╚██████╔╝██████╔╝███████╗
╚═════╝ ╚══════╝╚══════╝╚═╝ ╚═════╝ ╚═════╝ ╚═════╝ ╚══════╝</pre>
</td>
</tr>
</table>
<div align="center">
<a href="https://trendshift.io/repositories/14665" target="_blank"><img src="https://trendshift.io/api/badge/repositories/14665" alt="HKUDS%2FDeepCode | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>
</div>
<!-- <img src="https://readme-typing-svg.herokuapp.com?font=Russo+One&size=28&duration=2000&pause=800&color=06B6D4&background=00000000¢er=true&vCenter=true&width=800&height=50&lines=%E2%9A%A1+OPEN+AGENTIC+CODING+%E2%9A%A1" alt="DeepCode Tech Subtitle" style="margin-top: 5px; filter: drop-shadow(0 0 12px #06B6D4) drop-shadow(0 0 24px rgba(6,182,212,0.4));"/> -->
# <img src="https://github.com/Zongwei9888/Experiment_Images/raw/43c585dca3d21b8e4b6390d835cdd34dc4b4b23d/DeepCode_images/title_logo.svg" alt="DeepCode Logo" width="32" height="32" style="vertical-align: middle; margin-right: 8px;"/> DeepCode: Open Agentic Coding
### *Advancing Code Generation with Multi-Agent Systems*
<!-- <p align="center">
<img src="https://img.shields.io/badge/Version-1.0.0-00d4ff?style=for-the-badge&logo=rocket&logoColor=white" alt="Version">
<img src="https://img.shields.io/badge/License-MIT-4ecdc4?style=for-the-badge&logo=opensourceinitiative&logoColor=white" alt="License">
<img src="https://img.shields.io/badge/AI-Multi--Agent-9b59b6?style=for-the-badge&logo=brain&logoColor=white" alt="AI">
<img src="https://img.shields.io/badge/HKU-Data_Intelligence_Lab-f39c12?style=for-the-badge&logo=university&logoColor=white" alt="HKU">
</p> -->
<p>
<a href="https://github.com/HKUDS/DeepCode/stargazers"><img src='https://img.shields.io/github/stars/HKUDS/DeepCode?color=00d9ff&style=for-the-badge&logo=star&logoColor=white&labelColor=1a1a2e' /></a>
<a href='https://arxiv.org/abs/2512.07921'><img src="https://img.shields.io/badge/Paper-arXiv-orange?style=for-the-badge&logo=arxiv&logoColor=white&labelColor=1a1a2e"></a>
<img src="https://img.shields.io/badge/🐍Python-3.13-4ecdc4?style=for-the-badge&logo=python&logoColor=white&labelColor=1a1a2e">
<!-- <a href="https://pypi.org/project/deepcode-hku/"><img src="https://img.shields.io/pypi/v/deepcode-hku.svg?style=for-the-badge&logo=pypi&logoColor=white&labelColor=1a1a2e&color=ff6b6b"></a> -->
</p>
<p>
<a href="https://discord.gg/yF2MmDJyGJ"><img src="https://img.shields.io/badge/💬Discord-Community-7289da?style=for-the-badge&logo=discord&logoColor=white&labelColor=1a1a2e"></a>
<a href="https://github.com/HKUDS/DeepCode/issues/11"><img src="https://img.shields.io/badge/💬WeChat-Group-07c160?style=for-the-badge&logo=wechat&logoColor=white&labelColor=1a1a2e"></a>
</p>
<div align="center">
<div style="width: 100%; height: 2px; margin: 20px 0; background: linear-gradient(90deg, transparent, #00d9ff, transparent);"></div>
</div>
<div align="center">
<a href="#-quick-start" style="text-decoration: none;">
<img src="https://img.shields.io/badge/Quick%20Start-Get%20Started%20Now-00d9ff?style=for-the-badge&logo=rocket&logoColor=white&labelColor=1a1a2e">
</a>
</div>
<div align="center" style="margin-top: 10px;">
<a href="README.md">
<img src="https://img.shields.io/badge/English-00d4ff?style=for-the-badge&logo=readme&logoColor=white&labelColor=1a1a2e" alt="English">
</a>
<a href="README_ZH.md">
<img src="https://img.shields.io/badge/中文-00d4ff?style=for-the-badge&logo=readme&logoColor=white&labelColor=1a1a2e" alt="中文">
</a>
</div>
### 🖥️ **Interface Showcase**
<table align="center" width="100%" style="border: none; border-collapse: collapse; margin: 30px 0;">
<tr>
<td width="50%" align="center" style="vertical-align: top; padding: 20px;">
#### 🖥️ **CLI Interface**
**Terminal-Based Development**
<div align="center">
<img src="https://github.com/Zongwei9888/Experiment_Images/blob/8882a7313c504ca97ead6e7b36c51aa761b6a4f3/DeepCode_images/CLI.gif" alt="CLI Interface Demo" width="100%" style="border-radius: 10px; box-shadow: 0 8px 20px rgba(45,55,72,0.3); margin: 15px 0;"/>
<div style="background: linear-gradient(135deg, #2D3748 0%, #4A5568 100%); border-radius: 12px; padding: 15px; margin: 15px 0; color: white;">
<strong>🚀 Advanced Terminal Experience</strong><br/>
<small>⚡ Fast command-line workflow<br/>🔧 Developer-friendly interface<br/>📊 Real-time progress tracking</small>
</div>
*Professional terminal interface for advanced users and CI/CD integration*
</div>
</td>
<td width="50%" align="center" style="vertical-align: top; padding: 20px;">
#### 🌐 **Web Interface**
**Visual Interactive Experience**
<div align="center">
<img src="https://github.com/Zongwei9888/Experiment_Images/raw/8882a7313c504ca97ead6e7b36c51aa761b6a4f3/DeepCode_images/UI.gif" alt="Web Interface Demo" width="100%" style="border-radius: 10px; box-shadow: 0 8px 20px rgba(14,165,233,0.3); margin: 15px 0;"/>
<div style="background: linear-gradient(135deg, #0EA5E9 0%, #00D4FF 100%); border-radius: 12px; padding: 15px; margin: 15px 0; color: white;">
<strong>🎨 Modern Web Dashboard</strong><br/>
<small>🖱️ Intuitive drag-and-drop<br/>📱 Responsive design<br/>🎯 Visual progress tracking</small>
</div>
*Beautiful web interface with streamlined workflow for all skill levels*
</div>
</td>
</tr>
</table>
---
<div align="center">
### 🎬 **Introduction Video**
<div style="margin: 20px 0;">
<a href="https://youtu.be/PRgmP8pOI08" target="_blank">
<img src="https://img.youtube.com/vi/PRgmP8pOI08/maxresdefault.jpg"
alt="DeepCode Introduction Video"
width="75%"
style="border-radius: 12px; box-shadow: 0 8px 25px rgba(0,0,0,0.15); transition: transform 0.3s ease;"/>
</a>
</div>
*🎯 **Watch our complete introduction** - See how DeepCode transforms research papers and natural language into production-ready code*
<p>
<a href="https://youtu.be/PRgmP8pOI08" target="_blank">
<img src="https://img.shields.io/badge/▶️_Watch_Video-FF0000?style=for-the-badge&logo=youtube&logoColor=white" alt="Watch Video"/>
</a>
</p>
</div>
---
> *"Where AI Agents Transform Ideas into Production-Ready Code"*
</div>
---
## 📑 Table of Contents
- [📰 News](#-news)
- [🚀 Key Features](#-key-features)
- [🏗️ Architecture](#️-architecture)
- [📊 Experimental Results](#-experimental-results)
- [🚀 Quick Start](#-quick-start)
- [🤖 nanobot Integration (Feishu Chatbot)](#-nanobot-integration-feishu-chatbot)
- [💡 Examples](#-examples)
- [🎬 Live Demonstrations](#-live-demonstrations)
- [⭐ Star History](#-star-history)
- [📄 License](#-license)
---
## 📰 News
🎉 **[2026-02] nanobot ✖️ DeepCode. Just chat naturally with openclaw/nanobot to handle your coding tasks:**
<div align="center">
<table><tr>
<td align="center"><a href="https://github.com/HKUDS/DeepCode"><img src="./assets/logo.png" alt="DeepCode" height="60"/></a></td>
<td align="center"><h2>✦</h2></td>
<td align="center"><a href="https://github.com/HKUDS/nanobot"><img src="./assets/nanobot.png" alt="nanobot" height="60"/></a></td>
</tr></table>
</div>
- [nanobot](https://github.com/HKUDS/nanobot) nanobot now powers your agentic coding & engineering! 🤖💻
- Step away from your laptop — make vibe coding even more vibe! Code directly from your phone! 📱✨
- One-command deploy: `./nanobot/run_nanobot.sh` → **[Setup Guide →](#-nanobot-integration-feishu-chatbot)**
<div align="center">
<table width="100%"><tr>
<td width="50%" align="center">
<img src="./assets/IMG_8098.jpeg" alt="Feishu Chat Example 1" width="95%" style="border-radius: 10px; box-shadow: 0 4px 15px rgba(0,0,0,0.2);"/>
</td>
<td width="50%" align="center">
<img src="./assets/IMG_8099.jpeg" alt="Feishu Chat Example 2" width="95%" style="border-radius: 10px; box-shadow: 0 4px 15px rgba(0,0,0,0.2);"/>
</td>
</tr></table>
<sub><em>Feishu Bot in Action — Natural language → Full code generation with setup instructions</em></sub>
</div>
---
🎉 **[2026-02] New Web UI Experience Upgrade!**
- 🔄 **User-in-Loop Interaction**: Support real-time user interaction during workflows - AI asks clarifying questions directly in the chat
- 💬 **Inline Interaction Design**: Interaction prompts appear naturally within the chat flow for a seamless experience
- 🚀 **One-Click Launch**: Simply run `deepcode` to start the new UI (cross-platform: Windows/macOS/Linux)
- 🔧 **Improved Process Management**: Enhanced service start/stop mechanism with automatic port cleanup
- 📡 **WebSocket Real-time Communication**: Fixed message loss issues, ensuring proper interaction state synchronization
<div align="center">
<img src="./assets/NewUI.png" alt="DeepCode New UI" width="85%" style="border-radius: 12px; box-shadow: 0 4px 20px rgba(0,0,0,0.15);" />
<br/>
<sub><em>DeepCode New Web UI - Modern React-based Interface</em></sub>
</div>
---
🎉 **[2025-10-28] DeepCode Achieves SOTA on PaperBench!**
DeepCode sets new benchmarks on OpenAI's PaperBench Code-Dev across all categories:
- 🏆 **Surpasses Human Experts**: **75.9%** (DeepCode) vs Top Machine Learning PhDs 72.4% (+3.5%).
- 🥇 **Outperforms SOTA Commercial Code Agents**: **84.8%** (DeepCode) vs Leading Commercial Code Agents (+26.1%) (Cursor, Claude Code, and Codex).
- 🔬 **Advances Scientific Coding**: **73.5%** (DeepCode) vs PaperCoder 51.1% (+22.4%).
- 🚀 **Beats LLM Agents**: **73.5%** (DeepCode) vs best LLM frameworks 43.3% (+30.2%).
---
## 🚀 Key Features
<br/>
<table align="center" width="100%" style="border: none; table-layout: fixed;">
<tr>
<td width="30%" align="center" style="vertical-align: top; padding: 20px;">
<div style="height: 80px; display: flex; align-items: center; justify-content: center;">
<h3 style="margin: 0; padding: 0;">🚀 <strong>Paper2Code</strong></h3>
</div>
<div align="center" style="margin: 15px 0;">
<img src="https://img.shields.io/badge/ALGORITHM-IMPLEMENTATION-ff6b6b?style=for-the-badge&logo=algorithm&logoColor=white" alt="Algorithm Badge" />
</div>
<div style="height: 80px; display: flex; align-items: center; justify-content: center;">
<p align="center"><strong>Automated Implementation of Complex Algorithms</strong></p>
</div>
<div style="height: 60px; display: flex; align-items: center; justify-content: center;">
<p align="center">Effortlessly converts complex algorithms from research papers into <strong>high-quality</strong>, <strong>production-ready</strong> code, accelerating algorithm reproduction.</p>
</div>
</td>
<td width="30%" align="center" style="vertical-align: top; padding: 20px;">
<div style="height: 80px; display: flex; align-items: center; justify-content: center;">
<h3 style="margin: 0; padding: 0;">🎨 <strong>Text2Web</strong></h3>
</div>
<div align="center" style="margin: 15px 0;">
<img src="https://img.shields.io/badge/FRONTEND-DEVELOPMENT-4ecdc4?style=for-the-badge&logo=react&logoColor=white" alt="Frontend Badge" />
</div>
<div style="height: 80px; display: flex; align-items: center; justify-content: center;">
<p align="center"><strong>Automated Front-End Web Development</strong></p>
</div>
<div style="height: 60px; display: flex; align-items: center; justify-content: center;">
<p align="center">Translates plain textual descriptions into <strong>fully functional</strong>, <strong>visually appealing</strong> front-end web code for rapid interface creation.</p>
</div>
</td>
<td width="30%" align="center" style="vertical-align: top; padding: 20px;">
<div style="height: 80px; display: flex; align-items: center; justify-content: center;">
<h3 style="margin: 0; padding: 0;">⚙️ <strong>Text2Backend</strong></h3>
</div>
<div align="center" style="margin: 15px 0;">
<img src="https://img.shields.io/badge/BACKEND-DEVELOPMENT-9b59b6?style=for-the-badge&logo=server&logoColor=white" alt="Backend Badge" />
</div>
<div style="height: 80px; display: flex; align-items: center; justify-content: center;">
<p align="center"><strong>Automated Back-End Development</strong></p>
</div>
<div style="height: 60px; display: flex; align-items: center; justify-content: center;">
<p align="center">Generates <strong>efficient</strong>, <strong>scalable</strong>, and <strong>feature-rich</strong> back-end code from simple text inputs, streamlining server-side development.</p>
</div>
</td>
</tr>
</table>
<br/>
---
## 📊 Experimental Results
<div align="center">
<img src='./assets/result_main02.jpg' /><br>
</div>
<br/>
We evaluate **DeepCode** on the [*PaperBench*](https://openai.com/index/paperbench/) benchmark (released by OpenAI), a rigorous testbed requiring AI agents to independently reproduce 20 ICML 2024 papers from scratch. The benchmark comprises 8,316 gradable components assessed using SimpleJudge with hierarchical weighting.
Our experiments compare DeepCode against four baseline categories: **(1) Human Experts**, **(2) State-of-the-Art Commercial Code Agents**, **(3) Scientific Code Agents**, and **(4) LLM-Based Agents**.
### ① 🧠 Human Expert Performance (Top Machine Learning PhD)
**DeepCode: 75.9% vs. Top Machine Learning PhD: 72.4% (+3.5%)**
DeepCode achieves **75.9%** on the 3-paper human evaluation subset, **surpassing the best-of-3 human expert baseline (72.4%) by +3.5 percentage points**. This demonstrates that our framework not only matches but exceeds expert-level code reproduction capabilities, representing a significant milestone in autonomous scientific software engineering.
### ② 💼 State-of-the-Art Commercial Code Agents
**DeepCode: 84.8% vs. Best Commercial Agent: 58.7% (+26.1%)**
On the 5-paper subset, DeepCode substantially outperforms leading commercial coding tools:
- Cursor: 58.4%
- Claude Code: 58.7%
- Codex: 40.0%
- **DeepCode: 84.8%**
This represents a **+26.1% improvement** over the leading commercial code agent. All commercial agents utilize Claude Sonnet 4.5 or GPT-5 Codex-high, highlighting that **DeepCode's superior architecture**—rather than base model capability—drives this performance gap.
### ③ 🔬 Scientific Code Agents
**DeepCode: 73.5% vs. PaperCoder: 51.1% (+22.4%)**
Compared to PaperCoder (**51.1%**), the state-of-the-art scientific code reproduction framework, DeepCode achieves **73.5%**, demonstrating a **+22.4% relative improvement**. This substantial margin validates our multi-module architecture combining planning, hierarchical task decomposition, code generation, and iterative debugging over simpler pipeline-based approaches.
### ④ 🤖 LLM-Based Agents
**DeepCode: 73.5% vs. Best LLM Agent: 43.3% (+30.2%)**
DeepCode significantly outperforms all tested LLM agents:
- Claude 3.5 Sonnet + IterativeAgent: 27.5%
- o1 + IterativeAgent (36 hours): 42.4%
- o1 BasicAgent: 43.3%
- **DeepCode: 73.5%**
The **+30.2% improvement** over the best-performing LLM agent demonstrates that sophisticated agent scaffolding, rather than extended inference time or larger models, is critical for complex code reproduction tasks.
---
### 🎯 **Autonomous Self-Orchestrating Multi-Agent Architecture**
**The Challenges**:
- 📄 **Implementation Complexity**: Converting academic papers and complex algorithms into working code requires significant technical effort and domain expertise
- 🔬 **Research Bottleneck**: Researchers spend valuable time implementing algorithms instead of focusing on their core research and discovery work
- ⏱️ **Development Delays**: Product teams experience long wait times between concept and testable prototypes, slowing down innovation cycles
- 🔄 **Repetitive Coding**: Developers repeatedly implement similar patterns and functionality instead of building on existing solutions
**DeepCode** addresses these workflow inefficiencies by providing reliable automation for common development tasks, streamlining your development workflow from concept to code.
<div align="center">
```mermaid
flowchart LR
A["📄 Research Papers<br/>💬 Text Prompts<br/>🌐 URLs & Document<br/>📎 Files: PDF, DOC, PPTX, TXT, HTML"] --> B["🧠 DeepCode<br/>Multi-Agent Engine"]
B --> C["🚀 Algorithm Implementation <br/>🎨 Frontend Development <br/>⚙️ Backend Development"]
style A fill:#ff6b6b,stroke:#c0392b,stroke-width:2px,color:#000
style B fill:#00d4ff,stroke:#0984e3,stroke-width:3px,color:#000
style C fill:#00b894,stroke:#00a085,stroke-width:2px,color:#000
```
</div>
---
## 🏗️ Architecture
### 📊 **System Overview**
**DeepCode** is an AI-powered development platform that automates code generation and implementation tasks. Our multi-agent system handles the complexity of translating requirements into functional, well-structured code, allowing you to focus on innovation rather than implementation details.
🎯 **Technical Capabilities**:
🧬 **Research-to-Production Pipeline**<br>
Multi-modal document analysis engine that extracts algorithmic logic and mathematical models from academic papers. Generates optimized implementations with proper data structures while preserving computational complexity characteristics.
🪄 **Natural Language Code Synthesis**<br>
Context-aware code generation using fine-tuned language models trained on curated code repositories. Maintains architectural consistency across modules while supporting multiple programming languages and frameworks.
⚡ **Automated Prototyping Engine**<br>
Intelligent scaffolding system generating complete application structures including database schemas, API endpoints, and frontend components. Uses dependency analysis to ensure scalable architecture from initial generation.
💎 **Quality Assurance Automation**<br>
Integrated static analysis with automated unit test generation and documentation synthesis. Employs AST analysis for code correctness and property-based testing for comprehensive coverage.
🔮 **CodeRAG Integration System**<br>
Advanced retrieval-augmented generation combining semantic vector embeddings with graph-based dependency analysis. Automatically discovers optimal libraries and implementation patterns from large-scale code corpus.
---
### 🔧 **Core Techniques**
- 🧠 **Intelligent Orchestration Agent**: Central decision-making system that coordinates workflow phases and analyzes requirements. Employs dynamic planning algorithms to adapt execution strategies in real-time based on evolving project complexity. Dynamically selects optimal processing strategies for each implementation step. <br>
- 💾 **Efficient Memory Mechanism**: Advanced context engineering system that manages large-scale code contexts efficiently. Implements hierarchical memory structures with intelligent compression for handling complex codebases. This component enables instant retrieval of implementation patterns and maintains semantic coherence across extended development sessions. <br>
- 🔍 **Advanced CodeRAG System**: Global code comprehension engine that analyzes complex inter-dependencies across repositories. Performs cross-codebase relationship mapping to understand architectural patterns from a holistic perspective. This module leverages dependency graphs and semantic analysis to provide globally-aware code recommendations during implementation.
---
### 🤖 **Multi-Agent Architecture of DeepCode**:
- **🎯 Central Orchestrating Agent**: Orchestrates entire workflow execution and makes strategic decisions. Coordinates specialized agents based on input complexity analysis. Implements dynamic task planning and resource allocation algorithms. <br>
- **📝 Intent Understanding Agent**: Performs deep semantic analysis of user requirements to decode complex intentions. Extracts functional specifications and technical constraints through advanced NLP processing. Transforms ambiguous human descriptions into precise, actionable development specifications with structured task decomposition. <br>
- **📄 Document Parsing Agent**: Processes complex technical documents and research papers with advanced parsing capabilities. Extracts algorithms and methodologies using document understanding models. Converts academic concepts into practical implementation specifications through intelligent content analysis. <br>
- **🏗️ Code Planning Agent**: Performs architectural design and technology stack optimization. Dynamic planning for adaptive development roadmaps. Enforces coding standards and generates modular structures through automated design pattern selection.<br>
- **🔍 Code Reference Mining Agent**: Discovers relevant repositories and frameworks through intelligent search algorithms. Analyzes codebases for compatibility and integration potential. Provides recommendations based on similarity metrics and automated dependency analysis. <br>
- **📚 Code Indexing Agent**: Builds comprehensive knowledge graphs of discovered codebases. Maintains semantic relationships between code components. Enables intelligent retrieval and cross-reference capabilities. <br>
- **🧬 Code Generation Agent**: Synthesizes gathered information into executable code implementations. Creates functional interfaces and integrates discovered components. Generates comprehensive test suites and documentation for reproducibility.
---
#### 🛠️ **Implementation Tools Matrix**
**🔧 Powered by MCP (Model Context Protocol)**
DeepCode leverages the **Model Context Protocol (MCP)** standard to seamlessly integrate with various tools and services. This standardized approach ensures reliable communication between AI agents and external systems, enabling powerful automation capabilities.
##### 📡 **MCP Servers & Tools**
| 🛠️ **MCP Server** | 🔧 **Primary Function** | 💡 **Purpose & Capabilities** |
|-------------------|-------------------------|-------------------------------|
| **🔍 brave** | Web Search Engine | Real-time information retrieval via Brave Search API |
| **🌐 bocha-mcp** | Alternative Search | Secondary search option with independent API access |
| **📂 filesystem** | File System Operations | Local file and directory management, read/write operations |
| **🌐 fetch** | Web Content Retrieval | Fetch and extract content from URLs and web resources |
| **📥 github-downloader** | Repository Management | Clone and download GitHub repositories for analysis |
| **📋 file-downloader** | Document Processing | Download and convert files (PDF, DOCX, etc.) to Markdown |
| **⚡ command-executor** | System Commands | Execute bash/shell commands for environment management |
| **🧬 code-implementation** | Code Generation Hub | Comprehensive code reproduction with execution and testing |
| **📚 code-reference-indexer** | Smart Code Search | Intelligent indexing and search of code repositories |
| **📄 document-segmentation** | Smart Document Analysis | Intelligent document segmentation for large papers and technical documents |
##### 🔧 **Legacy Tool Functions** *(for reference)*
| 🛠️ **Function** | 🎯 **Usage Context** |
|-----------------|---------------------|
| **📄 read_code_mem** | Efficient code context retrieval from memory |
| **✍️ write_file** | Direct file content generation and modification |
| **🐍 execute_python** | Python code testing and validation |
| **📁 get_file_structure** | Project structure analysis and organization |
| **⚙️ set_workspace** | Dynamic workspace and environment configuration |
| **📊 get_operation_history** | Process monitoring and operation tracking |
---
🎛️ **Multi-Interface Framework**<br>
RESTful API with CLI and web frontends featuring real-time code streaming, interactive debugging, and extensible plugin architecture for CI/CD integration.
**🚀 Multi-Agent Intelligent Pipeline:**
<div align="center">
### 🌟 **Intelligence Processing Flow**
<table align="center" width="100%" style="border: none; border-collapse: collapse;">
<tr>
<td colspan="3" align="center" style="padding: 20px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border-radius: 15px; color: white; font-weight: bold;">
💡 <strong>INPUT LAYER</strong><br/>
📄 Research Papers • 💬 Natural Language • 🌐 URLs • 📋 Requirements
</td>
</tr>
<tr><td colspan="3" height="20"></td></tr>
<tr>
<td colspan="3" align="center" style="padding: 15px; background: linear-gradient(135deg, #ff6b6b 0%, #ee5a24 100%); border-radius: 12px; color: white; font-weight: bold;">
🎯 <strong>CENTRAL ORCHESTRATION</strong><br/>
Strategic Decision Making • Workflow Coordination • Agent Management
</td>
</tr>
<tr><td colspan="3" height="15"></td></tr>
<tr>
<td align="center" style="padding: 12px; background: linear-gradient(135deg, #3742fa 0%, #2f3542 100%); border-radius: 10px; color: white; width: 50%;">
📝 <strong>TEXT ANALYSIS</strong><br/>
<small>Requirement Processing</small>
</td>
<td width="10"></td>
<td align="center" style="padding: 12px; background: linear-gradient(135deg, #8c7ae6 0%, #9c88ff 100%); border-radius: 10px; color: white; width: 50%;">
📄 <strong>DOCUMENT ANALYSIS</strong><br/>
<small>Paper & Spec Processing</small>
</td>
</tr>
<tr><td colspan="3" height="15"></td></tr>
<tr>
<td colspan="3" align="center" style="padding: 15px; background: linear-gradient(135deg, #00d2d3 0%, #54a0ff 100%); border-radius: 12px; color: white; font-weight: bold;">
📋 <strong>REPRODUCTION PLANNING</strong><br/>
Deep Paper Analysis • Code Requirements Parsing • Reproduction Strategy Development
</td>
</tr>
<tr><td colspan="3" height="15"></td></tr>
<tr>
<td align="center" style="padding: 12px; background: linear-gradient(135deg, #ffa726 0%, #ff7043 100%); border-radius: 10px; color: white; width: 50%;">
🔍 <strong>REFERENCE ANALYSIS</strong><br/>
<small>Repository Discovery</small>
</td>
<td width="10"></td>
<td align="center" style="padding: 12px; background: linear-gradient(135deg, #e056fd 0%, #f368e0 100%); border-radius: 10px; color: white; width: 50%;">
📚 <strong>CODE INDEXING</strong><br/>
<small>Knowledge Graph Building</small>
</td>
</tr>
<tr><td colspan="3" height="15"></td></tr>
<tr>
<td colspan="3" align="center" style="padding: 15px; background: linear-gradient(135deg, #26de81 0%, #20bf6b 100%); border-radius: 12px; color: white; font-weight: bold;">
🧬 <strong>CODE IMPLEMENTATION</strong><br/>
Implementation Generation • Testing • Documentation
</td>
</tr>
<tr><td colspan="3" height="15"></td></tr>
<tr>
<td colspan="3" align="center" style="padding: 20px; background: linear-gradient(135deg, #045de9 0%, #09c6f9 100%); border-radius: 15px; color: white; font-weight: bold;">
⚡ <strong>OUTPUT DELIVERY</strong><br/>
📦 Complete Codebase • 🧪 Test Suite • 📚 Documentation • 🚀 Deployment Ready
</td>
</tr>
</table>
</div>
<div align="center">
<br/>
### 🔄 **Process Intelligence Features**
<table align="center" style="border: none;">
<tr>
<td align="center" width="25%" style="padding: 15px;">
<div style="background: #f8f9fa; border-radius: 10px; padding: 15px; border-left: 4px solid #ff6b6b;">
<h4>🎯 Adaptive Flow</h4>
<p><small>Dynamic agent selection based on input complexity</small></p>
</div>
</td>
<td align="center" width="25%" style="padding: 15px;">
<div style="background: #f8f9fa; border-radius: 10px; padding: 15px; border-left: 4px solid #4ecdc4;">
<h4>🧠 Smart Coordination</h4>
<p><small>Intelligent task distribution and parallel processing</small></p>
</div>
</td>
<td align="center" width="25%" style="padding: 15px;">
<div style="background: #f8f9fa; border-radius: 10px; padding: 15px; border-left: 4px solid #45b7d1;">
<h4>🔍 Context Awareness</h4>
<p><small>Deep understanding through CodeRAG integration</small></p>
</div>
</td>
<td align="center" width="25%" style="padding: 15px;">
<div style="background: #f8f9fa; border-radius: 10px; padding: 15px; border-left: 4px solid #96ceb4;">
<h4>⚡ Quality Assurance</h4>
<p><small>Automated testing and validation throughout</small></p>
</div>
</td>
</tr>
</table>
</div>
---
## 🚀 Quick Start
### 📋 **Prerequisites**
Before installing DeepCode, ensure you have the following:
| Requirement | Version | Purpose |
|-------------|---------|---------|
| **Python** | 3.9+ | Core runtime |
| **Node.js** | 18+ | New UI frontend |
| **npm** | 8+ | Package management |
```bash
# Check your versions
python --version # Should be 3.9+
node --version # Should be 18+
npm --version # Should be 8+
```
<details>
<summary><strong>📥 Install Node.js (if not installed)</strong></summary>
```bash
# macOS (using Homebrew)
brew install node
# Ubuntu/Debian
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
sudo apt-get install -y nodejs
# Windows
# Download from https://nodejs.org/
```
</details>
### 📦 **Step 1: Installation**
Choose one of the following installation methods:
#### ⚡ **Direct Installation (Recommended)**
```bash
# 🚀 Install DeepCode package directly
pip install deepcode-hku
# 🔑 Download configuration files
curl -O https://raw.githubusercontent.com/HKUDS/DeepCode/main/mcp_agent.config.yaml
curl -O https://raw.githubusercontent.com/HKUDS/DeepCode/main/mcp_agent.secrets.yaml
```
#### 🔧 **Development Installation (From Source)**
<details>
<summary><strong>📂 Click to expand development installation options</strong></summary>
##### 🔥 **Using UV (Recommended for Development)**
```bash
git clone https://github.com/HKUDS/DeepCode.git
cd DeepCode/
curl -LsSf https://astral.sh/uv/install.sh | sh
uv venv --python=3.13
source .venv/bin/activate # On Windows: .venv\Scripts\activate
uv pip install -r requirements.txt
# Install frontend dependencies
npm install --prefix new_ui/frontend
```
##### 🐍 **Using Traditional pip**
```bash
git clone https://github.com/HKUDS/DeepCode.git
cd DeepCode/
pip install -r requirements.txt
# Install frontend dependencies
npm install --prefix new_ui/frontend
```
</details>
### 🔧 **Step 2: Configuration**
> The following configuration applies to **all installation methods** (pip, UV, source, and Docker).
#### 🔑 API Keys *(required)*
Edit `mcp_agent.secrets.yaml` with your API keys:
```yaml
# At least ONE provider API key is required
openai:
api_key: "your_openai_api_key"
base_url: "https://openrouter.ai/api/v1" # Optional: for OpenRouter or custom endpoints
anthropic:
api_key: "your_anthropic_api_key" # For Claude models
google:
api_key: "your_google_api_key" # For Gemini models
```
#### 🤖 LLM Provider *(optional)*
Edit `mcp_agent.config.yaml` to choose your preferred LLM provider (line ~106):
```yaml
# Options: "google", "anthropic", "openai"
# If not set or unavailable, will automatically fallback to first available provider
llm_provider: "google"
```
#### 🔍 Search API Keys *(optional)*
Configure web search in `mcp_agent.config.yaml`:
```yaml
# For Brave Search (default) — set in brave.env section (line ~28)
brave:
env:
BRAVE_API_KEY: "your_brave_api_key_here"
# For Bocha-MCP (alternative) — set in bocha-mcp.env section (line ~74)
bocha-mcp:
env:
BOCHA_API_KEY: "your_bocha_api_key_here"
```
#### 📄 Document Segmentation *(optional)*
Control document processing in `mcp_agent.config.yaml`:
```yaml
document_segmentation:
enabled: true # true/false — whether to use intelligent document segmentation
size_threshold_chars: 50000 # Document size threshold to trigger segmentation
```
<details>
<summary><strong>🪟 Windows Users: Additional MCP Server Configuration</strong></summary>
If you're using Windows, you may need to configure MCP servers manually in `mcp_agent.config.yaml`:
```bash
# 1. Install MCP servers globally
npm i -g @modelcontextprotocol/server-brave-search
npm i -g @modelcontextprotocol/server-filesystem
# 2. Find your global node_modules path
npm -g root
```
Then update your `mcp_agent.config.yaml` to use absolute paths:
```yaml
mcp:
servers:
brave:
command: "node"
args: ["C:/Program Files/nodejs/node_modules/@modelcontextprotocol/server-brave-search/dist/index.js"]
filesystem:
command: "node"
args: ["C:/Program Files/nodejs/node_modules/@modelcontextprotocol/server-filesystem/dist/index.js", "."]
```
> **Note**: Replace the path with your actual global node_modules path from step 2.
</details>
<details>
<summary><strong>🔍 Search Server Configuration (Optional)</strong></summary>
DeepCode supports multiple search servers for web search functionality. You can configure your preferred option in `mcp_agent.config.yaml`:
```yaml
# Default search server configuration
# Options: "brave" or "bocha-mcp"
default_search_server: "brave"
```
**Available Options:**
- **🔍 Brave Search** (`"brave"`): Default option with high-quality search results. Requires `BRAVE_API_KEY`. Recommended for most users.
- **🌐 Bocha-MCP** (`"bocha-mcp"`): Alternative search server. Requires `BOCHA_API_KEY`. Uses local Python server implementation.
**Full MCP server configuration in mcp_agent.config.yaml:**
```yaml
# For Brave Search (default) - around line 28
brave:
command: "npx"
args: ["-y", "@modelcontextprotocol/server-brave-search"]
env:
BRAVE_API_KEY: "your_brave_api_key_here"
# For Bocha-MCP (alternative) - around line 74
bocha-mcp:
command: "python"
args: ["tools/bocha_search_server.py"]
env:
PYTHONPATH: "."
BOCHA_API_KEY: "your_bocha_api_key_here"
```
> **💡 Tip**: Both search servers require API key configuration. Choose the one that best fits your API access and requirements.
</details>
### ⚡ **Step 3: Launch Application**
Choose your preferred launch method:
<table width="100%">
<tr>
<th width="33%">🐳 Docker (Recommended)</th>
<th width="33%">🚀 Local (<code>deepcode</code> command)</th>
<th width="33%">🛠️ Other Methods</th>
</tr>
<tr><td>
No Python/Node needed — everything in container.
```bash
git clone https://github.com/HKUDS/DeepCode.git
cd DeepCode/
cp mcp_agent.secrets.yaml.example \
mcp_agent.secrets.yaml
# Edit secrets with your API keys
./deepcode_docker/run_docker.sh
# Access → http://localhost:8000
```
</td><td>
Auto-installs deps on first run.
```bash
deepcode
# Frontend → http://localhost:5173
# Backend → http://localhost:8000
# Ctrl+C to stop
```
Features: User-in-Loop, real-time progress, inline chat.
</td><td>
```bash
# macOS / Linux
./run.sh
# or: python deepcode.py
# Windows
run.bat
# or: python deepcode.py
# Classic Streamlit UI
deepcode --classic
# CLI mode
deepcode --cli
# or: python cli/main_cli.py
```
</td></tr>
</table>
<details>
<summary><strong>🐳 Docker Management Commands</strong></summary>
```bash
./deepcode_docker/run_docker.sh stop # Stop
./deepcode_docker/run_docker.sh restart # Restart (no rebuild needed for config changes)
./deepcode_docker/run_docker.sh --build # Force rebuild
./deepcode_docker/run_docker.sh logs # Real-time logs
./deepcode_docker/run_docker.sh status # Health check
./deepcode_docker/run_docker.sh clean # Remove containers & images
```
Or with Docker Compose directly:
```bash
docker compose -f deepcode_docker/docker-compose.yml up --build # Build & start
docker compose -f deepcode_docker/docker-compose.yml down # Stop
docker compose -f deepcode_docker/docker-compose.yml logs -f # Logs
```
> **💡** Config files are mounted as volumes — edit and restart, no rebuild needed.
> **💡** Windows users: run `docker compose` commands directly if shell scripts aren't available.
</details>
### 🎯 **Step 4: Generate Code**
1. **📄 Input** — Upload a research paper, type requirements, or paste a URL
2. **🤖 Processing** — The multi-agent system analyzes, plans, and generates
3. **⚡ Output** — Receive production-ready code with tests and documentation
---
### 🔧 **Troubleshooting**
<details>
<summary><strong>❓ Common Issues & Solutions</strong></summary>
| Problem | Cause | Fix |
|---|---|---|
| Docker build fails with `tsc: not found` | Corrupted build cache | `docker builder prune -f` then rebuild with `--no-cache` |
| `error during connect` / `cannot find the file` | Docker Desktop not running | Start Docker Desktop, wait until ready, retry |
| Frontend blank page | Corrupted `node_modules` | `cd new_ui/frontend && rm -rf node_modules && npm install` |
| `ERR_CONNECTION_REFUSED` | Wrong port / backend not running | Docker: `http://localhost:8000`. Local: `http://localhost:5173` |
| `npm install` → `Could not read package.json` | Wrong directory | Use `npm install --prefix new_ui/frontend` |
| Windows: MCP servers not working | Need absolute paths | See [Windows MCP Configuration](#-step-2-configuration) above |
</details>
---
## 🤖 nanobot Integration (Feishu Chatbot)
> Chat with DeepCode from **Feishu** — powered by [nanobot](https://github.com/HKUDS/nanobot).
<div align="center">
```mermaid
flowchart LR
subgraph Clients["💬 Chat Platforms"]
direction TB
F["<b>Feishu</b><br/>WebSocket"]
T["<b>Telegram</b><br/>Polling"]
D["<b>Discord</b><br/>Gateway"]
end
subgraph Gateway["🐈 nanobot Gateway"]
direction TB
A["Agent Loop<br/><i>LLM + Tool Calls</i>"]
end
subgraph Engine["🧠 DeepCode Engine"]
direction TB
P2C["Paper → Code"]
C2C["Chat → Code"]
TRK["Task Tracking"]
end
F & T & D <-->|"messages"| A
A -->|"HTTP API"| P2C & C2C & TRK
A -.->|"LLM API"| LLM["☁️ OpenRouter"]
style Clients fill:#1a1a2e,stroke:#00d9ff,color:#fff
style Gateway fill:#1a1a2e,stroke:#4ecdc4,color:#fff
style Engine fill:#1a1a2e,stroke:#ff6b6b,color:#fff
style LLM fill:#1a1a2e,stroke:#9b59b6,color:#fff
```
</div>
<div align="center">
<table><tr>
<td align="center"><a href="https://github.com/HKUDS/DeepCode"><img src="./assets/logo.png" alt="DeepCode" height="55"/></a></td>
<td align="center"><h2>✦</h2></td>
<td align="center"><a href="https://github.com/HKUDS/nanobot"><img src="./assets/nanobot.png" alt="nanobot" height="55"/></a></td>
</tr></table>
</div>
Both services run inside the same **Docker Compose** network. Prerequisites: **Docker Desktop** + **OpenRouter API Key** ([get one](https://openrouter.ai/keys)) + **Feishu App**.
---
### Step 1 · Create a Feishu Bot
<details open>
<summary><b>Feishu / Lark</b> (Recommended — WebSocket, no public IP needed)</summary>
1. Go to [Feishu Open Platform](https://open.feishu.cn/app) → **Create Custom App**
2. Enable **Bot** capability in App Features
3. Add permissions: `im:message` · `im:message:send_as_bot`
4. Event Subscription → select **Long Connection** → add `im.message.receive_v1`
5. Note your **App ID** (`cli_xxx`) and **App Secret** → Publish the app
> **Note**: Feishu requires an active WebSocket connection before you can save "Long Connection" mode. Start nanobot first (Step 3), then come back to configure Event Subscription.
</details>
### Step 2 · Configure
```bash
cp nanobot_config.json.example nanobot_config.json
```
Edit `nanobot_config.json` — fill in the 3 required fields:
```jsonc
{
"channels": {
"feishu": {
"enabled": true,
"appId": "cli_xxx", // ← Feishu App ID
"appSecret": "xxx", // ← Feishu App Secret
"allowFrom": [] // [] = allow all users
}
},
"providers": {
"openrouter": {
"apiKey": "sk-or-v1-xxx" // ← OpenRouter API Key
}
},
"agents": {
"defaults": {
"model": "anthropic/claude-sonnet-4-20250514"
}
}
}
```
> **Model choice**: Any model on [openrouter.ai/models](https://openrouter.ai/models). Use `anthropic/claude-sonnet-4-20250514` for English, `minimax/minimax-m2.1` for Chinese.
---
### Step 3 · Launch
Make sure `mcp_agent.secrets.yaml` has your DeepCode API keys (see [Configuration](#-step-2-configuration)), then:
```bash
./nanobot/run_nanobot.sh -d # Start both DeepCode + nanobot in background
```
The script checks Docker, validates configs, builds images (first run only), and starts both containers.
```
✓ DeepCode API: http://localhost:8000
✓ Nanobot: http://localhost:18790
```
Now open Feishu → find your bot → send a message!
<details>
<summary><b>Management Commands</b></summary>
```bash
./nanobot/run_nanobot.sh # Start (foreground)
./nanobot/run_nanobot.sh -d # Start (background)
./nanobot/run_nanobot.sh stop # Stop all services
./nanobot/run_nanobot.sh restart # Restart (config changes take effect immediately)
./nanobot/run_nanobot.sh --build # Force rebuild Docker images
./nanobot/run_nanobot.sh logs # View real-time logs
./nanobot/run_nanobot.sh status # Health check
./nanobot/run_nanobot.sh clean # Remove containers & images
```
</details>
<details>
<summary><b>Troubleshooting</b></summary>
| Problem | Fix |
|---|---|
| Feishu bot doesn't respond | Check logs (`./nanobot/run_nanobot.sh logs`), verify `appId`/`appSecret`, ensure app is published with Long Connection mode |
| Can't connect to DeepCode | Verify `deepcode` container is healthy: `curl http://localhost:8000/health` |
| Wrong language output | Switch model — `minimax-m2.1` defaults to Chinese, use Claude/GPT for English |
| Config not taking effect | Just restart: `./nanobot/run_nanobot.sh restart` (no rebuild needed) |
| Clear chat history | Send `/clear` in chat, or: `docker exec nanobot sh -c 'rm -rf /root/.nanobot/sessions/*.jsonl'` |
</details>
---
## 💡 Examples
### 🎬 **Live Demonstrations**
<table align="center">
<tr>
<td width="33%" align="center">
#### 📄 **Paper2Code Demo**
**Research to Implementation**
<div align="center">
<a href="https://www.youtube.com/watch?v=MQZYpLkzsbw">
<img src="https://img.youtube.com/vi/MQZYpLkzsbw/maxresdefault.jpg" alt="Paper2Code Demo" width="100%" style="border-radius: 10px; box-shadow: 0 4px 8px rgba(0,0,0,0.1);"/>
</a>
**[▶️ Watch Demo](https://www.youtube.com/watch?v=MQZYpLkzsbw)**
*Transform academic papers into production-ready code automatically*
</div>
</td>
<td width="33%" align="center">
#### 🖼️ **Image Processing Demo**
**AI-Powered Image Tools**
<div align="center">
<a href="https://www.youtube.com/watch?v=nFt5mLaMEac">
<img src="https://img.youtube.com/vi/nFt5mLaMEac/maxresdefault.jpg" alt="Image Processing Demo" width="100%" style="border-radius: 10px; box-shadow: 0 4px 8px rgba(0,0,0,0.1);"/>
</a>
**[▶️ Watch Demo](https://www.youtube.com/watch?v=nFt5mLaMEac)**
*Intelligent image processing with background removal and enhancement*
</div>
</td>
<td width="33%" align="center">
#### 🌐 **Frontend Implementation**
**Complete Web Application**
<div align="center">
<a href="https://www.youtube.com/watch?v=78wx3dkTaAU">
<img src="https://img.youtube.com/vi/78wx3dkTaAU/maxresdefault.jpg" alt="Frontend Demo" width="100%" style="border-radius: 10px; box-shadow: 0 4px 8px rgba(0,0,0,0.1);"/>
</a>
**[▶️ Watch Demo](https://www.youtube.com/watch?v=78wx3dkTaAU)**
*Full-stack web development from concept to deployment*
</div>
</td>
</tr>
</table>
### 🆕 **Recent Updates**
#### 📄 **Smart Document Segmentation (v1.2.0)**
- **Intelligent Processing**: Automatically handles large research papers and technical documents that exceed LLM token limits
- **Configurable Control**: Toggle segmentation via configuration with size-based thresholds
- **Semantic Analysis**: Advanced content understanding with algorithm, concept, and formula preservation
- **Backward Compatibility**: Seamlessly falls back to traditional processing for smaller documents
### 🚀 **Coming Soon**
We're continuously enhancing DeepCode with exciting new features:
#### 🔧 **Enhanced Code Reliability & Validation**
- **Automated Testing**: Comprehensive functionality testing with execution verification and error detection.
- **Code Quality Assurance**: Multi-level validation through static analysis, dynamic testing, and performance benchmarking.
- **Smart Debugging**: AI-powered error detection with automatic correction suggestions
#### 📊 **PaperBench Performance Showcase**
- **Benchmark Dashboard**: Comprehensive performance metrics on the PaperBench evaluation suite.
- **Accuracy Metrics**: Detailed comparison with state-of-the-art paper reproduction systems.
- **Success Analytics**: Statistical analysis across paper categories and complexity levels.
#### ⚡ **System-wide Optimizations**
- **Performance Boost**: Multi-threaded processing and optimized agent coordination for faster generation.
- **Enhanced Reasoning**: Advanced reasoning capabilities with improved context understanding.
- **Expanded Support**: Extended compatibility with additional programming languages and frameworks.
---
## ⭐ Star History
<div align="center">
*Community Growth Trajectory*
<a href="https://star-history.com/#HKUDS/DeepCode&Date">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=HKUDS/DeepCode&type=Date&theme=dark" />
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=HKUDS/DeepCode&type=Date" />
<img alt="Star History Chart" src="https://api.star-history.com/svg?repos=HKUDS/DeepCode&type=Date" style="border-radius: 15px; box-shadow: 0 0 30px rgba(0, 217, 255, 0.3);" />
</picture>
</a>
</div>
---
### 🚀 **Ready to Transform Development?**
<div align="center">
<p>
<a href="#-quick-start"><img src="https://img.shields.io/badge/🚀_Get_Started-00d4ff?style=for-the-badge&logo=rocket&logoColor=white" alt="Get Started"></a>
<a href="https://github.com/HKUDS"><img src="https://img.shields.io/badge/🏛️_View_on_GitHub-00d4ff?style=for-the-badge&logo=github&logoColor=white" alt="View on GitHub"></a>
<a href="https://github.com/HKUDS/deepcode-agent"><img src="https://img.shields.io/badge/⭐_Star_Project-00d4ff?style=for-the-badge&logo=star&logoColor=white" alt="Star Project"></a>
</p>
---
<div align="left">
### 📖 **Citation**
If you find DeepCode useful in your research or applications, please kindly cite:
```
@misc{li2025deepcodeopenagenticcoding,
title={DeepCode: Open Agentic Coding},
author={Zongwei Li and Zhonghang Li and Zirui Guo and Xubin Ren and Chao Huang},
year={2025},
eprint={2512.07921},
archivePrefix={arXiv},
primaryClass={cs.SE},
url={https://arxiv.org/abs/2512.07921},
}
```
---
### 📄 **License**
<div align="center">
<img src="https://img.shields.io/badge/License-MIT-4ecdc4?style=for-the-badge&logo=opensourceinitiative&logoColor=white" alt="MIT License">
**MIT License** - Copyright (c) 2025 Data Intelligence Lab, The University of Hong Kong
---
<img src="https://visitor-badge.laobi.icu/badge?page_id=deepcode.readme&style=for-the-badge&color=00d4ff" alt="Visitors">
</div>
================================================
FILE: README_ZH.md
================================================
<div align="center">
<table style="border: none; margin: 0 auto; padding: 0; border-collapse: collapse;">
<tr>
<td align="center" style="vertical-align: middle; padding: 10px; border: none; width: 250px;">
<img src="assets/logo.png" alt="DeepCode Logo" width="200" style="margin: 0; padding: 0; display: block;"/>
</td>
<td align="left" style="vertical-align: middle; padding: 10px 0 10px 30px; border: none;">
<pre style="font-family: 'Courier New', monospace; font-size: 16px; color: #0EA5E9; margin: 0; padding: 0; text-shadow: 0 0 10px #0EA5E9, 0 0 20px rgba(14,165,233,0.5); line-height: 1.2; transform: skew(-1deg, 0deg); display: block;"> ██████╗ ███████╗███████╗██████╗ ██████╗ ██████╗ ██████╗ ███████╗
██╔══██╗██╔════╝██╔════╝██╔══██╗██╔════╝██╔═══██╗██╔══██╗██╔════╝
██║ ██║█████╗ █████╗ ██████╔╝██║ ██║ ██║██║ ██║█████╗
██║ ██║██╔══╝ ██╔══╝ ██╔═══╝ ██║ ██║ ██║██║ ██║██╔══╝
██████╔╝███████╗███████╗██║ ╚██████╗╚██████╔╝██████╔╝███████╗
╚═════╝ ╚══════╝╚══════╝╚═╝ ╚═════╝ ╚═════╝ ╚═════╝ ╚══════╝</pre>
</td>
</tr>
</table>
<div align="center">
<a href="https://trendshift.io/repositories/14665" target="_blank"><img src="https://trendshift.io/api/badge/repositories/14665" alt="HKUDS%2FDeepCode | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>
</div>
<!-- <img src="https://readme-typing-svg.herokuapp.com?font=Russo+One&size=28&duration=2000&pause=800&color=06B6D4&background=00000000¢er=true&vCenter=true&width=800&height=50&lines=%E2%9A%A1+OPEN+AGENTIC+CODING+%E2%9A%A1" alt="DeepCode Tech Subtitle" style="margin-top: 5px; filter: drop-shadow(0 0 12px #06B6D4) drop-shadow(0 0 24px rgba(6,182,212,0.4));"/> -->
# <img src="https://github.com/Zongwei9888/Experiment_Images/raw/43c585dca3d21b8e4b6390d835cdd34dc4b4b23d/DeepCode_images/title_logo.svg" alt="DeepCode Logo" width="32" height="32" style="vertical-align: middle; margin-right: 8px;"/> DeepCode: 开源智能体编程
### *基于多智能体系统推进代码生成技术*
<!-- <p align="center">
<img src="https://img.shields.io/badge/Version-1.0.0-00d4ff?style=for-the-badge&logo=rocket&logoColor=white" alt="Version">
<img src="https://img.shields.io/badge/License-MIT-4ecdc4?style=for-the-badge&logo=opensourceinitiative&logoColor=white" alt="License">
<img src="https://img.shields.io/badge/AI-Multi--Agent-9b59b6?style=for-the-badge&logo=brain&logoColor=white" alt="AI">
<img src="https://img.shields.io/badge/HKU-Data_Intelligence_Lab-f39c12?style=for-the-badge&logo=university&logoColor=white" alt="HKU">
</p> -->
<p>
<a href="https://github.com/HKUDS/DeepCode/stargazers"><img src='https://img.shields.io/github/stars/HKUDS/DeepCode?color=00d9ff&style=for-the-badge&logo=star&logoColor=white&labelColor=1a1a2e' /></a>
<img src="https://img.shields.io/badge/🐍Python-3.13-4ecdc4?style=for-the-badge&logo=python&logoColor=white&labelColor=1a1a2e">
<a href="https://pypi.org/project/deepcode-hku/"><img src="https://img.shields.io/pypi/v/deepcode-hku.svg?style=for-the-badge&logo=pypi&logoColor=white&labelColor=1a1a2e&color=ff6b6b"></a>
</p>
<p>
<a href="https://discord.gg/yF2MmDJyGJ"><img src="https://img.shields.io/badge/💬Discord-社区-7289da?style=for-the-badge&logo=discord&logoColor=white&labelColor=1a1a2e"></a>
<a href="https://github.com/HKUDS/DeepCode/issues/11"><img src="https://img.shields.io/badge/💬微信-群组-07c160?style=for-the-badge&logo=wechat&logoColor=white&labelColor=1a1a2e"></a>
</p>
<div align="center">
<div style="width: 100%; height: 2px; margin: 20px 0; background: linear-gradient(90deg, transparent, #00d9ff, transparent);"></div>
</div>
<div align="center">
<a href="#-快速开始" style="text-decoration: none;">
<img src="https://img.shields.io/badge/快速开始-立即开始-00d9ff?style=for-the-badge&logo=rocket&logoColor=white&labelColor=1a1a2e">
</a>
</div>
<div align="center" style="margin-top: 10px;">
<a href="README.md">
<img src="https://img.shields.io/badge/English-00d4ff?style=for-the-badge&logo=readme&logoColor=white&labelColor=1a1a2e" alt="English">
</a>
<a href="README_ZH.md">
<img src="https://img.shields.io/badge/中文-00d4ff?style=for-the-badge&logo=readme&logoColor=white&labelColor=1a1a2e" alt="中文">
</a>
</div>
### 🖥️ **界面展示**
<table align="center" width="100%" style="border: none; border-collapse: collapse; margin: 30px 0;">
<tr>
<td width="50%" align="center" style="vertical-align: top; padding: 20px;">
#### 🖥️ **命令行界面**
**基于终端的开发环境**
<div align="center">
<img src="https://github.com/Zongwei9888/Experiment_Images/blob/8882a7313c504ca97ead6e7b36c51aa761b6a4f3/DeepCode_images/CLI.gif" alt="CLI Interface Demo" width="100%" style="border-radius: 10px; box-shadow: 0 8px 20px rgba(45,55,72,0.3); margin: 15px 0;"/>
<div style="background: linear-gradient(135deg, #2D3748 0%, #4A5568 100%); border-radius: 12px; padding: 15px; margin: 15px 0; color: white;">
<strong>🚀 高级终端体验</strong><br/>
<small>⚡ 快速命令行工作流<br/>🔧 开发者友好界面<br/>📊 实时进度跟踪</small>
</div>
*专业终端界面,适合高级用户和CI/CD集成*
</div>
</td>
<td width="50%" align="center" style="vertical-align: top; padding: 20px;">
#### 🌐 **Web界面**
**可视化交互体验**
<div align="center">
<img src="https://github.com/Zongwei9888/Experiment_Images/raw/8882a7313c504ca97ead6e7b36c51aa761b6a4f3/DeepCode_images/UI.gif" alt="Web Interface Demo" width="100%" style="border-radius: 10px; box-shadow: 0 8px 20px rgba(14,165,233,0.3); margin: 15px 0;"/>
<div style="background: linear-gradient(135deg, #0EA5E9 0%, #00D4FF 100%); border-radius: 12px; padding: 15px; margin: 15px 0; color: white;">
<strong>🎨 现代化Web仪表板</strong><br/>
<small>🖱️ 直观的拖拽操作<br/>📱 响应式设计<br/>🎯 可视化进度跟踪</small>
</div>
*美观的Web界面,为所有技能水平用户提供流畅的工作流程*
</div>
</td>
</tr>
</table>
---
<div align="center">
### 🎬 **介绍视频**
<div style="margin: 20px 0;">
<a href="https://youtu.be/PRgmP8pOI08" target="_blank">
<img src="https://img.youtube.com/vi/PRgmP8pOI08/maxresdefault.jpg"
alt="DeepCode Introduction Video"
width="75%"
style="border-radius: 12px; box-shadow: 0 8px 25px rgba(0,0,0,0.15); transition: transform 0.3s ease;"/>
</a>
</div>
*🎯 **观看我们的完整介绍** - 了解DeepCode如何将研究论文和自然语言转换为生产就绪的代码*
<p>
<a href="https://youtu.be/PRgmP8pOI08" target="_blank">
<img src="https://img.shields.io/badge/▶️_观看视频-FF0000?style=for-the-badge&logo=youtube&logoColor=white" alt="Watch Video"/>
</a>
</p>
</div>
---
> *"AI智能体将创意转化为生产就绪代码的地方"*
</div>
---
## 📑 目录
- [📰 新闻](#-新闻)
- [🚀 核心特性](#-核心特性)
- [🏗️ 架构](#️-架构)
- [📊 实验结果](#-实验结果)
- [🚀 快速开始](#-快速开始)
- [🤖 nanobot 集成(飞书聊天机器人)](#-nanobot-集成飞书聊天机器人)
- [💡 示例](#-示例)
- [🎬 实时演示](#-实时演示)
- [⭐ 星标历史](#-星标历史)
- [📄 许可证](#-许可证)
---
## 📰 新闻
🎉 **[2026-02] DeepCode + nanobot 集成 — 通过飞书聊天使用 DeepCode!**
<div align="center">
<table><tr>
<td align="center"><a href="https://github.com/HKUDS/DeepCode"><img src="./assets/logo.png" alt="DeepCode" height="60"/></a></td>
<td align="center"><h2>✦</h2></td>
<td align="center"><a href="https://github.com/HKUDS/nanobot"><img src="./assets/nanobot.png" alt="nanobot" height="60"/></a></td>
</tr></table>
</div>
- [nanobot](https://github.com/HKUDS/nanobot) 现已连接到 DeepCode — 在**飞书**中发送消息即可自动生成代码
- 支持**论文转代码**和**对话转代码**,以及实时任务跟踪,全部在聊天应用中完成
- 一键部署:`./nanobot/run_nanobot.sh` → **[设置指南 →](#-nanobot-集成飞书聊天机器人)**
<div align="center">
<table width="100%"><tr>
<td width="50%" align="center">
<img src="./assets/IMG_8098.jpeg" alt="飞书聊天示例 1" width="95%" style="border-radius: 10px; box-shadow: 0 4px 15px rgba(0,0,0,0.2);"/>
</td>
<td width="50%" align="center">
<img src="./assets/IMG_8099.jpeg" alt="飞书聊天示例 2" width="95%" style="border-radius: 10px; box-shadow: 0 4px 15px rgba(0,0,0,0.2);"/>
</td>
</tr></table>
<sub><em>飞书机器人实战 — 自然语言 → 完整代码生成,带设置说明</em></sub>
</div>
---
🎉 **[2026-02] 全新 Web UI 体验升级!**
- 🔄 **用户交互循环 (User-in-Loop)**: 支持工作流程中的实时用户交互,AI 会在对话中向您提问以澄清需求
- 💬 **内联交互设计**: 交互问题直接显示在对话框中,体验更自然流畅
- 🚀 **一键启动**: 运行 `deepcode` 即可启动新版 UI(跨平台支持:Windows/macOS/Linux)
- 🔧 **优化的进程管理**: 改进了服务启停机制,自动清理端口占用
- 📡 **WebSocket 实时通信**: 修复了消息丢失问题,确保交互状态正确同步
<div align="center">
<img src="./assets/NewUI.png" alt="DeepCode 全新 UI" width="85%" style="border-radius: 12px; box-shadow: 0 4px 20px rgba(0,0,0,0.15);" />
<br/>
<sub><em>DeepCode 全新 Web UI - 基于 React 的现代界面</em></sub>
</div>
---
🎉 **[2025-10-28] DeepCode在PaperBench上达到最先进水平!**
DeepCode在OpenAI的PaperBench Code-Dev所有类别中创造新基准:
- 🏆 **超越人类专家**: **75.9%** (DeepCode) vs 顶级机器学习博士 72.4% (+3.5%)。
- 🥇 **超越最先进商业代码智能体**: **84.8%** (DeepCode) vs 领先商业代码智能体 (+26.1%) (Cursor, Claude Code, 和 Codex)。
- 🔬 **推进科学编程**: **73.5%** (DeepCode) vs PaperCoder 51.1% (+22.4%)。
- 🚀 **击败LLM智能体**: **73.5%** (DeepCode) vs 最佳LLM框架 43.3% (+30.2%)。
---
## 🚀 核心特性
<br/>
<table align="center" width="100%" style="border: none; table-layout: fixed;">
<tr>
<td width="30%" align="center" style="vertical-align: top; padding: 20px;">
<div style="height: 80px; display: flex; align-items: center; justify-content: center;">
<h3 style="margin: 0; padding: 0;">🚀 <strong>论文转代码</strong></h3>
</div>
<div align="center" style="margin: 15px 0;">
<img src="https://img.shields.io/badge/算法-实现-ff6b6b?style=for-the-badge&logo=algorithm&logoColor=white" alt="Algorithm Badge" />
</div>
<div style="height: 80px; display: flex; align-items: center; justify-content: center;">
<p align="center"><strong>复杂算法的自动化实现</strong></p>
</div>
<div style="height: 60px; display: flex; align-items: center; justify-content: center;">
<p align="center">轻松将研究论文中的复杂算法转换为<strong>高质量</strong>、<strong>生产就绪</strong>的代码,加速算法复现。</p>
</div>
</td>
<td width="30%" align="center" style="vertical-align: top; padding: 20px;">
<div style="height: 80px; display: flex; align-items: center; justify-content: center;">
<h3 style="margin: 0; padding: 0;">🎨 <strong>文本转Web</strong></h3>
</div>
<div align="center" style="margin: 15px 0;">
<img src="https://img.shields.io/badge/前端-开发-4ecdc4?style=for-the-badge&logo=react&logoColor=white" alt="Frontend Badge" />
</div>
<div style="height: 80px; display: flex; align-items: center; justify-content: center;">
<p align="center"><strong>自动化前端Web开发</strong></p>
</div>
<div style="height: 60px; display: flex; align-items: center; justify-content: center;">
<p align="center">将纯文本描述转换为<strong>功能完整</strong>、<strong>视觉美观</strong>的前端Web代码,快速创建界面。</p>
</div>
</td>
<td width="30%" align="center" style="vertical-align: top; padding: 20px;">
<div style="height: 80px; display: flex; align-items: center; justify-content: center;">
<h3 style="margin: 0; padding: 0;">⚙️ <strong>文本转后端</strong></h3>
</div>
<div align="center" style="margin: 15px 0;">
<img src="https://img.shields.io/badge/后端-开发-9b59b6?style=for-the-badge&logo=server&logoColor=white" alt="Backend Badge" />
</div>
<div style="height: 80px; display: flex; align-items: center; justify-content: center;">
<p align="center"><strong>自动化后端开发</strong></p>
</div>
<div style="height: 60px; display: flex; align-items: center; justify-content: center;">
<p align="center">从简单的文本输入生成<strong>高效</strong>、<strong>可扩展</strong>和<strong>功能丰富</strong>的后端代码,简化服务器端开发。</p>
</div>
</td>
</tr>
</table>
<br/>
---
## 📊 实验结果
<div align="center">
<img src='./assets/result_main02.jpg' /><br>
</div>
<br/>
我们在[*PaperBench*](https://openai.com/index/paperbench/)基准测试(由OpenAI发布)上评估**DeepCode**,这是一个严格的测试平台,要求AI智能体从头独立复现20篇ICML 2024论文。该基准包含8,316个可评分组件,使用带有分层权重的SimpleJudge进行评估。
我们的实验将DeepCode与四个基线类别进行比较:**(1) 人类专家**,**(2) 最先进商业代码智能体**,**(3) 科学代码智能体**,以及 **(4) 基于LLM的智能体**。
### ① 🧠 人类专家表现(顶级机器学习博士)
**DeepCode: 75.9% vs. 顶级机器学习博士: 72.4% (+3.5%)**
DeepCode在3篇论文的人类评估子集上达到**75.9%**,**超越3次人类专家基线(72.4%)+3.5个百分点**。这表明我们的框架不仅匹配而且超越了专家级代码复现能力,代表了自主科学软件工程的重要里程碑。
### ② 💼 最先进商业代码智能体
**DeepCode: 84.8% vs. 最佳商业智能体: 58.7% (+26.1%)**
在5篇论文的子集上,DeepCode大幅超越领先的商业编码工具:
- Cursor: 58.4%
- Claude Code: 58.7%
- Codex: 40.0%
- **DeepCode: 84.8%**
这代表了相对于领先商业代码智能体的**+26.1%改进**。所有商业智能体都使用Claude Sonnet 4.5或GPT-5 Codex-high,突出了**DeepCode的卓越架构**——而非基础模型能力——推动了这一性能差距。
### ③ 🔬 科学代码智能体
**DeepCode: 73.5% vs. PaperCoder: 51.1% (+22.4%)**
与最先进的科学代码复现框架PaperCoder(**51.1%**)相比,DeepCode达到**73.5%**,展示了**+22.4%的相对改进**。这一显著差距验证了我们结合规划、分层任务分解、代码生成和迭代调试的多模块架构优于简单的管道式方法。
### ④ 🤖 基于LLM的智能体
**DeepCode: 73.5% vs. 最佳LLM智能体: 43.3% (+30.2%)**
DeepCode显著超越所有测试的LLM智能体:
- Claude 3.5 Sonnet + IterativeAgent: 27.5%
- o1 + IterativeAgent (36小时): 42.4%
- o1 BasicAgent: 43.3%
- **DeepCode: 73.5%**
相对于表现最佳的LLM智能体的**+30.2%改进**表明,复杂的智能体框架,而非延长的推理时间或更大的模型,对于复杂的代码复现任务至关重要。
---
### 🎯 **自主多智能体工作流**
**面临的挑战**:
- 📄 **实现复杂性**: 将学术论文和复杂算法转换为可运行代码需要大量技术投入和领域专业知识
- 🔬 **研究瓶颈**: 研究人员将宝贵时间花在算法实现上,而不是专注于核心研究和发现工作
- ⏱️ **开发延迟**: 产品团队在概念和可测试原型之间经历长时间等待,减慢创新周期
- 🔄 **重复编码**: 开发者重复实现相似的模式和功能,而不是基于现有解决方案构建
**DeepCode** 通过为常见开发任务提供可靠的自动化来解决这些工作流程低效问题,简化从概念到代码的开发工作流程。
<div align="center">
```mermaid
flowchart LR
A["📄 研究论文<br/>💬 文本提示<br/>🌐 URL和文档<br/>📎 文件: PDF, DOC, PPTX, TXT, HTML"] --> B["🧠 DeepCode<br/>多智能体引擎"]
B --> C["🚀 算法实现 <br/>🎨 前端开发 <br/>⚙️ 后端开发"]
style A fill:#ff6b6b,stroke:#c0392b,stroke-width:2px,color:#000
style B fill:#00d4ff,stroke:#0984e3,stroke-width:3px,color:#000
style C fill:#00b894,stroke:#00a085,stroke-width:2px,color:#000
```
</div>
---
## 🏗️ 架构
### 📊 **系统概述**
**DeepCode** 是一个AI驱动的开发平台,自动化代码生成和实现任务。我们的多智能体系统处理将需求转换为功能性、结构良好代码的复杂性,让您专注于创新而非实现细节。
🎯 **技术能力**:
🧬 **研究到生产流水线**<br>
多模态文档分析引擎,从学术论文中提取算法逻辑和数学模型。生成优化的实现,使用适当的数据结构,同时保持计算复杂度特征。
🪄 **自然语言代码合成**<br>
使用在精选代码库上训练的微调语言模型进行上下文感知代码生成。在支持多种编程语言和框架的同时保持模块间架构一致性。
⚡ **自动化原型引擎**<br>
智能脚手架系统,生成包括数据库模式、API端点和前端组件的完整应用程序结构。使用依赖分析确保从初始生成开始的可扩展架构。
💎 **质量保证自动化**<br>
集成静态分析与自动化单元测试生成和文档合成。采用AST分析进行代码正确性检查和基于属性的测试进行全面覆盖。
🔮 **CodeRAG集成系统**<br>
高级检索增强生成,结合语义向量嵌入和基于图的依赖分析。从大规模代码语料库中自动发现最优库和实现模式。
---
### 🔧 **核心技术**
- 🧠 **智能编排智能体**: 协调工作流阶段和分析需求的中央决策系统。采用动态规划算法,根据不断发展的项目复杂性实时调整执行策略。为每个实现步骤动态选择最优处理策略。 <br>
- 💾 **高效内存机制**: 高效管理大规模代码上下文的高级上下文工程系统。实现分层内存结构,具有智能压缩功能,用于处理复杂代码库。该组件实现实现模式的即时检索,并在扩展开发会话中保持语义一致性。 <br>
- 🔍 **高级CodeRAG系统**: 分析跨存储库复杂相互依赖关系的全局代码理解引擎。执行跨代码库关系映射,从整体角度理解架构模式。该模块利用依赖图和语义分析在实现过程中提供全局感知的代码建议。
---
### 🤖 **DeepCode的多智能体架构**:
- **🎯 中央编排智能体**: 编排整个工作流程执行并做出战略决策。基于输入复杂性分析协调专门智能体。实现动态任务规划和资源分配算法。 <br>
- **📝 意图理解智能体**: 对用户需求进行深度语义分析以解码复杂意图。通过高级NLP处理提取功能规范和技术约束。通过结构化任务分解将模糊的人类描述转换为精确、可操作的开发规范。 <br>
- **📄 文档解析智能体**: 使用高级解析能力处理复杂的技术文档和研究论文。使用文档理解模型提取算法和方法。通过智能内容分析将学术概念转换为实用的实现规范。 <br>
- **🏗️ 代码规划智能体**: 执行架构设计和技术栈优化。动态规划适应性开发路线图。通过自动化设计模式选择执行编码标准并生成模块化结构。<br>
- **🔍 代码参考挖掘智能体**: 通过智能搜索算法发现相关存储库和框架。分析代码库的兼容性和集成潜力。基于相似性度量和自动化依赖分析提供建议。 <br>
- **📚 代码索引智能体**: 构建发现代码库的综合知识图谱。维护代码组件之间的语义关系。实现智能检索和交叉引用能力。 <br>
- **🧬 代码生成智能体**: 将收集的信息合成为可执行的代码实现。创建功能接口并集成发现的组件。生成全面的测试套件和文档以确保可重现性。
---
#### 🛠️ **实现工具矩阵**
**🔧 基于MCP (模型上下文协议) 驱动**
DeepCode利用**模型上下文协议 (MCP)** 标准与各种工具和服务无缝集成。这种标准化方法确保AI智能体和外部系统之间的可靠通信,实现强大的自动化能力。
##### 📡 **MCP服务器和工具**
| 🛠️ **MCP服务器** | 🔧 **主要功能** | 💡 **目的和能力** |
|-------------------|-------------------------|-------------------------------|
| **🔍 brave** | Web搜索引擎 | 通过Brave搜索API进行实时信息检索 |
| **🌐 bocha-mcp** | 替代搜索 | 具有独立API访问的辅助搜索选项 |
| **📂 filesystem** | 文件系统操作 | 本地文件和目录管理,读/写操作 |
| **🌐 fetch** | Web内容检索 | 从URL和Web资源获取和提取内容 |
| **📥 github-downloader** | 存储库管理 | 克隆和下载GitHub存储库进行分析 |
| **📋 file-downloader** | 文档处理 | 下载文件(PDF、DOCX等)并转换为Markdown |
| **⚡ command-executor** | 系统命令 | 执行bash/shell命令进行环境管理 |
| **🧬 code-implementation** | 代码生成中心 | 具有执行和测试的综合代码复现 |
| **📚 code-reference-indexer** | 智能代码搜索 | 代码存储库的智能索引和搜索 |
| **📄 document-segmentation** | 智能文档分析 | 大型论文和技术文档的智能文档分割 |
##### 🔧 **传统工具功能** *(供参考)*
| 🛠️ **功能** | 🎯 **使用上下文** |
|-----------------|---------------------|
| **📄 read_code_mem** | 从内存高效检索代码上下文 |
| **✍️ write_file** | 直接文件内容生成和修改 |
| **🐍 execute_python** | Python代码测试和验证 |
| **📁 get_file_structure** | 项目结构分析和组织 |
| **⚙️ set_workspace** | 动态工作空间和环境配置 |
| **📊 get_operation_history** | 过程监控和操作跟踪 |
---
🎛️ **多界面框架**<br>
具有CLI和Web前端的RESTful API,具有实时代码流、交互式调试和可扩展插件架构,用于CI/CD集成。
**🚀 多智能体智能流水线:**
<div align="center">
### 🌟 **智能处理流程**
<table align="center" width="100%" style="border: none; border-collapse: collapse;">
<tr>
<td colspan="3" align="center" style="padding: 20px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border-radius: 15px; color: white; font-weight: bold;">
💡 <strong>输入层</strong><br/>
📄 研究论文 • 💬 自然语言 • 🌐 URL • 📋 需求
</td>
</tr>
<tr><td colspan="3" height="20"></td></tr>
<tr>
<td colspan="3" align="center" style="padding: 15px; background: linear-gradient(135deg, #ff6b6b 0%, #ee5a24 100%); border-radius: 12px; color: white; font-weight: bold;">
🎯 <strong>中央编排</strong><br/>
战略决策制定 • 工作流程协调 • 智能体管理
</td>
</tr>
<tr><td colspan="3" height="15"></td></tr>
<tr>
<td align="center" style="padding: 12px; background: linear-gradient(135deg, #3742fa 0%, #2f3542 100%); border-radius: 10px; color: white; width: 50%;">
📝 <strong>文本分析</strong><br/>
<small>需求处理</small>
</td>
<td width="10"></td>
<td align="center" style="padding: 12px; background: linear-gradient(135deg, #8c7ae6 0%, #9c88ff 100%); border-radius: 10px; color: white; width: 50%;">
📄 <strong>文档分析</strong><br/>
<small>论文和规范处理</small>
</td>
</tr>
<tr><td colspan="3" height="15"></td></tr>
<tr>
<td colspan="3" align="center" style="padding: 15px; background: linear-gradient(135deg, #00d2d3 0%, #54a0ff 100%); border-radius: 12px; color: white; font-weight: bold;">
📋 <strong>复现规划</strong><br/>
深度论文分析 • 代码需求解析 • 复现策略开发
</td>
</tr>
<tr><td colspan="3" height="15"></td></tr>
<tr>
<td align="center" style="padding: 12px; background: linear-gradient(135deg, #ffa726 0%, #ff7043 100%); border-radius: 10px; color: white; width: 50%;">
🔍 <strong>参考分析</strong><br/>
<small>存储库发现</small>
</td>
<td width="10"></td>
<td align="center" style="padding: 12px; background: linear-gradient(135deg, #e056fd 0%, #f368e0 100%); border-radius: 10px; color: white; width: 50%;">
📚 <strong>代码索引</strong><br/>
<small>知识图谱构建</small>
</td>
</tr>
<tr><td colspan="3" height="15"></td></tr>
<tr>
<td colspan="3" align="center" style="padding: 15px; background: linear-gradient(135deg, #26de81 0%, #20bf6b 100%); border-radius: 12px; color: white; font-weight: bold;">
🧬 <strong>代码实现</strong><br/>
实现生成 • 测试 • 文档
</td>
</tr>
<tr><td colspan="3" height="15"></td></tr>
<tr>
<td colspan="3" align="center" style="padding: 20px; background: linear-gradient(135deg, #045de9 0%, #09c6f9 100%); border-radius: 15px; color: white; font-weight: bold;">
⚡ <strong>输出交付</strong><br/>
📦 完整代码库 • 🧪 测试套件 • 📚 文档 • 🚀 部署就绪
</td>
</tr>
</table>
</div>
<div align="center">
<br/>
### 🔄 **流程智能特性**
<table align="center" style="border: none;">
<tr>
<td align="center" width="25%" style="padding: 15px;">
<div style="background: #f8f9fa; border-radius: 10px; padding: 15px; border-left: 4px solid #ff6b6b;">
<h4>🎯 自适应流程</h4>
<p><small>基于输入复杂性的动态智能体选择</small></p>
</div>
</td>
<td align="center" width="25%" style="padding: 15px;">
<div style="background: #f8f9fa; border-radius: 10px; padding: 15px; border-left: 4px solid #4ecdc4;">
<h4>🧠 智能协调</h4>
<p><small>智能任务分配和并行处理</small></p>
</div>
</td>
<td align="center" width="25%" style="padding: 15px;">
<div style="background: #f8f9fa; border-radius: 10px; padding: 15px; border-left: 4px solid #45b7d1;">
<h4>🔍 上下文感知</h4>
<p><small>通过CodeRAG集成的深度理解</small></p>
</div>
</td>
<td align="center" width="25%" style="padding: 15px;">
<div style="background: #f8f9fa; border-radius: 10px; padding: 15px; border-left: 4px solid #96ceb4;">
<h4>⚡ 质量保证</h4>
<p><small>全程自动化测试和验证</small></p>
</div>
</td>
</tr>
</table>
</div>
---
## 🚀 快速开始
### 📋 **前置条件**
在安装 DeepCode 之前,请确保您已安装以下软件:
| 要求 | 版本 | 用途 |
|------|------|------|
| **Python** | 3.9+ | 核心运行环境 |
| **Node.js** | 18+ | 新版 UI 前端 |
| **npm** | 8+ | 包管理工具 |
```bash
# 检查您的版本
python --version # 应为 3.9+
node --version # 应为 18+
npm --version # 应为 8+
```
<details>
<summary><strong>📥 安装 Node.js(如果未安装)</strong></summary>
```bash
# macOS (使用 Homebrew)
brew install node
# Ubuntu/Debian
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
sudo apt-get install -y nodejs
# Windows
# 从 https://nodejs.org/ 下载安装
```
</details>
### 📦 **步骤1: 安装**
选择以下任一安装方式:
#### ⚡ **直接安装 (推荐)**
```bash
# 🚀 直接安装 DeepCode 包
pip install deepcode-hku
# 🔑 下载配置文件
curl -O https://raw.githubusercontent.com/HKUDS/DeepCode/main/mcp_agent.config.yaml
curl -O https://raw.githubusercontent.com/HKUDS/DeepCode/main/mcp_agent.secrets.yaml
```
#### 🔧 **开发安装 (从源码)**
<details>
<summary><strong>📂 点击展开开发安装选项</strong></summary>
##### 🔥 **使用 UV (开发推荐)**
```bash
git clone https://github.com/HKUDS/DeepCode.git
cd DeepCode/
curl -LsSf https://astral.sh/uv/install.sh | sh
uv venv --python=3.13
source .venv/bin/activate # Windows下: .venv\Scripts\activate
uv pip install -r requirements.txt
# 安装前端依赖
npm install --prefix new_ui/frontend
```
##### 🐍 **使用传统 pip**
```bash
git clone https://github.com/HKUDS/DeepCode.git
cd DeepCode/
pip install -r requirements.txt
# 安装前端依赖
npm install --prefix new_ui/frontend
```
</details>
### 🔧 **步骤2: 配置**
> 以下配置适用于**所有安装方式**(pip、UV、源码安装和 Docker 均通用)。
#### 🔑 API 密钥 *(必需)*
编辑 `mcp_agent.secrets.yaml`,填入你的 API 密钥:
```yaml
# 至少需要配置一个 LLM 提供商的 API Key
openai:
api_key: "your_openai_api_key"
base_url: "https://openrouter.ai/api/v1" # 可选: 用于 OpenRouter 或自定义端点
anthropic:
api_key: "your_anthropic_api_key" # 用于 Claude 模型
google:
api_key: "your_google_api_key" # 用于 Gemini 模型
```
#### 🤖 LLM 提供商 *(可选)*
编辑 `mcp_agent.config.yaml` 选择你偏好的 LLM 提供商(第 ~106 行):
```yaml
# 选项: "google", "anthropic", "openai"
# 如果未设置或不可用,将自动回退到第一个可用的提供商
llm_provider: "google"
```
#### 🔍 搜索 API 密钥 *(可选)*
在 `mcp_agent.config.yaml` 中配置 Web 搜索:
```yaml
# Brave 搜索 (默认) — 在 brave.env 部分设置 (第 ~28 行)
brave:
env:
BRAVE_API_KEY: "your_brave_api_key_here"
# Bocha-MCP (替代) — 在 bocha-mcp.env 部分设置 (第 ~74 行)
bocha-mcp:
env:
BOCHA_API_KEY: "your_bocha_api_key_here"
```
#### 📄 文档分割 *(可选)*
在 `mcp_agent.config.yaml` 中控制文档处理:
```yaml
document_segmentation:
enabled: true # true/false — 是否使用智能文档分割
size_threshold_chars: 50000 # 触发分割的文档大小阈值
```
<details>
<summary><strong>🪟 Windows 用户: 额外的 MCP 服务器配置</strong></summary>
如果您使用 Windows,可能需要在 `mcp_agent.config.yaml` 中手动配置 MCP 服务器:
```bash
# 1. 全局安装 MCP 服务器
npm i -g @modelcontextprotocol/server-brave-search
npm i -g @modelcontextprotocol/server-filesystem
# 2. 找到您的全局 node_modules 路径
npm -g root
```
然后更新您的 `mcp_agent.config.yaml` 使用绝对路径:
```yaml
mcp:
servers:
brave:
command: "node"
args: ["C:/Program Files/nodejs/node_modules/@modelcontextprotocol/server-brave-search/dist/index.js"]
filesystem:
command: "node"
args: ["C:/Program Files/nodejs/node_modules/@modelcontextprotocol/server-filesystem/dist/index.js", "."]
```
> **注意**: 将路径替换为步骤 2 中您实际的全局 node_modules 路径。
</details>
<details>
<summary><strong>🔍 搜索服务器配置(可选)</strong></summary>
DeepCode 支持多个搜索服务器进行 Web 搜索功能。您可以在 `mcp_agent.config.yaml` 中配置首选选项:
```yaml
# 默认搜索服务器配置
# 选项: "brave" 或 "bocha-mcp"
default_search_server: "brave"
```
**可用选项:**
- **🔍 Brave 搜索** (`"brave"`): 具有高质量搜索结果的默认选项。需要 `BRAVE_API_KEY`。推荐给大多数用户。
- **🌐 Bocha-MCP** (`"bocha-mcp"`): 替代搜索服务器。需要 `BOCHA_API_KEY`。使用本地 Python 服务器实现。
**完整 MCP 服务器配置(mcp_agent.config.yaml):**
```yaml
# Brave 搜索 (默认) - 第 28 行左右
brave:
command: "npx"
args: ["-y", "@modelcontextprotocol/server-brave-search"]
env:
BRAVE_API_KEY: "your_brave_api_key_here"
# Bocha-MCP (替代) - 第 74 行左右
bocha-mcp:
command: "python"
args: ["tools/bocha_search_server.py"]
env:
PYTHONPATH: "."
BOCHA_API_KEY: "your_bocha_api_key_here"
```
> **💡 提示**: 两个搜索服务器都需要 API 密钥配置。选择最适合您的 API 访问和需求的选项。
</details>
### ⚡ **步骤3: 启动应用程序**
选择您偏好的启动方式:
<table width="100%">
<tr>
<th width="33%">🐳 Docker (推荐)</th>
<th width="33%">🚀 本地 (<code>deepcode</code> 命令)</th>
<th width="33%">🛠️ 其他方式</th>
</tr>
<tr><td>
无需 Python/Node — 一切在容器内。
```bash
git clone https://github.com/HKUDS/DeepCode.git
cd DeepCode/
cp mcp_agent.secrets.yaml.example \
mcp_agent.secrets.yaml
# 编辑填入 API Key
./deepcode_docker/run_docker.sh
# 访问 → http://localhost:8000
```
</td><td>
首次运行自动安装依赖。
```bash
deepcode
# 前端 → http://localhost:5173
# 后端 → http://localhost:8000
# Ctrl+C 停止
```
特性:用户交互循环、实时进度、内联对话。
</td><td>
```bash
# macOS / Linux
./run.sh
# 或: python deepcode.py
# Windows
run.bat
# 或: python deepcode.py
# 经典 Streamlit UI
deepcode --classic
# CLI 模式
deepcode --cli
# 或: python cli/main_cli.py
```
</td></tr>
</table>
<details>
<summary><strong>🐳 Docker 管理命令</strong></summary>
```bash
./deepcode_docker/run_docker.sh stop # 停止
./deepcode_docker/run_docker.sh restart # 重启(配置更改无需重建)
./deepcode_docker/run_docker.sh --build # 强制重建
./deepcode_docker/run_docker.sh logs # 实时日志
./deepcode_docker/run_docker.sh status # 健康检查
./deepcode_docker/run_docker.sh clean # 删除容器和镜像
```
或直接使用 Docker Compose:
```bash
docker compose -f deepcode_docker/docker-compose.yml up --build # 构建并启动
docker compose -f deepcode_docker/docker-compose.yml down # 停止
docker compose -f deepcode_docker/docker-compose.yml logs -f # 查看日志
```
> **💡** 配置文件以卷方式挂载 — 编辑后重启即可,无需重建。
> **💡** Windows 用户:如果脚本不可用,可直接运行 `docker compose` 命令。
</details>
### 🎯 **步骤4: 生成代码**
1. **📄 输入** — 上传研究论文、输入需求,或粘贴 URL
2. **🤖 处理** — 多智能体系统分析、规划并生成
3. **⚡ 输出** — 接收带测试和文档的生产就绪代码
---
### 🔧 **常见问题排查**
<details>
<summary><strong>❓ 常见问题与解决方案</strong></summary>
| 问题 | 原因 | 解决方案 |
|---|---|---|
| Docker 构建失败 `tsc: not found` | 构建缓存损坏 | `docker builder prune -f` 然后用 `--no-cache` 重建 |
| `error during connect` / `cannot find the file` | Docker Desktop 未运行 | 启动 Docker Desktop,等待就绪后重试 |
| 前端空白页面 | `node_modules` 损坏 | `cd new_ui/frontend && rm -rf node_modules && npm install` |
| `ERR_CONNECTION_REFUSED` | 端口错误/后端未运行 | Docker: `http://localhost:8000`。本地: `http://localhost:5173` |
| `npm install` → `Could not read package.json` | 目录错误 | 使用 `npm install --prefix new_ui/frontend` |
| Windows: MCP 服务器无法工作 | 需要绝对路径 | 参见上方 [Windows MCP 配置](#-步骤2-配置) |
</details>
---
## 🤖 nanobot 集成(飞书聊天机器人)
**直接在飞书中使用 DeepCode — 发送消息,获取代码!**
[nanobot](https://github.com/HKUDS/nanobot) 是一个超轻量级 AI 助手,现已与 DeepCode 深度集成。通过飞书聊天,您可以:
- 🚀 提交**论文转代码**任务(`paper2code`)— 粘贴 arXiv 链接即可
- 💬 启动**对话转代码**(`chat2code`)— 用自然语言描述需求
- 📊 实时查询任务状态(`deepcode_status`)— 获取进度和结果
- ✅ 响应 DeepCode 交互提示 — 当 AI 需要澄清需求时直接在聊天中回答
### 🏗️ 架构概览
```mermaid
flowchart TB
subgraph ChatPlatforms[💬 聊天平台]
Feishu[<b>飞书</b><br/>📱 当前支持]
Telegram[Telegram<br/>🔜 即将支持]
Discord[Discord<br/>🔜 即将支持]
end
subgraph NanobotCore[🤖 Nanobot 核心]
LLM[LLM 推理引擎<br/>Claude / GPT / Minimax]
Tools[工具层<br/>web_fetch / code_executor / deepcode]
end
subgraph DeepCodeEngine[⚡ DeepCode 引擎]
API[HTTP API<br/>任务提交 & 查询]
Agents[多智能体系统<br/>规划 / 分析 / 生成]
Output[代码输出<br/>测试 + 文档]
end
Feishu -->|WebSocket| NanobotCore
Telegram -.->|未来集成| NanobotCore
Discord -.->|未来集成| NanobotCore
NanobotCore -->|调用 deepcode_* 工具| DeepCodeEngine
DeepCodeEngine -->|返回结果 & 进度| NanobotCore
NanobotCore -->|推送消息| Feishu
style Feishu fill:#0EA5E9,stroke:#0284c7,stroke-width:3px,color:#fff
style NanobotCore fill:#8b5cf6,stroke:#7c3aed,stroke-width:2px,color:#fff
style DeepCodeEngine fill:#10b981,stroke:#059669,stroke-width:2px,color:#fff
style Telegram fill:#d1d5db,stroke:#9ca3af,stroke-width:1px,color:#4b5563,stroke-dasharray: 5 5
style Discord fill:#d1d5db,stroke:#9ca3af,stroke-width:1px,color:#4b5563,stroke-dasharray: 5 5
```
> 🎯 **当前支持**: 飞书(Feishu / Lark)
> 🔮 **架构预留**: Telegram 和 Discord 节点为未来扩展保留
---
### 📋 前置条件
- ✅ DeepCode 后端正在运行(见上方 [快速开始](#-快速开始))
- ✅ 飞书企业应用(或租用应用)— 免费创建
- ✅ LLM API 密钥(OpenRouter / Claude / Minimax)
---
### 🚀 三步完成设置
#### **Step 1 · 创建飞书机器人**
<details>
<summary><strong>📱 点击展开飞书应用创建步骤</strong></summary>
1. 登录 [飞书开放平台](https://open.feishu.cn/app)
2. 点击 **创建企业自建应用**
3. 填写应用名称和描述,上传图标
4. 进入 **凭证与基础信息** 页面,复制:
- `App ID`
- `App Secret`
5. 进入 **事件订阅** 页面:
- **请求地址 URL**: `http://your-server-ip:8081/feishu/event`(公网可访问)
- **消息加密**: 复制 `Encrypt Key` 和 `Verification Token`
6. 进入 **权限管理**,开通以下权限:
- `im:message`(接收消息)
- `im:message:send_as_bot`(发送消息)
- `im:chat`(获取群信息)
7. **发布版本** → 等待管理员审核通过
> 💡 **开发环境**: 可使用 [ngrok](https://ngrok.com/) 或 [localhost.run](https://localhost.run/) 将本地 8081 端口映射到公网。
</details>
---
#### **Step 2 · 配置**
编辑项目根目录的 `nanobot_config.json`:
```json
{
"channels": [
{
"type": "feishu",
"app_id": "cli_xxxxxxxxxxxxx",
"app_secret": "your_app_secret",
"encrypt_key": "your_encrypt_key",
"verification_token": "your_verification_token"
}
],
"llm": {
"provider": "openai", // 或 "anthropic" / "minimax"
"model": "openai/gpt-4o", // 推荐英文模型
"api_key": "your_api_key",
"base_url": "https://openrouter.ai/api/v1" // 可选
},
"deepcode": {
"api_url": "http://localhost:8000" // DeepCode 后端地址
}
}
```
> 💡 **提示**: 使用 `nanobot_config.json.example` 作为模板。
---
#### **Step 3 · 启动**
确保 DeepCode 后端已运行,然后启动 nanobot:
```bash
cd DeepCode/
./nanobot/run_nanobot.sh
```
**Docker Compose 模式** (同时启动 DeepCode + nanobot):
```bash
docker compose -f deepcode_docker/docker-compose.yml up -d
```
访问飞书,找到你的机器人,发送消息测试:
```
hi
```
如果收到回复,说明配置成功!🎉
---
### 💡 使用示例
| 操作 | 命令示例 |
|---|---|
| **论文转代码** | `paper2code https://arxiv.org/abs/2104.09864` |
| **对话转代码** | `chat2code 实现一个计算斐波那契数列的 Python 函数` |
| **查询任务状态** | `deepcode_status task_abc123` |
| **响应交互** | 当 AI 询问"需要测试用例吗?"时直接回复 `是` 或 `否` |
---
<details>
<summary><strong>🛠️ nanobot 管理命令</strong></summary>
```bash
# 查看日志(Docker 模式)
docker compose -f deepcode_docker/docker-compose.yml logs -f nanobot
# 重启 nanobot(Docker 模式)
docker compose -f deepcode_docker/docker-compose.yml restart nanobot
# 停止所有服务(Docker 模式)
docker compose -f deepcode_docker/docker-compose.yml down
```
</details>
---
<details>
<summary><strong>🔧 常见问题(nanobot)</strong></summary>
| 问题 | 解决方案 |
|---|---|
| nanobot 响应为中文 | 修改 `nanobot_config.json` 中 `llm.model` 为英文模型(如 `gpt-4o`) |
| 飞书收不到消息 | 检查事件订阅 URL 是否可公网访问,端口 8081 是否开放 |
| DeepCode 任务提交失败 | 确认 `deepcode.api_url` 正确,后端正在运行 |
| nanobot 容器无法启动 | 检查 `nanobot_config.json` 格式是否正确(使用 JSON 验证器) |
</details>
---
---
## 💡 示例
### 🎬 **实时演示**
<table align="center">
<tr>
<td width="33%" align="center">
#### 📄 **论文转代码演示**
**研究到实现**
<div align="center">
<a href="https://www.youtube.com/watch?v=MQZYpLkzsbw">
<img src="https://img.youtube.com/vi/MQZYpLkzsbw/maxresdefault.jpg" alt="Paper2Code Demo" width="100%" style="border-radius: 10px; box-shadow: 0 4px 8px rgba(0,0,0,0.1);"/>
</a>
**[▶️ 观看演示](https://www.youtube.com/watch?v=MQZYpLkzsbw)**
*自动将学术论文转换为生产就绪代码*
</div>
</td>
<td width="33%" align="center">
#### 🖼️ **图像处理演示**
**AI驱动的图像工具**
<div align="center">
<a href="https://www.youtube.com/watch?v=nFt5mLaMEac">
<img src="https://img.youtube.com/vi/nFt5mLaMEac/maxresdefault.jpg" alt="Image Processing Demo" width="100%" style="border-radius: 10px; box-shadow: 0 4px 8px rgba(0,0,0,0.1);"/>
</a>
**[▶️ 观看演示](https://www.youtube.com/watch?v=nFt5mLaMEac)**
*智能图像处理,具有背景移除和增强功能*
</div>
</td>
<td width="33%" align="center">
#### 🌐 **前端实现**
**完整Web应用程序**
<div align="center">
<a href="https://www.youtube.com/watch?v=78wx3dkTaAU">
<img src="https://img.youtube.com/vi/78wx3dkTaAU/maxresdefault.jpg" alt="Frontend Demo" width="100%" style="border-radius: 10px; box-shadow: 0 4px 8px rgba(0,0,0,0.1);"/>
</a>
**[▶️ 观看演示](https://www.youtube.com/watch?v=78wx3dkTaAU)**
*从概念到部署的全栈Web开发*
</div>
</td>
</tr>
</table>
### 🆕 **最新更新**
#### 📄 **智能文档分割 (v1.2.0)**
- **智能处理**: 自动处理超出LLM令牌限制的大型研究论文和技术文档
- **可配置控制**: 通过配置切换分割功能,具有基于大小的阈值
- **语义分析**: 高级内容理解,保留算法、概念和公式
- **向后兼容**: 对较小文档无缝回退到传统处理
### 🚀 **即将推出**
我们正在不断增强DeepCode的令人兴奋的新功能:
#### 🔧 **增强的代码可靠性和验证**
- **自动化测试**: 具有执行验证和错误检测的全面功能测试。
- **代码质量保证**: 通过静态分析、动态测试和性能基准测试进行多级验证。
- **智能调试**: AI驱动的错误检测,具有自动纠正建议
#### 📊 **PaperBench性能展示**
- **基准仪表板**: PaperBench评估套件的综合性能指标。
- **准确性指标**: 与最先进的论文复现系统的详细比较。
- **成功分析**: 跨论文类别和复杂度水平的统计分析。
#### ⚡ **系统级优化**
- **性能提升**: 多线程处理和优化智能体协调,实现更快的生成。
- **增强推理**: 具有改进上下文理解的高级推理能力。
- **扩展支持**: 扩展与其他编程语言和框架的兼容性。
---
## ⭐ 星标历史
<div align="center">
*社区增长轨迹*
<a href="https://star-history.com/#HKUDS/DeepCode&Date">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=HKUDS/DeepCode&type=Date&theme=dark" />
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=HKUDS/DeepCode&type=Date" />
<img alt="Star History Chart" src="https://api.star-history.com/svg?repos=HKUDS/DeepCode&type=Date" style="border-radius: 15px; box-shadow: 0 0 30px rgba(0, 217, 255, 0.3);" />
</picture>
</a>
</div>
---
### 🚀 **准备好变革开发方式了吗?**
<div align="center">
<p>
<a href="#-快速开始"><img src="https://img.shields.io/badge/🚀_立即开始-00d4ff?style=for-the-badge&logo=rocket&logoColor=white" alt="Get Started"></a>
<a href="https://github.com/HKUDS"><img src="https://img.shields.io/badge/🏛️_在GitHub上查看-00d4ff?style=for-the-badge&logo=github&logoColor=white" alt="View on GitHub"></a>
<a href="https://github.com/HKUDS/deepcode-agent"><img src="https://img.shields.io/badge/⭐_星标项目-00d4ff?style=for-the-badge&logo=star&logoColor=white" alt="Star Project"></a>
</p>
---
### 📄 **许可证**
<img src="https://img.shields.io/badge/License-MIT-4ecdc4?style=for-the-badge&logo=opensourceinitiative&logoColor=white" alt="MIT License">
**MIT许可证** - 版权所有 (c) 2025 香港大学数据智能实验室
---
<img src="https://visitor-badge.laobi.icu/badge?page_id=deepcode.readme&style=for-the-badge&color=00d4ff" alt="Visitors">
</div>
================================================
FILE: __init__.py
================================================
"""
DeepCode - AI Research Engine
🧬 Next-Generation AI Research Automation Platform
⚡ Transform research papers into working code automatically
"""
__version__ = "1.2.0"
__author__ = "DeepCode Team"
__url__ = "https://github.com/HKUDS/DeepCode"
__repo__ = "https://github.com/Jany-M/DeepCode/"
# Import main components for easy access
from utils import FileProcessor, DialogueLogger
__all__ = [
"FileProcessor",
"DialogueLogger",
"__version__",
"__author__",
"__url__",
]
================================================
FILE: cli/__init__.py
================================================
"""
CLI Module for DeepCode Agent
DeepCode智能体CLI模块
包含以下组件 / Contains the following components:
- cli_app: CLI应用主程序 / CLI application main program
- cli_interface: CLI界面组件 / CLI interface components
- cli_launcher: CLI启动器 / CLI launcher
"""
__version__ = "1.0.0"
__author__ = "DeepCode Team - Data Intelligence Lab @ HKU"
from .cli_app import main as cli_main
from .cli_interface import CLIInterface
from .cli_launcher import main as launcher_main
__all__ = ["cli_main", "CLIInterface", "launcher_main"]
================================================
FILE: cli/cli_app.py
================================================
#!/usr/bin/env python3
"""
DeepCode - CLI Application Main Program
深度代码 - CLI应用主程序
🧬 Open-Source Code Agent by Data Intelligence Lab @ HKU
⚡ Revolutionizing research reproducibility through collaborative AI
"""
import os
import sys
import asyncio
import time
import json
# 禁止生成.pyc文件
os.environ["PYTHONDONTWRITEBYTECODE"] = "1"
# 添加项目根目录到路径
current_dir = os.path.dirname(os.path.abspath(__file__))
parent_dir = os.path.dirname(current_dir)
if parent_dir not in sys.path:
sys.path.insert(0, parent_dir)
# 导入MCP应用和工作流
from cli.workflows import CLIWorkflowAdapter
from cli.cli_interface import CLIInterface, Colors
class CLIApp:
"""CLI应用主类 - 升级版智能体编排引擎"""
def __init__(self):
self.cli = CLIInterface()
self.workflow_adapter = CLIWorkflowAdapter(cli_interface=self.cli)
self.app = None # Will be initialized by workflow adapter
self.logger = None
self.context = None
# Document segmentation will be managed by CLI interface
async def initialize_mcp_app(self):
"""初始化MCP应用 - 使用工作流适配器"""
# Workflow adapter will handle MCP initialization
return await self.workflow_adapter.initialize_mcp_app()
async def cleanup_mcp_app(self):
"""清理MCP应用 - 使用工作流适配器"""
await self.workflow_adapter.cleanup_mcp_app()
async def process_requirement_analysis_non_interactive(self, initial_idea: str):
"""处理需求分析工作流(非交互式,用于命令行参数) (NEW: matching UI version)"""
try:
self.cli.print_separator()
self.cli.print_status(
"🧠 Starting requirement analysis workflow...", "info"
)
# Step 1: Generate guiding questions
self.cli.print_status(
"🤖 Generating AI-guided questions to refine your requirements...",
"processing",
)
questions_result = (
await self.workflow_adapter.execute_requirement_analysis_workflow(
user_input=initial_idea, analysis_mode="generate_questions"
)
)
if questions_result["status"] != "success":
self.cli.print_status(
f"❌ Failed to generate questions: {questions_result.get('error', 'Unknown error')}",
"error",
)
return questions_result
# Step 2: Display questions
questions_json = questions_result["result"]
self.cli.display_guiding_questions(questions_json)
# For non-interactive mode, we can't get user answers, so we provide a summary
self.cli.print_status(
"ℹ️ In non-interactive mode, using initial idea for implementation",
"info",
)
self.cli.print_status(
"💡 For guided analysis, please use interactive mode (python main_cli.py)",
"info",
)
# Proceed directly with the initial idea as the requirement
self.cli.print_status(
"🚀 Starting code implementation based on initial requirements...",
"processing",
)
implementation_result = await self.process_input(initial_idea, "chat")
return {
"status": "success",
"questions_generated": questions_result,
"implementation": implementation_result,
}
except Exception as e:
error_msg = str(e)
self.cli.print_error_box("Requirement Analysis Error", error_msg)
self.cli.print_status(
f"Error during requirement analysis: {error_msg}", "error"
)
return {"status": "error", "error": error_msg}
async def process_requirement_analysis(self):
"""处理需求分析工作流(交互式) (NEW: matching UI version)"""
try:
# Step 1: Get initial requirements from user
self.cli.print_separator()
self.cli.print_status(
"🧠 Starting requirement analysis workflow...", "info"
)
user_input = self.cli.get_requirement_analysis_input()
if not user_input:
self.cli.print_status("Requirement analysis cancelled", "warning")
return {"status": "cancelled"}
# Step 2: Generate guiding questions
self.cli.print_status(
"🤖 Generating AI-guided questions to refine your requirements...",
"processing",
)
questions_result = (
await self.workflow_adapter.execute_requirement_analysis_workflow(
user_input=user_input, analysis_mode="generate_questions"
)
)
if questions_result["status"] != "success":
self.cli.print_status(
f"❌ Failed to generate questions: {questions_result.get('error', 'Unknown error')}",
"error",
)
return questions_result
# Step 3: Display questions and get user answers
questions_json = questions_result["result"]
self.cli.display_guiding_questions(questions_json)
# Ask if user wants to answer the questions
proceed = (
input(
f"\n{Colors.BOLD}{Colors.YELLOW}Would you like to answer these questions? (y/n):{Colors.ENDC} "
)
.strip()
.lower()
)
if proceed != "y":
self.cli.print_status(
"You can still use the initial requirements for chat input",
"info",
)
return {"status": "partial", "initial_requirements": user_input}
user_answers = self.cli.get_question_answers(questions_json)
# Step 4: Generate requirement summary
self.cli.print_status(
"📄 Generating detailed requirement document...", "processing"
)
summary_result = (
await self.workflow_adapter.execute_requirement_analysis_workflow(
user_input=user_input,
analysis_mode="summarize_requirements",
user_answers=user_answers,
)
)
if summary_result["status"] != "success":
self.cli.print_status(
f"❌ Failed to generate summary: {summary_result.get('error', 'Unknown error')}",
"error",
)
return summary_result
# Step 5: Display requirement summary
requirement_summary = summary_result["result"]
should_proceed = self.cli.display_requirement_summary(requirement_summary)
if should_proceed:
# Step 6: Proceed with chat-based implementation
self.cli.print_status(
"🚀 Starting code implementation based on analyzed requirements...",
"processing",
)
implementation_result = await self.process_input(
requirement_summary, "chat"
)
return {
"status": "success",
"requirement_analysis": summary_result,
"implementation": implementation_result,
}
else:
self.cli.print_status(
"Requirement analysis completed. Implementation skipped.", "info"
)
return {
"status": "success",
"requirement_analysis": summary_result,
"implementation": None,
}
except Exception as e:
error_msg = str(e)
self.cli.print_error_box("Requirement Analysis Error", error_msg)
self.cli.print_status(
f"Error during requirement analysis: {error_msg}", "error"
)
return {"status": "error", "error": error_msg}
async def process_input(self, input_source: str, input_type: str):
"""处理输入源(URL或文件)- 使用升级版智能体编排引擎"""
try:
# Document segmentation configuration is managed by CLI interface
self.cli.print_separator()
self.cli.print_status(
"🚀 Starting intelligent agent orchestration...", "processing"
)
# 显示处理阶段(根据配置决定)
chat_mode = input_type == "chat"
self.cli.display_processing_stages(
0, self.cli.enable_indexing, chat_mode=chat_mode
)
# 使用工作流适配器进行处理
result = await self.workflow_adapter.process_input_with_orchestration(
input_source=input_source,
input_type=input_type,
enable_indexing=self.cli.enable_indexing,
)
if result["status"] == "success":
# 显示完成状态
if chat_mode:
final_stage = 4
else:
final_stage = 8 if self.cli.enable_indexing else 5
self.cli.display_processing_stages(
final_stage, self.cli.enable_indexing, chat_mode=chat_mode
)
self.cli.print_status(
"🎉 Agent orchestration completed successfully!", "complete"
)
# 显示结果
self.display_results(
result.get("analysis_result", ""),
result.get("download_result", ""),
result.get("repo_result", ""),
result.get("pipeline_mode", "comprehensive"),
)
else:
self.cli.print_status(
f"❌ Processing failed: {result.get('error', 'Unknown error')}",
"error",
)
# 添加到历史记录
self.cli.add_to_history(input_source, result)
return result
except Exception as e:
error_msg = str(e)
self.cli.print_error_box("Agent Orchestration Error", error_msg)
self.cli.print_status(f"Error during orchestration: {error_msg}", "error")
# 添加错误到历史记录
error_result = {"status": "error", "error": error_msg}
self.cli.add_to_history(input_source, error_result)
return error_result
def display_results(
self,
analysis_result: str,
download_result: str,
repo_result: str,
pipeline_mode: str = "comprehensive",
):
"""显示处理结果"""
self.cli.print_results_header()
# 显示流水线模式
if pipeline_mode == "chat":
mode_display = "💬 Chat Planning Mode"
elif pipeline_mode == "comprehensive":
mode_display = "🧠 Comprehensive Mode"
else:
mode_display = "⚡ Optimized Mode"
print(
f"{Colors.BOLD}{Colors.PURPLE}🤖 PIPELINE MODE: {mode_display}{Colors.ENDC}"
)
self.cli.print_separator("─", 79, Colors.PURPLE)
print(f"{Colors.BOLD}{Colors.OKCYAN}📊 ANALYSIS PHASE RESULTS:{Colors.ENDC}")
self.cli.print_separator("─", 79, Colors.CYAN)
# 尝试解析并格式化分析结果
try:
if analysis_result.strip().startswith("{"):
parsed_analysis = json.loads(analysis_result)
print(json.dumps(parsed_analysis, indent=2, ensure_ascii=False))
else:
print(
analysis_result[:1000] + "..."
if len(analysis_result) > 1000
else analysis_result
)
except Exception:
print(
analysis_result[:1000] + "..."
if len(analysis_result) > 1000
else analysis_result
)
print(f"\n{Colors.BOLD}{Colors.PURPLE}📥 DOWNLOAD PHASE RESULTS:{Colors.ENDC}")
self.cli.print_separator("─", 79, Colors.PURPLE)
print(
download_result[:1000] + "..."
if len(download_result) > 1000
else download_result
)
print(
f"\n{Colors.BOLD}{Colors.GREEN}⚙️ IMPLEMENTATION PHASE RESULTS:{Colors.ENDC}"
)
self.cli.print_separator("─", 79, Colors.GREEN)
print(repo_result[:1000] + "..." if len(repo_result) > 1000 else repo_result)
# 尝试提取生成的代码目录信息
if "Code generated in:" in repo_result:
code_dir = (
repo_result.split("Code generated in:")[-1].strip().split("\n")[0]
)
print(
f"\n{Colors.BOLD}{Colors.YELLOW}📁 Generated Code Directory: {Colors.ENDC}{code_dir}"
)
# 显示处理完成的工作流阶段
print(
f"\n{Colors.BOLD}{Colors.OKCYAN}🔄 COMPLETED WORKFLOW STAGES:{Colors.ENDC}"
)
if pipeline_mode == "chat":
stages = [
"🚀 Engine Initialization",
"💬 Requirements Analysis",
"🏗️ Workspace Setup",
"📝 Implementation Plan Generation",
"⚙️ Code Implementation",
]
else:
stages = [
"📄 Document Processing",
"🔍 Reference Analysis",
"📋 Plan Generation",
"📦 Repository Download",
"🗂️ Codebase Indexing",
"⚙️ Code Implementation",
]
for stage in stages:
print(f" ✅ {stage}")
self.cli.print_separator()
async def run_interactive_session(self):
"""运行交互式会话"""
# 清屏并显示启动界面
self.cli.clear_screen()
self.cli.print_logo()
self.cli.print_welcome_banner()
# 初始化MCP应用
await self.initialize_mcp_app()
try:
# 主交互循环
while self.cli.is_running:
self.cli.create_menu()
choice = self.cli.get_user_input()
if choice in ["q", "quit", "exit"]:
self.cli.print_goodbye()
break
elif choice in ["u", "url"]:
url = self.cli.get_url_input()
if url:
await self.process_input(url, "url")
elif choice in ["f", "file"]:
file_path = self.cli.upload_file_gui()
if file_path:
await self.process_input(f"file://{file_path}", "file")
elif choice in ["t", "chat", "text"]:
chat_input = self.cli.get_chat_input()
if chat_input:
await self.process_input(chat_input, "chat")
elif choice in ["r", "req", "requirement", "requirements"]:
# NEW: Requirement Analysis workflow
await self.process_requirement_analysis()
elif choice in ["h", "history"]:
self.cli.show_history()
elif choice in ["c", "config", "configure"]:
# Show configuration menu - all settings managed by CLI interface
self.cli.show_configuration_menu()
else:
self.cli.print_status(
"Invalid choice. Please select U, F, T, R, C, H, or Q.",
"warning",
)
# 询问是否继续
if self.cli.is_running and choice in [
"u",
"f",
"t",
"r",
"chat",
"text",
"req",
"requirement",
"requirements",
]:
if not self.cli.ask_continue():
self.cli.is_running = False
self.cli.print_status("Session ended by user", "info")
except KeyboardInterrupt:
print(f"\n{Colors.WARNING}⚠️ Process interrupted by user{Colors.ENDC}")
except Exception as e:
print(f"\n{Colors.FAIL}❌ Unexpected error: {str(e)}{Colors.ENDC}")
finally:
# 清理资源
await self.cleanup_mcp_app()
async def main():
"""主函数"""
start_time = time.time()
try:
# 创建并运行CLI应用
app = CLIApp()
await app.run_interactive_session()
except KeyboardInterrupt:
print(f"\n{Colors.WARNING}⚠️ Application interrupted by user{Colors.ENDC}")
except Exception as e:
print(f"\n{Colors.FAIL}❌ Application error: {str(e)}{Colors.ENDC}")
finally:
end_time = time.time()
print(
f"\n{Colors.BOLD}{Colors.CYAN}⏱️ Total runtime: {end_time - start_time:.2f} seconds{Colors.ENDC}"
)
# 清理缓存文件
print(f"{Colors.YELLOW}🧹 Cleaning up cache files...{Colors.ENDC}")
if os.name == "nt": # Windows
os.system(
"powershell -Command \"Get-ChildItem -Path . -Filter '__pycache__' -Recurse -Directory | Remove-Item -Recurse -Force\" 2>nul"
)
else: # Unix/Linux/macOS
os.system('find . -type d -name "__pycache__" -exec rm -r {} + 2>/dev/null')
print(
f"{Colors.OKGREEN}✨ Goodbye! Thanks for using DeepCode CLI! ✨{Colors.ENDC}"
)
if __name__ == "__main__":
asyncio.run(main())
================================================
FILE: cli/cli_interface.py
================================================
#!/usr/bin/env python3
"""
Enhanced CLI Interface Module for DeepCode
增强版CLI界面模块 - 专为DeepCode设计
"""
import os
import time
import platform
from typing import Optional
class Colors:
"""ANSI color codes for terminal styling"""
HEADER = "\033[95m"
OKBLUE = "\033[94m"
OKCYAN = "\033[96m"
OKGREEN = "\033[92m"
WARNING = "\033[93m"
FAIL = "\033[91m"
ENDC = "\033[0m"
BOLD = "\033[1m"
UNDERLINE = "\033[4m"
# Gradient colors
PURPLE = "\033[35m"
MAGENTA = "\033[95m"
BLUE = "\033[34m"
CYAN = "\033[36m"
GREEN = "\033[32m"
YELLOW = "\033[33m"
class CLIInterface:
"""Enhanced CLI interface with modern styling for DeepCode"""
def __init__(self):
self.uploaded_file = None
self.is_running = True
self.processing_history = []
self.enable_indexing = (
False # Default configuration (matching UI: fast mode by default)
)
# Load segmentation config from the same source as UI
self._load_segmentation_config()
# Initialize tkinter availability
self._init_tkinter()
def _load_segmentation_config(self):
"""Load segmentation configuration from mcp_agent.config.yaml"""
try:
from utils.llm_utils import get_document_segmentation_config
seg_config = get_document_segmentation_config()
self.segmentation_enabled = seg_config.get("enabled", True)
self.segmentation_threshold = seg_config.get("size_threshold_chars", 50000)
except Exception as e:
print(f"⚠️ Warning: Failed to load segmentation config: {e}")
# Fall back to defaults
self.segmentation_enabled = True
self.segmentation_threshold = 50000
def _save_segmentation_config(self):
"""Save segmentation configuration to mcp_agent.config.yaml"""
import yaml
import os
# Get the project root directory (where mcp_agent.config.yaml is located)
current_file = os.path.abspath(__file__)
cli_dir = os.path.dirname(current_file) # cli directory
project_root = os.path.dirname(cli_dir) # project root
config_path = os.path.join(project_root, "mcp_agent.config.yaml")
try:
# Read current config
with open(config_path, "r", encoding="utf-8") as f:
config = yaml.safe_load(f)
# Update document segmentation settings
if "document_segmentation" not in config:
config["document_segmentation"] = {}
config["document_segmentation"]["enabled"] = self.segmentation_enabled
config["document_segmentation"]["size_threshold_chars"] = (
self.segmentation_threshold
)
# Write updated config
with open(config_path, "w", encoding="utf-8") as f:
yaml.dump(config, f, default_flow_style=False, allow_unicode=True)
print(
f"{Colors.OKGREEN}✅ Document segmentation configuration updated{Colors.ENDC}"
)
except Exception as e:
print(
f"{Colors.WARNING}⚠️ Failed to update segmentation config: {str(e)}{Colors.ENDC}"
)
def _init_tkinter(self):
"""Initialize tkinter availability check"""
# Check tkinter availability for file dialogs
self.tkinter_available = True
try:
import tkinter as tk
# Test if tkinter can create a window
test_root = tk.Tk()
test_root.withdraw()
test_root.destroy()
except Exception:
self.tkinter_available = False
def clear_screen(self):
"""Clear terminal screen"""
os.system("cls" if os.name == "nt" else "clear")
def print_logo(self):
"""Print enhanced ASCII logo for DeepCode CLI"""
logo = f"""
{Colors.CYAN}╔═══════════════════════════════════════════════════════════════════════════════╗
║ ║
║ {Colors.BOLD}{Colors.MAGENTA}██████╗ ███████╗███████╗██████╗ ██████╗ ██████╗ ██████╗ ███████╗{Colors.CYAN} ║
║ {Colors.BOLD}{Colors.PURPLE}██╔══██╗██╔════╝██╔════╝██╔══██╗██╔════╝██╔═══██╗██╔══██╗██╔════╝{Colors.CYAN} ║
║ {Colors.BOLD}{Colors.BLUE}██║ ██║█████╗ █████╗ ██████╔╝██║ ██║ ██║██║ ██║█████╗ {Colors.CYAN} ║
║ {Colors.BOLD}{Colors.OKBLUE}██║ ██║██╔══╝ ██╔══╝ ██╔═══╝ ██║ ██║ ██║██║ ██║██╔══╝ {Colors.CYAN} ║
║ {Colors.BOLD}{Colors.OKCYAN}██████╔╝███████╗███████╗██║ ╚██████╗╚██████╔╝██████╔╝███████╗{Colors.CYAN} ║
║ {Colors.BOLD}{Colors.GREEN}╚═════╝ ╚══════╝╚══════╝╚═╝ ╚═════╝ ╚═════╝ ╚═════╝ ╚══════╝{Colors.CYAN} ║
║ ║
║ {Colors.BOLD}{Colors.GREEN}🧬 OPEN-SOURCE CODE AGENT • DATA INTELLIGENCE LAB @ HKU 🚀 {Colors.CYAN}║
║ {Colors.BOLD}{Colors.GREEN}⚡ REVOLUTIONIZING RESEARCH REPRODUCIBILITY ⚡ {Colors.CYAN}║
║ ║
╚═══════════════════════════════════════════════════════════════════════════════╝{Colors.ENDC}
"""
print(logo)
def print_welcome_banner(self):
"""Print enhanced welcome banner"""
banner = f"""
{Colors.BOLD}{Colors.CYAN}╔═══════════════════════════════════════════════════════════════════════════════╗
║ WELCOME TO DEEPCODE CLI ║
╠═══════════════════════════════════════════════════════════════════════════════╣
║ {Colors.YELLOW}Open-Source Code Agent | Data Intelligence Lab @ HKU | MIT License {Colors.CYAN}║
║ {Colors.GREEN}Status: Ready | Engine: Multi-Agent Architecture Initialized {Colors.CYAN}║
║ {Colors.PURPLE}Mission: Revolutionizing Research Reproducibility {Colors.CYAN}║
║ ║
║ {Colors.BOLD}{Colors.OKCYAN}💎 CORE CAPABILITIES:{Colors.ENDC} {Colors.CYAN}║
║ {Colors.BOLD}{Colors.OKCYAN}▶ Automated Paper-to-Code Reproduction {Colors.CYAN}║
║ {Colors.BOLD}{Colors.OKCYAN}▶ Collaborative Multi-Agent Architecture {Colors.CYAN}║
║ {Colors.BOLD}{Colors.OKCYAN}▶ Intelligent Code Implementation & Validation {Colors.CYAN}║
║ {Colors.BOLD}{Colors.OKCYAN}▶ Future Vision: One Sentence → Complete Codebase {Colors.CYAN}║
╚═══════════════════════════════════════════════════════════════════════════════╝{Colors.ENDC}
"""
print(banner)
def print_separator(self, char="═", length=79, color=Colors.CYAN):
"""Print a styled separator line"""
print(f"{color}{char * length}{Colors.ENDC}")
def print_status(self, message: str, status_type: str = "info"):
"""Print status message with appropriate styling"""
status_styles = {
"success": f"{Colors.OKGREEN}✅",
"error": f"{Colors.FAIL}❌",
"warning": f"{Colors.WARNING}⚠️ ",
"info": f"{Colors.OKBLUE}ℹ️ ",
"processing": f"{Colors.YELLOW}⏳",
"upload": f"{Colors.PURPLE}📁",
"download": f"{Colors.CYAN}📥",
"analysis": f"{Colors.MAGENTA}🔍",
"implementation": f"{Colors.GREEN}⚙️ ",
"complete": f"{Colors.OKGREEN}🎉",
}
icon = status_styles.get(status_type, status_styles["info"])
timestamp = time.strftime("%H:%M:%S")
print(
f"[{Colors.BOLD}{timestamp}{Colors.ENDC}] {icon} {Colors.BOLD}{message}{Colors.ENDC}"
)
def create_menu(self):
"""Create enhanced interactive menu"""
# Display current configuration
pipeline_mode = "🧠 COMPREHENSIVE" if self.enable_indexing else "⚡ OPTIMIZED"
index_status = "✅ Enabled" if self.enable_indexing else "🔶 Disabled"
segmentation_mode = (
"📄 SMART" if self.segmentation_enabled else "📋 TRADITIONAL"
)
menu = f"""
{Colors.BOLD}{Colors.CYAN}╔═══════════════════════════════════════════════════════════════════════════════╗
║ MAIN MENU ║
╠═══════════════════════════════════════════════════════════════════════════════╣
║ {Colors.OKGREEN}🌐 [U] Process URL {Colors.CYAN}│ {Colors.PURPLE}📁 [F] Upload File {Colors.CYAN}│ {Colors.MAGENTA}💬 [T] Chat Input{Colors.CYAN} ║
║ {Colors.BLUE}🧠 [R] Req. Analysis {Colors.CYAN}│ {Colors.OKCYAN}⚙️ [C] Configure {Colors.CYAN}│ {Colors.YELLOW}📊 [H] History{Colors.CYAN} ║
║ {Colors.FAIL}❌ [Q] Quit{Colors.CYAN} ║
║ ║
║ {Colors.BOLD}🤖 Current Pipeline Mode: {pipeline_mode}{Colors.CYAN} ║
║ {Colors.BOLD}🗂️ Codebase Indexing: {index_status}{Colors.CYAN} ║
║ {Colors.BOLD}📄 Document Processing: {segmentation_mode}{Colors.CYAN} ║
║ ║
║ {Colors.YELLOW}📝 URL Processing:{Colors.CYAN} ║
║ {Colors.YELLOW} ▶ Enter research paper URL (arXiv, IEEE, ACM, etc.) {Colors.CYAN}║
║ {Colors.YELLOW} ▶ Supports direct PDF links and academic paper pages {Colors.CYAN}║
║ ║
║ {Colors.PURPLE}📁 File Processing:{Colors.CYAN} ║
║ {Colors.PURPLE} ▶ Upload PDF, DOCX, PPTX, HTML, or TXT files {Colors.CYAN}║
║ {Colors.PURPLE} ▶ Intelligent file format detection and processing {Colors.CYAN}║
║ ║
║ {Colors.MAGENTA}💬 Chat Input:{Colors.CYAN} ║
║ {Colors.MAGENTA} ▶ Describe your coding requirements in natural language {Colors.CYAN}║
║ {Colors.MAGENTA} ▶ AI generates implementation plan and code automatically {Colors.CYAN}║
║ ║
║ {Colors.BLUE}🧠 Requirement Analysis (NEW):{Colors.CYAN} ║
║ {Colors.BLUE} ▶ Get AI-guided questions to refine your requirements {Colors.CYAN}║
║ {Colors.BLUE} ▶ Generate detailed requirement documents from your answers {Colors.CYAN}║
║ ║
║ {Colors.OKCYAN}🔄 Processing Pipeline:{Colors.CYAN} ║
║ {Colors.OKCYAN} ▶ Intelligent agent orchestration → Code synthesis {Colors.CYAN}║
║ {Colors.OKCYAN} ▶ Multi-agent coordination with progress tracking {Colors.CYAN}║
╚═══════════════════════════════════════════════════════════════════════════════╝{Colors.ENDC}
"""
print(menu)
def get_user_input(self):
"""Get user input with styled prompt"""
print(f"\n{Colors.BOLD}{Colors.OKCYAN}➤ Your choice: {Colors.ENDC}", end="")
return input().strip().lower()
def upload_file_gui(self) -> Optional[str]:
"""Enhanced file upload interface with better error handling"""
if not self.tkinter_available:
self.print_status(
"GUI file dialog not available - using manual input", "warning"
)
return self._get_manual_file_path()
def select_file():
try:
import tkinter as tk
from tkinter import filedialog
root = tk.Tk()
root.withdraw()
root.attributes("-topmost", True)
file_types = [
("Research Papers", "*.pdf;*.docx;*.doc"),
("PDF Files", "*.pdf"),
("Word Documents", "*.docx;*.doc"),
("PowerPoint Files", "*.pptx;*.ppt"),
("HTML Files", "*.html;*.htm"),
("Text Files", "*.txt;*.md"),
("All Files", "*.*"),
]
if platform.system() == "Darwin":
file_types = [
("Research Papers", ".pdf .docx .doc"),
("PDF Files", ".pdf"),
("Word Documents", ".docx .doc"),
("PowerPoint Files", ".pptx .ppt"),
("HTML Files", ".html .htm"),
("Text Files", ".txt .md"),
("All Files", ".*"),
]
file_path = filedialog.askopenfilename(
title="Select Research File - DeepCode CLI",
filetypes=file_types,
initialdir=os.getcwd(),
)
root.destroy()
return file_path
except Exception as e:
self.print_status(f"File dialog error: {str(e)}", "error")
return self._get_manual_file_path()
self.print_status("Opening file browser dialog...", "upload")
file_path = select_file()
if file_path:
self.print_status(
f"File selected: {os.path.basename(file_path)}", "success"
)
return file_path
else:
self.print_status("No file selected", "warning")
return None
def _get_manual_file_path(self) -> Optional[str]:
"""Get file path through manual input with validation"""
self.print_separator("─", 79, Colors.YELLOW)
print(f"{Colors.BOLD}{Colors.YELLOW}📁 Manual File Path Input{Colors.ENDC}")
print(
f"{Colors.CYAN}Please enter the full path to your research paper file:{Colors.ENDC}"
)
print(
f"{Colors.CYAN}Supported formats: PDF, DOCX, PPTX, HTML, TXT, MD{Colors.ENDC}"
)
self.print_separator("─", 79, Colors.YELLOW)
while True:
print(f"\n{Colors.BOLD}{Colors.OKCYAN}📂 File path: {Colors.ENDC}", end="")
file_path = input().strip()
if not file_path:
self.print_status(
"Empty path entered. Please try again or press Ctrl+C to cancel.",
"warning",
)
continue
file_path = os.path.expanduser(file_path)
file_path = os.path.abspath(file_path)
if not os.path.exists(file_path):
self.print_status(f"File not found: {file_path}", "error")
retry = (
input(f"{Colors.YELLOW}Try again? (y/n): {Colors.ENDC}")
.strip()
.lower()
)
if retry != "y":
return None
continue
if not os.path.isfile(file_path):
self.print_status(f"Path is not a file: {file_path}", "error")
continue
supported_extensions = {
".pdf",
".docx",
".doc",
".pptx",
".ppt",
".html",
".htm",
".txt",
".md",
}
file_ext = os.path.splitext(file_path)[1].lower()
if file_ext not in supported_extensions:
self.print_status(f"Unsupported file format: {file_ext}", "warning")
proceed = (
input(f"{Colors.YELLOW}Process anyway? (y/n): {Colors.ENDC}")
.strip()
.lower()
)
if proceed != "y":
continue
self.print_status(
f"File validated: {os.path.basename(file_path)}", "success"
)
return file_path
def get_url_input(self) -> str:
"""Enhanced URL input with validation"""
self.print_separator("─", 79, Colors.GREEN)
print(f"{Colors.BOLD}{Colors.GREEN}🌐 URL Input Interface{Colors.ENDC}")
print(
f"{Colors.CYAN}Enter a research paper URL from supported platforms:{Colors.ENDC}"
)
print(
f"{Colors.CYAN}• arXiv (arxiv.org) • IEEE Xplore (ieeexplore.ieee.org){Colors.ENDC}"
)
print(
f"{Colors.CYAN}• ACM Digital Library • SpringerLink • Nature • Science{Colors.ENDC}"
)
print(
f"{Colors.CYAN}• Direct PDF links • Academic publisher websites{Colors.ENDC}"
)
self.print_separator("─", 79, Colors.GREEN)
while True:
print(f"\n{Colors.BOLD}{Colors.OKCYAN}🔗 URL: {Colors.ENDC}", end="")
url = input().strip()
if not url:
self.print_status(
"Empty URL entered. Please try again or press Ctrl+C to cancel.",
"warning",
)
continue
if not url.startswith(("http://", "https://")):
self.print_status("URL must start with http:// or https://", "error")
retry = (
input(f"{Colors.YELLOW}Try again? (y/n): {Colors.ENDC}")
.strip()
.lower()
)
if retry != "y":
return ""
continue
academic_domains = [
"arxiv.org",
"ieeexplore.ieee.org",
"dl.acm.org",
"link.springer.com",
"nature.com",
"science.org",
"scholar.google.com",
"researchgate.net",
"semanticscholar.org",
]
is_academic = any(domain in url.lower() for domain in academic_domains)
if not is_academic and not url.lower().endswith(".pdf"):
self.print_status(
"URL doesn't appear to be from a known academic platform", "warning"
)
proceed = (
input(f"{Colors.YELLOW}Process anyway? (y/n): {Colors.ENDC}")
.strip()
.lower()
)
if proceed != "y":
continue
self.print_status(f"URL validated: {url}", "success")
return url
def get_chat_input(self) -> str:
"""Enhanced chat input interface for coding requirements"""
self.print_separator("─", 79, Colors.PURPLE)
print(f"{Colors.BOLD}{Colors.PURPLE}💬 Chat Input Interface{Colors.ENDC}")
print(
f"{Colors.CYAN}Describe your coding requirements in natural language.{Colors.ENDC}"
)
print(
f"{Colors.CYAN}Our AI will analyze your needs and generate a comprehensive implementation plan.{Colors.ENDC}"
)
self.print_separator("─", 79, Colors.PURPLE)
# Display examples to help users
print(f"\n{Colors.BOLD}{Colors.YELLOW}💡 Examples:{Colors.ENDC}")
print(f"{Colors.CYAN}Academic Research:{Colors.ENDC}")
print(
" • 'I need to implement a reinforcement learning algorithm for robotic control'"
)
print(
" • 'Create a neural network for image classification with attention mechanisms'"
)
print(f"{Colors.CYAN}Engineering Projects:{Colors.ENDC}")
print(
" • 'Develop a web application for project management with user authentication'"
)
print(" • 'Create a data visualization dashboard for sales analytics'")
print(f"{Colors.CYAN}Mixed Projects:{Colors.ENDC}")
print(
" • 'Implement a machine learning model with a web interface for real-time predictions'"
)
self.print_separator("─", 79, Colors.PURPLE)
print(
f"\n{Colors.BOLD}{Colors.OKCYAN}✏️ Enter your coding requirements below:{Colors.ENDC}"
)
print(
f"{Colors.YELLOW}(Type your description, press Enter twice when finished, or Ctrl+C to cancel){Colors.ENDC}"
)
lines = []
empty_line_count = 0
while True:
try:
if len(lines) == 0:
print(f"{Colors.BOLD}> {Colors.ENDC}", end="")
else:
print(f"{Colors.BOLD} {Colors.ENDC}", end="")
line = input()
if line.strip() == "":
empty_line_count += 1
if empty_line_count >= 2:
# Two consecutive empty lines means user finished input
break
lines.append("") # Keep empty line for formatting
else:
empty_line_count = 0
lines.append(line)
except KeyboardInterrupt:
print(f"\n{Colors.WARNING}Input cancelled by user{Colors.ENDC}")
return ""
# Join all lines and clean up
user_input = "\n".join(lines).strip()
if not user_input:
self.print_status("No input provided", "warning")
return ""
if len(user_input) < 20:
self.print_status(
"Input too short. Please provide more detailed requirements (at least 20 characters)",
"warning",
)
retry = (
input(f"{Colors.YELLOW}Try again? (y/n): {Colors.ENDC}").strip().lower()
)
if retry == "y":
return self.get_chat_input() # Recursive call for retry
return ""
# Display input summary
word_count = len(user_input.split())
char_count = len(user_input)
print(f"\n{Colors.BOLD}{Colors.GREEN}📋 Input Summary:{Colors.ENDC}")
print(f" • {Colors.CYAN}Word count: {word_count}{Colors.ENDC}")
print(f" • {Colors.CYAN}Character count: {char_count}{Colors.ENDC}")
# Show preview
preview = user_input[:200] + "..." if len(user_input) > 200 else user_input
print(f"\n{Colors.BOLD}{Colors.CYAN}📄 Preview:{Colors.ENDC}")
print(f"{Colors.YELLOW}{preview}{Colors.ENDC}")
# Confirm with user
confirm = (
input(
f"\n{Colors.BOLD}{Colors.OKCYAN}Proceed with this input? (y/n): {Colors.ENDC}"
)
.strip()
.lower()
)
if confirm != "y":
retry = (
input(f"{Colors.YELLOW}Edit input? (y/n): {Colors.ENDC}")
.strip()
.lower()
)
if retry == "y":
return self.get_chat_input() # Recursive call for retry
return ""
self.print_status(
f"Chat input captured: {word_count} words, {char_count} characters",
"success",
)
return user_input
def show_progress_bar(self, message: str, duration: float = 2.0):
"""Show animated progress bar"""
print(f"\n{Colors.BOLD}{Colors.CYAN}{message}{Colors.ENDC}")
bar_length = 50
for i in range(bar_length + 1):
percent = (i / bar_length) * 100
filled = "█" * i
empty = "░" * (bar_length - i)
print(
f"\r{Colors.OKGREEN}[{filled}{empty}] {percent:3.0f}%{Colors.ENDC}",
end="",
flush=True,
)
time.sleep(duration / bar_length)
print(f"\n{Colors.OKGREEN}✓ {message} completed{Colors.ENDC}")
def show_spinner(self, message: str, duration: float = 1.0):
"""Show spinner animation"""
spinner_chars = "⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏"
end_time = time.time() + duration
print(
f"{Colors.BOLD}{Colors.CYAN}{message}... {Colors.ENDC}", end="", flush=True
)
i = 0
while time.time() < end_time:
print(
f"\r{Colors.BOLD}{Colors.CYAN}{message}... {Colors.YELLOW}{spinner_chars[i % len(spinner_chars)]}{Colors.ENDC}",
end="",
flush=True,
)
time.sleep(0.1)
i += 1
print(
f"\r{Colors.BOLD}{Colors.CYAN}{message}... {Colors.OKGREEN}✓{Colors.ENDC}"
)
def display_processing_stages(
self,
current_stage: int = 0,
enable_indexing: bool = True,
chat_mode: bool = False,
):
"""Display processing pipeline stages with current progress"""
if chat_mode:
# Chat mode - simplified workflow for user requirements
stages = [
("🚀", "Initialize", "Setting up chat engine"),
("💬", "Planning", "Analyzing requirements"),
("🏗️", "Setup", "Creating workspace"),
("📝", "Save Plan", "Saving implementation plan"),
("⚙️", "Implement", "Generating code"),
]
pipeline_mode = "CHAT PLANNING"
elif enable_indexing:
# Full pipeline with all stages
stages = [
("🚀", "Initialize", "Setting up AI engine"),
("📊", "Analyze", "Analyzing research content"),
("📥", "Download", "Processing document"),
("📋", "Plan", "Generating code architecture"),
("🔍", "References", "Analyzing references"),
("📦", "Repos", "Downloading repositories"),
("🗂️", "Index", "Building code index"),
("⚙️", "Implement", "Implementing code"),
]
pipeline_mode = "COMPREHENSIVE"
else:
# Fast mode - skip indexing related stages
stages = [
("🚀", "Initialize", "Setting up AI engine"),
("📊", "Analyze", "Analyzing research content"),
("📥", "Download", "Processing document"),
("📋", "Plan", "Generating code architecture"),
("⚙️", "Implement", "Implementing code"),
]
pipeline_mode = "OPTIMIZED"
print(
f"\n{Colors.BOLD}{Colors.CYAN}📋 {pipeline_mode} PIPELINE STATUS{Colors.ENDC}"
)
self.print_separator("─", 79, Colors.CYAN)
for i, (icon, name, desc) in enumerate(stages):
if i < current_stage:
status = f"{Colors.OKGREEN}✓ COMPLETED{Colors.ENDC}"
elif i == current_stage:
status = f"{Colors.YELLOW}⏳ IN PROGRESS{Colors.ENDC}"
else:
status = f"{Colors.CYAN}⏸️ PENDING{Colors.ENDC}"
print(
f"{icon} {Colors.BOLD}{name:<12}{Colors.ENDC} │ {desc:<25} │ {status}"
)
self.print_separator("─", 79, Colors.CYAN)
def print_results_header(self):
"""Print results section header"""
header = f"""
{Colors.BOLD}{Colors.OKGREEN}╔═══════════════════════════════════════════════════════════════════════════════╗
║ PROCESSING RESULTS ║
╚═══════════════════════════════════════════════════════════════════════════════╝{Colors.ENDC}
"""
print(header)
def print_error_box(self, title: str, error_msg: str):
"""Print formatted error box"""
print(
f"\n{Colors.FAIL}╔══════════════════════════════════════════════════════════════╗"
)
print(f"║ {Colors.BOLD}ERROR: {title:<50}{Colors.FAIL} ║")
print("╠══════════════════════════════════════════════════════════════╣")
words = error_msg.split()
lines = []
current_line = ""
for word in words:
if len(current_line + word) <= 54:
current_line += word + " "
else:
lines.append(current_line.strip())
current_line = word + " "
if current_line:
lines.append(current_line.strip())
for line in lines:
print(f"║ {line:<56} ║")
print(
f"╚══════════════════════════════════════════════════════════════╝{Colors.ENDC}"
)
def cleanup_cache(self):
"""清理Python缓存文件 / Clean up Python cache files"""
try:
self.print_status("Cleaning up cache files...", "info")
# 清理__pycache__目录
os.system('find . -type d -name "__pycache__" -exec rm -r {} + 2>/dev/null')
# 清理.pyc文件
os.system('find . -name "*.pyc" -delete 2>/dev/null')
self.print_status("Cache cleanup completed", "success")
except Exception as e:
self.print_status(f"Cache cleanup failed: {e}", "warning")
def print_goodbye(self):
"""Print goodbye message"""
# 清理缓存文件
self.cleanup_cache()
goodbye = f"""
{Colors.BOLD}{Colors.CYAN}╔═══════════════════════════════════════════════════════════════════════════════╗
║ GOODBYE ║
╠═══════════════════════════════════════════════════════════════════════════════╣
║ {Colors.OKGREEN}🎉 Thank you for using DeepCode CLI! {Colors.CYAN}║
║ ║
║ {Colors.YELLOW}🧬 Join our community in revolutionizing research reproducibility {Colors.CYAN}║
║ {Colors.PURPLE}⚡ Together, we're building the future of automated code generation {Colors.CYAN}║
║ ║
║ {Colors.OKCYAN}💡 Questions? Contribute to our open-source mission at GitHub {Colors.CYAN}║
║ {Colors.GREEN}🧹 Cache files cleaned up for optimal performance {Colors.CYAN}║
║ ║
╚═══════════════════════════════════════════════════════════════════════════════╝{Colors.ENDC}
"""
print(goodbye)
def get_requirement_analysis_input(self) -> str:
"""Enhanced requirement analysis input interface (NEW: matching UI version)"""
self.print_separator("─", 79, Colors.BLUE)
print(
f"{Colors.BOLD}{Colors.BLUE}🧠 Requirement Analysis Interface{Colors.ENDC}"
)
print(
f"{Colors.CYAN}Describe your project idea or requirements briefly.{Colors.ENDC}"
)
print(
f"{Colors.CYAN}Our AI will generate guiding questions to help you refine your vision.{Colors.ENDC}"
)
self.print_separator("─", 79, Colors.BLUE)
# Display examples
print(f"\n{Colors.BOLD}{Colors.YELLOW}💡 Examples:{Colors.ENDC}")
print(
f"{Colors.CYAN} • 'I want to build a machine learning system for image recognition'{Colors.ENDC}"
)
print(
f"{Colors.CYAN} • 'Create a web app for project management with real-time collaboration'{Colors.ENDC}"
)
print(
f"{Colors.CYAN} • 'Develop a data analysis pipeline for financial forecasting'{Colors.ENDC}"
)
self.print_separator("─", 79, Colors.BLUE)
print(
f"\n{Colors.BOLD}{Colors.OKCYAN}✏️ Enter your initial requirements below:{Colors.ENDC}"
)
print(
f"{Colors.YELLOW}(Type your description, press Enter twice when finished, or Ctrl+C to cancel){Colors.ENDC}"
)
lines = []
empty_line_count = 0
while True:
try:
if len(lines) == 0:
print(f"{Colors.BOLD}> {Colors.ENDC}", end="")
else:
print(f"{Colors.BOLD} {Colors.ENDC}", end="")
line = input()
if line.strip() == "":
empty_line_count += 1
if empty_line_count >= 2:
break
lines.append("")
else:
empty_line_count = 0
lines.append(line)
except KeyboardInterrupt:
print(f"\n{Colors.WARNING}Input cancelled by user{Colors.ENDC}")
return ""
user_input = "\n".join(lines).strip()
if not user_input:
self.print_status("No input provided", "warning")
return ""
if len(user_input) < 20:
self.print_status(
"Input too short. Please provide more details (at least 20 characters)",
"warning",
)
retry = (
input(f"{Colors.YELLOW}Try again? (y/n): {Colors.ENDC}").strip().lower()
)
if retry == "y":
return self.get_requirement_analysis_input()
return ""
# Display input summary
word_count = len(user_input.split())
char_count = len(user_input)
print(f"\n{Colors.BOLD}{Colors.GREEN}📋 Input Summary:{Colors.ENDC}")
print(f" • {Colors.CYAN}Word count: {word_count}{Colors.ENDC}")
print(f" • {Colors.CYAN}Character count: {char_count}{Colors.ENDC}")
# Show preview
preview = user_input[:200] + "..." if len(user_input) > 200 else user_input
print(f"\n{Colors.BOLD}{Colors.CYAN}📄 Preview:{Colors.ENDC}")
print(f"{Colors.YELLOW}{preview}{Colors.ENDC}")
# Confirm
confirm = (
input(
f"\n{Colors.BOLD}{Colors.OKCYAN}Proceed with this input? (y/n): {Colors.ENDC}"
)
.strip()
.lower()
)
if confirm != "y":
retry = (
input(f"{Colors.YELLOW}Edit input? (y/n): {Colors.ENDC}")
.strip()
.lower()
)
if retry == "y":
return self.get_requirement_analysis_input()
return ""
self.print_status(
f"Requirement input captured: {word_count} words, {char_count} characters",
"success",
)
return user_input
def display_guiding_questions(self, questions_json: str):
"""Display AI-generated guiding questions (NEW: matching UI version)"""
import json
try:
questions = json.loads(questions_json)
self.print_separator("═", 79, Colors.GREEN)
print(
f"\n{Colors.BOLD}{Colors.GREEN}🤖 AI-Generated Guiding Questions{Colors.ENDC}"
)
print(
f"{Colors.CYAN}Please answer these questions to help refine your requirements:{Colors.ENDC}\n"
)
self.print_separator("─", 79, Colors.GREEN)
for i, q in enumerate(questions, 1):
print(
f"\n{Colors.BOLD}{Colors.YELLOW}Question {i}:{Colors.ENDC} {Colors.CYAN}{q}{Colors.ENDC}"
)
self.print_separator("═", 79, Colors.GREEN)
except json.JSONDecodeError:
self.print_status("Failed to parse questions", "error")
print(questions_json)
def get_question_answers(self, questions_json: str) -> dict:
"""Get user answers to guiding questions (NEW: matching UI version)"""
import json
try:
questions = json.loads(questions_json)
answers = {}
print(
f"\n{Colors.BOLD}{Colors.BLUE}📝 Answer the following questions:{Colors.ENDC}"
)
print(
f"{Colors.CYAN}(Type your answer and press Enter for each question){Colors.ENDC}\n"
)
for i, question in enumerate(questions, 1):
print(
f"\n{Colors.BOLD}{Colors.YELLOW}Q{i}:{Colors.ENDC} {Colors.CYAN}{question}{Colors.ENDC}"
)
print(f"{Colors.BOLD}{Colors.OKCYAN}Your answer:{Colors.ENDC} ", end="")
answer = input().strip()
answers[f"question_{i}"] = answer
if answer:
self.print_status(f"Answer {i} recorded", "success")
else:
self.print_status(f"Answer {i} left blank", "warning")
return answers
except json.JSONDecodeError:
self.print_status("Failed to parse questions", "error")
return {}
def display_requirement_summary(self, summary: str):
"""Display generated requirement document (NEW: matching UI version)"""
self.print_separator("═", 79, Colors.GREEN)
print(
f"\n{Colors.BOLD}{Colors.GREEN}📄 Generated Requirement Document{Colors.ENDC}\n"
)
self.print_separator("─", 79, Colors.GREEN)
print(f"{Colors.CYAN}{summary}{Colors.ENDC}")
self.print_separator("═", 79, Colors.GREEN)
# Ask if user wants to proceed with implementation
proceed = (
input(
f"\n{Colors.BOLD}{Colors.YELLOW}Would you like to proceed with code implementation based on these requirements? (y/n):{Colors.ENDC} "
)
.strip()
.lower()
)
return proceed == "y"
def ask_continue(self) -> bool:
"""Ask if user wants to continue with another paper"""
self.print_separator("─", 79, Colors.YELLOW)
print(f"\n{Colors.BOLD}{Colors.YELLOW}🔄 Process another paper?{Colors.ENDC}")
choice = input(f"{Colors.OKCYAN}Continue? (y/n): {Colors.ENDC}").strip().lower()
return choice in ["y", "yes", "1", "true"]
def add_to_history(self, input_source: str, result: dict):
"""Add processing result to history"""
entry = {
"timestamp": time.strftime("%Y-%m-%d %H:%M:%S"),
"input_source": input_source,
"status": result.get("status", "unknown"),
"result": result,
}
self.processing_history.append(entry)
def show_history(self):
"""Display processing history"""
if not self.processing_history:
self.print_status("No processing history available", "info")
return
print(f"\n{Colors.BOLD}{Colors.CYAN}📚 PROCESSING HISTORY{Colors.ENDC}")
self.print_separator("─", 79, Colors.CYAN)
for i, entry in enumerate(self.processing_history, 1):
status_icon = "✅" if entry["status"] == "success" else "❌"
source = entry["input_source"]
if len(source) > 50:
source = source[:47] + "..."
print(f"{i}. {status_icon} {entry['timestamp']} | {source}")
self.print_separator("─", 79, Colors.CYAN)
def show_configuration_menu(self):
"""Show configuration options menu"""
self.clear_screen()
# Get segmentation config status
segmentation_enabled = getattr(self, "segmentation_enabled", True)
segmentation_threshold = getattr(self, "segmentation_threshold", 50000)
print(f"""
{Colors.BOLD}{Colors.CYAN}╔═══════════════════════════════════════════════════════════════════════════════╗
║ CONFIGURATION MENU ║
╠═══════════════════════════════════════════════════════════════════════════════╣
║ ║
║ {Colors.BOLD}🤖 Agent Orchestration Engine Configuration{Colors.CYAN} ║
║ ║
║ {Colors.OKCYAN}[1] Pipeline Mode:{Colors.CYAN} ║
║ {Colors.BOLD}🧠 Comprehensive Mode{Colors.CYAN} - Full intelligence analysis (Default) ║
║ ✓ Research Analysis + Resource Processing ║
║ ✓ Reference Intelligence Discovery ║
║ ✓ Automated Repository Acquisition ║
║ ✓ Codebase Intelligence Orchestration ║
║ ✓ Intelligent Code Implementation Synthesis ║
║ ║
║ {Colors.BOLD}⚡ Optimized Mode{Colors.CYAN} - Fast processing (Skip indexing) ║
║ ✓ Research Analysis + Resource Processing ║
║ ✓ Code Architecture Synthesis ║
║ ✓ Intelligent Code Implementation Synthesis ║
║ ✗ Reference Intelligence Discovery (Skipped) ║
║ ✗ Repository Acquisition (Skipped) ║
║ ✗ Codebase Intelligence Orchestration (Skipped) ║
║ ║
║ {Colors.OKCYAN}[2] Document Processing:{Colors.CYAN} ║
║ {Colors.BOLD}📄 Smart Segmentation{Colors.CYAN} - Intelligent document analysis (Default) ║
║ ✓ Semantic boundary detection ║
║ ✓ Algorithm integrity preservation ║
║ ✓ Formula chain recognition ║
║ ✓ Adaptive character limits ║
║ ║
║ {Colors.BOLD}📋 Traditional Processing{Colors.CYAN} - Full document reading ║
║ ✓ Complete document analysis ║
║ ✗ Smart segmentation (Disabled) ║
║ ║
║ {Colors.YELLOW}Current Settings:{Colors.CYAN} ║
║ Pipeline: {'🧠 Comprehensive Mode' if self.enable_indexing else '⚡ Optimized Mode'} ║
║ Document: {'📄 Smart Segmentation' if segmentation_enabled else '📋 Traditional Processing'} ║
║ Threshold: {segmentation_threshold} characters ║
║ ║
║ {Colors.OKGREEN}[T] Toggle Pipeline {Colors.BLUE}[S] Toggle Segmentation {Colors.FAIL}[B] Back{Colors.CYAN} ║
╚═══════════════════════════════════════════════════════════════════════════════╝{Colors.ENDC}
""")
while True:
print(
f"\n{Colors.BOLD}{Colors.OKCYAN}➤ Configuration choice: {Colors.ENDC}",
end="",
)
choice = input().strip().lower()
if choice in ["t", "toggle"]:
self.enable_indexing = not self.enable_indexing
mode = "🧠 Comprehensive" if self.enable_indexing else "⚡ Optimized"
self.print_status(f"Pipeline mode switched to: {mode}", "success")
time.sleep(1)
self.show_configuration_menu()
return
elif choice in ["s", "segmentation"]:
current_state = getattr(self, "segmentation_enabled", True)
self.segmentation_enabled = not current_state
# Save the configuration to file
self._save_segmentation_config()
seg_mode = (
"📄 Smart Segmentation"
if self.segmentation_enabled
else "📋 Traditional Processing"
)
self.print_status(
f"Document processing switched to: {seg_mode}", "success"
)
time.sleep(1)
self.show_configuration_menu()
return
elif choice in ["b", "back"]:
return
else:
self.print_status(
"Invalid choice. Please enter 'T', 'S', or 'B'.", "warning"
)
================================================
FILE: cli/cli_launcher.py
================================================
#!/usr/bin/env python3
"""
DeepCode - CLI Research Engine Launcher
DeepCode - CLI研究引擎启动器
🧬 Open-Source Code Agent by Data Intelligence Lab @ HKU (CLI Edition)
⚡ Revolutionizing research reproducibility through collaborative AI via command line
"""
import sys
from pathlib import Path
def check_dependencies():
"""检查必要的依赖是否已安装 / Check if necessary dependencies are installed"""
import importlib.util
print("🔍 Checking CLI dependencies...")
missing_deps = []
# Check asyncio availability
if importlib.util.find_spec("asyncio") is not None:
print("✅ Asyncio is available")
else:
missing_deps.append("asyncio")
# Check PyYAML availability
if importlib.util.find_spec("yaml") is not None:
print("✅ PyYAML is installed")
else:
missing_deps.append("pyyaml")
# Check Tkinter availability
if importlib.util.find_spec("tkinter") is not None:
print("✅ Tkinter is available (for file dialogs)")
else:
print("⚠️ Tkinter not available - file dialogs will use manual input")
# Check for MCP agent dependencies
if importlib.util.find_spec("mcp_agent.app") is not None:
print("✅ MCP Agent framework is available")
else:
missing_deps.append("mcp-agent")
# Check for workflow dependencies
# 添加项目根目录到路径
current_dir = Path(__file__).parent
project_root = current_dir.parent
if str(project_root) not in sys.path:
sys.path.insert(0, str(project_root))
if importlib.util.find_spec("workflows.agent_orchestration_engine") is not None:
print("✅ Workflow modules are available")
else:
print("⚠️ Workflow modules may not be properly configured")
# Check for CLI components
if importlib.util.find_spec("cli.cli_app") is not None:
print("✅ CLI application components are available")
else:
print("❌ CLI application components missing")
missing_deps.append("cli-components")
if missing_deps:
print("\n❌ Missing dependencies:")
for dep in missing_deps:
print(f" - {dep}")
print("\nPlease install missing dependencies using:")
print(
f"pip install {' '.join([d for d in missing_deps if d != 'cli-components'])}"
)
if "cli-components" in missing_deps:
print(
"CLI components appear to be missing - please check the cli/ directory"
)
return False
print("✅ All CLI dependencies satisfied")
return True
def print_banner():
"""显示CLI启动横幅 / Display CLI startup banner"""
banner = """
╔══════════════════════════════════════════════════════════════╗
║ ║
║ 🧬 DeepCode - Open-Source Code Agent ║
║ ║
║ ⚡ DATA INTELLIGENCE LAB @ HKU ⚡ ║
║ ║
║ ║
║ ║
╚══════════════════════════════════════════════════════════════╝
"""
print(banner)
def main():
"""主函数 / Main function"""
print_banner()
# 检查依赖 / Check dependencies
if not check_dependencies():
print("\n🚨 Please install missing dependencies and try again.")
sys.exit(1)
# 获取当前脚本目录 / Get current script directory
current_dir = Path(__file__).parent
project_root = current_dir.parent
cli_app_path = current_dir / "cli_app.py"
# 检查cli_app.py是否存在 / Check if cli_app.py exists
if not cli_app_path.exists():
print(f"❌ CLI application file not found: {cli_app_path}")
print("Please ensure the cli/cli_app.py file exists.")
sys.exit(1)
print(f"\n📁 CLI App location: {cli_app_path}")
print("🖥️ Starting DeepCode CLI interface...")
print("🚀 Initializing command line application")
print("=" * 70)
print("💡 Tip: Follow the interactive prompts to process your research")
print("🛑 Press Ctrl+C to exit at any time")
print("=" * 70)
# 启动CLI应用 / Launch CLI application
try:
# 导入并运行CLI应用
if str(project_root) not in sys.path:
sys.path.insert(0, str(project_root)) # 添加项目根目录到路径
from cli.cli_app import main as cli_main
print("\n🎯 Launching CLI application...")
# 使用asyncio运行主函数
import asyncio
asyncio.run(cli_main())
except KeyboardInterrupt:
print("\n\n🛑 DeepCode CLI stopped by user")
print("Thank you for using DeepCode CLI! 🧬")
except ImportError as e:
print(f"\n❌ Failed to import CLI application: {e}")
print("Please check if all modules are properly installed.")
sys.exit(1)
except Exception as e:
print(f"\n❌ Unexpected error: {e}")
print("Please check your Python environment and try again.")
sys.exit(1)
if __name__ == "__main__":
main()
================================================
FILE: cli/main_cli.py
================================================
#!/usr/bin/env python3
"""
DeepCode CLI - Open-Source Code Agent
深度代码CLI - 开源代码智能体
🧬 Data Intelligence Lab @ HKU
⚡ Revolutionizing Research Reproducibility through Multi-Agent Architecture
"""
import os
import sys
import asyncio
import argparse
# 禁止生成.pyc文件
os.environ["PYTHONDONTWRITEBYTECODE"] = "1"
# 添加项目根目录到路径
current_dir = os.path.dirname(os.path.abspath(__file__))
parent_dir = os.path.dirname(current_dir)
if parent_dir not in sys.path:
sys.path.insert(0, parent_dir)
# 导入CLI应用
from cli.cli_app import CLIApp, Colors
def print_enhanced_banner():
"""显示增强版启动横幅"""
banner = f"""
{Colors.CYAN}╔══════════════════════════════════════════════════════════════════════════════╗
║ ║
║ {Colors.BOLD}{Colors.MAGENTA}🧬 DeepCode - Open-Source Code Agent{Colors.CYAN} ║
║ ║
║ {Colors.BOLD}{Colors.YELLOW}⚡ DATA INTELLIGENCE LAB @ HKU ⚡{Colors.CYAN} ║
║ ║
║ Revolutionizing research reproducibility through collaborative AI ║
║ Building the future where code is reproduced from natural language ║
║ ║
║ {Colors.BOLD}{Colors.GREEN}🤖 Key Features:{Colors.CYAN} ║
║ • Automated paper-to-code reproduction ║
║ • Multi-agent collaborative architecture ║
║ • Open-source and extensible design ║
║ • Join our growing research community ║
║ ║
╚══════════════════════════════════════════════════════════════════════════════╝{Colors.ENDC}
"""
print(banner)
def check_environment():
"""检查运行环境"""
print(f"{Colors.CYAN}🔍 Checking environment...{Colors.ENDC}")
# 检查Python版本
if sys.version_info < (3, 8):
print(
f"{Colors.FAIL}❌ Python 3.8+ required. Current: {sys.version}{Colors.ENDC}"
)
return False
print(f"{Colors.OKGREEN}✅ Python {sys.version.split()[0]} - OK{Colors.ENDC}")
# 检查必要模块
required_modules = [
("asyncio", "Async IO support"),
("pathlib", "Path handling"),
("typing", "Type hints"),
]
missing_modules = []
for module, desc in required_modules:
try:
__import__(module)
print(f"{Colors.OKGREEN}✅ {desc} - OK{Colors.ENDC}")
except ImportError:
missing_modules.append(module)
print(f"{Colors.FAIL}❌ {desc} - Missing{Colors.ENDC}")
if missing_modules:
print(
f"{Colors.FAIL}❌ Missing required modules: {', '.join(missing_modules)}{Colors.ENDC}"
)
return False
print(f"{Colors.OKGREEN}✅ Environment check passed{Colors.ENDC}")
return True
def parse_arguments():
"""解析命令行参数"""
parser = argparse.ArgumentParser(
description="DeepCode CLI - Open-Source Code Agent by Data Intelligence Lab @ HKU",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog=f"""
{Colors.BOLD}Examples:{Colors.ENDC}
{Colors.CYAN}python main_cli.py{Colors.ENDC} # Interactive mode
{Colors.CYAN}python main_cli.py --file paper.pdf{Colors.ENDC} # Process file directly
{Colors.CYAN}python main_cli.py --url https://...{Colors.ENDC} # Process URL directly
{Colors.CYAN}python main_cli.py --chat "Build a web app..."{Colors.ENDC} # Process chat requirements
{Colors.CYAN}python main_cli.py --requirement "ML system for..."{Colors.ENDC} # Guided requirement analysis (NEW)
{Colors.CYAN}python main_cli.py --optimized{Colors.ENDC} # Use optimized mode
{Colors.CYAN}python main_cli.py --disable-segmentation{Colors.ENDC} # Disable document segmentation
{Colors.CYAN}python main_cli.py --segmentation-threshold 30000{Colors.ENDC} # Custom segmentation threshold
{Colors.BOLD}Pipeline Modes:{Colors.ENDC}
{Colors.GREEN}Comprehensive{Colors.ENDC}: Full intelligence analysis with indexing
{Colors.YELLOW}Optimized{Colors.ENDC}: Fast processing without indexing
{Colors.BLUE}Requirement Analysis{Colors.ENDC}: Guided Q&A to refine requirements (NEW)
{Colors.BOLD}Document Processing:{Colors.ENDC}
{Colors.BLUE}Smart Segmentation{Colors.ENDC}: Intelligent document segmentation for large papers
{Colors.MAGENTA}Supported Formats{Colors.ENDC}: PDF, DOCX, DOC, PPT, PPTX, XLS, XLSX, HTML, TXT, MD
""",
)
parser.add_argument(
"--file", "-f", type=str, help="Process a specific file (PDF, DOCX, TXT, etc.)"
)
parser.add_argument(
"--url", "-u", type=str, help="Process a research paper from URL"
)
parser.add_argument(
"--chat",
"-t",
type=str,
help="Process coding requirements via chat input (provide requirements as argument)",
)
parser.add_argument(
"--requirement",
"-r",
type=str,
help="Process requirements via guided analysis (provide initial idea as argument)",
)
parser.add_argument(
"--optimized",
"-o",
action="store_true",
help="Use optimized mode (skip indexing for faster processing)",
)
parser.add_argument(
"--disable-segmentation",
action="store_true",
help="Disable intelligent document segmentation (use traditional full-document processing)",
)
parser.add_argument(
"--segmentation-threshold",
type=int,
default=50000,
help="Document size threshold (characters) to trigger segmentation (default: 50000)",
)
parser.add_argument(
"--verbose", "-v", action="store_true", help="Enable verbose output"
)
return parser.parse_args()
async def run_direct_processing(app: CLIApp, input_source: str, input_type: str):
"""直接处理模式(非交互式)"""
try:
print(
f"\n{Colors.BOLD}{Colors.CYAN}🚀 Starting direct processing mode...{Colors.ENDC}"
)
print(f"{Colors.CYAN}Input: {input_source}{Colors.ENDC}")
print(f"{Colors.CYAN}Type: {input_type}{Colors.ENDC}")
print(
f"{Colors.CYAN}Mode: {'🧠 Comprehensive' if app.cli.enable_indexing else '⚡ Optimized'}{Colors.ENDC}"
)
# 初始化应用
init_result = await app.initialize_mcp_app()
if init_result["status"] != "success":
print(
f"{Colors.FAIL}❌ Initialization failed: {init_result['message']}{Colors.ENDC}"
)
return False
# 处理输入
result = await app.process_input(input_source, input_type)
if result["status"] == "success":
print(
f"\n{Colors.BOLD}{Colors.OKGREEN}🎉 Processing completed successfully!{Colors.ENDC}"
)
return True
else:
print(
f"\n{Colors.BOLD}{Colors.FAIL}❌ Processing failed: {result.get('error', 'Unknown error')}{Colors.ENDC}"
)
return False
except Exception as e:
print(f"\n{Colors.FAIL}❌ Direct processing error: {str(e)}{Colors.ENDC}")
return False
finally:
await app.cleanup_mcp_app()
async def run_requirement_analysis(app: CLIApp, initial_idea: str):
"""需求分析模式(非交互式) - NEW: matching UI version"""
try:
print(
f"\n{Colors.BOLD}{Colors.BLUE}🧠 Starting requirement analysis mode...{Colors.ENDC}"
)
print(f"{Colors.CYAN}Initial Idea: {initial_idea}{Colors.ENDC}")
# 初始化应用
init_result = await app.initialize_mcp_app()
if init_result["status"] != "success":
print(
f"{Colors.FAIL}❌ Initialization failed: {init_result['message']}{Colors.ENDC}"
)
return False
# 执行需求分析工作流
result = await app.process_requirement_analysis_non_interactive(initial_idea)
if result["status"] == "success":
print(
f"\n{Colors.BOLD}{Colors.OKGREEN}🎉 Requirement analysis completed successfully!{Colors.ENDC}"
)
return True
else:
print(
f"\n{Colors.BOLD}{Colors.FAIL}❌ Requirement analysis failed: {result.get('error', 'Unknown error')}{Colors.ENDC}"
)
return False
except Exception as e:
print(f"\n{Colors.FAIL}❌ Requirement analysis error: {str(e)}{Colors.ENDC}")
return False
finally:
await app.cleanup_mcp_app()
async def main():
"""主函数"""
# 解析命令行参数
args = parse_arguments()
# 显示横幅
print_enhanced_banner()
# 检查环境
if not check_environment():
print(
f"\n{Colors.FAIL}🚨 Environment check failed. Please fix the issues and try again.{Colors.ENDC}"
)
sys.exit(1)
try:
# 创建CLI应用
app = CLIApp()
# 设置配置 - 默认禁用索引功能以加快处理速度
if args.optimized:
app.cli.enable_indexing = False
print(
f"\n{Colors.YELLOW}⚡ Optimized mode enabled - indexing disabled{Colors.ENDC}"
)
else:
# 默认也禁用索引功能
app.cli.enable_indexing = False
print(
f"\n{Colors.YELLOW}⚡ Fast mode enabled - indexing disabled by default{Colors.ENDC}"
)
# Configure document segmentation settings
if hasattr(args, "disable_segmentation") and args.disable_segmentation:
print(
f"\n{Colors.MAGENTA}📄 Document segmentation disabled - using traditional processing{Colors.ENDC}"
)
app.cli.segmentation_enabled = False
app.cli.segmentation_threshold = args.segmentation_threshold
app.cli._save_segmentation_config()
else:
print(
f"\n{Colors.BLUE}📄 Smart document segmentation enabled (threshold: {args.segmentation_threshold} chars){Colors.ENDC}"
)
app.cli.segmentation_enabled = True
app.cli.segmentation_threshold = args.segmentation_threshold
app.cli._save_segmentation_config()
# 检查是否为直接处理模式
if args.file or args.url or args.chat or args.requirement:
if args.file:
# 验证文件存在
if not os.path.exists(args.file):
print(f"{Colors.FAIL}❌ File not found: {args.file}{Colors.ENDC}")
sys.exit(1)
# 使用 file:// 前缀保持与交互模式一致,确保文件被复制而非移动
file_url = f"file://{os.path.abspath(args.file)}"
success = await run_direct_processing(app, file_url, "file")
elif args.url:
success = await run_direct_processing(app, args.url, "url")
elif args.chat:
# 验证chat输入长度
if len(args.chat.strip()) < 20:
print(
f"{Colors.FAIL}❌ Chat input too short. Please provide more detailed requirements (at least 20 characters){Colors.ENDC}"
)
sys.exit(1)
success = await run_direct_processing(app, args.chat, "chat")
elif args.requirement:
# NEW: Requirement analysis mode
# 验证需求输入长度
if len(args.requirement.strip()) < 10:
print(
f"{Colors.FAIL}❌ Requirement input too short. Please provide more details (at least 10 characters){Colors.ENDC}"
)
sys.exit(1)
success = await run_requirement_analysis(app, args.requirement)
sys.exit(0 if success else 1)
else:
# 交互式模式
print(f"\n{Colors.CYAN}🎮 Starting interactive mode...{Colors.ENDC}")
await app.run_interactive_session()
except KeyboardInterrupt:
print(f"\n{Colors.WARNING}⚠️ Application interrupted by user{Colors.ENDC}")
sys.exit(1)
except Exception as e:
print(f"\n{Colors.FAIL}❌ Application errors: {str(e)}{Colors.ENDC}")
sys.exit(1)
if __name__ == "__main__":
asyncio.run(main())
================================================
FILE: cli/workflows/__init__.py
================================================
"""
CLI-specific Workflow Adapters
CLI专用工作流适配器
This module provides CLI-optimized versions of workflow components that are
specifically adapted for command-line interface usage patterns.
"""
from .cli_workflow_adapter import CLIWorkflowAdapter
__all__ = ["CLIWorkflowAdapter"]
================================================
FILE: cli/workflows/cli_workflow_adapter.py
================================================
"""
CLI Workflow Adapter for Agent Orchestration Engine
CLI工作流适配器 - 智能体编排引擎
This adapter provides CLI-optimized interface to the latest agent orchestration engine,
with enhanced progress reporting, error handling, and CLI-specific optimizations.
Version: 2.1 (Updated to match UI version - Added Requirement Analysis)
Changes:
- Default enable_indexing=False for faster processing (matching UI defaults)
- Mode-aware progress callback with detailed stage mapping
- Chat pipeline now accepts enable_indexing parameter
- Improved error handling and resource management
- Enhanced progress display for different modes (fast/comprehensive/chat)
- NEW: Added requirement analysis workflow support
"""
import os
from typing import Callable, Dict, Any
from mcp_agent.app import MCPApp
class CLIWorkflowAdapter:
"""
CLI-optimized workflow adapter for the intelligent agent orchestration engine.
This adapter provides:
- Enhanced CLI progress reporting
- Optimized error handling for CLI environments
- Streamlined interface for command-line usage
- Integration with the latest agent orchestration engine
"""
def __init__(self, cli_interface=None):
"""
Initialize CLI workflow adapter.
Args:
cli_interface: CLI interface instance for progress reporting
"""
self.cli_interface = cli_interface
self.app = None
self.logger = None
self.context = None
async def initialize_mcp_app(self) -> Dict[str, Any]:
"""
Initialize MCP application for CLI usage (improved version matching UI).
Returns:
dict: Initialization result
"""
try:
if self.cli_interface:
self.cli_interface.show_spinner(
"🚀 Initializing Agent Orchestration Engine", 2.0
)
# Initialize MCP application using async context manager (matching UI pattern)
self.app = MCPApp(name="cli_agent_orchestration")
self.app_context = self.app.run()
agent_app = await self.app_context.__aenter__()
self.logger = agent_app.logger
self.context = agent_app.context
# Configure filesystem access
self.context.config.mcp.servers["filesystem"].args.extend([os.getcwd()])
if self.cli_interface:
self.cli_interface.print_status(
"🧠 Agent Orchestration Engine initialized successfully", "success"
)
return {
"status": "success",
"message": "MCP application initialized successfully",
}
except Exception as e:
error_msg = f"Failed to initialize MCP application: {str(e)}"
if self.cli_interface:
self.cli_interface.print_status(error_msg, "error")
return {"status": "error", "message": error_msg}
async def cleanup_mcp_app(self):
"""
Clean up MCP application resources.
"""
if hasattr(self, "app_context"):
try:
await self.app_context.__aexit__(None, None, None)
if self.cli_interface:
self.cli_interface.print_status(
"🧹 Resources cleaned up successfully", "info"
)
except Exception as e:
if self.cli_interface:
self.cli_interface.print_status(
f"⚠️ Cleanup warning: {str(e)}", "warning"
)
def create_cli_progress_callback(self, enable_indexing: bool = True) -> Callable:
"""
Create CLI-optimized progress callback function with mode-aware stage mapping.
This matches the UI version's detailed progress mapping logic.
Args:
enable_indexing: Whether indexing is enabled (affects stage mapping)
Returns:
Callable: Progress callback function
"""
def progress_callback(progress: int, message: str):
if self.cli_interface:
# Mode-aware stage mapping (matching UI version logic)
if enable_indexing:
# Full workflow mapping: Initialize -> Analyze -> Download -> Plan -> References -> Repos -> Index -> Implement
if progress <= 5:
stage = 0 # Initialize
elif progress <= 10:
stage = 1 # Analyze
elif progress <= 25:
stage = 2 # Download
elif progress <= 40:
stage = 3 # Plan
elif progress <= 50:
stage = 4 # References
elif progress <= 60:
stage = 5 # Repos
elif progress <= 70:
stage = 6 # Index
elif progress <= 85:
stage = 7 # Implement
else:
stage = 8 # Complete
else:
# Fast mode mapping: Initialize -> Analyze -> Download -> Plan -> Implement
if progress <= 5:
stage = 0 # Initialize
elif progress <= 10:
stage = 1 # Analyze
elif progress <= 25:
stage = 2 # Download
elif progress <= 40:
stage = 3 # Plan
elif progress <= 85:
stage = 4 # Implement (skip References, Repos, Index)
else:
stage = 4 # Complete
self.cli_interface.display_processing_stages(stage, enable_indexing)
# Display status message
self.cli_interface.print_status(message, "processing")
return progress_callback
async def execute_full_pipeline(
self, input_source: str, enable_indexing: bool = False
) -> Dict[str, Any]:
"""
Execute the complete intelligent multi-agent research orchestration pipeline.
Updated to match UI version: default enable_indexing=False for faster processing.
Args:
input_source: Research input source (file path, URL, or preprocessed analysis)
enable_indexing: Whether to enable advanced intelligence analysis (default: False)
Returns:
dict: Comprehensive pipeline execution result
"""
try:
# Import the latest agent orchestration engine
from workflows.agent_orchestration_engine import (
execute_multi_agent_research_pipeline,
)
# Create CLI progress callback with mode awareness
progress_callback = self.create_cli_progress_callback(enable_indexing)
# Display pipeline start
if self.cli_interface:
if enable_indexing:
mode_msg = "🧠 comprehensive (with indexing)"
else:
mode_msg = "⚡ fast (indexing disabled)"
self.cli_interface.print_status(
f"🚀 Starting {mode_msg} agent orchestration pipeline...",
"processing",
)
self.cli_interface.display_processing_stages(0, enable_indexing)
# Execute the pipeline
result = await execute_multi_agent_research_pipeline(
input_source=input_source,
logger=self.logger,
progress_callback=progress_callback,
enable_indexing=enable_indexing,
)
# Display completion
if self.cli_interface:
final_stage = 8 if enable_indexing else 4
self.cli_interface.display_processing_stages(
final_stage, enable_indexing
)
self.cli_interface.print_status(
"🎉 Agent orchestration pipeline completed successfully!",
"complete",
)
return {
"status": "success",
"result": result,
"pipeline_mode": "comprehensive" if enable_indexing else "optimized",
}
except Exception as e:
error_msg = f"Pipeline execution failed: {str(e)}"
if self.cli_interface:
self.cli_interface.print_status(error_msg, "error")
return {
"status": "error",
"error": error_msg,
"pipeline_mode": "comprehensive" if enable_indexing else "optimized",
}
async def execute_requirement_analysis_workflow(
self, user_input: str, analysis_mode: str, user_answers: Dict[str, str] = None
) -> Dict[str, Any]:
"""
Execute requirement analysis workflow (NEW: matching UI version).
This workflow helps users refine their requirements through guided questions
and intelligent analysis before starting code implementation.
Args:
user_input: User's initial requirements or description
analysis_mode: Analysis mode ("generate_questions" or "summarize_requirements")
user_answers: Dictionary of user answers to guiding questions (for summarize mode)
Returns:
dict: Analysis result with questions or requirement summary
"""
try:
# Import the requirement analysis workflow
from workflows.agent_orchestration_engine import (
execute_requirement_analysis_workflow,
)
# Create CLI progress callback
def analysis_progress_callback(progress: int, message: str):
if self.cli_interface:
self.cli_interface.print_status(message, "processing")
# Display workflow start
if self.cli_interface:
if analysis_mode == "generate_questions":
self.cli_interface.print_status(
"🤖 Generating guiding questions for your requirements...",
"processing",
)
else:
self.cli_interface.print_status(
"📄 Analyzing and summarizing your detailed requirements...",
"processing",
)
# Execute the requirement analysis workflow
result = await execute_requirement_analysis_workflow(
user_input=user_input,
analysis_mode=analysis_mode,
user_answers=user_answers,
logger=self.logger,
progress_callback=analysis_progress_callback,
)
# Display completion
if self.cli_interface:
if result["status"] == "success":
if analysis_mode == "generate_questions":
self.cli_interface.print_status(
"✅ Guiding questions generated successfully!", "success"
)
else:
self.cli_interface.print_status(
"✅ Requirements analysis completed successfully!",
"success",
)
else:
self.cli_interface.print_status(
f"❌ Analysis failed: {result.get('error', 'Unknown error')}",
"error",
)
return result
except Exception as e:
error_msg = f"Requirement analysis workflow failed: {str(e)}"
if self.cli_interface:
self.cli_interface.print_status(error_msg, "error")
return {"status": "error", "error": error_msg}
async def execute_chat_pipeline(
self, user_input: str, enable_indexing: bool = False
) -> Dict[str, Any]:
"""
Execute the chat-based planning and implementation pipeline.
Updated to match UI version: accepts enable_indexing parameter.
Args:
user_input: User's coding requirements and description
enable_indexing: Whether to enable indexing for enhanced code understanding (default: False)
Returns:
dict: Chat pipeline execution result
"""
try:
# Import the chat-based pipeline
from workflows.agent_orchestration_engine import (
execute_chat_based_planning_pipeline,
)
# Create CLI progress callback for chat mode
def chat_progress_callback(progress: int, message: str):
if self.cli_interface:
# Map progress to CLI stages for chat mode (matching UI logic)
if progress <= 5:
stage = 0 # Initialize
elif progress <= 30:
stage = 1 # Planning
elif progress <= 50:
stage = 2 # Setup
elif progress <= 70:
stage = 3 # Save Plan
else:
stage = 4 # Implement
self.cli_interface.display_processing_stages(stage, chat_mode=True)
# Display status message
self.cli_interface.print_status(message, "processing")
# Display pipeline start
if self.cli_interface:
indexing_note = (
" (with indexing)" if enable_indexing else " (fast mode)"
)
self.cli_interface.print_status(
f"🚀 Starting chat-based planning pipeline{indexing_note}...",
"processing",
)
self.cli_interface.display_processing_stages(0, chat_mode=True)
# Execute the chat pipeline with configurable indexing
result = await execute_chat_based_planning_pipeline(
user_input=user_input,
logger=self.logger,
progress_callback=chat_progress_callback,
enable_indexing=enable_indexing, # Pass through enable_indexing parameter
)
# Display completion
if self.cli_interface:
self.cli_interface.display_processing_stages(4, chat_mode=True)
self.cli_interface.print_status(
"🎉 Chat-based planning pipeline completed successfully!",
"complete",
)
return {"status": "success", "result": result, "pipeline_mode": "chat"}
except Exception as e:
error_msg = f"Chat pipeline execution failed: {str(e)}"
if self.cli_interface:
self.cli_interface.print_status(error_msg, "error")
return {"status": "error", "error": error_msg, "pipeline_mode": "chat"}
async def process_input_with_orchestration(
self, input_source: str, input_type: str, enable_indexing: bool = False
) -> Dict[str, Any]:
"""
Process input using the intelligent agent orchestration engine.
This is the main CLI interface to the latest agent orchestration capabilities.
Updated to match UI version: default enable_indexing=False.
Args:
input_source: Input source (file path, URL, or chat input)
input_type: Type of input ('file', 'url', or 'chat')
enable_indexing: Whether to enable advanced intelligence analysis (default: False)
Returns:
dict: Processing result with status and details
"""
pipeline_result = None
try:
# Initialize MCP app
init_result = await self.initialize_mcp_app()
if init_result["status"] != "success":
return init_result
# Process file:// URLs for traditional file/URL inputs
if input_source.startswith("file://"):
file_path = input_source[7:]
if os.name == "nt" and file_path.startswith("/"):
file_path = file_path.lstrip("/")
input_source = file_path
# Execute appropriate pipeline based on input type
if input_type == "chat":
# Use chat-based planning pipeline for user requirements
# Pass enable_indexing to chat pipeline as well
pipeline_result = await self.execute_chat_pipeline(
input_source, enable_indexing=enable_indexing
)
else:
# Use traditional multi-agent research pipeline for files/URLs
pipeline_result = await self.execute_full_pipeline(
input_source, enable_indexing=enable_indexing
)
return {
"status": pipeline_result["status"],
"analysis_result": "Integrated into agent orchestration pipeline",
"download_result": "Integrated into agent orchestration pipeline",
"repo_result": pipeline_result.get("result", ""),
"pipeline_mode": pipeline_result.get("pipeline_mode", "comprehensive"),
"error": pipeline_result.get("error"),
}
except Exception as e:
error_msg = f"Error during orchestrated processing: {str(e)}"
if self.cli_interface:
self.cli_interface.print_status(error_msg, "error")
return {
"status": "error",
"error": error_msg,
"analysis_result": "",
"download_result": "",
"repo_result": "",
"pipeline_mode": "comprehensive" if enable_indexing else "optimized",
}
finally:
# Clean up resources
await self.cleanup_mcp_app()
================================================
FILE: config/mcp_tool_definitions.py
================================================
"""
MCP工具定义配置模块
MCP Tool Definitions Configuration Module
将工具定义从主程序逻辑中分离,提供标准化的工具定义格式
Separate tool definitions from main program logic, providing standardized tool definition format
支持的工具类型:
- 文件操作工具 (File Operations)
- 代码执行工具 (Code Execution)
- 搜索工具 (Search Tools)
- 项目结构工具 (Project Structure Tools)
"""
from typing import Dict, List, Any
class MCPToolDefinitions:
"""MCP工具定义管理器"""
@staticmethod
def get_code_implementation_tools() -> List[Dict[str, Any]]:
"""
获取代码实现相关的工具定义
Get tool definitions for code implementation
"""
return [
# MCPToolDefinitions._get_read_file_tool(),
# MCPToolDefinitions._get_read_multiple_files_tool(),
# MCPToolDefinitions._get_read_code_mem_tool(),
MCPToolDefinitions._get_write_file_tool(),
# MCPToolDefinitions._get_write_multiple_files_tool(),
# MCPToolDefinitions._get_execute_python_tool(),
# MCPToolDefinitions._get_execute_bash_tool(),
]
@staticmethod
def _get_read_file_tool() -> Dict[str, Any]:
"""读取文件工具定义"""
return {
"name": "read_file",
"description": "Read file content, supports specifying line number range",
"input_schema": {
"type": "object",
"properties": {
"file_path": {
"type": "string",
"description": "File path, relative to workspace",
},
"start_line": {
"type": "integer",
"description": "Start line number (starting from 1, optional)",
gitextract_3wtguj4a/
├── .dockerignore
├── .gitattributes
├── .github/
│ ├── ISSUE_TEMPLATE/
│ │ ├── bug_report.yml
│ │ ├── config.yml
│ │ ├── feature_request.yml
│ │ └── question.yml
│ ├── dependabot.yml
│ ├── pull_request_template.md
│ └── workflows/
│ ├── linting.yaml
│ └── pypi-publish.yml
├── .gitignore
├── .pre-commit-config.yaml
├── CHANGELOG.md
├── LICENSE
├── MANIFEST.in
├── README.md
├── README_ZH.md
├── __init__.py
├── cli/
│ ├── __init__.py
│ ├── cli_app.py
│ ├── cli_interface.py
│ ├── cli_launcher.py
│ ├── main_cli.py
│ └── workflows/
│ ├── __init__.py
│ └── cli_workflow_adapter.py
├── config/
│ ├── mcp_tool_definitions.py
│ └── mcp_tool_definitions_index.py
├── deepcode.py
├── deepcode_docker/
│ ├── .dockerignore
│ ├── Dockerfile
│ ├── docker-compose.yml
│ ├── docker-entrypoint.sh
│ └── run_docker.sh
├── mcp_agent.config.yaml
├── mcp_agent.secrets.yaml.example
├── nanobot/
│ ├── .dockerignore
│ ├── .gitignore
│ ├── COMMUNICATION.md
│ ├── Dockerfile
│ ├── LICENSE
│ ├── README.md
│ ├── SECURITY.md
│ ├── bridge/
│ │ ├── package.json
│ │ ├── src/
│ │ │ ├── index.ts
│ │ │ ├── server.ts
│ │ │ ├── types.d.ts
│ │ │ └── whatsapp.ts
│ │ └── tsconfig.json
│ ├── core_agent_lines.sh
│ ├── nanobot/
│ │ ├── __init__.py
│ │ ├── __main__.py
│ │ ├── agent/
│ │ │ ├── __init__.py
│ │ │ ├── context.py
│ │ │ ├── loop.py
│ │ │ ├── memory.py
│ │ │ ├── skills.py
│ │ │ ├── subagent.py
│ │ │ └── tools/
│ │ │ ├── __init__.py
│ │ │ ├── base.py
│ │ │ ├── cron.py
│ │ │ ├── deepcode.py
│ │ │ ├── filesystem.py
│ │ │ ├── message.py
│ │ │ ├── registry.py
│ │ │ ├── shell.py
│ │ │ ├── spawn.py
│ │ │ └── web.py
│ │ ├── bus/
│ │ │ ├── __init__.py
│ │ │ ├── events.py
│ │ │ └── queue.py
│ │ ├── channels/
│ │ │ ├── __init__.py
│ │ │ ├── base.py
│ │ │ ├── dingtalk.py
│ │ │ ├── discord.py
│ │ │ ├── email.py
│ │ │ ├── feishu.py
│ │ │ ├── manager.py
│ │ │ ├── qq.py
│ │ │ ├── slack.py
│ │ │ ├── telegram.py
│ │ │ └── whatsapp.py
│ │ ├── cli/
│ │ │ ├── __init__.py
│ │ │ └── commands.py
│ │ ├── config/
│ │ │ ├── __init__.py
│ │ │ ├── loader.py
│ │ │ └── schema.py
│ │ ├── cron/
│ │ │ ├── __init__.py
│ │ │ ├── service.py
│ │ │ └── types.py
│ │ ├── heartbeat/
│ │ │ ├── __init__.py
│ │ │ └── service.py
│ │ ├── providers/
│ │ │ ├── __init__.py
│ │ │ ├── base.py
│ │ │ ├── litellm_provider.py
│ │ │ ├── registry.py
│ │ │ └── transcription.py
│ │ ├── session/
│ │ │ ├── __init__.py
│ │ │ └── manager.py
│ │ ├── skills/
│ │ │ ├── README.md
│ │ │ ├── cron/
│ │ │ │ └── SKILL.md
│ │ │ ├── deepcode/
│ │ │ │ └── SKILL.md
│ │ │ ├── github/
│ │ │ │ └── SKILL.md
│ │ │ ├── skill-creator/
│ │ │ │ └── SKILL.md
│ │ │ ├── summarize/
│ │ │ │ └── SKILL.md
│ │ │ ├── tmux/
│ │ │ │ ├── SKILL.md
│ │ │ │ └── scripts/
│ │ │ │ ├── find-sessions.sh
│ │ │ │ └── wait-for-text.sh
│ │ │ └── weather/
│ │ │ └── SKILL.md
│ │ └── utils/
│ │ ├── __init__.py
│ │ └── helpers.py
│ ├── pyproject.toml
│ ├── run_nanobot.sh
│ └── workspace/
│ ├── AGENTS.md
│ ├── HEARTBEAT.md
│ ├── SOUL.md
│ ├── TOOLS.md
│ ├── USER.md
│ └── memory/
│ └── MEMORY.md
├── nanobot_config.json.example
├── new_ui/
│ ├── README.md
│ ├── backend/
│ │ ├── __init__.py
│ │ ├── api/
│ │ │ ├── __init__.py
│ │ │ ├── routes/
│ │ │ │ ├── __init__.py
│ │ │ │ ├── config.py
│ │ │ │ ├── files.py
│ │ │ │ ├── requirements.py
│ │ │ │ └── workflows.py
│ │ │ └── websockets/
│ │ │ ├── __init__.py
│ │ │ ├── code_stream_ws.py
│ │ │ ├── logs_ws.py
│ │ │ └── workflow_ws.py
│ │ ├── app_utils/
│ │ │ └── __init__.py
│ │ ├── main.py
│ │ ├── models/
│ │ │ ├── __init__.py
│ │ │ ├── requests.py
│ │ │ └── responses.py
│ │ ├── services/
│ │ │ ├── __init__.py
│ │ │ ├── requirement_service.py
│ │ │ ├── session_service.py
│ │ │ └── workflow_service.py
│ │ └── settings.py
│ ├── frontend/
│ │ ├── index.html
│ │ ├── package.json
│ │ ├── postcss.config.js
│ │ ├── src/
│ │ │ ├── App.tsx
│ │ │ ├── components/
│ │ │ │ ├── common/
│ │ │ │ │ ├── Button.tsx
│ │ │ │ │ ├── Card.tsx
│ │ │ │ │ ├── ConfirmDialog.tsx
│ │ │ │ │ ├── GuardedLink.tsx
│ │ │ │ │ ├── TaskRecoveryBanner.tsx
│ │ │ │ │ ├── Toaster.tsx
│ │ │ │ │ └── index.ts
│ │ │ │ ├── input/
│ │ │ │ │ ├── ChatInput.tsx
│ │ │ │ │ ├── FileUploader.tsx
│ │ │ │ │ ├── UrlInput.tsx
│ │ │ │ │ └── index.ts
│ │ │ │ ├── interaction/
│ │ │ │ │ ├── InlineChatInteraction.tsx
│ │ │ │ │ ├── InteractionPanel.tsx
│ │ │ │ │ └── index.ts
│ │ │ │ ├── layout/
│ │ │ │ │ ├── Header.tsx
│ │ │ │ │ ├── Layout.tsx
│ │ │ │ │ ├── Sidebar.tsx
│ │ │ │ │ └── index.ts
│ │ │ │ ├── results/
│ │ │ │ │ ├── CodePreview.tsx
│ │ │ │ │ ├── FileTree.tsx
│ │ │ │ │ └── index.ts
│ │ │ │ ├── streaming/
│ │ │ │ │ ├── ActivityLogViewer.tsx
│ │ │ │ │ ├── CodeStreamViewer.tsx
│ │ │ │ │ ├── LogViewer.tsx
│ │ │ │ │ ├── ProgressTracker.tsx
│ │ │ │ │ └── index.ts
│ │ │ │ └── workflow/
│ │ │ │ ├── WorkflowCanvas.tsx
│ │ │ │ ├── WorkflowNode.tsx
│ │ │ │ └── index.ts
│ │ │ ├── hooks/
│ │ │ │ ├── index.ts
│ │ │ │ ├── useAdaptiveLayout.ts
│ │ │ │ ├── useNavigationGuard.ts
│ │ │ │ ├── useStreaming.ts
│ │ │ │ ├── useTaskRecovery.ts
│ │ │ │ └── useWebSocket.ts
│ │ │ ├── index.css
│ │ │ ├── main.tsx
│ │ │ ├── pages/
│ │ │ │ ├── ChatPlanningPage.tsx
│ │ │ │ ├── HomePage.tsx
│ │ │ │ ├── PaperToCodePage.tsx
│ │ │ │ ├── SettingsPage.tsx
│ │ │ │ ├── WorkflowEditorPage.tsx
│ │ │ │ └── index.ts
│ │ │ ├── services/
│ │ │ │ └── api.ts
│ │ │ ├── stores/
│ │ │ │ ├── index.ts
│ │ │ │ ├── sessionStore.ts
│ │ │ │ └── workflowStore.ts
│ │ │ └── types/
│ │ │ ├── api.ts
│ │ │ ├── common.ts
│ │ │ ├── index.ts
│ │ │ └── workflow.ts
│ │ ├── tailwind.config.js
│ │ ├── tsconfig.json
│ │ ├── tsconfig.node.json
│ │ └── vite.config.ts
│ └── scripts/
│ ├── build.sh
│ └── start_dev.sh
├── prompts/
│ └── code_prompts.py
├── requirements.txt
├── run.bat
├── run.sh
├── schema/
│ └── mcp-agent.config.schema.json
├── setup.py
├── tools/
│ ├── __init__.py
│ ├── bocha_search_server.py
│ ├── code_implementation_server.py
│ ├── code_indexer.py
│ ├── code_reference_indexer.py
│ ├── command_executor.py
│ ├── document_segmentation_server.py
│ ├── git_command.py
│ ├── indexer_config.yaml
│ ├── pdf_converter.py
│ ├── pdf_downloader.py
│ └── pdf_utils.py
├── ui/
│ ├── __init__.py
│ ├── app.py
│ ├── components.py
│ ├── handlers.py
│ ├── layout.py
│ ├── sidebar_feed.py
│ ├── streamlit_app.py
│ └── styles.py
├── utils/
│ ├── __init__.py
│ ├── cli_interface.py
│ ├── cross_platform_file_handler.py
│ ├── dialogue_logger.py
│ ├── file_processor.py
│ ├── llm_utils.py
│ ├── loop_detector.py
│ ├── model_limits.py
│ └── simple_llm_logger.py
└── workflows/
├── __init__.py
├── agent_orchestration_engine.py
├── agents/
│ ├── __init__.py
│ ├── code_implementation_agent.py
│ ├── document_segmentation_agent.py
│ ├── memory_agent_concise.py
│ ├── memory_agent_concise_index.py
│ ├── memory_agent_concise_multi.py
│ └── requirement_analysis_agent.py
├── code_implementation_workflow.py
├── code_implementation_workflow_index.py
├── codebase_index_workflow.py
└── plugins/
├── USAGE.md
├── __init__.py
├── base.py
├── integration.py
├── plan_review.py
└── requirement_analysis.py
SYMBOL INDEX (1398 symbols across 140 files)
FILE: cli/cli_app.py
class CLIApp (line 31) | class CLIApp:
method __init__ (line 34) | def __init__(self):
method initialize_mcp_app (line 42) | async def initialize_mcp_app(self):
method cleanup_mcp_app (line 47) | async def cleanup_mcp_app(self):
method process_requirement_analysis_non_interactive (line 51) | async def process_requirement_analysis_non_interactive(self, initial_i...
method process_requirement_analysis (line 115) | async def process_requirement_analysis(self):
method process_input (line 230) | async def process_input(self, input_source: str, input_type: str):
method display_results (line 295) | def display_results(
method run_interactive_session (line 389) | async def run_interactive_session(self):
function main (line 466) | async def main():
FILE: cli/cli_interface.py
class Colors (line 13) | class Colors:
class CLIInterface (line 35) | class CLIInterface:
method __init__ (line 38) | def __init__(self):
method _load_segmentation_config (line 52) | def _load_segmentation_config(self):
method _save_segmentation_config (line 66) | def _save_segmentation_config(self):
method _init_tkinter (line 104) | def _init_tkinter(self):
method clear_screen (line 118) | def clear_screen(self):
method print_logo (line 122) | def print_logo(self):
method print_welcome_banner (line 141) | def print_welcome_banner(self):
method print_separator (line 160) | def print_separator(self, char="═", length=79, color=Colors.CYAN):
method print_status (line 164) | def print_status(self, message: str, status_type: str = "info"):
method create_menu (line 185) | def create_menu(self):
method get_user_input (line 229) | def get_user_input(self):
method upload_file_gui (line 234) | def upload_file_gui(self) -> Optional[str]:
method _get_manual_file_path (line 297) | def _get_manual_file_path(self) -> Optional[str]:
method get_url_input (line 366) | def get_url_input(self) -> str:
method get_chat_input (line 434) | def get_chat_input(self) -> str:
method show_progress_bar (line 556) | def show_progress_bar(self, message: str, duration: float = 2.0):
method show_spinner (line 575) | def show_spinner(self, message: str, duration: float = 1.0):
method display_processing_stages (line 598) | def display_processing_stages(
method print_results_header (line 658) | def print_results_header(self):
method print_error_box (line 667) | def print_error_box(self, title: str, error_msg: str):
method cleanup_cache (line 695) | def cleanup_cache(self):
method print_goodbye (line 707) | def print_goodbye(self):
method get_requirement_analysis_input (line 728) | def get_requirement_analysis_input(self) -> str:
method display_guiding_questions (line 843) | def display_guiding_questions(self, questions_json: str):
method get_question_answers (line 870) | def get_question_answers(self, questions_json: str) -> dict:
method display_requirement_summary (line 905) | def display_requirement_summary(self, summary: str):
method ask_continue (line 928) | def ask_continue(self) -> bool:
method add_to_history (line 935) | def add_to_history(self, input_source: str, result: dict):
method show_history (line 945) | def show_history(self):
method show_configuration_menu (line 964) | def show_configuration_menu(self):
FILE: cli/cli_launcher.py
function check_dependencies (line 14) | def check_dependencies():
function print_banner (line 83) | def print_banner():
function main (line 99) | def main():
FILE: cli/main_cli.py
function print_enhanced_banner (line 28) | def print_enhanced_banner():
function check_environment (line 51) | def check_environment():
function parse_arguments (line 90) | def parse_arguments():
function run_direct_processing (line 166) | async def run_direct_processing(app: CLIApp, input_source: str, input_ty...
function run_requirement_analysis (line 207) | async def run_requirement_analysis(app: CLIApp, initial_idea: str):
function main (line 244) | async def main():
FILE: cli/workflows/cli_workflow_adapter.py
class CLIWorkflowAdapter (line 23) | class CLIWorkflowAdapter:
method __init__ (line 34) | def __init__(self, cli_interface=None):
method initialize_mcp_app (line 46) | async def initialize_mcp_app(self) -> Dict[str, Any]:
method cleanup_mcp_app (line 86) | async def cleanup_mcp_app(self):
method create_cli_progress_callback (line 103) | def create_cli_progress_callback(self, enable_indexing: bool = True) -...
method execute_full_pipeline (line 161) | async def execute_full_pipeline(
method execute_requirement_analysis_workflow (line 233) | async def execute_requirement_analysis_workflow(
method execute_chat_pipeline (line 310) | async def execute_chat_pipeline(
method process_input_with_orchestration (line 387) | async def process_input_with_orchestration(
FILE: config/mcp_tool_definitions.py
class MCPToolDefinitions (line 18) | class MCPToolDefinitions:
method get_code_implementation_tools (line 22) | def get_code_implementation_tools() -> List[Dict[str, Any]]:
method _get_read_file_tool (line 38) | def _get_read_file_tool() -> Dict[str, Any]:
method _get_read_multiple_files_tool (line 64) | def _get_read_multiple_files_tool() -> Dict[str, Any]:
method _get_read_code_mem_tool (line 89) | def _get_read_code_mem_tool() -> Dict[str, Any]:
method _get_write_file_tool (line 108) | def _get_write_file_tool() -> Dict[str, Any]:
method _get_write_multiple_files_tool (line 140) | def _get_write_multiple_files_tool() -> Dict[str, Any]:
method _get_execute_python_tool (line 175) | def _get_execute_python_tool() -> Dict[str, Any]:
method _get_execute_bash_tool (line 195) | def _get_execute_bash_tool() -> Dict[str, Any]:
method _get_file_structure_tool (line 218) | def _get_file_structure_tool() -> Dict[str, Any]:
method _get_search_code_references_tool (line 241) | def _get_search_code_references_tool() -> Dict[str, Any]:
method _get_get_indexes_overview_tool (line 273) | def _get_get_indexes_overview_tool() -> Dict[str, Any]:
method _get_set_workspace_tool (line 291) | def _get_set_workspace_tool() -> Dict[str, Any]:
method get_available_tool_sets (line 327) | def get_available_tool_sets() -> Dict[str, str]:
method get_tool_set (line 340) | def get_tool_set(tool_set_name: str) -> List[Dict[str, Any]]:
method get_all_tools (line 352) | def get_all_tools() -> List[Dict[str, Any]]:
function get_mcp_tools (line 364) | def get_mcp_tools(tool_set: str = "code_implementation") -> List[Dict[st...
FILE: config/mcp_tool_definitions_index.py
class MCPToolDefinitions (line 18) | class MCPToolDefinitions:
method get_code_implementation_tools (line 22) | def get_code_implementation_tools() -> List[Dict[str, Any]]:
method get_code_evaluation_tools (line 43) | def get_code_evaluation_tools() -> List[Dict[str, Any]]:
method _get_read_file_tool (line 61) | def _get_read_file_tool() -> Dict[str, Any]:
method _get_read_multiple_files_tool (line 87) | def _get_read_multiple_files_tool() -> Dict[str, Any]:
method _get_read_code_mem_tool (line 112) | def _get_read_code_mem_tool() -> Dict[str, Any]:
method _get_write_file_tool (line 131) | def _get_write_file_tool() -> Dict[str, Any]:
method _get_write_multiple_files_tool (line 163) | def _get_write_multiple_files_tool() -> Dict[str, Any]:
method _get_execute_python_tool (line 198) | def _get_execute_python_tool() -> Dict[str, Any]:
method _get_execute_bash_tool (line 218) | def _get_execute_bash_tool() -> Dict[str, Any]:
method _get_file_structure_tool (line 241) | def _get_file_structure_tool() -> Dict[str, Any]:
method _get_search_code_references_tool (line 264) | def _get_search_code_references_tool() -> Dict[str, Any]:
method _get_search_code_tool (line 296) | def _get_search_code_tool() -> Dict[str, Any]:
method _get_operation_history_tool (line 328) | def _get_operation_history_tool() -> Dict[str, Any]:
method _get_get_indexes_overview_tool (line 346) | def _get_get_indexes_overview_tool() -> Dict[str, Any]:
method _get_set_workspace_tool (line 364) | def _get_set_workspace_tool() -> Dict[str, Any]:
method _get_analyze_repo_structure_tool (line 401) | def _get_analyze_repo_structure_tool() -> Dict[str, Any]:
method _get_detect_dependencies_tool (line 418) | def _get_detect_dependencies_tool() -> Dict[str, Any]:
method _get_assess_code_quality_tool (line 435) | def _get_assess_code_quality_tool() -> Dict[str, Any]:
method _get_evaluate_documentation_tool (line 452) | def _get_evaluate_documentation_tool() -> Dict[str, Any]:
method _get_check_reproduction_readiness_tool (line 473) | def _get_check_reproduction_readiness_tool() -> Dict[str, Any]:
method _get_generate_evaluation_summary_tool (line 494) | def _get_generate_evaluation_summary_tool() -> Dict[str, Any]:
method _get_detect_empty_files_tool (line 515) | def _get_detect_empty_files_tool() -> Dict[str, Any]:
method _get_detect_missing_files_tool (line 532) | def _get_detect_missing_files_tool() -> Dict[str, Any]:
method _get_generate_code_revision_report_tool (line 549) | def _get_generate_code_revision_report_tool() -> Dict[str, Any]:
method get_available_tool_sets (line 570) | def get_available_tool_sets() -> Dict[str, str]:
method get_tool_set (line 584) | def get_tool_set(tool_set_name: str) -> List[Dict[str, Any]]:
method get_all_tools (line 597) | def get_all_tools() -> List[Dict[str, Any]]:
function get_mcp_tools (line 609) | def get_mcp_tools(tool_set: str = "code_implementation") -> List[Dict[st...
FILE: deepcode.py
function get_platform (line 26) | def get_platform():
function check_dependencies (line 37) | def check_dependencies():
function is_port_in_use (line 126) | def is_port_in_use(port: int) -> bool:
function kill_process_on_port (line 132) | def kill_process_on_port(port: int):
function cleanup_ports (line 172) | def cleanup_ports():
function install_backend_deps (line 181) | def install_backend_deps():
function install_frontend_deps (line 202) | def install_frontend_deps(frontend_dir: Path):
function start_backend (line 218) | def start_backend(backend_dir: Path):
function start_frontend (line 260) | def start_frontend(frontend_dir: Path):
function cleanup_processes (line 293) | def cleanup_processes():
function cleanup_cache (line 339) | def cleanup_cache():
function print_banner (line 352) | def print_banner():
function launch_classic_ui (line 369) | def launch_classic_ui():
function _check_docker_prerequisites (line 414) | def _check_docker_prerequisites():
function launch_docker (line 482) | def launch_docker():
function launch_docker_cli (line 523) | def launch_docker_cli():
function launch_paper_test (line 553) | def launch_paper_test(paper_name: str, fast_mode: bool = False):
function main (line 586) | def main():
FILE: nanobot/bridge/src/index.ts
constant PORT (line 26) | const PORT = parseInt(process.env.BRIDGE_PORT || '3001', 10);
constant AUTH_DIR (line 27) | const AUTH_DIR = process.env.AUTH_DIR || join(homedir(), '.nanobot', 'wh...
FILE: nanobot/bridge/src/server.ts
type SendCommand (line 8) | interface SendCommand {
type BridgeMessage (line 14) | interface BridgeMessage {
class BridgeServer (line 19) | class BridgeServer {
method constructor (line 24) | constructor(private port: number, private authDir: string) {}
method start (line 26) | async start(): Promise<void> {
method handleCommand (line 70) | private async handleCommand(cmd: SendCommand): Promise<void> {
method broadcast (line 76) | private broadcast(msg: BridgeMessage): void {
method stop (line 85) | async stop(): Promise<void> {
FILE: nanobot/bridge/src/whatsapp.ts
constant VERSION (line 18) | const VERSION = '0.1.0';
type InboundMessage (line 20) | interface InboundMessage {
type WhatsAppClientOptions (line 29) | interface WhatsAppClientOptions {
class WhatsAppClient (line 36) | class WhatsAppClient {
method constructor (line 41) | constructor(options: WhatsAppClientOptions) {
method connect (line 45) | async connect(): Promise<void> {
method extractMessageContent (line 136) | private extractMessageContent(msg: any): string | null {
method sendMessage (line 173) | async sendMessage(to: string, text: string): Promise<void> {
method disconnect (line 181) | async disconnect(): Promise<void> {
FILE: nanobot/nanobot/agent/context.py
class ContextBuilder (line 13) | class ContextBuilder:
method __init__ (line 23) | def __init__(self, workspace: Path):
method build_system_prompt (line 28) | def build_system_prompt(self, skill_names: list[str] | None = None) ->...
method _get_identity (line 73) | def _get_identity(self) -> str:
method _load_bootstrap_files (line 110) | def _load_bootstrap_files(self) -> str:
method build_messages (line 122) | def build_messages(
method _build_user_content (line 162) | def _build_user_content(self, text: str, media: list[str] | None) -> s...
method add_tool_result (line 180) | def add_tool_result(
method add_assistant_message (line 200) | def add_assistant_message(
FILE: nanobot/nanobot/agent/loop.py
class AgentLoop (line 32) | class AgentLoop:
method __init__ (line 44) | def __init__(
method _register_default_tools (line 85) | def _register_default_tools(self) -> None:
method run (line 128) | async def run(self) -> None:
method stop (line 156) | def stop(self) -> None:
method _process_message (line 161) | async def _process_message(self, msg: InboundMessage) -> OutboundMessa...
method _process_system_message (line 270) | async def _process_system_message(self, msg: InboundMessage) -> Outbou...
method process_direct (line 364) | async def process_direct(
FILE: nanobot/nanobot/agent/memory.py
class MemoryStore (line 9) | class MemoryStore:
method __init__ (line 16) | def __init__(self, workspace: Path):
method get_today_file (line 21) | def get_today_file(self) -> Path:
method read_today (line 25) | def read_today(self) -> str:
method append_today (line 32) | def append_today(self, content: str) -> None:
method read_long_term (line 46) | def read_long_term(self) -> str:
method write_long_term (line 52) | def write_long_term(self, content: str) -> None:
method get_recent_memories (line 56) | def get_recent_memories(self, days: int = 7) -> str:
method list_memory_files (line 82) | def list_memory_files(self) -> list[Path]:
method get_memory_context (line 90) | def get_memory_context(self) -> str:
FILE: nanobot/nanobot/agent/skills.py
class SkillsLoader (line 13) | class SkillsLoader:
method __init__ (line 21) | def __init__(self, workspace: Path, builtin_skills_dir: Path | None = ...
method list_skills (line 26) | def list_skills(self, filter_unavailable: bool = True) -> list[dict[st...
method load_skill (line 63) | def load_skill(self, name: str) -> str | None:
method load_skills_for_context (line 86) | def load_skills_for_context(self, skill_names: list[str]) -> str:
method build_skills_summary (line 105) | def build_skills_summary(self) -> str:
method _get_missing_requirements (line 146) | def _get_missing_requirements(self, skill_meta: dict) -> str:
method _get_skill_description (line 158) | def _get_skill_description(self, name: str) -> str:
method _strip_frontmatter (line 165) | def _strip_frontmatter(self, content: str) -> str:
method _parse_nanobot_metadata (line 173) | def _parse_nanobot_metadata(self, raw: str) -> dict:
method _check_requirements (line 181) | def _check_requirements(self, skill_meta: dict) -> bool:
method _get_skill_meta (line 192) | def _get_skill_meta(self, name: str) -> dict:
method get_always_skills (line 197) | def get_always_skills(self) -> list[str]:
method get_skill_metadata (line 207) | def get_skill_metadata(self, name: str) -> dict | None:
FILE: nanobot/nanobot/agent/subagent.py
class SubagentManager (line 25) | class SubagentManager:
method __init__ (line 34) | def __init__(
method spawn (line 55) | async def spawn(
method _run_subagent (line 92) | async def _run_subagent(
method _announce_result (line 191) | async def _announce_result(
method _build_subagent_prompt (line 225) | def _build_subagent_prompt(self, task: str) -> str:
method get_running_count (line 256) | def get_running_count(self) -> int:
FILE: nanobot/nanobot/agent/tools/base.py
class Tool (line 7) | class Tool(ABC):
method name (line 26) | def name(self) -> str:
method description (line 32) | def description(self) -> str:
method parameters (line 38) | def parameters(self) -> dict[str, Any]:
method execute (line 43) | async def execute(self, **kwargs: Any) -> str:
method validate_params (line 55) | def validate_params(self, params: dict[str, Any]) -> list[str]:
method _validate (line 62) | def _validate(self, val: Any, schema: dict[str, Any], path: str) -> li...
method to_schema (line 95) | def to_schema(self) -> dict[str, Any]:
FILE: nanobot/nanobot/agent/tools/cron.py
class CronTool (line 10) | class CronTool(Tool):
method __init__ (line 13) | def __init__(self, cron_service: CronService):
method set_context (line 18) | def set_context(self, channel: str, chat_id: str) -> None:
method name (line 24) | def name(self) -> str:
method description (line 28) | def description(self) -> str:
method parameters (line 32) | def parameters(self) -> dict[str, Any]:
method execute (line 55) | async def execute(
method _add_job (line 72) | def _add_job(self, message: str, every_seconds: int | None, cron_expr:...
method _list_jobs (line 96) | def _list_jobs(self) -> str:
method _remove_job (line 103) | def _remove_job(self, job_id: str | None) -> str:
FILE: nanobot/nanobot/agent/tools/deepcode.py
function _get_deepcode_url (line 19) | def _get_deepcode_url() -> str:
class DeepCodePaper2CodeTool (line 24) | class DeepCodePaper2CodeTool(Tool):
method __init__ (line 27) | def __init__(self, api_url: str | None = None):
method name (line 31) | def name(self) -> str:
method description (line 35) | def description(self) -> str:
method parameters (line 45) | def parameters(self) -> dict[str, Any]:
method execute (line 66) | async def execute(
class DeepCodeChat2CodeTool (line 105) | class DeepCodeChat2CodeTool(Tool):
method __init__ (line 108) | def __init__(self, api_url: str | None = None):
method name (line 112) | def name(self) -> str:
method description (line 116) | def description(self) -> str:
method parameters (line 125) | def parameters(self) -> dict[str, Any]:
method execute (line 141) | async def execute(
class DeepCodeStatusTool (line 177) | class DeepCodeStatusTool(Tool):
method __init__ (line 180) | def __init__(self, api_url: str | None = None):
method name (line 184) | def name(self) -> str:
method description (line 188) | def description(self) -> str:
method parameters (line 196) | def parameters(self) -> dict[str, Any]:
method execute (line 208) | async def execute(self, task_id: str, **kwargs: Any) -> str:
class DeepCodeListTasksTool (line 256) | class DeepCodeListTasksTool(Tool):
method __init__ (line 259) | def __init__(self, api_url: str | None = None):
method name (line 263) | def name(self) -> str:
method description (line 267) | def description(self) -> str:
method parameters (line 274) | def parameters(self) -> dict[str, Any]:
method execute (line 287) | async def execute(self, limit: int = 10, **kwargs: Any) -> str:
class DeepCodeCancelTool (line 343) | class DeepCodeCancelTool(Tool):
method __init__ (line 346) | def __init__(self, api_url: str | None = None):
method name (line 350) | def name(self) -> str:
method description (line 354) | def description(self) -> str:
method parameters (line 358) | def parameters(self) -> dict[str, Any]:
method execute (line 370) | async def execute(self, task_id: str, **kwargs: Any) -> str:
class DeepCodeRespondTool (line 388) | class DeepCodeRespondTool(Tool):
method __init__ (line 391) | def __init__(self, api_url: str | None = None):
method name (line 395) | def name(self) -> str:
method description (line 399) | def description(self) -> str:
method parameters (line 408) | def parameters(self) -> dict[str, Any]:
method execute (line 433) | async def execute(
function create_all_tools (line 477) | def create_all_tools(api_url: str | None = None) -> list[Tool]:
FILE: nanobot/nanobot/agent/tools/filesystem.py
function _resolve_path (line 9) | def _resolve_path(path: str, allowed_dir: Path | None = None) -> Path:
class ReadFileTool (line 17) | class ReadFileTool(Tool):
method __init__ (line 20) | def __init__(self, allowed_dir: Path | None = None):
method name (line 24) | def name(self) -> str:
method description (line 28) | def description(self) -> str:
method parameters (line 32) | def parameters(self) -> dict[str, Any]:
method execute (line 39) | async def execute(self, path: str, **kwargs: Any) -> str:
class WriteFileTool (line 55) | class WriteFileTool(Tool):
method __init__ (line 58) | def __init__(self, allowed_dir: Path | None = None):
method name (line 62) | def name(self) -> str:
method description (line 66) | def description(self) -> str:
method parameters (line 70) | def parameters(self) -> dict[str, Any]:
method execute (line 80) | async def execute(self, path: str, content: str, **kwargs: Any) -> str:
class EditFileTool (line 92) | class EditFileTool(Tool):
method __init__ (line 95) | def __init__(self, allowed_dir: Path | None = None):
method name (line 99) | def name(self) -> str:
method description (line 103) | def description(self) -> str:
method parameters (line 107) | def parameters(self) -> dict[str, Any]:
method execute (line 118) | async def execute(self, path: str, old_text: str, new_text: str, **kwa...
class ListDirTool (line 144) | class ListDirTool(Tool):
method __init__ (line 147) | def __init__(self, allowed_dir: Path | None = None):
method name (line 151) | def name(self) -> str:
method description (line 155) | def description(self) -> str:
method parameters (line 159) | def parameters(self) -> dict[str, Any]:
method execute (line 166) | async def execute(self, path: str, **kwargs: Any) -> str:
FILE: nanobot/nanobot/agent/tools/message.py
class MessageTool (line 9) | class MessageTool(Tool):
method __init__ (line 12) | def __init__(
method set_context (line 22) | def set_context(self, channel: str, chat_id: str) -> None:
method set_send_callback (line 27) | def set_send_callback(self, callback: Callable[[OutboundMessage], Awai...
method name (line 32) | def name(self) -> str:
method description (line 36) | def description(self) -> str:
method parameters (line 40) | def parameters(self) -> dict[str, Any]:
method execute (line 54) | async def execute(
FILE: nanobot/nanobot/agent/tools/registry.py
class ToolRegistry (line 8) | class ToolRegistry:
method __init__ (line 15) | def __init__(self):
method register (line 18) | def register(self, tool: Tool) -> None:
method unregister (line 22) | def unregister(self, name: str) -> None:
method get (line 26) | def get(self, name: str) -> Tool | None:
method has (line 30) | def has(self, name: str) -> bool:
method get_definitions (line 34) | def get_definitions(self) -> list[dict[str, Any]]:
method execute (line 38) | async def execute(self, name: str, params: dict[str, Any]) -> str:
method tool_names (line 65) | def tool_names(self) -> list[str]:
method __len__ (line 69) | def __len__(self) -> int:
method __contains__ (line 72) | def __contains__(self, name: str) -> bool:
FILE: nanobot/nanobot/agent/tools/shell.py
class ExecTool (line 12) | class ExecTool(Tool):
method __init__ (line 15) | def __init__(
method name (line 39) | def name(self) -> str:
method description (line 43) | def description(self) -> str:
method parameters (line 47) | def parameters(self) -> dict[str, Any]:
method execute (line 60) | async def execute(self, command: str, working_dir: str | None = None, ...
method _guard_command (line 105) | def _guard_command(self, command: str, cwd: str) -> str | None:
FILE: nanobot/nanobot/agent/tools/spawn.py
class SpawnTool (line 11) | class SpawnTool(Tool):
method __init__ (line 19) | def __init__(self, manager: "SubagentManager"):
method set_context (line 24) | def set_context(self, channel: str, chat_id: str) -> None:
method name (line 30) | def name(self) -> str:
method description (line 34) | def description(self) -> str:
method parameters (line 42) | def parameters(self) -> dict[str, Any]:
method execute (line 58) | async def execute(self, task: str, label: str | None = None, **kwargs:...
FILE: nanobot/nanobot/agent/tools/web.py
function _strip_tags (line 19) | def _strip_tags(text: str) -> str:
function _normalize (line 27) | def _normalize(text: str) -> str:
function _validate_url (line 33) | def _validate_url(url: str) -> tuple[bool, str]:
class WebSearchTool (line 46) | class WebSearchTool(Tool):
method __init__ (line 65) | def __init__(self, api_key: str | None = None, max_results: int = 5):
method execute (line 69) | async def execute(self, query: str, count: int | None = None, **kwargs...
class WebFetchTool (line 98) | class WebFetchTool(Tool):
method __init__ (line 113) | def __init__(self, max_chars: int = 50000):
method execute (line 116) | async def execute(
method _to_markdown (line 181) | def _to_markdown(self, html: str) -> str:
FILE: nanobot/nanobot/bus/events.py
class InboundMessage (line 9) | class InboundMessage:
method session_key (line 21) | def session_key(self) -> str:
class OutboundMessage (line 27) | class OutboundMessage:
FILE: nanobot/nanobot/bus/queue.py
class MessageBus (line 11) | class MessageBus:
method __init__ (line 19) | def __init__(self):
method publish_inbound (line 27) | async def publish_inbound(self, msg: InboundMessage) -> None:
method consume_inbound (line 31) | async def consume_inbound(self) -> InboundMessage:
method publish_outbound (line 35) | async def publish_outbound(self, msg: OutboundMessage) -> None:
method consume_outbound (line 39) | async def consume_outbound(self) -> OutboundMessage:
method subscribe_outbound (line 43) | def subscribe_outbound(
method dispatch_outbound (line 51) | async def dispatch_outbound(self) -> None:
method stop (line 69) | def stop(self) -> None:
method inbound_size (line 74) | def inbound_size(self) -> int:
method outbound_size (line 79) | def outbound_size(self) -> int:
FILE: nanobot/nanobot/channels/base.py
class BaseChannel (line 12) | class BaseChannel(ABC):
method __init__ (line 22) | def __init__(self, config: Any, bus: MessageBus):
method start (line 35) | async def start(self) -> None:
method stop (line 47) | async def stop(self) -> None:
method send (line 52) | async def send(self, msg: OutboundMessage) -> None:
method is_allowed (line 61) | def is_allowed(self, sender_id: str) -> bool:
method _handle_message (line 86) | async def _handle_message(
method is_running (line 125) | def is_running(self) -> bool:
FILE: nanobot/nanobot/channels/dingtalk.py
class NanobotDingTalkHandler (line 36) | class NanobotDingTalkHandler(CallbackHandler):
method __init__ (line 42) | def __init__(self, channel: "DingTalkChannel"):
method process (line 46) | async def process(self, message: CallbackMessage):
class DingTalkChannel (line 84) | class DingTalkChannel(BaseChannel):
method __init__ (line 97) | def __init__(self, config: DingTalkConfig, bus: MessageBus):
method start (line 110) | async def start(self) -> None:
method stop (line 142) | async def stop(self) -> None:
method _get_access_token (line 154) | async def _get_access_token(self) -> str | None:
method send (line 181) | async def send(self, msg: OutboundMessage) -> None:
method _on_message (line 218) | async def _on_message(self, content: str, sender_id: str, sender_name:...
FILE: nanobot/nanobot/channels/discord.py
class DiscordChannel (line 21) | class DiscordChannel(BaseChannel):
method __init__ (line 26) | def __init__(self, config: DiscordConfig, bus: MessageBus):
method start (line 35) | async def start(self) -> None:
method stop (line 58) | async def stop(self) -> None:
method send (line 74) | async def send(self, msg: OutboundMessage) -> None:
method _gateway_loop (line 109) | async def _gateway_loop(self) -> None:
method _identify (line 147) | async def _identify(self) -> None:
method _start_heartbeat (line 166) | async def _start_heartbeat(self, interval_s: float) -> None:
method _handle_message_create (line 183) | async def _handle_message_create(self, payload: dict[str, Any]) -> None:
method _start_typing (line 242) | async def _start_typing(self, channel_id: str) -> None:
method _stop_typing (line 258) | async def _stop_typing(self, channel_id: str) -> None:
FILE: nanobot/nanobot/channels/email.py
class EmailChannel (line 25) | class EmailChannel(BaseChannel):
method __init__ (line 53) | def __init__(self, config: EmailConfig, bus: MessageBus):
method start (line 61) | async def start(self) -> None:
method stop (line 101) | async def stop(self) -> None:
method send (line 105) | async def send(self, msg: OutboundMessage) -> None:
method _validate_config (line 151) | def _validate_config(self) -> bool:
method _smtp_send (line 171) | def _smtp_send(self, msg: EmailMessage) -> None:
method _fetch_new_messages (line 189) | def _fetch_new_messages(self) -> list[dict[str, Any]]:
method fetch_messages_between_dates (line 198) | def fetch_messages_between_dates(
method _fetch_messages (line 224) | def _fetch_messages(
method _format_imap_date (line 322) | def _format_imap_date(cls, value: date) -> str:
method _extract_message_bytes (line 328) | def _extract_message_bytes(fetched: list[Any]) -> bytes | None:
method _extract_uid (line 339) | def _extract_uid(fetched: list[Any]) -> str:
method _decode_header_value (line 349) | def _decode_header_value(value: str) -> str:
method _extract_text_body (line 358) | def _extract_text_body(cls, msg: Any) -> str:
method _html_to_text (line 398) | def _html_to_text(raw_html: str) -> str:
method _reply_subject (line 404) | def _reply_subject(self, base_subject: str) -> str:
FILE: nanobot/nanobot/channels/feishu.py
class FeishuChannel (line 43) | class FeishuChannel(BaseChannel):
method __init__ (line 57) | def __init__(self, config: FeishuConfig, bus: MessageBus):
method start (line 66) | async def start(self) -> None:
method stop (line 123) | async def stop(self) -> None:
method _add_reaction_sync (line 133) | def _add_reaction_sync(self, message_id: str, emoji_type: str) -> None:
method _add_reaction (line 156) | async def _add_reaction(self, message_id: str, emoji_type: str = "THUM...
method _split_row (line 175) | def _split_row(row: str) -> list[str]:
method _parse_md_table (line 180) | def _parse_md_table(table_text: str) -> dict | None:
method _build_card_elements (line 200) | def _build_card_elements(self, content: str) -> list[dict]:
method send (line 216) | async def send(self, msg: OutboundMessage) -> None:
method _on_message_sync (line 264) | def _on_message_sync(self, data: "P2ImMessageReceiveV1") -> None:
method _on_message (line 272) | async def _on_message(self, data: "P2ImMessageReceiveV1") -> None:
FILE: nanobot/nanobot/channels/manager.py
class ChannelManager (line 18) | class ChannelManager:
method __init__ (line 28) | def __init__(
method _init_channels (line 39) | def _init_channels(self) -> None:
method _start_channel (line 130) | async def _start_channel(self, name: str, channel: BaseChannel) -> None:
method start_all (line 137) | async def start_all(self) -> None:
method stop_all (line 155) | async def stop_all(self) -> None:
method _dispatch_outbound (line 175) | async def _dispatch_outbound(self) -> None:
method get_channel (line 197) | def get_channel(self, name: str) -> BaseChannel | None:
method get_status (line 201) | def get_status(self) -> dict[str, Any]:
method enabled_channels (line 209) | def enabled_channels(self) -> list[str]:
FILE: nanobot/nanobot/channels/qq.py
function _make_bot_class (line 28) | def _make_bot_class(channel: "QQChannel") -> "type[botpy.Client]":
class QQChannel (line 48) | class QQChannel(BaseChannel):
method __init__ (line 53) | def __init__(self, config: QQConfig, bus: MessageBus):
method start (line 60) | async def start(self) -> None:
method _run_bot (line 77) | async def _run_bot(self) -> None:
method stop (line 85) | async def stop(self) -> None:
method send (line 96) | async def send(self, msg: OutboundMessage) -> None:
method _on_message (line 110) | async def _on_message(self, data: "C2CMessage") -> None:
FILE: nanobot/nanobot/channels/slack.py
class SlackChannel (line 18) | class SlackChannel(BaseChannel):
method __init__ (line 23) | def __init__(self, config: SlackConfig, bus: MessageBus):
method start (line 30) | async def start(self) -> None:
method stop (line 63) | async def stop(self) -> None:
method send (line 73) | async def send(self, msg: OutboundMessage) -> None:
method _on_socket_request (line 92) | async def _on_socket_request(
method _is_allowed (line 175) | def _is_allowed(self, sender_id: str, chat_id: str, channel_type: str)...
method _should_respond_in_channel (line 188) | def _should_respond_in_channel(self, event_type: str, text: str, chat_...
method _strip_bot_mention (line 199) | def _strip_bot_mention(self, text: str) -> str:
FILE: nanobot/nanobot/channels/telegram.py
function _markdown_to_telegram_html (line 22) | def _markdown_to_telegram_html(text: str) -> str:
class TelegramChannel (line 87) | class TelegramChannel(BaseChannel):
method __init__ (line 103) | def __init__(
method start (line 118) | async def start(self) -> None:
method stop (line 178) | async def stop(self) -> None:
method send (line 193) | async def send(self, msg: OutboundMessage) -> None:
method _on_start (line 218) | async def _on_start(self, update: Update, context: ContextTypes.DEFAUL...
method _on_reset (line 230) | async def _on_reset(self, update: Update, context: ContextTypes.DEFAUL...
method _on_help (line 251) | async def _on_help(self, update: Update, context: ContextTypes.DEFAULT...
method _on_message (line 265) | async def _on_message(self, update: Update, context: ContextTypes.DEFA...
method _start_typing (line 369) | def _start_typing(self, chat_id: str) -> None:
method _stop_typing (line 375) | def _stop_typing(self, chat_id: str) -> None:
method _typing_loop (line 381) | async def _typing_loop(self, chat_id: str) -> None:
method _get_extension (line 392) | def _get_extension(self, media_type: str, mime_type: str | None) -> str:
FILE: nanobot/nanobot/channels/whatsapp.py
class WhatsAppChannel (line 14) | class WhatsAppChannel(BaseChannel):
method __init__ (line 24) | def __init__(self, config: WhatsAppConfig, bus: MessageBus):
method start (line 30) | async def start(self) -> None:
method stop (line 65) | async def stop(self) -> None:
method send (line 74) | async def send(self, msg: OutboundMessage) -> None:
method _handle_bridge_message (line 86) | async def _handle_bridge_message(self, raw: str) -> None:
FILE: nanobot/nanobot/cli/commands.py
function _flush_pending_tty_input (line 40) | def _flush_pending_tty_input() -> None:
function _save_history (line 68) | def _save_history() -> None:
function _restore_terminal (line 77) | def _restore_terminal() -> None:
function _enable_line_editing (line 89) | def _enable_line_editing() -> None:
function _prompt_text (line 132) | def _prompt_text() -> str:
function _print_agent_response (line 142) | def _print_agent_response(response: str, render_markdown: bool) -> None:
function _is_exit_command (line 159) | def _is_exit_command(command: str) -> bool:
function _read_interactive_input_async (line 164) | async def _read_interactive_input_async() -> str:
function version_callback (line 172) | def version_callback(value: bool):
function main (line 179) | def main(
function onboard (line 192) | def onboard():
function _create_workspace_templates (line 227) | def _create_workspace_templates(workspace: Path):
function _make_provider (line 299) | def _make_provider(config):
function gateway (line 324) | def gateway(
function agent (line 441) | def agent(
function channels_status (line 552) | def channels_status():
function _get_bridge_dir (line 583) | def _get_bridge_dir() -> Path:
function channels_login (line 642) | def channels_login():
function cron_list (line 668) | def cron_list(
function cron_add (line 718) | def cron_add(
function cron_remove (line 765) | def cron_remove(
function cron_enable (line 782) | def cron_enable(
function cron_run (line 802) | def cron_run(
function status (line 828) | def status():
FILE: nanobot/nanobot/config/loader.py
function get_config_path (line 10) | def get_config_path() -> Path:
function get_data_dir (line 15) | def get_data_dir() -> Path:
function load_config (line 22) | def load_config(config_path: Path | None = None) -> Config:
function save_config (line 47) | def save_config(config: Config, config_path: Path | None = None) -> None:
function _migrate_config (line 66) | def _migrate_config(data: dict) -> dict:
function convert_keys (line 76) | def convert_keys(data: Any) -> Any:
function convert_to_camel (line 85) | def convert_to_camel(data: Any) -> Any:
function camel_to_snake (line 94) | def camel_to_snake(name: str) -> str:
function snake_to_camel (line 104) | def snake_to_camel(name: str) -> str:
FILE: nanobot/nanobot/config/schema.py
class WhatsAppConfig (line 9) | class WhatsAppConfig(BaseModel):
class TelegramConfig (line 17) | class TelegramConfig(BaseModel):
class FeishuConfig (line 28) | class FeishuConfig(BaseModel):
class DingTalkConfig (line 39) | class DingTalkConfig(BaseModel):
class DiscordConfig (line 48) | class DiscordConfig(BaseModel):
class EmailConfig (line 58) | class EmailConfig(BaseModel):
class SlackDMConfig (line 92) | class SlackDMConfig(BaseModel):
class SlackConfig (line 100) | class SlackConfig(BaseModel):
class QQConfig (line 114) | class QQConfig(BaseModel):
class ChannelsConfig (line 125) | class ChannelsConfig(BaseModel):
class AgentDefaults (line 138) | class AgentDefaults(BaseModel):
class AgentsConfig (line 148) | class AgentsConfig(BaseModel):
class ProviderConfig (line 154) | class ProviderConfig(BaseModel):
class ProvidersConfig (line 162) | class ProvidersConfig(BaseModel):
class GatewayConfig (line 178) | class GatewayConfig(BaseModel):
class WebSearchConfig (line 185) | class WebSearchConfig(BaseModel):
class WebToolsConfig (line 192) | class WebToolsConfig(BaseModel):
class ExecToolConfig (line 198) | class ExecToolConfig(BaseModel):
class ToolsConfig (line 204) | class ToolsConfig(BaseModel):
class Config (line 212) | class Config(BaseSettings):
method workspace_path (line 222) | def workspace_path(self) -> Path:
method _match_provider (line 226) | def _match_provider(
method get_provider (line 247) | def get_provider(self, model: str | None = None) -> ProviderConfig | N...
method get_provider_name (line 252) | def get_provider_name(self, model: str | None = None) -> str | None:
method get_api_key (line 257) | def get_api_key(self, model: str | None = None) -> str | None:
method get_api_base (line 262) | def get_api_base(self, model: str | None = None) -> str | None:
class Config (line 278) | class Config:
FILE: nanobot/nanobot/cron/service.py
function _now_ms (line 15) | def _now_ms() -> int:
function _compute_next_run (line 19) | def _compute_next_run(schedule: CronSchedule, now_ms: int) -> int | None:
class CronService (line 43) | class CronService:
method __init__ (line 46) | def __init__(
method _load_store (line 57) | def _load_store(self) -> CronStore:
method _save_store (line 106) | def _save_store(self) -> None:
method start (line 150) | async def start(self) -> None:
method stop (line 161) | def stop(self) -> None:
method _recompute_next_runs (line 168) | def _recompute_next_runs(self) -> None:
method _get_next_wake_ms (line 177) | def _get_next_wake_ms(self) -> int | None:
method _arm_timer (line 186) | def _arm_timer(self) -> None:
method _on_timer (line 205) | async def _on_timer(self) -> None:
method _execute_job (line 223) | async def _execute_job(self, job: CronJob) -> None:
method list_jobs (line 257) | def list_jobs(self, include_disabled: bool = False) -> list[CronJob]:
method add_job (line 263) | def add_job(
method remove_job (line 302) | def remove_job(self, job_id: str) -> bool:
method enable_job (line 316) | def enable_job(self, job_id: str, enabled: bool = True) -> CronJob | N...
method run_job (line 332) | async def run_job(self, job_id: str, force: bool = False) -> bool:
method status (line 345) | def status(self) -> dict:
FILE: nanobot/nanobot/cron/types.py
class CronSchedule (line 8) | class CronSchedule:
class CronPayload (line 23) | class CronPayload:
class CronJobState (line 35) | class CronJobState:
class CronJob (line 45) | class CronJob:
class CronStore (line 60) | class CronStore:
FILE: nanobot/nanobot/heartbeat/service.py
function _is_heartbeat_empty (line 21) | def _is_heartbeat_empty(content: str | None) -> bool:
class HeartbeatService (line 38) | class HeartbeatService:
method __init__ (line 46) | def __init__(
method heartbeat_file (line 61) | def heartbeat_file(self) -> Path:
method _read_heartbeat_file (line 64) | def _read_heartbeat_file(self) -> str | None:
method start (line 73) | async def start(self) -> None:
method stop (line 83) | def stop(self) -> None:
method _run_loop (line 90) | async def _run_loop(self) -> None:
method _tick (line 102) | async def _tick(self) -> None:
method trigger_now (line 126) | async def trigger_now(self) -> str | None:
FILE: nanobot/nanobot/providers/base.py
class ToolCallRequest (line 9) | class ToolCallRequest:
class LLMResponse (line 18) | class LLMResponse:
method has_tool_calls (line 28) | def has_tool_calls(self) -> bool:
class LLMProvider (line 33) | class LLMProvider(ABC):
method __init__ (line 41) | def __init__(self, api_key: str | None = None, api_base: str | None = ...
method chat (line 46) | async def chat(
method get_default_model (line 70) | def get_default_model(self) -> str:
FILE: nanobot/nanobot/providers/litellm_provider.py
class LiteLLMProvider (line 14) | class LiteLLMProvider(LLMProvider):
method __init__ (line 23) | def __init__(
method _setup_env (line 52) | def _setup_env(self, api_key: str, api_base: str | None, model: str) -...
method _resolve_model (line 73) | def _resolve_model(self, model: str) -> str:
method _apply_model_overrides (line 92) | def _apply_model_overrides(self, model: str, kwargs: dict[str, Any]) -...
method chat (line 102) | async def chat(
method _parse_response (line 157) | def _parse_response(self, response: Any) -> LLMResponse:
method get_default_model (line 199) | def get_default_model(self) -> str:
FILE: nanobot/nanobot/providers/registry.py
class ProviderSpec (line 20) | class ProviderSpec:
method label (line 55) | def label(self) -> str:
function find_by_model (line 272) | def find_by_model(model: str) -> ProviderSpec | None:
function find_gateway (line 284) | def find_gateway(
function find_by_name (line 315) | def find_by_name(name: str) -> ProviderSpec | None:
FILE: nanobot/nanobot/providers/transcription.py
class GroqTranscriptionProvider (line 10) | class GroqTranscriptionProvider:
method __init__ (line 17) | def __init__(self, api_key: str | None = None):
method transcribe (line 21) | async def transcribe(self, file_path: str | Path) -> str:
FILE: nanobot/nanobot/session/manager.py
class Session (line 15) | class Session:
method add_message (line 28) | def add_message(self, role: str, content: str, **kwargs: Any) -> None:
method get_history (line 34) | def get_history(self, max_messages: int = 50) -> list[dict[str, Any]]:
method clear (line 52) | def clear(self) -> None:
class SessionManager (line 58) | class SessionManager:
method __init__ (line 65) | def __init__(self, workspace: Path):
method _get_session_path (line 70) | def _get_session_path(self, key: str) -> Path:
method get_or_create (line 75) | def get_or_create(self, key: str) -> Session:
method _load (line 97) | def _load(self, key: str) -> Session | None:
method save (line 137) | def save(self, session: Session) -> None:
method delete (line 157) | def delete(self, key: str) -> bool:
method list_sessions (line 177) | def list_sessions(self) -> list[dict[str, Any]]:
FILE: nanobot/nanobot/utils/helpers.py
function ensure_dir (line 7) | def ensure_dir(path: Path) -> Path:
function get_data_path (line 13) | def get_data_path() -> Path:
function get_workspace_path (line 18) | def get_workspace_path(workspace: str | None = None) -> Path:
function get_sessions_path (line 35) | def get_sessions_path() -> Path:
function get_memory_path (line 40) | def get_memory_path(workspace: Path | None = None) -> Path:
function get_skills_path (line 46) | def get_skills_path(workspace: Path | None = None) -> Path:
function today_date (line 52) | def today_date() -> str:
function timestamp (line 57) | def timestamp() -> str:
function truncate_string (line 62) | def truncate_string(s: str, max_len: int = 100, suffix: str = "...") -> ...
function safe_filename (line 69) | def safe_filename(name: str) -> str:
function parse_session_key (line 78) | def parse_session_key(key: str) -> tuple[str, str]:
FILE: new_ui/backend/api/routes/config.py
function get_settings (line 25) | async def get_settings():
function get_llm_providers (line 40) | async def get_llm_providers():
function set_llm_provider (line 62) | async def set_llm_provider(request: LLMProviderUpdateRequest):
FILE: new_ui/backend/api/routes/files.py
function upload_file (line 23) | async def upload_file(file: UploadFile = File(...)):
function download_file (line 85) | async def download_file(file_id: str):
function delete_file (line 105) | async def delete_file(file_id: str):
function get_file_info (line 130) | async def get_file_info(file_id: str):
FILE: new_ui/backend/api/routes/requirements.py
function generate_questions (line 21) | async def generate_questions(request: GenerateQuestionsRequest):
function summarize_requirements (line 38) | async def summarize_requirements(request: SummarizeRequirementsRequest):
function modify_requirements (line 58) | async def modify_requirements(request: ModifyRequirementsRequest):
FILE: new_ui/backend/api/routes/workflows.py
function start_paper_to_code (line 21) | async def start_paper_to_code(
function start_chat_planning (line 48) | async def start_chat_planning(
function get_workflow_status (line 74) | async def get_workflow_status(task_id: str):
function cancel_workflow (line 100) | async def cancel_workflow(task_id: str):
function respond_to_interaction (line 114) | async def respond_to_interaction(task_id: str, request: InteractionRespo...
function get_pending_interaction (line 159) | async def get_pending_interaction(task_id: str):
function get_active_tasks (line 186) | async def get_active_tasks():
function get_recent_tasks (line 207) | async def get_recent_tasks(limit: int = 10):
FILE: new_ui/backend/api/websockets/code_stream_ws.py
function code_stream_websocket (line 17) | async def code_stream_websocket(websocket: WebSocket, task_id: str):
FILE: new_ui/backend/api/websockets/logs_ws.py
function logs_websocket (line 18) | async def logs_websocket(websocket: WebSocket, session_id: str):
FILE: new_ui/backend/api/websockets/workflow_ws.py
class ConnectionManager (line 16) | class ConnectionManager:
method __init__ (line 19) | def __init__(self):
method connect (line 22) | async def connect(self, websocket: WebSocket, task_id: str):
method disconnect (line 28) | def disconnect(self, websocket: WebSocket, task_id: str):
method broadcast (line 35) | async def broadcast(self, task_id: str, message: dict):
function workflow_websocket (line 48) | async def workflow_websocket(websocket: WebSocket, task_id: str):
FILE: new_ui/backend/main.py
function lifespan (line 54) | async def lifespan(app: FastAPI):
function health_check (line 122) | async def health_check():
function serve_spa (line 129) | async def serve_spa(request: Request, full_path: str):
function root (line 140) | async def root():
function health_check_dev (line 150) | async def health_check_dev():
FILE: new_ui/backend/models/requests.py
class PaperToCodeRequest (line 7) | class PaperToCodeRequest(BaseModel):
class ChatPlanningRequest (line 15) | class ChatPlanningRequest(BaseModel):
class GenerateQuestionsRequest (line 22) | class GenerateQuestionsRequest(BaseModel):
class SummarizeRequirementsRequest (line 28) | class SummarizeRequirementsRequest(BaseModel):
class ModifyRequirementsRequest (line 37) | class ModifyRequirementsRequest(BaseModel):
class LLMProviderUpdateRequest (line 44) | class LLMProviderUpdateRequest(BaseModel):
class FileUploadResponse (line 52) | class FileUploadResponse(BaseModel):
class InteractionResponseRequest (line 61) | class InteractionResponseRequest(BaseModel):
FILE: new_ui/backend/models/responses.py
class TaskResponse (line 8) | class TaskResponse(BaseModel):
class WorkflowStatusResponse (line 17) | class WorkflowStatusResponse(BaseModel):
class QuestionsResponse (line 30) | class QuestionsResponse(BaseModel):
class RequirementsSummaryResponse (line 37) | class RequirementsSummaryResponse(BaseModel):
class ConfigResponse (line 44) | class ConfigResponse(BaseModel):
class SettingsResponse (line 53) | class SettingsResponse(BaseModel):
class ErrorResponse (line 62) | class ErrorResponse(BaseModel):
FILE: new_ui/backend/services/requirement_service.py
class RequirementService (line 13) | class RequirementService:
method generate_questions (line 16) | async def generate_questions(self, initial_requirement: str) -> Dict[s...
method summarize_requirements (line 51) | async def summarize_requirements(
method modify_requirements (line 88) | async def modify_requirements(
FILE: new_ui/backend/services/session_service.py
class Session (line 13) | class Session:
class SessionService (line 24) | class SessionService:
method __init__ (line 27) | def __init__(self, timeout_minutes: int = 60):
method create_session (line 31) | def create_session(self) -> Session:
method get_session (line 38) | def get_session(self, session_id: str) -> Optional[Session]:
method delete_session (line 49) | def delete_session(self, session_id: str):
method add_to_history (line 54) | def add_to_history(
method get_history (line 73) | def get_history(self, session_id: str, limit: int = 50) -> List[Dict[s...
method add_active_task (line 80) | def add_active_task(self, session_id: str, task_id: str):
method remove_active_task (line 86) | def remove_active_task(self, session_id: str, task_id: str):
method update_preferences (line 92) | def update_preferences(self, session_id: str, preferences: Dict[str, A...
method cleanup_expired_sessions (line 98) | def cleanup_expired_sessions(self):
FILE: new_ui/backend/services/workflow_service.py
class WorkflowTask (line 21) | class WorkflowTask:
class WorkflowService (line 39) | class WorkflowService:
method __init__ (line 42) | def __init__(self):
method _get_plugin_integration (line 50) | def _get_plugin_integration(self):
method create_task (line 63) | def create_task(self) -> WorkflowTask:
method get_task (line 71) | def get_task(self, task_id: str) -> Optional[WorkflowTask]:
method subscribe (line 75) | def subscribe(self, task_id: str) -> Optional[asyncio.Queue]:
method unsubscribe (line 87) | def unsubscribe(self, task_id: str, queue: asyncio.Queue):
method _broadcast (line 95) | async def _broadcast(self, task_id: str, message: Dict[str, Any]):
method get_progress_queue (line 112) | def get_progress_queue(self, task_id: str) -> Optional[asyncio.Queue]:
method _create_progress_callback (line 117) | async def _create_progress_callback(
method execute_paper_to_code (line 144) | async def execute_paper_to_code(
method execute_chat_planning (line 234) | async def execute_chat_planning(
method cancel_task (line 370) | def cancel_task(self, task_id: str) -> bool:
method cleanup_task (line 379) | def cleanup_task(self, task_id: str):
method get_active_tasks (line 386) | def get_active_tasks(self) -> List[WorkflowTask]:
method get_recent_tasks (line 390) | def get_recent_tasks(self, limit: int = 10) -> List[WorkflowTask]:
FILE: new_ui/backend/settings.py
class Settings (line 21) | class Settings(BaseSettings):
class Config (line 46) | class Config:
function load_mcp_config (line 53) | def load_mcp_config() -> Dict[str, Any]:
function load_secrets (line 62) | def load_secrets() -> Dict[str, Any]:
function get_llm_provider (line 71) | def get_llm_provider() -> str:
function get_llm_models (line 77) | def get_llm_models(provider: Optional[str] = None) -> Dict[str, str]:
function get_api_key (line 90) | def get_api_key(provider: str) -> Optional[str]:
function is_indexing_enabled (line 97) | def is_indexing_enabled() -> bool:
FILE: new_ui/frontend/src/App.tsx
function App (line 10) | function App() {
FILE: new_ui/frontend/src/components/common/Button.tsx
type ButtonProps (line 5) | interface ButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {
FILE: new_ui/frontend/src/components/common/Card.tsx
type CardProps (line 4) | interface CardProps {
function Card (line 10) | function Card({
FILE: new_ui/frontend/src/components/common/ConfirmDialog.tsx
type ConfirmDialogProps (line 10) | interface ConfirmDialogProps {
function ConfirmDialog (line 21) | function ConfirmDialog({
FILE: new_ui/frontend/src/components/common/GuardedLink.tsx
type GuardedLinkProps (line 13) | interface GuardedLinkProps extends Omit<LinkProps, 'onClick'> {
function GuardedLink (line 17) | function GuardedLink({ to, children, ...props }: GuardedLinkProps) {
FILE: new_ui/frontend/src/components/common/TaskRecoveryBanner.tsx
type TaskRecoveryBannerProps (line 12) | interface TaskRecoveryBannerProps {
function TaskRecoveryBanner (line 18) | function TaskRecoveryBanner({
FILE: new_ui/frontend/src/components/common/Toaster.tsx
type Toast (line 5) | interface Toast {
function Toaster (line 72) | function Toaster() {
FILE: new_ui/frontend/src/components/input/ChatInput.tsx
type ChatInputProps (line 5) | interface ChatInputProps {
function ChatInput (line 12) | function ChatInput({
FILE: new_ui/frontend/src/components/input/FileUploader.tsx
type FileUploaderProps (line 7) | interface FileUploaderProps {
function FileUploader (line 14) | function FileUploader({
FILE: new_ui/frontend/src/components/input/UrlInput.tsx
type UrlInputProps (line 5) | interface UrlInputProps {
function UrlInput (line 12) | function UrlInput({
FILE: new_ui/frontend/src/components/interaction/InlineChatInteraction.tsx
type InlineChatInteractionProps (line 25) | interface InlineChatInteractionProps {
function InlineChatInteraction (line 31) | function InlineChatInteraction({
FILE: new_ui/frontend/src/components/interaction/InteractionPanel.tsx
type InteractionPanelProps (line 27) | interface InteractionPanelProps {
function InteractionPanel (line 33) | function InteractionPanel({
FILE: new_ui/frontend/src/components/layout/Header.tsx
function Header (line 6) | function Header() {
FILE: new_ui/frontend/src/components/layout/Layout.tsx
type LayoutProps (line 9) | interface LayoutProps {
function Layout (line 13) | function Layout({ children }: LayoutProps) {
FILE: new_ui/frontend/src/components/layout/Sidebar.tsx
function Sidebar (line 11) | function Sidebar() {
FILE: new_ui/frontend/src/components/results/CodePreview.tsx
type CodePreviewProps (line 4) | interface CodePreviewProps {
function CodePreview (line 10) | function CodePreview({
FILE: new_ui/frontend/src/components/results/FileTree.tsx
type FileNode (line 5) | interface FileNode {
type FileTreeProps (line 11) | interface FileTreeProps {
function FileTree (line 17) | function FileTree({ files, onFileSelect, selectedFile }: FileTreeProps) {
type TreeNodeProps (line 84) | interface TreeNodeProps {
function TreeNode (line 92) | function TreeNode({
FILE: new_ui/frontend/src/components/streaming/ActivityLogViewer.tsx
type LogEntry (line 24) | interface LogEntry {
type ActivityLogViewerProps (line 32) | interface ActivityLogViewerProps {
function getIconForMessage (line 39) | function getIconForMessage(message: string): React.ReactNode {
function formatTime (line 70) | function formatTime(date: Date): string {
function ActivityLogViewer (line 79) | function ActivityLogViewer({
FILE: new_ui/frontend/src/components/streaming/CodeStreamViewer.tsx
type CodeStreamViewerProps (line 7) | interface CodeStreamViewerProps {
function CodeStreamViewer (line 14) | function CodeStreamViewer({
FILE: new_ui/frontend/src/components/streaming/LogViewer.tsx
type LogEntry (line 5) | interface LogEntry {
type LogViewerProps (line 13) | interface LogViewerProps {
function LogViewer (line 26) | function LogViewer({
FILE: new_ui/frontend/src/components/streaming/ProgressTracker.tsx
type ProgressTrackerProps (line 5) | interface ProgressTrackerProps {
function ProgressTracker (line 10) | function ProgressTracker({
FILE: new_ui/frontend/src/components/workflow/WorkflowCanvas.tsx
type WorkflowCanvasProps (line 18) | interface WorkflowCanvasProps {
function WorkflowCanvas (line 28) | function WorkflowCanvas({
FILE: new_ui/frontend/src/components/workflow/WorkflowNode.tsx
type WorkflowNodeData (line 6) | interface WorkflowNodeData {
function WorkflowNode (line 15) | function WorkflowNode({ data }: NodeProps<WorkflowNodeData>) {
FILE: new_ui/frontend/src/hooks/useAdaptiveLayout.ts
function useAdaptiveLayout (line 31) | function useAdaptiveLayout(taskType: TaskType): LayoutConfig {
FILE: new_ui/frontend/src/hooks/useNavigationGuard.ts
type NavigationGuardState (line 13) | interface NavigationGuardState {
function useNavigationGuard (line 19) | function useNavigationGuard() {
FILE: new_ui/frontend/src/hooks/useStreaming.ts
type WSMessage (line 12) | type WSMessage = WSProgressMessage | WSCompleteMessage | WSErrorMessage ...
function useStreaming (line 14) | function useStreaming(taskId: string | null) {
FILE: new_ui/frontend/src/hooks/useTaskRecovery.ts
type RecoveryState (line 19) | interface RecoveryState {
function useTaskRecovery (line 25) | function useTaskRecovery() {
FILE: new_ui/frontend/src/hooks/useWebSocket.ts
type UseWebSocketOptions (line 4) | interface UseWebSocketOptions {
function useWebSocket (line 14) | function useWebSocket(
FILE: new_ui/frontend/src/pages/ChatPlanningPage.tsx
function ChatPlanningPage (line 17) | function ChatPlanningPage() {
FILE: new_ui/frontend/src/pages/HomePage.tsx
function HomePage (line 74) | function HomePage() {
FILE: new_ui/frontend/src/pages/PaperToCodePage.tsx
type InputMethod (line 16) | type InputMethod = 'file' | 'url';
function PaperToCodePage (line 18) | function PaperToCodePage() {
FILE: new_ui/frontend/src/pages/SettingsPage.tsx
function SettingsPage (line 9) | function SettingsPage() {
FILE: new_ui/frontend/src/pages/WorkflowEditorPage.tsx
function WorkflowEditorPage (line 7) | function WorkflowEditorPage() {
FILE: new_ui/frontend/src/stores/sessionStore.ts
type SessionState (line 5) | interface SessionState {
FILE: new_ui/frontend/src/stores/workflowStore.ts
type ActivityLogEntry (line 9) | interface ActivityLogEntry {
type PendingInteraction (line 18) | interface PendingInteraction {
type WorkflowState (line 39) | interface WorkflowState {
FILE: new_ui/frontend/src/types/api.ts
type TaskResponse (line 3) | interface TaskResponse {
type WorkflowStatusResponse (line 10) | interface WorkflowStatusResponse {
type QuestionsResponse (line 21) | interface QuestionsResponse {
type Question (line 26) | interface Question {
type RequirementsSummaryResponse (line 34) | interface RequirementsSummaryResponse {
type ConfigResponse (line 39) | interface ConfigResponse {
type SettingsResponse (line 46) | interface SettingsResponse {
type FileUploadResponse (line 53) | interface FileUploadResponse {
type ErrorResponse (line 60) | interface ErrorResponse {
type WSProgressMessage (line 67) | interface WSProgressMessage {
type WSCompleteMessage (line 76) | interface WSCompleteMessage {
type WSErrorMessage (line 84) | interface WSErrorMessage {
type WSCodeChunkMessage (line 91) | interface WSCodeChunkMessage {
type WSLogMessage (line 99) | interface WSLogMessage {
type WSInteractionMessage (line 108) | interface WSInteractionMessage {
type WSMessage (line 126) | type WSMessage =
FILE: new_ui/frontend/src/types/common.ts
type Message (line 3) | interface Message {
type Notification (line 11) | interface Notification {
type LayoutConfig (line 19) | interface LayoutConfig {
type TaskType (line 26) | type TaskType = 'paper-to-code' | 'chat-planning' | 'workflow-editor' | ...
FILE: new_ui/frontend/src/types/workflow.ts
type WorkflowStatus (line 3) | type WorkflowStatus = 'idle' | 'running' | 'completed' | 'error' | 'canc...
type WorkflowStep (line 5) | interface WorkflowStep {
type WorkflowTask (line 13) | interface WorkflowTask {
type WorkflowInput (line 24) | interface WorkflowInput {
constant PAPER_TO_CODE_STEPS (line 32) | const PAPER_TO_CODE_STEPS: WorkflowStep[] = [
constant CHAT_PLANNING_STEPS (line 43) | const CHAT_PLANNING_STEPS: WorkflowStep[] = [
FILE: setup.py
function read_long_description (line 7) | def read_long_description():
function retrieve_metadata (line 15) | def retrieve_metadata():
function read_requirements (line 42) | def read_requirements():
FILE: tools/bocha_search_server.py
function bocha_web_search (line 43) | async def bocha_web_search(
function bocha_ai_search (line 115) | async def bocha_ai_search(
function main (line 198) | def main():
FILE: tools/code_implementation_server.py
function initialize_workspace (line 56) | def initialize_workspace(workspace_dir: str = None):
function ensure_workspace_exists (line 80) | def ensure_workspace_exists():
function validate_path (line 92) | def validate_path(path: str) -> Path:
function log_operation (line 103) | def log_operation(action: str, details: Dict[str, Any]):
function read_file (line 114) | async def read_file(
function read_multiple_files (line 180) | async def read_multiple_files(file_requests: str, max_files: int = 5) ->...
function write_file (line 403) | async def write_file(
function write_multiple_files (line 475) | async def write_multiple_files(
function execute_python (line 687) | async def execute_python(code: str, timeout: int = 30) -> str:
function execute_bash (line 767) | async def execute_bash(command: str, timeout: int = 30) -> str:
function read_code_mem (line 853) | async def read_code_mem(file_paths: List[str]) -> str:
function _extract_file_section_from_summary (line 986) | def _extract_file_section_from_summary(
function _normalize_file_path (line 1038) | def _normalize_file_path(file_path: str) -> str:
function _paths_match (line 1055) | def _paths_match(
function _remove_common_prefixes (line 1094) | def _remove_common_prefixes(file_path: str) -> str:
function _extract_file_section_alternative (line 1106) | def _extract_file_section_alternative(
function search_code (line 1156) | async def search_code(
function get_file_structure (line 1281) | async def get_file_structure(directory: str = ".", max_depth: int = 5) -...
function set_workspace (line 1396) | async def set_workspace(workspace_path: str) -> str:
function get_operation_history (line 1451) | async def get_operation_history(last_n: int = 10) -> str:
function main (line 1487) | def main():
FILE: tools/code_indexer.py
class FileRelationship (line 31) | class FileRelationship:
class FileSummary (line 44) | class FileSummary:
class RepoIndex (line 58) | class RepoIndex:
class CodeIndexer (line 68) | class CodeIndexer:
method __init__ (line 71) | def __init__(
method _setup_logger (line 251) | def _setup_logger(self) -> logging.Logger:
method _load_api_config (line 282) | def _load_api_config(self) -> Dict[str, Any]:
method _load_indexer_config (line 294) | def _load_indexer_config(self) -> Dict[str, Any]:
method _initialize_llm_client (line 311) | async def _initialize_llm_client(self):
method _call_llm (line 383) | async def _call_llm(
method _generate_mock_response (line 468) | def _generate_mock_response(self, prompt: str) -> str:
method _save_debug_response (line 519) | def _save_debug_response(self, provider: str, prompt: str, response: s...
method get_all_repo_files (line 545) | def get_all_repo_files(self, repo_path: Path) -> List[Path]:
method generate_file_tree (line 568) | def generate_file_tree(self, repo_path: Path, max_depth: int = 5) -> str:
method pre_filter_files (line 617) | async def pre_filter_files(self, repo_path: Path, file_tree: str) -> L...
method filter_files_by_paths (line 699) | def filter_files_by_paths(
method _get_cache_key (line 727) | def _get_cache_key(self, file_path: Path) -> str:
method _manage_cache_size (line 735) | def _manage_cache_size(self):
method analyze_file_content (line 753) | async def analyze_file_content(self, file_path: Path) -> FileSummary:
method find_relationships (line 865) | async def find_relationships(
method _analyze_single_file_with_relationships (line 951) | async def _analyze_single_file_with_relationships(
method process_repository (line 966) | async def process_repository(self, repo_path: Path) -> RepoIndex:
method _process_files_sequentially (line 1050) | async def _process_files_sequentially(self, files_to_analyze: list) ->...
method _process_files_concurrently (line 1070) | async def _process_files_concurrently(self, files_to_analyze: list) ->...
method build_all_indexes (line 1189) | async def build_all_indexes(self) -> Dict[str, str]:
method _extract_repository_statistics (line 1270) | def _extract_repository_statistics(self, repo_index: RepoIndex) -> Dic...
method generate_statistics_report (line 1322) | def generate_statistics_report(self, statistics_data: List[Dict[str, A...
method generate_summary_report (line 1429) | def generate_summary_report(self, output_files: Dict[str, str]) -> str:
function main (line 1464) | async def main():
function print_usage_example (line 1610) | def print_usage_example():
FILE: tools/code_reference_indexer.py
class CodeReference (line 38) | class CodeReference:
class RelationshipInfo (line 53) | class RelationshipInfo:
function load_index_files_from_directory (line 65) | def load_index_files_from_directory(indexes_directory: str) -> Dict[str,...
function extract_code_references (line 88) | def extract_code_references(index_data: Dict) -> List[CodeReference]:
function extract_relationships (line 111) | def extract_relationships(index_data: Dict) -> List[RelationshipInfo]:
function calculate_relevance_score (line 132) | def calculate_relevance_score(
function find_relevant_references_in_cache (line 175) | def find_relevant_references_in_cache(
function find_direct_relationships_in_cache (line 198) | def find_direct_relationships_in_cache(
function format_reference_output (line 239) | def format_reference_output(
function search_code_references (line 335) | async def search_code_references(
function get_indexes_overview (line 412) | async def get_indexes_overview(indexes_path: str) -> str:
function main (line 479) | def main():
FILE: tools/command_executor.py
function handle_list_tools (line 22) | async def handle_list_tools() -> list[types.Tool]:
function handle_call_tool (line 91) | async def handle_call_tool(name: str, arguments: dict) -> list[types.Tex...
function execute_command_batch (line 116) | async def execute_command_batch(
function execute_single_command (line 193) | async def execute_single_command(
function generate_execution_summary (line 239) | def generate_execution_summary(
function format_single_command_result (line 266) | def format_single_command_result(
function main (line 301) | async def main():
FILE: tools/document_segmentation_server.py
class DocumentSegment (line 96) | class DocumentSegment:
class DocumentIndex (line 112) | class DocumentIndex:
class DocumentAnalyzer (line 124) | class DocumentAnalyzer:
method analyze_document_type (line 168) | def analyze_document_type(self, content: str) -> Tuple[str, float]:
method _calculate_weighted_score (line 214) | def _calculate_weighted_score(
method _detect_pattern_score (line 228) | def _detect_pattern_score(self, content: str, patterns: List[str]) -> ...
method detect_segmentation_strategy (line 236) | def detect_segmentation_strategy(self, content: str, doc_type: str) ->...
method _calculate_algorithm_density (line 259) | def _calculate_algorithm_density(self, content: str) -> float:
method _calculate_concept_complexity (line 283) | def _calculate_concept_complexity(self, content: str) -> float:
method _calculate_implementation_detail_level (line 296) | def _calculate_implementation_detail_level(self, content: str) -> float:
class DocumentSegmenter (line 313) | class DocumentSegmenter:
method __init__ (line 316) | def __init__(self):
method segment_document (line 319) | def segment_document(self, content: str, strategy: str) -> List[Docume...
method _segment_by_headers (line 337) | def _segment_by_headers(self, content: str) -> List[DocumentSegment]:
method _segment_preserve_algorithm_integrity (line 407) | def _segment_preserve_algorithm_integrity(
method _segment_research_paper_semantically (line 441) | def _segment_research_paper_semantically(
method _segment_concept_implementation_hybrid (line 466) | def _segment_concept_implementation_hybrid(
method _segment_by_enhanced_semantic_chunks (line 491) | def _segment_by_enhanced_semantic_chunks(
method _segment_content_aware (line 533) | def _segment_content_aware(self, content: str) -> List[DocumentSegment]:
method _segment_academic_paper (line 556) | def _segment_academic_paper(self, content: str) -> List[DocumentSegment]:
method _detect_academic_sections (line 595) | def _detect_academic_sections(self, content: str) -> List[Dict]:
method _segment_by_semantic_chunks (line 654) | def _segment_by_semantic_chunks(self, content: str) -> List[DocumentSe...
method _segment_by_paragraphs (line 724) | def _segment_by_paragraphs(self, content: str) -> List[DocumentSegment]:
method _identify_algorithm_blocks (line 753) | def _identify_algorithm_blocks(self, content: str) -> List[Dict]:
method _identify_concept_groups (line 793) | def _identify_concept_groups(self, content: str) -> List[Dict]:
method _identify_formula_chains (line 826) | def _identify_formula_chains(self, content: str) -> List[Dict]:
method _merge_related_content_blocks (line 893) | def _merge_related_content_blocks(
method _are_blocks_related (line 942) | def _are_blocks_related(self, block1: Dict, block2: Dict) -> bool:
method _extract_algorithm_title (line 959) | def _extract_algorithm_title(self, text: str) -> str:
method _extract_concept_title (line 971) | def _extract_concept_title(self, text: str) -> str:
method _create_enhanced_segment (line 982) | def _create_enhanced_segment(
method _extract_enhanced_keywords (line 1018) | def _extract_enhanced_keywords(self, content: str, content_type: str) ...
method _calculate_enhanced_relevance_scores (line 1073) | def _calculate_enhanced_relevance_scores(
method _identify_research_paper_sections (line 1120) | def _identify_research_paper_sections(self, content: str) -> List[Dict]:
method _enhance_section_with_context (line 1125) | def _enhance_section_with_context(self, section: Dict, content: str) -...
method _identify_concept_implementation_pairs (line 1129) | def _identify_concept_implementation_pairs(self, content: str) -> List...
method _merge_concept_with_implementation (line 1133) | def _merge_concept_with_implementation(self, pair: Dict, content: str)...
method _detect_semantic_boundaries (line 1137) | def _detect_semantic_boundaries(self, content: str) -> List[Dict]:
method _classify_paragraph_type (line 1166) | def _classify_paragraph_type(self, paragraph: str) -> str:
method _calculate_paragraph_importance (line 1183) | def _calculate_paragraph_importance(
method _extract_paragraph_title (line 1198) | def _extract_paragraph_title(self, paragraph: str, index: int) -> str:
method _calculate_optimal_chunk_size (line 1208) | def _calculate_optimal_chunk_size(self, content: str) -> int:
method _create_content_aware_chunks (line 1219) | def _create_content_aware_chunks(self, content: str, chunk_size: int) ...
method _create_segment (line 1267) | def _create_segment(
method _extract_keywords (line 1298) | def _extract_keywords(self, content: str) -> List[str]:
method _classify_content_type (line 1338) | def _classify_content_type(self, title: str, content: str) -> str:
method _calculate_relevance_scores (line 1364) | def _calculate_relevance_scores(
function get_segments_dir (line 1436) | def get_segments_dir(paper_dir: str) -> str:
function ensure_segments_dir_exists (line 1441) | def ensure_segments_dir_exists(segments_dir: str):
function analyze_and_segment_document (line 1447) | async def analyze_and_segment_document(
function read_document_segments (line 1602) | async def read_document_segments(
function get_document_overview (line 1727) | async def get_document_overview(paper_dir: str) -> str:
function _calculate_adaptive_char_limit (line 1788) | def _calculate_adaptive_char_limit(
function _calculate_enhanced_keyword_score (line 1813) | def _calculate_enhanced_keyword_score(
function _calculate_completeness_bonus (line 1844) | def _calculate_completeness_bonus(
function _select_segments_with_integrity (line 1867) | def _select_segments_with_integrity(
FILE: tools/git_command.py
class GitHubURLExtractor (line 18) | class GitHubURLExtractor:
method extract_github_urls (line 22) | def extract_github_urls(text: str) -> List[str]:
method extract_target_path (line 79) | def extract_target_path(text: str) -> Optional[str]:
method infer_repo_name (line 108) | def infer_repo_name(url: str) -> str:
function check_git_installed (line 118) | async def check_git_installed() -> bool:
function clone_repository (line 133) | async def clone_repository(repo_url: str, target_path: str) -> Dict[str,...
function download_github_repo (line 158) | async def download_github_repo(instruction: str) -> str:
function parse_github_urls (line 253) | async def parse_github_urls(text: str) -> str:
function git_clone (line 286) | async def git_clone(
FILE: tools/pdf_converter.py
class PDFConverter (line 26) | class PDFConverter:
method __init__ (line 40) | def __init__(self) -> None:
method find_libreoffice_windows (line 45) | def find_libreoffice_windows() -> Optional[str]:
method convert_office_to_pdf (line 78) | def convert_office_to_pdf(
method convert_text_to_pdf (line 308) | def convert_text_to_pdf(
method _process_inline_markdown (line 527) | def _process_inline_markdown(text: str) -> str:
method convert_to_pdf (line 570) | def convert_to_pdf(
method check_dependencies (line 604) | def check_dependencies(self) -> dict:
function main (line 656) | def main():
FILE: tools/pdf_downloader.py
function format_success_message (line 72) | def format_success_message(action: str, details: Dict[str, Any]) -> str:
function format_error_message (line 77) | def format_error_message(action: str, error: str) -> str:
function format_warning_message (line 82) | def format_warning_message(action: str, warning: str) -> str:
function perform_document_conversion (line 87) | async def perform_document_conversion(
function format_file_operation_result (line 169) | def format_file_operation_result(
class LocalPathExtractor (line 223) | class LocalPathExtractor:
method is_local_path (line 227) | def is_local_path(path: str) -> bool:
method extract_local_paths (line 250) | def extract_local_paths(text: str) -> List[str]:
class URLExtractor (line 278) | class URLExtractor:
method convert_arxiv_url (line 288) | def convert_arxiv_url(url: str) -> str:
method extract_urls (line 299) | def extract_urls(cls, text: str) -> List[str]:
method infer_filename_from_url (line 339) | def infer_filename_from_url(url: str) -> str:
class PathExtractor (line 402) | class PathExtractor:
method extract_target_path (line 406) | def extract_target_path(text: str) -> Optional[str]:
class SimplePdfConverter (line 441) | class SimplePdfConverter:
method convert_pdf_to_markdown (line 444) | def convert_pdf_to_markdown(
class DoclingConverter (line 528) | class DoclingConverter:
method __init__ (line 531) | def __init__(self):
method is_supported_format (line 555) | def is_supported_format(self, file_path: str) -> bool:
method is_url (line 564) | def is_url(self, path: str) -> bool:
method extract_images (line 572) | def extract_images(self, doc, output_dir: str) -> Dict[str, str]:
method process_markdown_with_images (line 622) | def process_markdown_with_images(
method convert_to_markdown (line 650) | def convert_to_markdown(
function check_url_accessible (line 764) | async def check_url_accessible(url: str) -> Dict[str, Any]:
function download_file (line 785) | async def download_file(url: str, destination: str) -> Dict[str, Any]:
function move_local_file (line 843) | async def move_local_file(source_path: str, destination: str) -> Dict[st...
function download_files (line 890) | async def download_files(instruction: str) -> str:
function parse_download_urls (line 1039) | async def parse_download_urls(text: str) -> str:
function download_file_to (line 1086) | async def download_file_to(
function move_file_to (line 1195) | async def move_file_to(
FILE: tools/pdf_utils.py
function read_pdf_metadata (line 9) | def read_pdf_metadata(file_path: Path) -> dict:
FILE: ui/components.py
function _icon_data_uri (line 27) | def _icon_data_uri(name: str) -> str:
function icon_img (line 41) | def icon_img(name: str, size: int = 32, extra_style: str = "") -> str:
function clear_guided_answer_inputs (line 51) | def clear_guided_answer_inputs():
function display_header (line 60) | def display_header():
function display_features (line 79) | def display_features():
function display_status (line 138) | def display_status(message: str, status_type: str = "info"):
function _render_step_card (line 159) | def _render_step_card(title: str, subtitle: str, state: str) -> str:
function enhanced_progress_display_component (line 189) | def enhanced_progress_display_component(
function update_step_indicator (line 242) | def update_step_indicator(
function chat_input_component (line 272) | def chat_input_component(task_counter: int = 0) -> Optional[str]:
function _save_uploaded_pdf (line 283) | def _save_uploaded_pdf(uploaded_file) -> Optional[str]:
function input_method_selector (line 298) | def input_method_selector(task_counter: int) -> Tuple[Optional[str], Opt...
function results_display_component (line 346) | def results_display_component(result: Any, task_counter: int):
function system_status_component (line 396) | def system_status_component():
function error_troubleshooting_component (line 421) | def error_troubleshooting_component():
function footer_component (line 429) | def footer_component():
function render_sidebar_feed (line 441) | def render_sidebar_feed(max_items: int = 12):
function render_system_monitor (line 487) | def render_system_monitor():
function render_log_viewer (line 529) | def render_log_viewer(max_lines: int = 50):
function reset_guided_workflow_state (line 656) | def reset_guided_workflow_state(preserve_initial: bool = False):
function requirement_mode_selector (line 684) | def requirement_mode_selector() -> str:
function guided_requirement_workflow (line 710) | def guided_requirement_workflow() -> Tuple[Optional[str], bool]:
function sidebar_control_panel (line 942) | def sidebar_control_panel():
FILE: ui/handlers.py
function set_abort_requested (line 23) | def set_abort_requested(value: bool = True):
function is_abort_requested (line 30) | def is_abort_requested() -> bool:
function reset_abort_flag (line 34) | def reset_abort_flag():
function _emergency_cleanup (line 48) | def _emergency_cleanup():
function _signal_handler (line 59) | def _signal_handler(signum, frame):
function _safe_register_signal_handlers (line 77) | def _safe_register_signal_handlers():
function process_input_async (line 105) | async def process_input_async(
function run_async_task (line 177) | def run_async_task(coro):
function run_async_task_simple (line 304) | def run_async_task_simple(coro):
function handle_processing_workflow (line 399) | def handle_processing_workflow(
function update_session_state_with_result (line 619) | def update_session_state_with_result(result: Dict[str, Any], input_type:...
function cleanup_temp_file (line 660) | def cleanup_temp_file(input_source: str, input_type: str):
function handle_requirement_analysis_workflow (line 683) | async def handle_requirement_analysis_workflow(
function handle_requirement_modification_workflow (line 728) | async def handle_requirement_modification_workflow(
function handle_guided_mode_processing (line 786) | def handle_guided_mode_processing():
function _background_workflow_runner (line 880) | def _background_workflow_runner(
function handle_start_processing_button (line 933) | def handle_start_processing_button(input_source: str, input_type: str):
function check_background_workflow_status (line 994) | def check_background_workflow_status():
function handle_error_display (line 1058) | def handle_error_display():
function initialize_session_state (line 1068) | def initialize_session_state():
function cleanup_resources (line 1137) | def cleanup_resources():
FILE: ui/layout.py
function setup_page_config (line 29) | def setup_page_config():
function main_layout (line 42) | def main_layout():
function render_input_area (line 82) | def render_input_area():
FILE: ui/sidebar_feed.py
function _init_event_store (line 14) | def _init_event_store():
function log_sidebar_event (line 19) | def log_sidebar_event(
class SidebarLogHandler (line 59) | class SidebarLogHandler(logging.Handler):
method emit (line 62) | def emit(self, record: logging.LogRecord):
function ensure_sidebar_logging (line 78) | def ensure_sidebar_logging():
FILE: ui/streamlit_app.py
function main (line 23) | def main():
FILE: ui/styles.py
function get_main_styles (line 7) | def get_main_styles() -> str:
FILE: utils/cli_interface.py
class Colors (line 16) | class Colors:
class CLIInterface (line 38) | class CLIInterface:
method __init__ (line 41) | def __init__(self):
method clear_screen (line 57) | def clear_screen(self):
method print_logo (line 61) | def print_logo(self):
method print_welcome_banner (line 92) | def print_welcome_banner(self):
method print_separator (line 107) | def print_separator(self, char="═", length=79, color=Colors.CYAN):
method print_status (line 111) | def print_status(self, message: str, status_type: str = "info"):
method create_menu (line 127) | def create_menu(self):
method get_user_input (line 145) | def get_user_input(self):
method upload_file_gui (line 150) | def upload_file_gui(self) -> Optional[str]:
method _get_manual_file_path (line 280) | def _get_manual_file_path(self) -> Optional[str]:
method get_url_input (line 325) | def get_url_input(self) -> str:
method show_progress_bar (line 366) | def show_progress_bar(self, message: str, duration: float = 2.0):
method show_spinner (line 394) | def show_spinner(self, message: str, duration: float = 1.0):
method print_results_header (line 412) | def print_results_header(self):
method print_error_box (line 421) | def print_error_box(self, title: str, error_msg: str):
method print_goodbye (line 434) | def print_goodbye(self):
method ask_continue (line 452) | def ask_continue(self) -> bool:
FILE: utils/cross_platform_file_handler.py
class CrossPlatformFileHandler (line 27) | class CrossPlatformFileHandler:
method __init__ (line 38) | def __init__(self, logger: Optional[logging.Logger] = None):
method _create_default_logger (line 54) | def _create_default_logger(self) -> logging.Logger:
method normalize_path (line 68) | def normalize_path(path: Union[str, Path]) -> Path:
method create_safe_temp_file (line 90) | def create_safe_temp_file(
method temp_directory (line 155) | def temp_directory(self, prefix: str = "deepcode_"):
method safe_copy_file (line 186) | def safe_copy_file(
method safe_move_file (line 250) | def safe_move_file(
method safe_remove_file (line 305) | def safe_remove_file(self, file_path: Union[str, Path]) -> bool:
method cleanup_all_temp_files (line 342) | def cleanup_all_temp_files(self):
method get_system_temp_dir (line 369) | def get_system_temp_dir(self) -> Path:
method create_workspace_directory (line 378) | def create_workspace_directory(
function get_file_handler (line 409) | def get_file_handler(
FILE: utils/dialogue_logger.py
class DialogueLogger (line 15) | class DialogueLogger:
method __init__ (line 21) | def __init__(self, paper_id: str, base_path: str = None):
method _initialize_log_file (line 57) | def _initialize_log_file(self):
method start_new_round (line 85) | def start_new_round(
method log_system_prompt (line 114) | def log_system_prompt(self, prompt: str, prompt_type: str = "system"):
method log_user_message (line 134) | def log_user_message(self, message: str, message_type: str = "user_inp...
method log_assistant_response (line 154) | def log_assistant_response(
method log_tool_calls (line 176) | def log_tool_calls(self, tool_calls: List[Dict[str, Any]]):
method log_tool_results (line 196) | def log_tool_results(self, tool_results: List[Dict[str, Any]]):
method log_metadata (line 215) | def log_metadata(self, key: str, value: Any):
method log_memory_optimization (line 228) | def log_memory_optimization(
method complete_round (line 283) | def complete_round(self, summary: str = "", status: str = "completed"):
method _write_round_to_log (line 310) | def _write_round_to_log(self):
method log_complete_exchange (line 488) | def log_complete_exchange(
method get_session_stats (line 531) | def get_session_stats(self) -> Dict[str, Any]:
method finalize_session (line 543) | def finalize_session(self, final_summary: str = ""):
function create_dialogue_logger (line 576) | def create_dialogue_logger(paper_id: str, base_path: str = None) -> Dial...
function extract_paper_id_from_path (line 590) | def extract_paper_id_from_path(path: str) -> str:
FILE: utils/file_processor.py
class FileProcessor (line 11) | class FileProcessor:
method extract_file_path (line 17) | def extract_file_path(file_info: Union[str, Dict]) -> Optional[str]:
method find_markdown_file (line 74) | def find_markdown_file(directory: str) -> Optional[str]:
method parse_markdown_sections (line 93) | def parse_markdown_sections(content: str) -> List[Dict[str, Union[str,...
method _organize_sections (line 144) | def _organize_sections(sections: List[Dict]) -> List[Dict]:
method read_file_content (line 171) | async def read_file_content(file_path: str) -> str:
method format_section_content (line 226) | def format_section_content(section: Dict) -> str:
method standardize_output (line 259) | def standardize_output(sections: List[Dict]) -> str:
method process_file_input (line 279) | async def process_file_input(
method extract_json_from_text (line 433) | def extract_json_from_text(text: str) -> Optional[Dict]:
FILE: utils/llm_utils.py
function get_api_keys (line 13) | def get_api_keys(secrets_path: str = "mcp_agent.secrets.yaml") -> Dict[s...
function load_api_config (line 57) | def load_api_config(secrets_path: str = "mcp_agent.secrets.yaml") -> Dic...
function _get_llm_class (line 89) | def _get_llm_class(provider: str) -> Type[Any]:
function get_preferred_llm_class (line 109) | def get_preferred_llm_class(config_path: str = "mcp_agent.secrets.yaml")...
function get_token_limits (line 174) | def get_token_limits(config_path: str = "mcp_agent.config.yaml") -> Tupl...
function get_default_models (line 214) | def get_default_models(config_path: str = "mcp_agent.config.yaml"):
function _get_fallback_models (line 278) | def _get_fallback_models():
function get_document_segmentation_config (line 296) | def get_document_segmentation_config(
function should_use_document_segmentation (line 331) | def should_use_document_segmentation(
function get_adaptive_agent_config (line 366) | def get_adaptive_agent_config(
function get_adaptive_prompts (line 406) | def get_adaptive_prompts(use_segmentation: bool) -> Dict[str, str]:
FILE: utils/loop_detector.py
class LoopDetector (line 13) | class LoopDetector:
method __init__ (line 24) | def __init__(self, max_repeats: int = 5, timeout_seconds: int = 300,
method start_file (line 48) | def start_file(self, filename: str):
method check_tool_call (line 55) | def check_tool_call(self, tool_name: str) -> Dict[str, Any]:
method record_progress (line 112) | def record_progress(self):
method record_error (line 117) | def record_error(self, error_message: str):
method record_success (line 122) | def record_success(self):
method get_status_summary (line 127) | def get_status_summary(self) -> Dict[str, Any]:
method should_abort (line 142) | def should_abort(self) -> bool:
method get_abort_reason (line 147) | def get_abort_reason(self) -> Optional[str]:
class ProgressTracker (line 155) | class ProgressTracker:
method __init__ (line 160) | def __init__(self, total_files: int = 0):
method set_phase (line 167) | def set_phase(self, phase_name: str, progress_percent: int):
method complete_file (line 173) | def complete_file(self, filename: str):
method get_progress_info (line 178) | def get_progress_info(self) -> Dict[str, Any]:
FILE: utils/model_limits.py
function get_model_from_config (line 97) | def get_model_from_config(config_path: str = "mcp_agent.config.yaml") ->...
function get_model_limits (line 125) | def get_model_limits(model_name: Optional[str] = None, config_path: str ...
function get_safe_max_tokens (line 169) | def get_safe_max_tokens(
function calculate_token_cost (line 191) | def calculate_token_cost(
function get_retry_token_limits (line 218) | def get_retry_token_limits(
function get_provider_from_model (line 258) | def get_provider_from_model(model_name: Optional[str] = None, config_pat...
FILE: utils/simple_llm_logger.py
class SimpleLLMLogger (line 16) | class SimpleLLMLogger:
method __init__ (line 19) | def __init__(self, config_path: str = "mcp_agent.config.yaml"):
method _load_config (line 37) | def _load_config(self, config_path: str) -> Dict[str, Any]:
method _get_default_config (line 46) | def _get_default_config(self) -> Dict[str, Any]:
method _setup_logger (line 60) | def _setup_logger(self):
method log_response (line 78) | def log_response(self, content: str, model: str = "", agent: str = "",...
method _should_log (line 104) | def _should_log(self, content: str, model: str) -> bool:
method _build_entry (line 118) | def _build_entry(self, content: str, model: str, agent: str, extra: Di...
method _write_log (line 144) | def _write_log(self, entry: Dict):
method _console_log (line 165) | def _console_log(self, content: str, model: str, agent: str):
function get_llm_logger (line 175) | def get_llm_logger() -> SimpleLLMLogger:
function log_llm_response (line 183) | def log_llm_response(content: str, model: str = "", agent: str = "", **k...
FILE: workflows/agent_orchestration_engine.py
function _assess_output_completeness (line 68) | def _assess_output_completeness(text: str) -> float:
function _adjust_params_for_retry (line 150) | def _adjust_params_for_retry(
function execute_requirement_analysis_workflow (line 200) | async def execute_requirement_analysis_workflow(
function get_default_search_server (line 254) | def get_default_search_server(config_path: str = "mcp_agent.config.yaml"):
function get_search_server_names (line 281) | def get_search_server_names(
function extract_clean_json (line 305) | def extract_clean_json(llm_output: str) -> str:
function run_research_analyzer (line 374) | async def run_research_analyzer(prompt_text: str, logger) -> str:
function run_resource_processor (line 485) | async def run_resource_processor(analysis_result: str, logger) -> str:
function run_code_analyzer (line 635) | async def run_code_analyzer(
function github_repo_download (line 859) | async def github_repo_download(search_result: str, paper_dir: str, logge...
function paper_reference_analyzer (line 894) | async def paper_reference_analyzer(paper_dir: str, logger) -> str:
function _process_input_source (line 936) | async def _process_input_source(input_source: str, logger) -> str:
function orchestrate_research_analysis_agent (line 955) | async def orchestrate_research_analysis_agent(
function synthesize_workspace_infrastructure_agent (line 993) | async def synthesize_workspace_infrastructure_agent(
function orchestrate_reference_intelligence_agent (line 1036) | async def orchestrate_reference_intelligence_agent(
function orchestrate_document_preprocessing_agent (line 1075) | async def orchestrate_document_preprocessing_agent(
function orchestrate_code_planning_agent (line 1235) | async def orchestrate_code_planning_agent(
function automate_repository_acquisition_agent (line 1299) | async def automate_repository_acquisition_agent(
function orchestrate_codebase_intelligence_agent (line 1373) | async def orchestrate_codebase_intelligence_agent(
function synthesize_code_implementation_agent (line 1500) | async def synthesize_code_implementation_agent(
function run_chat_planning_agent (line 1589) | async def run_chat_planning_agent(user_input: str, logger) -> str:
function execute_multi_agent_research_pipeline (line 1698) | async def execute_multi_agent_research_pipeline(
function paper_code_preparation (line 1983) | async def paper_code_preparation(
function execute_chat_based_planning_pipeline (line 2005) | async def execute_chat_based_planning_pipeline(
FILE: workflows/agents/code_implementation_agent.py
class CodeImplementationAgent (line 33) | class CodeImplementationAgent:
method __init__ (line 45) | def __init__(
method _create_default_logger (line 127) | def _create_default_logger(self) -> logging.Logger:
method get_system_prompt (line 134) | def get_system_prompt(self) -> str:
method set_memory_agent (line 140) | def set_memory_agent(self, memory_agent, llm_client=None, llm_client_t...
method execute_tool_calls (line 154) | async def execute_tool_calls(self, tool_calls: List[Dict]) -> List[Dict]:
method _handle_read_file_with_memory_optimization (line 280) | async def _handle_read_file_with_memory_optimization(self, tool_call: ...
method _track_file_implementation_with_summary (line 411) | async def _track_file_implementation_with_summary(
method _track_file_implementation (line 451) | def _track_file_implementation(self, tool_call: Dict, result: Any):
method _track_dependency_analysis (line 548) | def _track_dependency_analysis(self, tool_call: Dict, result: Any):
method calculate_messages_token_count (line 575) | def calculate_messages_token_count(self, messages: List[Dict]) -> int:
method should_trigger_summary_by_tokens (line 616) | def should_trigger_summary_by_tokens(self, messages: List[Dict]) -> bool:
method should_trigger_summary (line 649) | def should_trigger_summary(
method mark_summary_triggered (line 677) | def mark_summary_triggered(self, messages: List[Dict] = None):
method get_implementation_summary (line 702) | def get_implementation_summary(self) -> Dict[str, Any]:
method get_files_implemented_count (line 709) | def get_files_implemented_count(self) -> int:
method get_read_tools_status (line 716) | def get_read_tools_status(self) -> Dict[str, Any]:
method add_technical_decision (line 731) | def add_technical_decision(self, decision: str, context: str = ""):
method add_constraint (line 745) | def add_constraint(self, constraint: str, impact: str = ""):
method add_architecture_note (line 759) | def add_architecture_note(self, note: str, component: str = ""):
method get_implementation_statistics (line 773) | def get_implementation_statistics(self) -> Dict[str, Any]:
method force_enable_optimization (line 803) | def force_enable_optimization(self):
method reset_implementation_tracking (line 816) | def reset_implementation_tracking(self):
method _track_tool_call_for_loop_detection (line 843) | def _track_tool_call_for_loop_detection(self, tool_name: str):
method is_in_analysis_loop (line 858) | def is_in_analysis_loop(self) -> bool:
method get_analysis_loop_guidance (line 889) | def get_analysis_loop_guidance(self) -> str:
method test_summary_functionality (line 912) | async def test_summary_functionality(self, test_file_path: str = None):
method test_automatic_read_file_optimization (line 970) | async def test_automatic_read_file_optimization(self):
method test_summary_optimization (line 1035) | async def test_summary_optimization(self, test_file_path: str = "confi...
method test_read_tools_configuration (line 1066) | async def test_read_tools_configuration(self):
FILE: workflows/agents/document_segmentation_agent.py
class DocumentSegmentationAgent (line 16) | class DocumentSegmentationAgent:
method __init__ (line 35) | def __init__(self, logger: Optional[logging.Logger] = None):
method _create_default_logger (line 39) | def _create_default_logger(self) -> logging.Logger:
method __aenter__ (line 45) | async def __aenter__(self):
method __aexit__ (line 50) | async def __aexit__(self, exc_type, exc_val, exc_tb):
method initialize (line 54) | async def initialize(self):
method cleanup (line 91) | async def cleanup(self):
method analyze_and_prepare_document (line 99) | async def analyze_and_prepare_document(
method get_document_overview (line 169) | async def get_document_overview(self, paper_dir: str) -> Dict[str, Any]:
method validate_segmentation_quality (line 207) | async def validate_segmentation_quality(self, paper_dir: str) -> Dict[...
function run_document_segmentation_analysis (line 255) | async def run_document_segmentation_analysis(
function prepare_document_segments (line 284) | async def prepare_document_segments(
FILE: workflows/agents/memory_agent_concise.py
class ConciseMemoryAgent (line 27) | class ConciseMemoryAgent:
method __init__ (line 43) | def __init__(
method _create_default_logger (line 119) | def _create_default_logger(self) -> logging.Logger:
method _parse_phase_structure (line 125) | def _parse_phase_structure(self) -> Dict[str, List[str]]:
method _extract_all_files (line 158) | def _extract_all_files(self) -> List[str]:
method _extract_files_from_generated_directory (line 184) | def _extract_files_from_generated_directory(self) -> List[str]:
method _extract_all_files_from_plan (line 303) | def _extract_all_files_from_plan(self) -> List[str]:
method _extract_from_tree_structure (line 342) | def _extract_from_tree_structure(self, lines: List[str]) -> List[str]:
method _is_directory (line 487) | def _is_directory(self, name: str) -> bool:
method _extract_from_simple_list (line 643) | def _extract_from_simple_list(self, lines: List[str]) -> List[str]:
method _extract_from_plan_content (line 663) | def _extract_from_plan_content(self, lines: List[str]) -> List[str]:
method _clean_and_validate_files (line 802) | def _clean_and_validate_files(self, files: List[str]) -> List[str]:
method record_file_implementation (line 977) | def record_file_implementation(
method create_code_implementation_summary (line 994) | async def create_code_implementation_summary(
method _create_code_summary_prompt (line 1073) | def _create_code_summary_prompt(
method _extract_summary_sections (line 1165) | def _extract_summary_sections(self, llm_summary: str) -> Dict[str, str]:
method _format_code_implementation_summary (line 1242) | def _format_code_implementation_summary(
method _create_fallback_code_summary (line 1288) | def _create_fallback_code_summary(
method _save_code_summary_to_file (line 1322) | async def _save_code_summary_to_file(self, new_summary: str, file_path...
method _call_llm_for_summary (line 1363) | async def _call_llm_for_summary(
method start_new_round (line 1477) | def start_new_round(self, iteration: Optional[int] = None):
method record_tool_result (line 1497) | def record_tool_result(
method should_use_concise_mode (line 1537) | def should_use_concise_mode(self) -> bool:
method create_concise_messages (line 1546) | def create_concise_messages(
method _read_code_knowledge_base (line 1681) | def _read_code_knowledge_base(self) -> Optional[str]:
method _extract_latest_implementation_entry (line 1706) | def _extract_latest_implementation_entry(self, content: str) -> Option...
method _format_tool_results (line 1759) | def _format_tool_results(self) -> str:
method _format_tool_result_content (line 1836) | def _format_tool_result_content(self, tool_result: Any) -> str:
method get_memory_statistics (line 1867) | def get_memory_statistics(self, files_implemented: int = 0) -> Dict[st...
method get_implemented_files (line 1899) | def get_implemented_files(self) -> List[str]:
method get_all_files_list (line 1903) | def get_all_files_list(self) -> List[str]:
method refresh_files_list_from_directory (line 1907) | def refresh_files_list_from_directory(self) -> bool:
method get_unimplemented_files (line 1929) | def get_unimplemented_files(self) -> List[str]:
method get_formatted_files_lists (line 1997) | def get_formatted_files_lists(self) -> Dict[str, str]:
method get_current_next_steps (line 2019) | def get_current_next_steps(self) -> str:
method clear_next_steps (line 2023) | def clear_next_steps(self):
method set_next_steps (line 2029) | def set_next_steps(self, next_steps: str):
method should_trigger_memory_optimization (line 2036) | def should_trigger_memory_optimization(
method apply_memory_optimization (line 2058) | def apply_memory_optimization(
method clear_current_round_tool_results (line 2097) | def clear_current_round_tool_results(self):
method debug_concise_state (line 2102) | def debug_concise_state(self, files_implemented: int = 0):
FILE: workflows/agents/memory_agent_concise_index.py
class ConciseMemoryAgent (line 27) | class ConciseMemoryAgent:
method __init__ (line 43) | def __init__(
method _create_default_logger (line 119) | def _create_default_logger(self) -> logging.Logger:
method _parse_phase_structure (line 125) | def _parse_phase_structure(self) -> Dict[str, List[str]]:
method _extract_all_files (line 158) | def _extract_all_files(self) -> List[str]:
method _extract_files_from_generated_directory (line 184) | def _extract_files_from_generated_directory(self) -> List[str]:
method _extract_all_files_from_plan (line 303) | def _extract_all_files_from_plan(self) -> List[str]:
method _extract_from_tree_structure (line 342) | def _extract_from_tree_structure(self, lines: List[str]) -> List[str]:
method _is_directory (line 487) | def _is_directory(self, name: str) -> bool:
method _extract_from_simple_list (line 643) | def _extract_from_simple_list(self, lines: List[str]) -> List[str]:
method _extract_from_plan_content (line 663) | def _extract_from_plan_content(self, lines: List[str]) -> List[str]:
method _clean_and_validate_files (line 802) | def _clean_and_validate_files(self, files: List[str]) -> List[str]:
method record_file_implementation (line 977) | def record_file_implementation(
method create_code_implementation_summary (line 994) | async def create_code_implementation_summary(
method _create_code_summary_prompt (line 1073) | def _create_code_summary_prompt(
method _extract_summary_sections (line 1165) | def _extract_summary_sections(self, llm_summary: str) -> Dict[str, str]:
method _format_code_implementation_summary (line 1242) | def _format_code_implementation_summary(
method _create_fallback_code_summary (line 1288) | def _create_fallback_code_summary(
method _save_code_summary_to_file (line 1322) | async def _save_code_summary_to_file(self, new_summary: str, file_path...
method _call_llm_for_summary (line 1363) | async def _call_llm_for_summary(
method start_new_round (line 1477) | def start_new_round(self, iteration: Optional[int] = None):
method record_tool_result (line 1497) | def record_tool_result(
method should_use_concise_mode (line 1537) | def should_use_concise_mode(self) -> bool:
method create_concise_messages (line 1546) | def create_concise_messages(
method _read_code_knowledge_base (line 1683) | def _read_code_knowledge_base(self) -> Optional[str]:
method _extract_latest_implementation_entry (line 1708) | def _extract_latest_implementation_entry(self, content: str) -> Option...
method _format_tool_results (line 1761) | def _format_tool_results(self) -> str:
method _format_tool_result_content (line 1838) | def _format_tool_result_content(self, tool_result: Any) -> str:
method get_memory_statistics (line 1869) | def get_memory_statistics(self, files_implemented: int = 0) -> Dict[st...
method get_implemented_files (line 1901) | def get_implemented_files(self) -> List[str]:
method get_all_files_list (line 1905) | def get_all_files_list(self) -> List[str]:
method refresh_files_list_from_directory (line 1909) | def refresh_files_list_from_directory(self) -> bool:
method get_unimplemented_files (line 1931) | def get_unimplemented_files(self) -> List[str]:
method get_formatted_files_lists (line 1999) | def get_formatted_files_lists(self) -> Dict[str, str]:
method get_current_next_steps (line 2021) | def get_current_next_steps(self) -> str:
method clear_next_steps (line 2025) | def clear_next_steps(self):
method set_next_steps (line 2031) | def set_next_steps(self, next_steps: str):
method should_trigger_memory_optimization (line 2038) | def should_trigger_memory_optimization(
method apply_memory_optimization (line 2060) | def apply_memory_optimization(
method clear_current_round_tool_results (line 2099) | def clear_current_round_tool_results(self):
method debug_concise_state (line 2104) | def debug_concise_state(self, files_implemented: int = 0):
FILE: workflows/agents/memory_agent_concise_multi.py
class ConciseMemoryAgent (line 30) | class ConciseMemoryAgent:
method __init__ (line 48) | def __init__(
method _create_default_logger (line 115) | def _create_default_logger(self) -> logging.Logger:
method create_multi_code_implementation_summary (line 121) | async def create_multi_code_implementation_summary(
method _create_multi_code_summary_prompt (line 223) | def _create_multi_code_summary_prompt(
method _extract_multi_summary_sections (line 315) | def _extract_multi_summary_sections(
method _format_code_implementation_summary (line 510) | def _format_code_implementation_summary(
method _create_fallback_multi_code_summary (line 537) | def _create_fallback_multi_code_summary(
method _save_code_summary_to_file (line 567) | async def _save_code_summary_to_file(self, new_summary: str, file_path...
method _call_llm_for_summary (line 606) | async def _call_llm_for_summary(
method start_new_round (line 712) | def start_new_round(self, iteration: Optional[int] = None):
method record_tool_result (line 728) | def record_tool_result(
method should_use_concise_mode (line 764) | def should_use_concise_mode(self) -> bool:
method create_concise_messages_revise (line 773) | def create_concise_messages_revise(
method _calculate_message_statistics (line 881) | def _calculate_message_statistics(
method _calculate_memory_savings (line 915) | def _calculate_memory_savings(
method _read_code_knowledge_base (line 958) | def _read_code_knowledge_base(self) -> Optional[str]:
method _extract_latest_implementation_entry (line 978) | def _extract_latest_implementation_entry(self, content: str) -> Option...
method _format_tool_results (line 1025) | def _format_tool_results(self) -> str:
method _format_tool_result_content (line 1095) | def _format_tool_result_content(self, tool_result: Any) -> str:
method get_memory_statistics (line 1122) | def get_memory_statistics(
method record_multi_file_implementation (line 1167) | def record_multi_file_implementation(self, file_implementations: Dict[...
method synchronize_revised_file_memory (line 1182) | async def synchronize_revised_file_memory(
method synchronize_multiple_revised_files (line 1250) | async def synchronize_multiple_revised_files(
method _create_file_revision_summary_prompt (line 1304) | def _create_file_revision_summary_prompt(
method _extract_revision_summary_sections (line 1377) | def _extract_revision_summary_sections(self, llm_summary: str) -> Dict...
method _format_file_revision_summary (line 1473) | def _format_file_revision_summary(
method _create_fallback_revision_summary (line 1540) | def _create_fallback_revision_summary(
method _save_revised_file_summary (line 1588) | async def _save_revised_file_summary(self, revision_summary: str, file...
method get_revision_memory_statistics (line 1663) | def get_revision_memory_statistics(
FILE: workflows/agents/requirement_analysis_agent.py
class RequirementAnalysisAgent (line 17) | class RequirementAnalysisAgent:
method __init__ (line 33) | def __init__(self, logger: Optional[logging.Logger] = None):
method _create_default_logger (line 43) | def _create_default_logger(self) -> logging.Logger:
method __aenter__ (line 49) | async def __aenter__(self):
method __aexit__ (line 54) | async def __aexit__(self, exc_type, exc_val, exc_tb):
method initialize (line 58) | async def initialize(self):
method cleanup (line 96) | async def cleanup(self):
method generate_guiding_questions (line 104) | async def generate_guiding_questions(self, user_input: str) -> List[Di...
method summarize_detailed_requirements (line 224) | async def summarize_detailed_requirements(
method modify_requirements (line 323) | async def modify_requirements(
FILE: workflows/code_implementation_workflow.py
class CodeImplementationWorkflow (line 39) | class CodeImplementationWorkflow:
method __init__ (line 51) | def __init__(self, config_path: str = "mcp_agent.secrets.yaml"):
method _load_api_config (line 67) | def _load_api_config(self) -> Dict[str, Any]:
method _create_logger (line 74) | def _create_logger(self) -> logging.Logger:
method _read_plan_file (line 81) | def _read_plan_file(self, plan_file_path: str) -> str:
method _check_file_tree_exists (line 92) | def _check_file_tree_exists(self, target_directory: str) -> bool:
method run_workflow (line 99) | async def run_workflow(
method create_file_structure (line 169) | async def create_file_structure(
method implement_code_pure (line 221) | async def implement_code_pure(
method _pure_code_implementation_loop (line 298) | async def _pure_code_implementation_loop(
method _initialize_mcp_agent (line 510) | async def _initialize_mcp_agent(self, code_directory: str):
method _cleanup_mcp_agent (line 542) | async def _cleanup_mcp_agent(self):
method _initialize_llm_client (line 553) | async def _initialize_llm_client(self):
method _call_llm_with_tools (line 696) | async def _call_llm_with_tools(
method _call_anthropic_with_tools (line 719) | async def _call_anthropic_with_tools(
method _call_google_with_tools (line 787) | async def _call_google_with_tools(
method _transform_schema_for_gemini (line 915) | def _transform_schema_for_gemini(self, schema: dict) -> dict:
method _repair_truncated_json (line 982) | def _repair_truncated_json(self, json_str: str, tool_name: str = "") -...
method _close_json_structures (line 1042) | def _close_json_structures(self, json_str: str) -> str:
method _call_openai_with_tools (line 1069) | async def _call_openai_with_tools(
method _validate_messages (line 1263) | def _validate_messages(self, messages: List[Dict]) -> List[Dict]:
method _prepare_mcp_tool_definitions (line 1276) | def _prepare_mcp_tool_definitions(self) -> List[Dict[str, Any]]:
method _check_tool_results_for_errors (line 1280) | def _check_tool_results_for_errors(self, tool_results: List[Dict]) -> ...
method _generate_success_guidance (line 1327) | def _generate_success_guidance(self, files_count: int) -> str:
method _generate_error_guidance (line 1340) | def _generate_error_guidance(self) -> str:
method _generate_no_tools_guidance (line 1353) | def _generate_no_tools_guidance(self, files_count: int) -> str:
method _compile_user_response (line 1368) | def _compile_user_response(self, tool_results: List[Dict], guidance: s...
method _generate_pure_code_final_report_with_concise_agents (line 1388) | async def _generate_pure_code_final_report_with_concise_agents(
function main (line 1487) | async def main():
FILE: workflows/code_implementation_workflow_index.py
class CodeImplementationWorkflowWithIndex (line 39) | class CodeImplementationWorkflowWithIndex:
method __init__ (line 52) | def __init__(self, config_path: str = "mcp_agent.secrets.yaml"):
method _load_api_config (line 68) | def _load_api_config(self) -> Dict[str, Any]:
method _create_logger (line 75) | def _create_logger(self) -> logging.Logger:
method _read_plan_file (line 82) | def _read_plan_file(self, plan_file_path: str) -> str:
method _check_file_tree_exists (line 93) | def _check_file_tree_exists(self, target_directory: str) -> bool:
method run_workflow (line 100) | async def run_workflow(
method create_file_structure (line 170) | async def create_file_structure(
method implement_code_pure (line 210) | async def implement_code_pure(
method _pure_code_implementation_loop (line 287) | async def _pure_code_implementation_loop(
method _initialize_mcp_agent (line 459) | async def _initialize_mcp_agent(self, code_directory: str):
method _cleanup_mcp_agent (line 491) | async def _cleanup_mcp_agent(self):
method _initialize_llm_client (line 502) | async def _initialize_llm_client(self):
method _call_llm_with_tools (line 646) | async def _call_llm_with_tools(
method _call_anthropic_with_tools (line 669) | async def _call_anthropic_with_tools(
method _call_google_with_tools (line 737) | async def _call_google_with_tools(
method _transform_schema_for_gemini (line 865) | def _transform_schema_for_gemini(self, schema: dict) -> dict:
method _repair_truncated_json (line 932) | def _repair_truncated_json(self, json_str: str, tool_name: str = "") -...
method _close_json_structures (line 992) | def _close_json_structures(self, json_str: str) -> str:
method _call_openai_with_tools (line 1019) | async def _call_openai_with_tools(
method _validate_messages (line 1213) | def _validate_messages(self, messages: List[Dict]) -> List[Dict]:
method _prepare_mcp_tool_definitions (line 1226) | def _prepare_mcp_tool_definitions(self) -> List[Dict[str, Any]]:
method _check_tool_results_for_errors (line 1250) | def _check_tool_results_for_errors(self, tool_results: List[Dict]) -> ...
method _generate_success_guidance (line 1297) | def _generate_success_guidance(self, files_count: int) -> str:
method _generate_error_guidance (line 1315) | def _generate_error_guidance(self) -> str:
method _generate_no_tools_guidance (line 1333) | def _generate_no_tools_guidance(self, files_count: int) -> str:
method _compile_user_response (line 1351) | def _compile_user_response(self, tool_results: List[Dict], guidance: s...
method _generate_pure_code_final_report_with_concise_agents (line 1371) | async def _generate_pure_code_final_report_with_concise_agents(
function main (line 1470) | async def main():
FILE: workflows/codebase_index_workflow.py
class CodebaseIndexWorkflow (line 30) | class CodebaseIndexWorkflow:
method __init__ (line 33) | def __init__(self, logger=None):
method _setup_default_logger (line 43) | def _setup_default_logger(self) -> logging.Logger:
method extract_file_tree_from_plan (line 58) | def extract_file_tree_from_plan(self, plan_content: str) -> Optional[s...
method load_target_structure_from_plan (line 196) | def load_target_structure_from_plan(self, plan_path: str) -> str:
method get_default_target_structure (line 240) | def get_default_target_structure(self) -> str:
method load_or_create_indexer_config (line 278) | def load_or_create_indexer_config(self, paper_dir: str) -> Dict[str, A...
method run_indexing_workflow (line 406) | async def run_indexing_workflow(
method print_banner (line 664) | def print_banner(self):
function run_codebase_indexing (line 682) | async def run_codebase_indexing(
function main (line 711) | async def main():
FILE: workflows/plugins/base.py
class InteractionPoint (line 34) | class InteractionPoint(Enum):
class InteractionRequest (line 58) | class InteractionRequest:
class InteractionResponse (line 71) | class InteractionResponse:
class InteractionPlugin (line 79) | class InteractionPlugin(ABC):
method __init__ (line 110) | def __init__(self, enabled: bool = True, config: Optional[Dict] = None):
method should_trigger (line 116) | async def should_trigger(self, context: Dict[str, Any]) -> bool:
method create_interaction (line 129) | async def create_interaction(self, context: Dict[str, Any]) -> Interac...
method process_response (line 142) | async def process_response(
method on_skip (line 157) | async def on_skip(self, context: Dict[str, Any]) -> Dict[str, Any]:
method on_timeout (line 171) | async def on_timeout(self, context: Dict[str, Any]) -> Dict[str, Any]:
class PluginRegistry (line 193) | class PluginRegistry:
method __init__ (line 218) | def __init__(self, interaction_callback: Optional[InteractionCallback]...
method register (line 225) | def register(self, plugin: InteractionPlugin) -> None:
method unregister (line 233) | def unregister(self, plugin_name: str) -> bool:
method enable (line 243) | def enable(self, plugin_name: str) -> bool:
method disable (line 253) | def disable(self, plugin_name: str) -> bool:
method set_interaction_callback (line 263) | def set_interaction_callback(self, callback: InteractionCallback) -> N...
method get_plugins (line 267) | def get_plugins(self, hook_point: InteractionPoint) -> List[Interactio...
method run_hook (line 271) | async def run_hook(
function get_default_registry (line 361) | def get_default_registry(auto_register: bool = True) -> PluginRegistry:
function reset_registry (line 389) | def reset_registry() -> None:
FILE: workflows/plugins/integration.py
class WorkflowPluginIntegration (line 42) | class WorkflowPluginIntegration:
method __init__ (line 75) | def __init__(
method create_context (line 94) | def create_context(self, task_id: str, **kwargs) -> Dict[str, Any]:
method run_hook (line 102) | async def run_hook(
method _handle_interaction (line 115) | async def _handle_interaction(
method submit_response (line 186) | def submit_response(
method has_pending_interaction (line 218) | def has_pending_interaction(self, task_id: str) -> bool:
method cancel_interaction (line 222) | def cancel_interaction(self, task_id: str) -> bool:
function create_plugin_enabled_wrapper (line 232) | def create_plugin_enabled_wrapper(
FILE: workflows/plugins/plan_review.py
class PlanReviewPlugin (line 24) | class PlanReviewPlugin(InteractionPlugin):
method __init__ (line 42) | def __init__(self, enabled: bool = True, config: Optional[Dict] = None):
method should_trigger (line 48) | async def should_trigger(self, context: Dict[str, Any]) -> bool:
method create_interaction (line 80) | async def create_interaction(self, context: Dict[str, Any]) -> Interac...
method process_response (line 115) | async def process_response(
method _modify_plan (line 184) | async def _modify_plan(
method on_skip (line 211) | async def on_skip(self, context: Dict[str, Any]) -> Dict[str, Any]:
method on_timeout (line 218) | async def on_timeout(self, context: Dict[str, Any]) -> Dict[str, Any]:
FILE: workflows/plugins/requirement_analysis.py
class RequirementAnalysisPlugin (line 24) | class RequirementAnalysisPlugin(InteractionPlugin):
method __init__ (line 41) | def __init__(self, enabled: bool = True, config: Optional[Dict] = None):
method _get_agent (line 45) | async def _get_agent(self):
method _cleanup_agent (line 56) | async def _cleanup_agent(self):
method should_trigger (line 62) | async def should_trigger(self, context: Dict[str, Any]) -> bool:
method create_interaction (line 84) | async def create_interaction(self, context: Dict[str, Any]) -> Interac...
method process_response (line 134) | async def process_response(
method on_skip (line 173) | async def on_skip(self, context: Dict[str, Any]) -> Dict[str, Any]:
method on_timeout (line 180) | async def on_timeout(self, context: Dict[str, Any]) -> Dict[str, Any]:
Condensed preview — 255 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (2,248K chars).
[
{
"path": ".dockerignore",
"chars": 439,
"preview": "# Git\n.git\n.gitignore\n\n# Node\nnew_ui/frontend/node_modules\nnew_ui/frontend/dist\n\n# Python\n__pycache__\n*.pyc\n*.pyo\n*.egg-"
},
{
"path": ".gitattributes",
"chars": 125,
"preview": "# Force LF line endings for shell scripts (prevents CRLF issues in Docker)\n*.sh text eol=lf\ndocker-entrypoint.sh text eo"
},
{
"path": ".github/ISSUE_TEMPLATE/bug_report.yml",
"chars": 2063,
"preview": "name: Bug Report\ndescription: File a bug report\ntitle: \"[Bug]:\"\nlabels: [\"bug\", \"triage\"]\n\nbody:\n - type: checkboxes\n "
},
{
"path": ".github/ISSUE_TEMPLATE/config.yml",
"chars": 28,
"preview": "blank_issues_enabled: false\n"
},
{
"path": ".github/ISSUE_TEMPLATE/feature_request.yml",
"chars": 1063,
"preview": "name: Feature Request\ndescription: File a feature request\nlabels: [\"enhancement\"]\ntitle: \"[Feature Request]:\"\n\nbody:\n -"
},
{
"path": ".github/ISSUE_TEMPLATE/question.yml",
"chars": 980,
"preview": "name: Question\ndescription: Ask a general question\nlabels: [\"question\"]\ntitle: \"[Question]:\"\n\nbody:\n - type: checkboxes"
},
{
"path": ".github/dependabot.yml",
"chars": 525,
"preview": "# To get started with Dependabot version updates, you'll need to specify which\n# package ecosystems to update and where "
},
{
"path": ".github/pull_request_template.md",
"chars": 732,
"preview": "<!--\nThanks for contributing to DeepCode!\n\nPlease ensure your pull request is ready for review before submitting.\n\nAbout"
},
{
"path": ".github/workflows/linting.yaml",
"chars": 681,
"preview": "name: Linting and Formatting\n\non:\n push:\n branches:\n - main\n pull_request:\n branches:\n "
},
{
"path": ".github/workflows/pypi-publish.yml",
"chars": 1014,
"preview": "name: Upload DeepCode Package\n\non:\n release:\n types: [published]\n\npermissions:\n contents: read\n\njobs:\n release-bui"
},
{
"path": ".gitignore",
"chars": 858,
"preview": "# Python-related files\n__pycache__/\n*.py[cod]\n*.egg-info/\n.eggs/\n*.tgz\n*.tar.gz\n*.ini\n\n# Virtual Environment\n.venv/\nenv/"
},
{
"path": ".pre-commit-config.yaml",
"chars": 482,
"preview": "repos:\n - repo: https://github.com/pre-commit/pre-commit-hooks\n rev: v5.0.0\n hooks:\n - id: trailing-whitespa"
},
{
"path": "CHANGELOG.md",
"chars": 4544,
"preview": "# Changelog\n\nAll notable changes to DeepCode will be documented in this file.\n\n## [1.0.6-jm] - 2025-10-19\n\n### Added\n- *"
},
{
"path": "LICENSE",
"chars": 1084,
"preview": "MIT License\n\nCopyright (c) 2025 ✨Data Intelligence Lab@HKU✨\n\nPermission is hereby granted, free of charge, to any person"
},
{
"path": "MANIFEST.in",
"chars": 462,
"preview": "include README.md\ninclude LICENSE\ninclude requirements.txt\ninclude __init__.py\ninclude *.png\ninclude *.yaml\nrecursive-in"
},
{
"path": "README.md",
"chars": 47265,
"preview": "<div align=\"center\">\n\n<table style=\"border: none; margin: 0 auto; padding: 0; border-collapse: collapse;\">\n<tr>\n<td alig"
},
{
"path": "README_ZH.md",
"chars": 33431,
"preview": "<div align=\"center\">\n\n<table style=\"border: none; margin: 0 auto; padding: 0; border-collapse: collapse;\">\n<tr>\n<td alig"
},
{
"path": "__init__.py",
"chars": 496,
"preview": "\"\"\"\nDeepCode - AI Research Engine\n\n🧬 Next-Generation AI Research Automation Platform\n⚡ Transform research papers into wo"
},
{
"path": "cli/__init__.py",
"chars": 507,
"preview": "\"\"\"\nCLI Module for DeepCode Agent\nDeepCode智能体CLI模块\n\n包含以下组件 / Contains the following components:\n- cli_app: CLI应用主程序 / CL"
},
{
"path": "cli/cli_app.py",
"chars": 17515,
"preview": "#!/usr/bin/env python3\n\"\"\"\nDeepCode - CLI Application Main Program\n深度代码 - CLI应用主程序\n\n🧬 Open-Source Code Agent by Data Int"
},
{
"path": "cli/cli_interface.py",
"chars": 44706,
"preview": "#!/usr/bin/env python3\n\"\"\"\nEnhanced CLI Interface Module for DeepCode\n增强版CLI界面模块 - 专为DeepCode设计\n\"\"\"\n\nimport os\nimport ti"
},
{
"path": "cli/cli_launcher.py",
"chars": 5018,
"preview": "#!/usr/bin/env python3\n\"\"\"\nDeepCode - CLI Research Engine Launcher\nDeepCode - CLI研究引擎启动器\n\n🧬 Open-Source Code Agent by Da"
},
{
"path": "cli/main_cli.py",
"chars": 12547,
"preview": "#!/usr/bin/env python3\n\"\"\"\nDeepCode CLI - Open-Source Code Agent\n深度代码CLI - 开源代码智能体\n\n🧬 Data Intelligence Lab @ HKU\n⚡ Revo"
},
{
"path": "cli/workflows/__init__.py",
"chars": 280,
"preview": "\"\"\"\nCLI-specific Workflow Adapters\nCLI专用工作流适配器\n\nThis module provides CLI-optimized versions of workflow components that "
},
{
"path": "cli/workflows/cli_workflow_adapter.py",
"chars": 18113,
"preview": "\"\"\"\nCLI Workflow Adapter for Agent Orchestration Engine\nCLI工作流适配器 - 智能体编排引擎\n\nThis adapter provides CLI-optimized interfa"
},
{
"path": "config/mcp_tool_definitions.py",
"chars": 13631,
"preview": "\"\"\"\nMCP工具定义配置模块\nMCP Tool Definitions Configuration Module\n\n将工具定义从主程序逻辑中分离,提供标准化的工具定义格式\nSeparate tool definitions from ma"
},
{
"path": "config/mcp_tool_definitions_index.py",
"chars": 22787,
"preview": "\"\"\"\nMCP工具定义配置模块\nMCP Tool Definitions Configuration Module\n\n将工具定义从主程序逻辑中分离,提供标准化的工具定义格式\nSeparate tool definitions from ma"
},
{
"path": "deepcode.py",
"chars": 25334,
"preview": "#!/usr/bin/env python3\n\"\"\"\nDeepCode - AI Research Engine Launcher\n\n🧬 Next-Generation AI Research Automation Platform\n⚡ T"
},
{
"path": "deepcode_docker/.dockerignore",
"chars": 439,
"preview": "# Git\n.git\n.gitignore\n\n# Node\nnew_ui/frontend/node_modules\nnew_ui/frontend/dist\n\n# Python\n__pycache__\n*.pyc\n*.pyo\n*.egg-"
},
{
"path": "deepcode_docker/Dockerfile",
"chars": 2804,
"preview": "# =============================================================\n# DeepCode - Docker Build\n# Multi-stage: Frontend build "
},
{
"path": "deepcode_docker/docker-compose.yml",
"chars": 1327,
"preview": "services:\n deepcode:\n build:\n context: ..\n dockerfile: deepcode_docker/Dockerfile\n container_name: deep"
},
{
"path": "deepcode_docker/docker-entrypoint.sh",
"chars": 1442,
"preview": "#!/bin/bash\nset -e\n\necho \"============================================\"\necho \" DeepCode - AI Research Engine (Docker)\"\n"
},
{
"path": "deepcode_docker/run_docker.sh",
"chars": 7055,
"preview": "#!/bin/bash\n# DeepCode Docker 一键启动脚本\n\nset -e\n\nSCRIPT_DIR=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)\"\nPROJECT_ROOT=\"$"
},
{
"path": "mcp_agent.config.yaml",
"chars": 3822,
"preview": "$schema: ./schema/mcp-agent.config.schema.json\nanthropic: null\ndefault_search_server: filesystem\ndocument_segmentation:\n"
},
{
"path": "mcp_agent.secrets.yaml.example",
"chars": 651,
"preview": "# =============================================================\n# DeepCode - API Keys Configuration\n# =================="
},
{
"path": "nanobot/.dockerignore",
"chars": 110,
"preview": "__pycache__\n*.pyc\n*.pyo\n*.pyd\n*.egg-info\ndist/\nbuild/\n.git\n.env\n.assets\nnode_modules/\nbridge/dist/\nworkspace/\n"
},
{
"path": "nanobot/.gitignore",
"chars": 164,
"preview": ".assets\n.env\n*.pyc\ndist/\nbuild/\ndocs/\n*.egg-info/\n*.egg\n*.pyc\n*.pyo\n*.pyd\n*.pyw\n*.pyz\n*.pywz\n*.pyzz\n.venv/\n__pycache__/\n"
},
{
"path": "nanobot/COMMUNICATION.md",
"chars": 241,
"preview": "We provide QR codes for joining the HKUDS discussion groups on **WeChat** and **Feishu**.\n\nYou can join by scanning the "
},
{
"path": "nanobot/Dockerfile",
"chars": 1404,
"preview": "FROM ghcr.io/astral-sh/uv:python3.12-bookworm-slim\n\n# Install Node.js 20 for the WhatsApp bridge\nRUN apt-get update && \\"
},
{
"path": "nanobot/LICENSE",
"chars": 1077,
"preview": "MIT License\n\nCopyright (c) 2025 nanobot contributors\n\nPermission is hereby granted, free of charge, to any person obtain"
},
{
"path": "nanobot/README.md",
"chars": 20984,
"preview": "<div align=\"center\">\n <img src=\"nanobot_logo.png\" alt=\"nanobot\" width=\"500\">\n <h1>nanobot: Ultra-Lightweight Personal "
},
{
"path": "nanobot/SECURITY.md",
"chars": 7173,
"preview": "# Security Policy\n\n## Reporting a Vulnerability\n\nIf you discover a security vulnerability in nanobot, please report it b"
},
{
"path": "nanobot/bridge/package.json",
"chars": 588,
"preview": "{\n \"name\": \"nanobot-whatsapp-bridge\",\n \"version\": \"0.1.0\",\n \"description\": \"WhatsApp bridge for nanobot using Baileys"
},
{
"path": "nanobot/bridge/src/index.ts",
"chars": 1248,
"preview": "#!/usr/bin/env node\n/**\n * nanobot WhatsApp Bridge\n *\n * This bridge connects WhatsApp Web to nanobot's Python backend\n "
},
{
"path": "nanobot/bridge/src/server.ts",
"chars": 2754,
"preview": "/**\n * WebSocket server for Python-Node.js bridge communication.\n */\n\nimport { WebSocketServer, WebSocket } from 'ws';\ni"
},
{
"path": "nanobot/bridge/src/types.d.ts",
"chars": 116,
"preview": "declare module 'qrcode-terminal' {\n export function generate(text: string, options?: { small?: boolean }): void;\n}\n"
},
{
"path": "nanobot/bridge/src/whatsapp.ts",
"chars": 5083,
"preview": "/**\n * WhatsApp client wrapper using Baileys.\n * Based on OpenClaw's working implementation.\n */\n\n/* eslint-disable @typ"
},
{
"path": "nanobot/bridge/tsconfig.json",
"chars": 355,
"preview": "{\n \"compilerOptions\": {\n \"target\": \"ES2022\",\n \"module\": \"ESNext\",\n \"moduleResolution\": \"node\",\n \"esModuleIn"
},
{
"path": "nanobot/core_agent_lines.sh",
"chars": 740,
"preview": "#!/bin/bash\n# Count core agent lines (excluding channels/, cli/, providers/ adapters)\ncd \"$(dirname \"$0\")\" || exit 1\n\nec"
},
{
"path": "nanobot/nanobot/__init__.py",
"chars": 89,
"preview": "\"\"\"\nnanobot - A lightweight AI agent framework\n\"\"\"\n\n__version__ = \"0.1.0\"\n__logo__ = \"🐈\"\n"
},
{
"path": "nanobot/nanobot/__main__.py",
"chars": 147,
"preview": "\"\"\"\nEntry point for running nanobot as a module: python -m nanobot\n\"\"\"\n\nfrom nanobot.cli.commands import app\n\nif __name_"
},
{
"path": "nanobot/nanobot/agent/__init__.py",
"chars": 281,
"preview": "\"\"\"Agent core module.\"\"\"\n\nfrom nanobot.agent.context import ContextBuilder\nfrom nanobot.agent.loop import AgentLoop\nfrom"
},
{
"path": "nanobot/nanobot/agent/context.py",
"chars": 7741,
"preview": "\"\"\"Context builder for assembling agent prompts.\"\"\"\n\nimport base64\nimport mimetypes\nimport platform\nfrom pathlib import "
},
{
"path": "nanobot/nanobot/agent/loop.py",
"chars": 14151,
"preview": "\"\"\"Agent loop: the core processing engine.\"\"\"\n\nfrom __future__ import annotations\n\nimport asyncio\nimport json\nimport os\n"
},
{
"path": "nanobot/nanobot/agent/memory.py",
"chars": 3291,
"preview": "\"\"\"Memory system for persistent agent memory.\"\"\"\n\nfrom datetime import datetime\nfrom pathlib import Path\n\nfrom nanobot.u"
},
{
"path": "nanobot/nanobot/agent/skills.py",
"chars": 8310,
"preview": "\"\"\"Skills loader for agent capabilities.\"\"\"\n\nimport json\nimport os\nimport re\nimport shutil\nfrom pathlib import Path\n\n# D"
},
{
"path": "nanobot/nanobot/agent/subagent.py",
"chars": 9099,
"preview": "\"\"\"Subagent manager for background task execution.\"\"\"\n\nfrom __future__ import annotations\n\nimport asyncio\nimport json\nim"
},
{
"path": "nanobot/nanobot/agent/tools/__init__.py",
"chars": 159,
"preview": "\"\"\"Agent tools module.\"\"\"\n\nfrom nanobot.agent.tools.base import Tool\nfrom nanobot.agent.tools.registry import ToolRegist"
},
{
"path": "nanobot/nanobot/agent/tools/base.py",
"chars": 3652,
"preview": "\"\"\"Base class for agent tools.\"\"\"\n\nfrom abc import ABC, abstractmethod\nfrom typing import Any\n\n\nclass Tool(ABC):\n \"\"\""
},
{
"path": "nanobot/nanobot/agent/tools/cron.py",
"chars": 3673,
"preview": "\"\"\"Cron tool for scheduling reminders and tasks.\"\"\"\n\nfrom typing import Any\n\nfrom nanobot.agent.tools.base import Tool\nf"
},
{
"path": "nanobot/nanobot/agent/tools/deepcode.py",
"chars": 18693,
"preview": "\"\"\"\nDeepCode integration tools for nanobot.\n\nThese tools allow nanobot to interact with the DeepCode backend API\nfor pap"
},
{
"path": "nanobot/nanobot/agent/tools/filesystem.py",
"chars": 6221,
"preview": "\"\"\"File system tools: read, write, edit.\"\"\"\n\nfrom pathlib import Path\nfrom typing import Any\n\nfrom nanobot.agent.tools.b"
},
{
"path": "nanobot/nanobot/agent/tools/message.py",
"chars": 2471,
"preview": "\"\"\"Message tool for sending messages to users.\"\"\"\n\nfrom typing import Any, Awaitable, Callable\n\nfrom nanobot.agent.tools"
},
{
"path": "nanobot/nanobot/agent/tools/registry.py",
"chars": 2026,
"preview": "\"\"\"Tool registry for dynamic tool management.\"\"\"\n\nfrom typing import Any\n\nfrom nanobot.agent.tools.base import Tool\n\n\ncl"
},
{
"path": "nanobot/nanobot/agent/tools/shell.py",
"chars": 4673,
"preview": "\"\"\"Shell execution tool.\"\"\"\n\nimport asyncio\nimport os\nimport re\nfrom pathlib import Path\nfrom typing import Any\n\nfrom na"
},
{
"path": "nanobot/nanobot/agent/tools/spawn.py",
"chars": 2024,
"preview": "\"\"\"Spawn tool for creating background subagents.\"\"\"\n\nfrom typing import TYPE_CHECKING, Any\n\nfrom nanobot.agent.tools.bas"
},
{
"path": "nanobot/nanobot/agent/tools/web.py",
"chars": 6996,
"preview": "\"\"\"Web tools: web_search and web_fetch.\"\"\"\n\nimport html\nimport json\nimport os\nimport re\nfrom typing import Any\nfrom urll"
},
{
"path": "nanobot/nanobot/bus/__init__.py",
"chars": 236,
"preview": "\"\"\"Message bus module for decoupled channel-agent communication.\"\"\"\n\nfrom nanobot.bus.events import InboundMessage, Outb"
},
{
"path": "nanobot/nanobot/bus/events.py",
"chars": 1024,
"preview": "\"\"\"Event types for the message bus.\"\"\"\n\nfrom dataclasses import dataclass, field\nfrom datetime import datetime\nfrom typi"
},
{
"path": "nanobot/nanobot/bus/queue.py",
"chars": 2889,
"preview": "\"\"\"Async message queue for decoupled channel-agent communication.\"\"\"\n\nimport asyncio\nfrom typing import Awaitable, Calla"
},
{
"path": "nanobot/nanobot/channels/__init__.py",
"chars": 197,
"preview": "\"\"\"Chat channels module with plugin architecture.\"\"\"\n\nfrom nanobot.channels.base import BaseChannel\nfrom nanobot.channel"
},
{
"path": "nanobot/nanobot/channels/base.py",
"chars": 3471,
"preview": "\"\"\"Base channel interface for chat platforms.\"\"\"\n\nfrom abc import ABC, abstractmethod\nfrom typing import Any\n\nfrom logur"
},
{
"path": "nanobot/nanobot/channels/dingtalk.py",
"chars": 8675,
"preview": "\"\"\"DingTalk/DingDing channel implementation using Stream Mode.\"\"\"\n\nimport asyncio\nimport json\nimport time\nfrom typing im"
},
{
"path": "nanobot/nanobot/channels/discord.py",
"chars": 9591,
"preview": "\"\"\"Discord channel implementation using Discord Gateway websocket.\"\"\"\n\nimport asyncio\nimport json\nfrom pathlib import Pa"
},
{
"path": "nanobot/nanobot/channels/email.py",
"chars": 14245,
"preview": "\"\"\"Email channel implementation using IMAP polling + SMTP replies.\"\"\"\n\nimport asyncio\nimport html\nimport imaplib\nimport "
},
{
"path": "nanobot/nanobot/channels/feishu.py",
"chars": 11547,
"preview": "\"\"\"Feishu/Lark channel implementation using lark-oapi SDK with WebSocket long connection.\"\"\"\n\nimport asyncio\nimport json"
},
{
"path": "nanobot/nanobot/channels/manager.py",
"chars": 7534,
"preview": "\"\"\"Channel manager for coordinating chat channels.\"\"\"\n\nfrom __future__ import annotations\n\nimport asyncio\nfrom typing im"
},
{
"path": "nanobot/nanobot/channels/qq.py",
"chars": 4088,
"preview": "\"\"\"QQ channel implementation using botpy SDK.\"\"\"\n\nimport asyncio\nfrom collections import deque\nfrom typing import TYPE_C"
},
{
"path": "nanobot/nanobot/channels/slack.py",
"chars": 7255,
"preview": "\"\"\"Slack channel implementation using Socket Mode.\"\"\"\n\nimport asyncio\nimport re\n\nfrom loguru import logger\nfrom slack_sd"
},
{
"path": "nanobot/nanobot/channels/telegram.py",
"chars": 14914,
"preview": "\"\"\"Telegram channel implementation using python-telegram-bot.\"\"\"\n\nfrom __future__ import annotations\n\nimport asyncio\nimp"
},
{
"path": "nanobot/nanobot/channels/whatsapp.py",
"chars": 4958,
"preview": "\"\"\"WhatsApp channel implementation using Node.js bridge.\"\"\"\n\nimport asyncio\nimport json\n\nfrom loguru import logger\n\nfrom"
},
{
"path": "nanobot/nanobot/cli/__init__.py",
"chars": 30,
"preview": "\"\"\"CLI module for nanobot.\"\"\"\n"
},
{
"path": "nanobot/nanobot/cli/commands.py",
"chars": 27060,
"preview": "\"\"\"CLI commands for nanobot.\"\"\"\n\nimport asyncio\nimport atexit\nimport os\nimport select\nimport signal\nimport sys\nfrom path"
},
{
"path": "nanobot/nanobot/config/__init__.py",
"chars": 201,
"preview": "\"\"\"Configuration module for nanobot.\"\"\"\n\nfrom nanobot.config.loader import get_config_path, load_config\nfrom nanobot.con"
},
{
"path": "nanobot/nanobot/config/loader.py",
"chars": 3137,
"preview": "\"\"\"Configuration loading utilities.\"\"\"\n\nimport json\nfrom pathlib import Path\nfrom typing import Any\n\nfrom nanobot.config"
},
{
"path": "nanobot/nanobot/config/schema.py",
"chars": 9779,
"preview": "\"\"\"Configuration schema using Pydantic.\"\"\"\n\nfrom pathlib import Path\n\nfrom pydantic import BaseModel, Field\nfrom pydanti"
},
{
"path": "nanobot/nanobot/cron/__init__.py",
"chars": 199,
"preview": "\"\"\"Cron service for scheduled agent tasks.\"\"\"\n\nfrom nanobot.cron.service import CronService\nfrom nanobot.cron.types impo"
},
{
"path": "nanobot/nanobot/cron/service.py",
"chars": 11923,
"preview": "\"\"\"Cron service for scheduling agent tasks.\"\"\"\n\nimport asyncio\nimport json\nimport time\nimport uuid\nfrom pathlib import P"
},
{
"path": "nanobot/nanobot/cron/types.py",
"chars": 1591,
"preview": "\"\"\"Cron types.\"\"\"\n\nfrom dataclasses import dataclass, field\nfrom typing import Literal\n\n\n@dataclass\nclass CronSchedule:\n"
},
{
"path": "nanobot/nanobot/heartbeat/__init__.py",
"chars": 141,
"preview": "\"\"\"Heartbeat service for periodic agent wake-ups.\"\"\"\n\nfrom nanobot.heartbeat.service import HeartbeatService\n\n__all__ = "
},
{
"path": "nanobot/nanobot/heartbeat/service.py",
"chars": 4193,
"preview": "\"\"\"Heartbeat service - periodic agent wake-up to check for tasks.\"\"\"\n\nimport asyncio\nfrom pathlib import Path\nfrom typin"
},
{
"path": "nanobot/nanobot/providers/__init__.py",
"chars": 224,
"preview": "\"\"\"LLM provider abstraction module.\"\"\"\n\nfrom nanobot.providers.base import LLMProvider, LLMResponse\nfrom nanobot.provide"
},
{
"path": "nanobot/nanobot/providers/base.py",
"chars": 1933,
"preview": "\"\"\"Base LLM provider interface.\"\"\"\n\nfrom abc import ABC, abstractmethod\nfrom dataclasses import dataclass, field\nfrom ty"
},
{
"path": "nanobot/nanobot/providers/litellm_provider.py",
"chars": 7244,
"preview": "\"\"\"LiteLLM provider implementation for multi-provider support.\"\"\"\n\nimport json\nimport os\nfrom typing import Any\n\nimport "
},
{
"path": "nanobot/nanobot/providers/registry.py",
"chars": 11570,
"preview": "\"\"\"\nProvider Registry — single source of truth for LLM provider metadata.\n\nAdding a new provider:\n 1. Add a ProviderSpe"
},
{
"path": "nanobot/nanobot/providers/transcription.py",
"chars": 1818,
"preview": "\"\"\"Voice transcription provider using Groq.\"\"\"\n\nimport os\nfrom pathlib import Path\n\nimport httpx\nfrom loguru import logg"
},
{
"path": "nanobot/nanobot/session/__init__.py",
"chars": 135,
"preview": "\"\"\"Session management module.\"\"\"\n\nfrom nanobot.session.manager import Session, SessionManager\n\n__all__ = [\"SessionManage"
},
{
"path": "nanobot/nanobot/session/manager.py",
"chars": 6224,
"preview": "\"\"\"Session management for conversation history.\"\"\"\n\nimport json\nfrom dataclasses import dataclass, field\nfrom datetime i"
},
{
"path": "nanobot/nanobot/skills/README.md",
"chars": 798,
"preview": "# nanobot Skills\n\nThis directory contains built-in skills that extend nanobot's capabilities.\n\n## Skill Format\n\nEach ski"
},
{
"path": "nanobot/nanobot/skills/cron/SKILL.md",
"chars": 870,
"preview": "---\nname: cron\ndescription: Schedule reminders and recurring tasks.\n---\n\n# Cron\n\nUse the `cron` tool to schedule reminde"
},
{
"path": "nanobot/nanobot/skills/deepcode/SKILL.md",
"chars": 3343,
"preview": "---\nname: deepcode\ndescription: \"DeepCode integration - automated code generation from papers and text requirements\"\nmet"
},
{
"path": "nanobot/nanobot/skills/github/SKILL.md",
"chars": 1371,
"preview": "---\nname: github\ndescription: \"Interact with GitHub using the `gh` CLI. Use `gh issue`, `gh pr`, `gh run`, and `gh api` "
},
{
"path": "nanobot/nanobot/skills/skill-creator/SKILL.md",
"chars": 18324,
"preview": "---\nname: skill-creator\ndescription: Create or update AgentSkills. Use when designing, structuring, or packaging skills "
},
{
"path": "nanobot/nanobot/skills/summarize/SKILL.md",
"chars": 2013,
"preview": "---\nname: summarize\ndescription: Summarize or extract text/transcripts from URLs, podcasts, and local files (great fallb"
},
{
"path": "nanobot/nanobot/skills/tmux/SKILL.md",
"chars": 4056,
"preview": "---\nname: tmux\ndescription: Remote-control tmux sessions for interactive CLIs by sending keystrokes and scraping pane ou"
},
{
"path": "nanobot/nanobot/skills/tmux/scripts/find-sessions.sh",
"chars": 2942,
"preview": "#!/usr/bin/env bash\nset -euo pipefail\n\nusage() {\n cat <<'USAGE'\nUsage: find-sessions.sh [-L socket-name|-S socket-path|"
},
{
"path": "nanobot/nanobot/skills/tmux/scripts/wait-for-text.sh",
"chars": 2139,
"preview": "#!/usr/bin/env bash\nset -euo pipefail\n\nusage() {\n cat <<'USAGE'\nUsage: wait-for-text.sh -t target -p pattern [options]\n"
},
{
"path": "nanobot/nanobot/skills/weather/SKILL.md",
"chars": 1145,
"preview": "---\nname: weather\ndescription: Get current weather and forecasts (no API key required).\nhomepage: https://wttr.in/:help\n"
},
{
"path": "nanobot/nanobot/utils/__init__.py",
"chars": 183,
"preview": "\"\"\"Utility functions for nanobot.\"\"\"\n\nfrom nanobot.utils.helpers import ensure_dir, get_data_path, get_workspace_path\n\n_"
},
{
"path": "nanobot/nanobot/utils/helpers.py",
"chars": 2408,
"preview": "\"\"\"Utility functions for nanobot.\"\"\"\n\nfrom datetime import datetime\nfrom pathlib import Path\n\n\ndef ensure_dir(path: Path"
},
{
"path": "nanobot/pyproject.toml",
"chars": 1853,
"preview": "[project]\nname = \"nanobot-ai\"\nversion = \"0.1.3.post5\"\ndescription = \"A lightweight personal AI assistant framework\"\nrequ"
},
{
"path": "nanobot/run_nanobot.sh",
"chars": 10355,
"preview": "#!/bin/bash\n# ============================================================\n# Nanobot + DeepCode 一键启动脚本\n# 自动检查环境、配置、构建 Do"
},
{
"path": "nanobot/workspace/AGENTS.md",
"chars": 1690,
"preview": "# Agent Instructions\n\nYou are a helpful AI assistant. Be concise, accurate, and friendly.\n\n## Guidelines\n\n- Always expla"
},
{
"path": "nanobot/workspace/HEARTBEAT.md",
"chars": 369,
"preview": "# Heartbeat Tasks\n\nThis file is checked every 30 minutes by your nanobot agent.\nAdd tasks below that you want the agent "
},
{
"path": "nanobot/workspace/SOUL.md",
"chars": 350,
"preview": "# Soul\n\nI am nanobot 🐈, a personal AI assistant.\n\n## Personality\n\n- Helpful and friendly\n- Concise and to the point\n- Cu"
},
{
"path": "nanobot/workspace/TOOLS.md",
"chars": 3366,
"preview": "# Available Tools\n\nThis document describes the tools available to nanobot.\n\n## File Operations\n\n### read_file\nRead the c"
},
{
"path": "nanobot/workspace/USER.md",
"chars": 839,
"preview": "# User Profile\n\nInformation about the user to help personalize interactions.\n\n## Basic Information\n\n- **Name**: (your na"
},
{
"path": "nanobot/workspace/memory/MEMORY.md",
"chars": 408,
"preview": "# Long-term Memory\n\nThis file stores important information that should persist across sessions.\n\n## User Information\n\n(I"
},
{
"path": "nanobot_config.json.example",
"chars": 1127,
"preview": "{\n \"_comment\": \"nanobot configuration for DeepCode integration. Copy to nanobot_config.json and fill in your keys.\",\n "
},
{
"path": "new_ui/README.md",
"chars": 3873,
"preview": "# DeepCode New UI\n\nModern, intelligent UI for DeepCode - AI-powered code generation platform.\n\n## Technology Stack\n\n- **"
},
{
"path": "new_ui/backend/__init__.py",
"chars": 101,
"preview": "\"\"\"\nDeepCode New UI Backend\nFastAPI-based backend for the new DeepCode UI\n\"\"\"\n\n__version__ = \"1.0.0\"\n"
},
{
"path": "new_ui/backend/api/__init__.py",
"chars": 18,
"preview": "\"\"\"API package\"\"\"\n"
},
{
"path": "new_ui/backend/api/routes/__init__.py",
"chars": 17,
"preview": "\"\"\"API Routes\"\"\"\n"
},
{
"path": "new_ui/backend/api/routes/config.py",
"chars": 2580,
"preview": "\"\"\"\nConfiguration API Routes\nHandles LLM provider and settings management\n\"\"\"\n\nfrom fastapi import APIRouter, HTTPExcept"
},
{
"path": "new_ui/backend/api/routes/files.py",
"chars": 3628,
"preview": "\"\"\"\nFiles API Routes\nHandles file upload and download operations\n\"\"\"\n\nimport uuid\nimport shutil\nfrom pathlib import Path"
},
{
"path": "new_ui/backend/api/routes/requirements.py",
"chars": 2235,
"preview": "\"\"\"\nRequirements API Routes\nHandles requirement analysis operations\n\"\"\"\n\nfrom fastapi import APIRouter, HTTPException\n\nf"
},
{
"path": "new_ui/backend/api/routes/workflows.py",
"chars": 6270,
"preview": "\"\"\"\nWorkflows API Routes\nHandles paper-to-code and chat-based planning workflows\n\"\"\"\n\nfrom fastapi import APIRouter, Bac"
},
{
"path": "new_ui/backend/api/websockets/__init__.py",
"chars": 25,
"preview": "\"\"\"WebSocket handlers\"\"\"\n"
},
{
"path": "new_ui/backend/api/websockets/code_stream_ws.py",
"chars": 5445,
"preview": "\"\"\"\nCode Stream WebSocket Handler\nProvides real-time streaming of generated code\n\"\"\"\n\nimport asyncio\nfrom datetime impor"
},
{
"path": "new_ui/backend/api/websockets/logs_ws.py",
"chars": 4064,
"preview": "\"\"\"\nLogs WebSocket Handler\nProvides real-time log streaming\n\"\"\"\n\nimport asyncio\nimport json\nfrom datetime import datetim"
},
{
"path": "new_ui/backend/api/websockets/workflow_ws.py",
"chars": 6477,
"preview": "\"\"\"\nWorkflow WebSocket Handler\nProvides real-time progress updates for running workflows\n\"\"\"\n\nimport asyncio\nfrom dateti"
},
{
"path": "new_ui/backend/app_utils/__init__.py",
"chars": 20,
"preview": "\"\"\"Utils package\"\"\"\n"
},
{
"path": "new_ui/backend/main.py",
"chars": 5596,
"preview": "\"\"\"\nDeepCode New UI - FastAPI Backend Entry Point\n\nSupports two modes:\n - Development: Frontend runs on Vite dev server"
},
{
"path": "new_ui/backend/models/__init__.py",
"chars": 937,
"preview": "\"\"\"Models package\"\"\"\n\nfrom .requests import (\n PaperToCodeRequest,\n ChatPlanningRequest,\n GenerateQuestionsRequ"
},
{
"path": "new_ui/backend/models/requests.py",
"chars": 2270,
"preview": "\"\"\"Request models for API endpoints\"\"\"\n\nfrom typing import Dict, Any\nfrom pydantic import BaseModel, Field\n\n\nclass Paper"
},
{
"path": "new_ui/backend/models/responses.py",
"chars": 1547,
"preview": "\"\"\"Response models for API endpoints\"\"\"\n\nfrom typing import Optional, Dict, Any, List\nfrom datetime import datetime\nfrom"
},
{
"path": "new_ui/backend/services/__init__.py",
"chars": 23,
"preview": "\"\"\"Services package\"\"\"\n"
},
{
"path": "new_ui/backend/services/requirement_service.py",
"chars": 3891,
"preview": "\"\"\"\nRequirement Analysis Service\nIntegration with existing requirement analysis workflow\n\nNOTE: This module uses lazy im"
},
{
"path": "new_ui/backend/services/session_service.py",
"chars": 3718,
"preview": "\"\"\"\nSession Service\nManages user sessions and conversation history\n\"\"\"\n\nimport uuid\nfrom datetime import datetime, timed"
},
{
"path": "new_ui/backend/services/workflow_service.py",
"chars": 14953,
"preview": "\"\"\"\nWorkflow Service - Integration with existing DeepCode workflows\n\nNOTE: This module uses lazy imports for DeepCode mo"
},
{
"path": "new_ui/backend/settings.py",
"chars": 2754,
"preview": "\"\"\"\nConfiguration management for DeepCode New UI Backend\nReads from existing mcp_agent.config.yaml and mcp_agent.secrets"
},
{
"path": "new_ui/frontend/index.html",
"chars": 789,
"preview": "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\" />\n <link rel=\"icon\" type=\"image/svg+xml\" href=\"h"
},
{
"path": "new_ui/frontend/package.json",
"chars": 1474,
"preview": "{\n \"name\": \"deepcode-new-ui\",\n \"private\": true,\n \"version\": \"1.0.0\",\n \"type\": \"module\",\n \"scripts\": {\n \"dev\": \"v"
},
{
"path": "new_ui/frontend/postcss.config.js",
"chars": 80,
"preview": "export default {\n plugins: {\n tailwindcss: {},\n autoprefixer: {},\n },\n}\n"
},
{
"path": "new_ui/frontend/src/App.tsx",
"chars": 926,
"preview": "import { BrowserRouter, Routes, Route } from 'react-router-dom'\nimport { Toaster } from './components/common/Toaster'\nim"
},
{
"path": "new_ui/frontend/src/components/common/Button.tsx",
"chars": 1588,
"preview": "import { ButtonHTMLAttributes, forwardRef } from 'react';\nimport { clsx } from 'clsx';\nimport { Loader2 } from 'lucide-r"
},
{
"path": "new_ui/frontend/src/components/common/Card.tsx",
"chars": 564,
"preview": "import { ReactNode } from 'react';\nimport { clsx } from 'clsx';\n\ninterface CardProps {\n children: ReactNode;\n classNam"
},
{
"path": "new_ui/frontend/src/components/common/ConfirmDialog.tsx",
"chars": 3207,
"preview": "/**\n * Confirm Dialog Component\n *\n * A reusable confirmation dialog for destructive or important actions.\n */\n\nimport {"
},
{
"path": "new_ui/frontend/src/components/common/GuardedLink.tsx",
"chars": 1782,
"preview": "/**\n * Guarded Link Component\n *\n * A Link component that respects the navigation guard.\n * Shows confirmation dialog wh"
},
{
"path": "new_ui/frontend/src/components/common/TaskRecoveryBanner.tsx",
"chars": 2589,
"preview": "/**\n * Task Recovery Banner\n *\n * Shows a notification when a running task is recovered after page refresh.\n */\n\nimport "
},
{
"path": "new_ui/frontend/src/components/common/Toaster.tsx",
"chars": 3464,
"preview": "import { useEffect, useState } from 'react';\nimport { X, CheckCircle, AlertCircle, Info, AlertTriangle } from 'lucide-re"
},
{
"path": "new_ui/frontend/src/components/common/index.ts",
"chars": 132,
"preview": "export { default as Button } from './Button';\nexport { default as Card } from './Card';\nexport { Toaster, toast } from '"
},
{
"path": "new_ui/frontend/src/components/input/ChatInput.tsx",
"chars": 2676,
"preview": "import { useState, useRef, KeyboardEvent } from 'react';\nimport { Send, Loader2 } from 'lucide-react';\nimport { motion }"
},
{
"path": "new_ui/frontend/src/components/input/FileUploader.tsx",
"chars": 6150,
"preview": "import { useCallback, useState } from 'react';\nimport { Upload, File, X, Loader2 } from 'lucide-react';\nimport { motion,"
},
{
"path": "new_ui/frontend/src/components/input/UrlInput.tsx",
"chars": 3369,
"preview": "import { useState } from 'react';\nimport { Link2, Check, X, Loader2 } from 'lucide-react';\nimport { motion, AnimatePrese"
},
{
"path": "new_ui/frontend/src/components/input/index.ts",
"chars": 160,
"preview": "export { default as FileUploader } from './FileUploader';\nexport { default as ChatInput } from './ChatInput';\nexport { d"
},
{
"path": "new_ui/frontend/src/components/interaction/InlineChatInteraction.tsx",
"chars": 10255,
"preview": "/**\n * InlineChatInteraction Component\n *\n * Displays User-in-Loop interactions inline within the chat flow.\n * Designed"
},
{
"path": "new_ui/frontend/src/components/interaction/InteractionPanel.tsx",
"chars": 9321,
"preview": "/**\n * InteractionPanel Component\n *\n * Displays User-in-Loop interactions from the workflow.\n * Supports different inte"
},
{
"path": "new_ui/frontend/src/components/interaction/index.ts",
"chars": 142,
"preview": "export { default as InteractionPanel } from './InteractionPanel';\nexport { default as InlineChatInteraction } from './In"
},
{
"path": "new_ui/frontend/src/components/layout/Header.tsx",
"chars": 4203,
"preview": "import { Link, useLocation, useNavigate } from 'react-router-dom';\nimport { Settings, Menu, Loader2 } from 'lucide-react"
},
{
"path": "new_ui/frontend/src/components/layout/Layout.tsx",
"chars": 1706,
"preview": "import { ReactNode, useState } from 'react';\nimport Header from './Header';\nimport Sidebar from './Sidebar';\nimport { Ta"
},
{
"path": "new_ui/frontend/src/components/layout/Sidebar.tsx",
"chars": 3754,
"preview": "import { Link, useLocation } from 'react-router-dom';\nimport {\n FileText,\n MessageSquare,\n GitBranch,\n Clock,\n Fold"
},
{
"path": "new_ui/frontend/src/components/layout/index.ts",
"chars": 140,
"preview": "export { default as Layout } from './Layout';\nexport { default as Header } from './Header';\nexport { default as Sidebar "
},
{
"path": "new_ui/frontend/src/components/results/CodePreview.tsx",
"chars": 1729,
"preview": "import Editor from '@monaco-editor/react';\nimport { Code } from 'lucide-react';\n\ninterface CodePreviewProps {\n code: st"
},
{
"path": "new_ui/frontend/src/components/results/FileTree.tsx",
"chars": 5126,
"preview": "import { useState } from 'react';\nimport { ChevronRight, ChevronDown, File, Folder, FolderOpen } from 'lucide-react';\nim"
},
{
"path": "new_ui/frontend/src/components/results/index.ts",
"chars": 106,
"preview": "export { default as CodePreview } from './CodePreview';\nexport { default as FileTree } from './FileTree';\n"
},
{
"path": "new_ui/frontend/src/components/streaming/ActivityLogViewer.tsx",
"chars": 6712,
"preview": "/**\n * Activity Log Viewer\n *\n * Displays real-time activity logs from the backend workflow.\n * Shows progress messages,"
},
{
"path": "new_ui/frontend/src/components/streaming/CodeStreamViewer.tsx",
"chars": 5012,
"preview": "import { useEffect, useRef } from 'react';\nimport Editor from '@monaco-editor/react';\nimport { motion } from 'framer-mot"
},
{
"path": "new_ui/frontend/src/components/streaming/LogViewer.tsx",
"chars": 4954,
"preview": "import { useEffect, useRef, useState } from 'react';\nimport { motion, AnimatePresence } from 'framer-motion';\nimport { T"
},
{
"path": "new_ui/frontend/src/components/streaming/ProgressTracker.tsx",
"chars": 2993,
"preview": "import { motion } from 'framer-motion';\nimport { CheckCircle, Circle, Loader2, XCircle } from 'lucide-react';\nimport typ"
},
{
"path": "new_ui/frontend/src/components/streaming/index.ts",
"chars": 250,
"preview": "export { default as CodeStreamViewer } from './CodeStreamViewer';\nexport { default as ProgressTracker } from './Progress"
},
{
"path": "new_ui/frontend/src/components/workflow/WorkflowCanvas.tsx",
"chars": 2640,
"preview": "import { useCallback } from 'react';\nimport ReactFlow, {\n Node,\n Edge,\n Controls,\n MiniMap,\n Background,\n useNodes"
},
{
"path": "new_ui/frontend/src/components/workflow/WorkflowNode.tsx",
"chars": 2574,
"preview": "import { memo } from 'react';\nimport { Handle, Position, NodeProps } from 'reactflow';\nimport { CheckCircle, Circle, Loa"
},
{
"path": "new_ui/frontend/src/components/workflow/index.ts",
"chars": 120,
"preview": "export { default as WorkflowCanvas } from './WorkflowCanvas';\nexport { default as WorkflowNode } from './WorkflowNode';\n"
},
{
"path": "new_ui/frontend/src/hooks/index.ts",
"chars": 151,
"preview": "export { useWebSocket } from './useWebSocket';\nexport { useStreaming } from './useStreaming';\nexport { useAdaptiveLayout"
},
{
"path": "new_ui/frontend/src/hooks/useAdaptiveLayout.ts",
"chars": 795,
"preview": "import { useMemo } from 'react';\nimport type { TaskType, LayoutConfig } from '../types/common';\n\nconst layoutConfigs: Re"
},
{
"path": "new_ui/frontend/src/hooks/useNavigationGuard.ts",
"chars": 2822,
"preview": "/**\n * Navigation Guard Hook\n *\n * Prevents accidental navigation away from a page when a task is running.\n * - Shows br"
},
{
"path": "new_ui/frontend/src/hooks/useStreaming.ts",
"chars": 6532,
"preview": "import { useEffect, useCallback, useRef } from 'react';\nimport { useWebSocket } from './useWebSocket';\nimport { useWorkf"
},
{
"path": "new_ui/frontend/src/hooks/useTaskRecovery.ts",
"chars": 4871,
"preview": "/**\n * Task Recovery Hook\n *\n * Handles automatic recovery of running tasks after page refresh.\n *\n * Flow:\n * 1. On mou"
},
{
"path": "new_ui/frontend/src/hooks/useWebSocket.ts",
"chars": 3919,
"preview": "import { useEffect, useRef, useCallback, useState } from 'react';\nimport type { WSMessage } from '../types/api';\n\ninterf"
},
{
"path": "new_ui/frontend/src/index.css",
"chars": 1890,
"preview": "@tailwind base;\n@tailwind components;\n@tailwind utilities;\n\n@layer base {\n :root {\n --border-color: #e5e7eb;\n }\n\n "
},
{
"path": "new_ui/frontend/src/main.tsx",
"chars": 531,
"preview": "import React from 'react'\nimport ReactDOM from 'react-dom/client'\nimport { QueryClient, QueryClientProvider } from '@tan"
},
{
"path": "new_ui/frontend/src/pages/ChatPlanningPage.tsx",
"chars": 12963,
"preview": "import { useState, useEffect, useRef } from 'react';\nimport { motion, AnimatePresence } from 'framer-motion';\nimport { C"
},
{
"path": "new_ui/frontend/src/pages/HomePage.tsx",
"chars": 5115,
"preview": "import { Link } from 'react-router-dom';\nimport { motion } from 'framer-motion';\nimport {\n FileText,\n MessageSquare,\n "
},
{
"path": "new_ui/frontend/src/pages/PaperToCodePage.tsx",
"chars": 10625,
"preview": "import { useState, useEffect } from 'react';\nimport { motion, AnimatePresence } from 'framer-motion';\nimport { Card, But"
},
{
"path": "new_ui/frontend/src/pages/SettingsPage.tsx",
"chars": 6709,
"preview": "import { useState, useEffect } from 'react';\nimport { motion } from 'framer-motion';\nimport { useQuery, useMutation, use"
},
{
"path": "new_ui/frontend/src/pages/WorkflowEditorPage.tsx",
"chars": 3969,
"preview": "import { motion } from 'framer-motion';\nimport { Card } from '../components/common';\nimport { WorkflowCanvas } from '../"
},
{
"path": "new_ui/frontend/src/pages/index.ts",
"chars": 308,
"preview": "export { default as HomePage } from './HomePage';\nexport { default as PaperToCodePage } from './PaperToCodePage';\nexport"
},
{
"path": "new_ui/frontend/src/services/api.ts",
"chars": 5171,
"preview": "import axios from 'axios';\nimport type {\n TaskResponse,\n WorkflowStatusResponse,\n QuestionsResponse,\n RequirementsSu"
},
{
"path": "new_ui/frontend/src/stores/index.ts",
"chars": 102,
"preview": "export { useWorkflowStore } from './workflowStore';\nexport { useSessionStore } from './sessionStore';\n"
},
{
"path": "new_ui/frontend/src/stores/sessionStore.ts",
"chars": 2139,
"preview": "import { create } from 'zustand';\nimport { persist } from 'zustand/middleware';\nimport type { Message } from '../types/c"
},
{
"path": "new_ui/frontend/src/stores/workflowStore.ts",
"chars": 6885,
"preview": "import { create } from 'zustand';\nimport { persist } from 'zustand/middleware';\nimport type {\n WorkflowStatus,\n Workfl"
},
{
"path": "new_ui/frontend/src/types/api.ts",
"chars": 2621,
"preview": "// API types\n\nexport interface TaskResponse {\n task_id: string;\n status: string;\n message: string;\n created_at?: str"
},
{
"path": "new_ui/frontend/src/types/common.ts",
"chars": 572,
"preview": "// Common types\n\nexport interface Message {\n id: string;\n role: 'user' | 'assistant' | 'system';\n content: string;\n "
},
{
"path": "new_ui/frontend/src/types/index.ts",
"chars": 77,
"preview": "export * from './workflow';\nexport * from './api';\nexport * from './common';\n"
},
{
"path": "new_ui/frontend/src/types/workflow.ts",
"chars": 2035,
"preview": "// Workflow types\n\nexport type WorkflowStatus = 'idle' | 'running' | 'completed' | 'error' | 'cancelled';\n\nexport interf"
},
{
"path": "new_ui/frontend/tailwind.config.js",
"chars": 1409,
"preview": "/** @type {import('tailwindcss').Config} */\nexport default {\n content: [\n \"./index.html\",\n \"./src/**/*.{js,ts,jsx"
},
{
"path": "new_ui/frontend/tsconfig.json",
"chars": 627,
"preview": "{\n \"compilerOptions\": {\n \"target\": \"ES2020\",\n \"useDefineForClassFields\": true,\n \"lib\": [\"ES2020\", \"DOM\", \"DOM."
},
{
"path": "new_ui/frontend/tsconfig.node.json",
"chars": 213,
"preview": "{\n \"compilerOptions\": {\n \"composite\": true,\n \"skipLibCheck\": true,\n \"module\": \"ESNext\",\n \"moduleResolution\""
},
{
"path": "new_ui/frontend/vite.config.ts",
"chars": 498,
"preview": "import { defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react'\nimport path from 'path'\n\n// https://vitejs."
}
]
// ... and 55 more files (download for full content)
About this extraction
This page contains the full source code of the HKUDS/DeepCode GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 255 files (2.0 MB), approximately 544.2k tokens, and a symbol index with 1398 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.