Repository navigation
Development Guide
Contributing to CogitoAgent
为 CogitoAgent 做贡献
This guide is for developers who want to contribute to CogitoAgent or build custom extensions. It covers the development workflow, code structure, testing, and contribution guidelines.
本指南面向希望为 CogitoAgent 做贡献或构建自定义扩展的开发者。它涵盖了开发工作流、代码结构、测试和贡献指南。
| Tool | Version | Notes |
|---|---|---|
| Node.js | 22.12+ | Required |
| npm | 9.x+ | Required |
| Python | 3.x | Optional, for Python execution |
| Git | 2.x+ | Required |
| VS Code | Latest | Recommended IDE |
| 工具 | 版本 | 说明 |
|---|---|---|
| Node.js | 22.12+ | 必需 |
| npm | 9.x+ | 必需 |
| Python | 3.x | 可选,用于 Python 执行 |
| Git | 2.x+ | 必需 |
| VS Code | 最新 | 推荐 IDE |
# Clone the repository | 克隆仓库
git clone https://github.com/SnowLeopard-io/CogitoAgent.git
cd cogito-agent
# Install dependencies | 安装依赖
npm install
# Copy environment file | 复制环境文件
cp .env.example .env
# Run type check | 运行类型检查
npm run typecheck
# Start development server | 启动开发服务器
npm run cliCreate .vscode/launch.json for debugging:
为调试创建 .vscode/launch.json:
{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Debug CLI",
"runtimeExecutable": "npm",
"runtimeArgs": ["run", "cli"]
},
{
"type": "node",
"request": "launch",
"name": "Debug Electron",
"runtimeExecutable": "npm",
"runtimeArgs": ["run", "electron:desktop"]
}
]
}cogito-agent/
├── src/ # TypeScript source | TypeScript 源码
│ ├── agent/ # Core agent | 核心 Agent
│ │ ├── Agent.ts # Think loop | 思考循环
│ │ ├── state.ts # State machine | 状态机
│ │ ├── registry.ts # Tool registry | 工具注册表
│ │ ├── session.ts # Session manager | 会话管理
│ │ ├── commands.ts # Command handler | 命令处理
│ │ ├── stats.ts # Usage stats | 使用统计
│ │ ├── tracing.ts # Observability | 可观测性
│ │ ├── retry.ts # Circuit breaker | 熔断器
│ │ ├── mcp.ts # MCP server | MCP 服务器
│ │ ├── plugin.ts # Plugin system | 插件系统
│ │ ├── orchestrator.ts # Agent cluster | 智能体集群
│ │ ├── wechat-manager.ts # WeChat channel | 微信通道
│ │ ├── tool-parser.ts # [TOOL] parser | 工具解析器
│ │ ├── thought-trace.ts # Thought chain | 思维链
│ │ └── tools/ # 28 tool modules | 工具模块
│ │ ├── file.ts
│ │ ├── web.ts
│ │ ├── browser.ts
│ │ ├── code.ts
│ │ ├── git.ts
│ │ ├── db.ts
│ │ ├── gis.ts
│ │ ├── bio.ts
│ │ ├── med.ts
│ │ ├── chem.ts
│ │ ├── finance.ts
│ │ ├── math.ts
│ │ └── ...
│ ├── api/ # API client | API 客户端
│ │ ├── client.ts # LLM client | LLM 客户端
│ │ └── webSearch.ts # Web search | 网络搜索
│ ├── io/ # I/O layer | I/O 层
│ │ ├── terminal.ts # Terminal UI | 终端 UI
│ │ └── ws-server.ts # WebSocket | WebSocket 服务器
│ ├── config.ts # Configuration | 配置加载器
│ ├── types/ # TypeScript types | 类型定义
│ └── index.ts # Entry point | 入口点
├── electron/ # Electron desktop | Electron 桌面应用
│ ├── main.js # Main process | 主进程
│ ├── preload.cjs # IPC bridge | IPC 桥接
│ ├── agent-bridge.js # Agent communication | Agent 通信
│ ├── desktop/ # Desktop mode | 桌面模式 UI
│ ├── dashboard/ # Dashboard mode | 仪表盘 UI
│ ├── monitor/ # Monitor panel | 监控面板
│ └── setup/ # Setup wizard | 配置向导
├── personas/ # 22 preset personas | 人设
├── data/ # Runtime data | 运行时数据
├── plugins/ # Custom plugins | 自定义插件
├── tests/ # Test files | 测试文件
├── config.json # Configuration | 配置文件
├── .env # Environment variables | 环境变量
├── tsconfig.json # TypeScript config | TS 配置
└── package.json # Dependencies | 依赖
| Command | Description | 说明 |
|---|---|---|
npm run cli |
Run CLI mode with hot reload | 以 CLI 模式运行,带热重载 |
npm run electron:desktop |
Run desktop mode | 运行桌面模式 |
npm run electron:dashboard |
Run dashboard mode | 运行仪表盘模式 |
npm run typecheck |
Run TypeScript type checking | 运行 TypeScript 类型检查 |
npm test |
Run unit tests | 运行单元测试 |
npm run test:e2e |
Run end-to-end tests | 运行端到端测试 |
npm run build |
Build Electron app | 构建 Electron 应用 |
npm run build:win |
Build Windows installer | 构建 Windows 安装程序 |
The project uses tsx for TypeScript execution without compilation:
项目使用 tsx 在无需编译的情况下执行 TypeScript:
# Run a single file | 运行单个文件
npx tsx src/agent/Agent.ts
# Run with watch mode | 带监听模式运行
npx tsx --watch src/index.ts// Use explicit types when possible | 尽可能使用显式类型
function calculateTotal(items: Item[]): number {
return items.reduce((sum, item) => sum + item.price, 0);
}
// Use async/await for asynchronous operations | 使用 async/await 处理异步操作
async function fetchData(url: string): Promise<Data> {
const response = await fetch(url);
return response.json();
}
// Use const for constants and immutable variables | 使用 const 表示常量和不可变变量
const MAX_RETRIES = 3;
// Use meaningful variable names | 使用有意义的变量名
const userSessionId = 'session_123';| Type | Convention | Example |
|---|---|---|
| Variables | camelCase |
userInput, sessionId
|
| Functions | camelCase |
getUserInfo(), parseResponse()
|
| Classes | PascalCase |
AgentOrchestrator, FileStorage
|
| Constants | UPPER_SNAKE_CASE |
MAX_TOKENS, DEFAULT_CONFIG
|
| Files | kebab-case |
tool-parser.ts, wechat-manager.ts
|
| Types/Interfaces | PascalCase |
ToolRegistryEntry, AgentState
|
Follow the Conventional Commits specification:
遵循 Conventional Commits 规范:
<type>(<scope>): <subject>
[optional body]
[optional footer]
| Type | Description |
|---|---|
feat |
New feature |
fix |
Bug fix |
docs |
Documentation |
style |
Code style (formatting, etc.) |
refactor |
Code refactoring |
test |
Add or modify tests |
chore |
Maintenance tasks |
Examples | 示例
feat(tools): add GIS coordinate conversion tools
Add 11 GIS tools including convertCoord, calcDistance,
pointInPolygon, and GeoJSON processing.
Closes #123
fix(session): prevent session history loss on persona switch
fix: correct WebSocket reconnection logic
docs: add comprehensive API documentation
flowchart LR
STEP1["1. Create tool function<br/>创建工具函数"] --> STEP2["2. Export from module<br/>从模块导出"]
STEP2 --> STEP3["3. Register in registry.ts<br/>在 registry.ts 中注册"]
STEP3 --> STEP4["4. Add to system prompt<br/>添加到系统提示词"]
STEP4 --> STEP5["5. Write tests<br/>编写测试"]
STEP5 --> STEP6["6. Test with CogitoAgent<br/>使用 CogitoAgent 测试"]
classDef step fill:#1a2332,stroke:#5eead4,color:#5eead4
class STEP1,STEP2,STEP3,STEP4,STEP5,STEP6 step
Create a tool in the appropriate module (e.g., tools/file.ts):
在相应模块中创建工具(例如 tools/file.ts):
/**
* Rename a file or directory
* @param {string} oldPath - Source path | 源路径
* @param {string} newPath - Destination path | 目标路径
* @returns {Promise<Object>} Result object | 结果对象
*/
async function rename(oldPath: string, newPath: string): Promise<any> {
const basePath = getBasePath();
const fullOldPath = path.isAbsolute(oldPath) ? oldPath : path.join(basePath, oldPath);
const fullNewPath = path.isAbsolute(newPath) ? newPath : path.join(basePath, newPath);
try {
await fs.rename(fullOldPath, fullNewPath);
return { success: true, data: `Renamed: ${oldPath} → ${newPath}` };
} catch (error: any) {
return { success: false, error: `Rename failed: ${error.message}` };
}
}// tools/file.ts
export { ls, read, copy, mkdir, create, rename };// registry.ts
const TOOL_REGISTRY = {
// ... existing tools | 现有工具
rename: { fn: tools.rename, argCount: 2, category: 'file' },
};// system-prompt.ts
case 'file':
toolList += `### 文件操作工具
- ls(path) - 列出目录内容
- read(path) - 读取文件内容
- copy(src, dest) - 复制文件
- mkdir(path) - 创建目录
- create(path, content) - 创建文件
- rename(oldPath, newPath) - 重命名文件或目录
`;
break;// tests/tools/file.test.ts
import { rename } from '../../src/agent/tools/file.js';
describe('rename tool', () => {
it('should rename a file successfully', async () => {
const result = await rename('old.txt', 'new.txt');
expect(result.success).toBe(true);
});
});# Run the tool manually | 手动运行工具
[TOOL] rename("old.txt", "new.txt") [/TOOL]
# Run tests | 运行测试
npm test tests/tools/file.test.tstests/
├── unit/ # Unit tests | 单元测试
│ ├── agent/
│ │ ├── Agent.test.ts
│ │ ├── registry.test.ts
│ │ └── session.test.ts
│ └── tools/
│ ├── file.test.ts
│ ├── web.test.ts
│ └── ...
├── integration/ # Integration tests | 集成测试
│ ├── api.test.ts
│ └── websocket.test.ts
└── e2e/ # End-to-end tests | 端到端测试
├── cli.test.ts
└── electron.test.ts
# Run all tests | 运行所有测试
npm test
# Run specific test file | 运行特定测试文件
npm test -- tests/unit/agent/Agent.test.ts
# Run with coverage | 运行并生成覆盖率报告
npm test -- --coverage
# Run in watch mode | 监听模式
npm test -- --watch
# Run end-to-end tests | 运行端到端测试
npm run test:e2eimport { describe, expect, it } from '@jest/globals';
import { ls } from '../../src/agent/tools/file.js';
describe('ls tool', () => {
it('should list directory contents', async () => {
const result = await ls('.');
expect(result.success).toBe(true);
expect(Array.isArray(result.data)).toBe(true);
expect(result.data.length).toBeGreaterThan(0);
});
it('should handle non-existent directory', async () => {
const result = await ls('/nonexistent/path');
expect(result.success).toBe(false);
expect(result.error).toContain('No such file or directory');
});
});The project uses GitHub Actions for CI/CD:
项目使用 GitHub Actions 进行持续集成与持续部署:
# .github/workflows/ci.yml
name: CI
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: '22'
- run: npm ci
- run: npm run typecheck
- run: npm test
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: '22'
- run: npm ci
- run: npm run buildEnable debug logging with environment variables:
使用环境变量启用调试日志:
# Enable debug mode | 启用调试模式
DEBUG=true
# Set log level | 设置日志级别
LOG_LEVEL=debug# Run with inspector | 带检查器运行
node --inspect-brk --loader tsx src/index.ts
# Then open chrome://inspect in Chrome | 然后在 Chrome 中打开 chrome://inspect| File | Function | Debug Focus |
|---|---|---|
Agent.ts |
thinkCycle() |
Main think loop |
Agent.ts |
executeTool() |
Tool execution |
session.ts |
addUserMessage() |
Session history |
registry.ts |
TOOL_REGISTRY |
Tool registration |
client.ts |
streamChat() |
LLM API calls |
| 文件 | 函数 | 调试重点 |
|---|---|---|
Agent.ts |
thinkCycle() |
主思考循环 |
Agent.ts |
executeTool() |
工具执行 |
session.ts |
addUserMessage() |
会话历史 |
registry.ts |
TOOL_REGISTRY |
工具注册 |
client.ts |
streamChat() |
LLM API 调用 |
# Build for all platforms | 为所有平台构建
npm run build
# Build for Windows | 为 Windows 构建
npm run build:win
# Build NSIS installer | 构建 NSIS 安装程序
npm run build:nsis# Build Docker image | 构建 Docker 镜像
docker build -t cogito-agent:latest .
# Or with Docker Compose | 或使用 Docker Compose
docker-compose build-
Fork the repository
-
Clone your fork locally
-
Create a feature branch (
feat/your-feature) -
Write code following the style guide
-
Write tests for your changes
-
Run tests to ensure everything passes
-
Update documentation as needed
-
Submit a Pull Request to the main branch
-
Fork 仓库
-
Clone 您的本地分支
-
创建功能分支(
feat/your-feature) -
编写代码,遵循风格指南
-
为您的更改编写测试
-
运行测试确保一切通过
-
根据需要更新文档
-
向主分支提交 Pull Request
- Code follows style guide | 代码遵循风格指南
- Tests pass | 测试通过
- TypeScript types are correct | TypeScript 类型正确
- Documentation is updated | 文档已更新
- No console.log statements in production code | 生产代码中无 console.log
- Error handling is complete | 错误处理完整
- No security vulnerabilities | 无安全漏洞
-
Contributing — Detailed contribution guidelines
-
Plugin System — Build custom plugins
-
贡献指南 — 详细的贡献指南
-
插件系统 — 构建自定义插件
Previous: FAQ →
上一篇: 常见问题 →