Metadata-Version: 2.4
Name: dundun-agent
Version: 1.1.2
Summary: Dundun Agent - AI-powered coding assistant
License: MIT License
        
        Copyright (c) 2025 Agent Developer
        
        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.
        
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: openai>=1.0.0
Requires-Dist: anthropic>=0.76.0
Requires-Dist: httpx>=0.25.0
Requires-Dist: tiktoken>=0.7.0
Requires-Dist: pydantic>=2.0.0
Requires-Dist: typer>=0.9.0
Requires-Dist: rich>=14.0.0
Requires-Dist: textual>=0.80.0
Requires-Dist: prompt_toolkit>=3.0.0
Requires-Dist: tenacity>=8.0.0
Requires-Dist: python-dotenv>=1.0.0
Requires-Dist: pyyaml>=6.0.0
Requires-Dist: mcp>=1.0.0
Requires-Dist: aiohttp>=3.9.0
Requires-Dist: fastapi>=0.104.0
Requires-Dist: uvicorn[standard]>=0.24.0
Requires-Dist: websockets>=12.0
Dynamic: license-file
Dynamic: requires-python

# Dundun Agent

<div align="center">

**一个模块化、可扩展的 AI 编程助手**

采用 Python 原生架构，支持多 Agent 协作、工具调用和 WebSocket 实时通信

[![Python Version](https://img.shields.io/badge/python-3.10+-blue.svg)](https://www.python.org/downloads/)
[![License](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE)

</div>

---

## ✨ 特性

### 🎯 核心能力

- **多 Agent 架构**：支持 Build、Plan、Explore、General 等多种专业 Agent
- **丰富的工具系统**：文件操作、系统命令、网络搜索、LSP 代码导航、子 Agent 调用等
- **智能权限管理**：细粒度的工具调用权限控制，支持交互式授权和持久化记忆
- **会话管理**：支持多会话、会话切换、上下文自动压缩
- **实时通信**：基于 WebSocket 的 C/S 架构，支持流式输出和事件驱动

### 🚀 扩展能力

- **Skill 系统**：可扩展的领域知识框架
- **MCP 集成**：支持 Model Context Protocol 服务器
- **Todo 管理**：内置任务跟踪系统
- **多搜索引擎**：支持 DuckDuckGo、Bing、Vertex AI 等
- **Rocket.Chat 集成**：通过 Bridge 进程桥接 Rocket.Chat，支持 @mention、私信、斜杠命令

---

## 🏗️ 系统架构

### 整体架构

```
┌─────────────────────────────────────────────────────────────┐
│                      用户交互层                               │
│   CLI / TUI (Rich) - 命令解析、渲染、用户交互                 │
└─────────────────────────────────────────────────────────────┘
                          │ WebSocket
                          ▼
┌─────────────────────────────────────────────────────────────┐
│                    服务端层 (FastAPI)                        │
│   WebSocket Handler - 消息路由、事件转发、连接管理            │
│   Session Manager - 会话生命周期、Agent 实例管理              │
│   Interaction Manager - 权限授权、用户确认、用户输入           │
└─────────────────────────────────────────────────────────────┘
                          │
                          ▼
┌─────────────────────────────────────────────────────────────┐
│                      Agent 层                                │
│   AgentSession (ReAct 循环) - 多轮对话、工具调用、死循环检测   │
│   Agent 类型 - Build / Plan / Explore / General              │
└─────────────────────────────────────────────────────────────┘
                          │
                          ▼
┌─────────────────────────────────────────────────────────────┐
│                      工具层                                  │
│   文件工具 (read/write/edit/glob/grep)                       │
│   系统工具 (bash)                                            │
│   网络工具 (websearch/webfetch)                              │
│   Agent 工具 (task/sub-agent)                                │
│   辅助工具 (todo/skill/mcp/lsp/codesearch)                   │
└─────────────────────────────────────────────────────────────┘
                          │
                          ▼
┌─────────────────────────────────────────────────────────────┐
│                      支撑层                                  │
│   LLM Client (Anthropic/OpenAI)                             │
│   Permission Manager (权限管理)                              │
│   Context Manager (上下文管理)                               │
│   Config / Logger / Session ID                              │
└─────────────────────────────────────────────────────────────┘
```

### 核心模块

| 模块 | 路径 | 职责 |
|------|------|------|
| **WebSocket Handler** | `src/server/handler.py` | 处理 WebSocket 连接、消息路由、事件转发 |
| **Session Manager** | `src/server/session.py` | 管理会话生命周期、Agent 实例 |
| **AgentSession** | `src/server/agent_session.py` | ReAct 循环、工具调用、上下文管理 |
| **Interaction Manager** | `src/core/interaction.py` | 统一交互管理（权限、确认、输入） |
| **Permission Manager** | `src/core/permission.py` | 权限规则、缓存、用户询问 |
| **Tool Registry** | `src/tools/registry.py` | 工具注册、权限过滤 |
| **LLM Client** | `src/provider/` | Anthropic/OpenAI 客户端封装 |

---

## 🚀 快速开始

### 环境要求

- Python 3.10+
- pip 或 uv 包管理器

### 安装

```bash
# 方式 1：从 PyPI 安装（发布后）
pip install dundun-agent

# 方式 2：从源码安装（开发者）
git clone <repository-url>
cd dundun-agent
pip install -r requirements.txt
pip install -e .

# 配置环境变量
cp .env.example .env
# 编辑 .env 设置 API 密钥
```

### 启动

```bash
# 方式 1: 统一入口（推荐）- 同时启动服务端和客户端
python -m src.main

# 方式 2: 只启动客户端，连接到已有服务端
python -m src.main --server localhost:8367

# 方式 3: 只启动服务端
python -m src.main --server-only --port 8367

# 调试模式
python -m src.main --debug
```

### 命令行选项

| 选项 | 说明 |
|------|------|
| `--server, -s` | 服务端地址，指定后只启动客户端 |
| `--server-only` | 只启动服务端 |
| `--port, -p` | 服务端端口（默认 8367） |
| `--host` | 服务端绑定地址（默认 0.0.0.0） |
| `--debug, -d` | 调试模式 |

---

## 📖 使用指南

### 交互命令

**系统命令：**

| 命令 | 别名 | 说明 |
|------|------|------|
| `/help` | `/h`, `/?` | 显示帮助 |
| `/exit` | `/quit`, `/q` | 退出程序 |
| `/clear` | `/cls` | 清屏 |
| `/status` | - | 显示状态 |

**会话命令：**

| 命令 | 说明 |
|------|------|
| `/session` | 显示当前会话 |
| `/session list` | 列出所有会话 |
| `/session new [title]` | 创建新会话 |
| `/session switch <id>` | 切换会话 |
| `/compact` | 压缩上下文 |
| `/history [n]` | 显示历史 |

**Agent 命令：**

| 命令 | 说明 |
|------|------|
| `/model` | 显示当前 Agent |
| `/model <type>` | 切换 Agent（build/plan/general/explore） |

**工具命令：**

| 命令 | 说明 |
|------|------|
| `/tools` | 列出可用工具 |
| `/todo` | 显示待办事项 |

### Agent 类型

| Agent | 说明 | 特点 |
|-------|------|------|
| **build** | 编程专家（默认） | 全功能，专注于软件开发任务 |
| **plan** | 规划分析 | 只读模式，专注于任务分析和设计 |
| **general** | 通用助手 | 任务执行、工具调用、自主规划、可调用子 Agent |
| **explore** | 代码探索 | 只读，用于代码库探索（子 Agent） |

### 示例任务

```bash
# 代码分析
> 分析 src/core/agent.py 的架构设计

# 文件操作
> 创建一个 Python 脚本实现快速排序

# 代码搜索
> 查找所有使用 async def 的函数

# 网络搜索
> 搜索 Python 3.12 的新特性

# 任务规划
> 帮我规划一个重构方案，将配置管理模块化
```

---

## 📁 项目结构

```
dundun-agent/
├── src/
│   ├── main.py                 # 统一启动入口
│   │
│   ├── core/                   # 核心模块
│   │   ├── config.py           # 配置加载
│   │   ├── session.py          # 会话管理
│   │   ├── permission.py       # 权限系统
│   │   ├── interaction.py      # 交互管理器
│   │   ├── context.py          # 上下文管理
│   │   ├── prompt.py           # 提示词系统
│   │   ├── session_id.py       # 会话 ID 生成
│   │   ├── agent_registry.py   # Agent 注册表
│   │   ├── agent.py            # Agent 配置管理
│   │   ├── memory.py           # 内存管理
│   │   ├── message.py          # 消息定义
│   │   ├── logger.py           # 日志系统
│   │   ├── todo.py             # Todo 管理
│   │   ├── skill.py            # Skill 系统
│   │   ├── mcp_manager.py      # MCP 管理
│   │   └── paths.py            # 路径管理
│   │
│   ├── provider/               # LLM 客户端
│   │   ├── base.py             # 基类定义
│   │   ├── factory.py          # 客户端工厂
│   │   ├── anthropic_client.py # Anthropic 客户端
│   │   └── openai_client.py    # OpenAI 客户端
│   │
│   ├── server/                 # 服务端
│   │   ├── app.py              # FastAPI 应用
│   │   ├── handler.py          # WebSocket 处理器
│   │   ├── session.py          # 服务端会话管理
│   │   ├── agent_session.py    # Agent 会话（ReAct 循环）
│   │   └── constants.py        # 常量定义
│   │
│   ├── interface/              # 客户端
│   │   ├── cli.py              # CLI 入口
│   │   ├── tui.py              # TUI 界面
│   │   ├── renderer.py         # Rich 渲染器
│   │   ├── commands.py         # 斜杠命令
│   │   └── websocket_client.py # WebSocket 客户端
│   │
│   ├── tools/                  # 工具系统
│   │   ├── base.py             # 工具基类
│   │   ├── registry.py         # 工具注册表
│   │   ├── filesystem.py       # 文件工具
│   │   ├── system.py           # 系统工具
│   │   ├── web_tools.py        # 网络工具
│   │   ├── task_tool.py        # 子 Agent 工具
│   │   ├── todo_tool.py        # Todo 工具
│   │   ├── skill_tool.py       # Skill 工具
│   │   ├── mcp_tool.py         # MCP 工具
│   │   ├── agent_tool.py       # Agent 工具
│   │   ├── lsp_tool.py         # LSP 工具
│   │   └── codesearch_tool.py  # 代码搜索工具
│   │
│   ├── agents/                 # Agent 实现
│   │   ├── base.py             # Agent 基类
│   │   ├── build.py            # 编程 Agent
│   │   ├── plan.py             # 规划 Agent
│   │   ├── explore.py          # 探索 Agent
│   │   └── general.py          # 通用 Agent
│   │
│   ├── lsp/                    # LSP 支持
│   │   ├── server.py           # LSP 服务器
│   │   ├── client.py           # LSP 客户端
│   │   ├── protocol.py         # LSP 协议
│   │   └── manager.py          # LSP 管理器
│   │
│   └── integrations/           # 外部集成
│       └── rocketchat_bridge.py # Rocket.Chat Bridge
│
├── src/assets/config/          # 配置文件（权限规则等）
│   └── permissions.yaml        # 权限配置
│
├── skills/                     # Skill 定义
│
├── docs/                       # 设计文档
│   ├── client-server-protocol.md
│   └── rocketchat.md           # Rocket.Chat Bridge 文档
│
├── tests/                      # 测试
│
├── .dundun/                     # 本地运行状态/配置
│   └── logs/                    # 日志
│
├── requirements.txt            # 依赖
├── setup.py                    # 安装配置（兼容）
├── pyproject.toml              # 现代打包配置
├── .env.example                # 环境变量示例
├── LICENSE                     # MIT 许可证
└── README.md                   # 本文件
```

---

## ⚙️ 配置说明

### LLM 配置 (.dundun/config.json)

```json
{
  "provider": {
    "anthropic": {
      "api_key": "${ANTHROPIC_API_KEY}",
      "context_window": 200000
    },
    "openai": {
      "api_key": "${OPENAI_API_KEY}",
      "context_window": 128000
    },
    "glm": {
      "api_key": "${GLM_API_KEY}"
    },
    "default": "anthropic/claude-opus-4-6"
  }
}
```

说明：`context_window` 是 provider 级的默认上下文窗口，主要用于你配置了自定义模型但内置模型库里没有该模型的上下文信息时提供默认值；不会覆盖内置模型自带的 `context_window`。

`models` 支持两种写法：
- 裸模型名（推荐放在对应 provider 段内）：例如在 `anthropic` 段里写 `"ceshi"`，会自动补齐为 `anthropic/ceshi`
- 全限定名：`"anthropic/ceshi"`（provider 前缀必须与段名一致，否则启动报错）

### 环境变量 (.env)

```bash
# Anthropic API Key
ANTHROPIC_API_KEY=your-api-key

# OpenAI API Key
OPENAI_API_KEY=your-api-key

# Bing Search API Key (可选)
BING_API_KEY=your-bing-key

# Google Vertex AI (可选)
VERTEX_PROJECT_ID=your-project-id
VERTEX_DATA_STORE_ID=your-data-store-id
```

### 权限规则

权限系统支持三种动作：
- `ALLOW`: 允许执行
- `DENY`: 拒绝执行
- `ASK`: 询问用户

默认规则定义在 `src/core/permission.py` 中，权限记录会自动保存到 `~/.dundun/permissions.json`。

---

## 🔌 扩展开发

### 添加新工具

```python
# src/tools/my_tool.py
from tools.base import BaseTool
from pydantic import BaseModel, Field

class MyToolInput(BaseModel):
    param: str = Field(..., description="参数说明")

class MyTool(BaseTool):
    name = "my_tool"
    description = "工具描述"
    args_schema = MyToolInput

    async def run(self, param: str) -> str:
        # 实现逻辑
        return result
```

### 添加新 Agent

```python
# src/agents/my_agent.py
from agents.base import BaseAgent
from tools.registry import ToolRegistry

class MyAgent(BaseAgent):
    @property
    def name(self) -> str:
        return "my_agent"

    @property
    def system_prompt(self) -> str:
        return "你是一个专业的..."

    def get_tools(self, registry: ToolRegistry):
        return registry.get_tools_by_mode("all")
```

### 添加新 Skill

在 `skills/` 目录创建：

```
skills/my-skill/
└── SKILL.md
```

```markdown
---
name: my-skill
description: Skill 描述
---

# Skill 内容

详细说明和示例...
```

---

## 📚 设计文档

详细设计文档位于 `docs/` 目录：

### 通信协议
- [client-server-protocol.md](docs/client-server-protocol.md) - WebSocket 协议规范

### 集成
- [rocketchat.md](docs/rocketchat.md) - Rocket.Chat Bridge 配置与使用

### 核心概念
- **ReAct 循环**：Agent 通过思考→行动→观察的循环完成任务
- **上下文管理**：自动压缩长对话，控制 token 使用
- **权限系统**：基于规则的权限控制，支持用户交互和持久化
- **事件驱动**：WebSocket 实时推送 Agent 执行状态

---

## 📝 日志

日志文件位于 `.dundun/logs/` 目录：

- `agent.log` - 主日志，包含所有事件
- `rocketchat.log` - Rocket.Chat Bridge 日志
- 支持实时查看：`tail -f .dundun/logs/agent.log`

---

## 🛠️ 开发路线

查看 [todo.md](todo.md) 了解当前开发进度和计划。

### 已完成 ✅

- ✅ LLM client 剥离为独立的 provider 模块
- ✅ 统一的日志系统
- ✅ 独立的上下文管理模块
- ✅ 扩大默认权限，支持持久化授权记录
- ✅ 默认使用 build agent
- ✅ 控制台展示随窗口大小自动调整
- ✅ Ctrl+C 中断处理
- ✅ General agent 重构为通用任务执行 Agent
- ✅ Agent 差异化配置移至 agents/ 目录
- ✅ 严格遵守 WebSocket 通信协议
- ✅ 会话记录保存到 `~/.dundun/`

### 进行中 🚧

- 持续优化和功能增强

---

## 📄 License

MIT License - 详见 [LICENSE](LICENSE) 文件

---

## 🤝 贡献

欢迎提交 Issue 和 Pull Request！

---

<div align="center">

**Made with ❤️ by the Dundun Agent team**

</div>



