Skip to content
Snow leopard edited this page Jul 16, 2026 · 1 revision

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 做贡献或构建自定义扩展的开发者。它涵盖了开发工作流、代码结构、测试和贡献指南。


Development Environment | 开发环境

Prerequisites | 前置要求

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

Setting Up | 设置

# 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 cli

VS Code Configuration | VS Code 配置

Create .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"]
    }
  ]
}

Project Structure | 项目结构

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 | 依赖

Development Commands | 开发命令

npm Scripts | npm 脚本

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 安装程序

Using tsx for Development | 使用 tsx 进行开发

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

Code Style | 代码风格

TypeScript Rules | TypeScript 规则

// 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';

Naming Conventions | 命名规范

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

Commit Message Format | 提交信息格式

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

Building Tools | 构建工具

Tool Development Workflow | 工具开发工作流

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
Loading

Step 1: Create Tool Function | 步骤 1:创建工具函数

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}` };
  }
}

Step 2: Export from Module | 步骤 2:从模块导出

// tools/file.ts
export { ls, read, copy, mkdir, create, rename };

Step 3: Register in Registry | 步骤 3:在注册表中注册

// registry.ts
const TOOL_REGISTRY = {
  // ... existing tools | 现有工具
  rename: { fn: tools.rename, argCount: 2, category: 'file' },
};

Step 4: Add to System Prompt | 步骤 4:添加到系统提示词

// system-prompt.ts
case 'file':
  toolList += `### 文件操作工具
- ls(path) - 列出目录内容
- read(path) - 读取文件内容
- copy(src, dest) - 复制文件
- mkdir(path) - 创建目录
- create(path, content) - 创建文件
- rename(oldPath, newPath) - 重命名文件或目录

`;
  break;

Step 5: Write Tests | 步骤 5:编写测试

// 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);
  });
});

Step 6: Test | 步骤 6:测试

# Run the tool manually | 手动运行工具
[TOOL] rename("old.txt", "new.txt") [/TOOL]

# Run tests | 运行测试
npm test tests/tools/file.test.ts

Testing | 测试

Test Structure | 测试结构

tests/
├── 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

Running Tests | 运行测试

# 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:e2e

Writing Tests | 编写测试

import { 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');
  });
});

CI/CD | 持续集成与持续部署

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 build

Debugging | 调试

Debug Logging | 调试日志

Enable debug logging with environment variables:

使用环境变量启用调试日志:

# Enable debug mode | 启用调试模式
DEBUG=true

# Set log level | 设置日志级别
LOG_LEVEL=debug

Node.js Inspector | Node.js 检查器

# Run with inspector | 带检查器运行
node --inspect-brk --loader tsx src/index.ts

# Then open chrome://inspect in Chrome | 然后在 Chrome 中打开 chrome://inspect

Common Debug Points | 常见调试点

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 调用

Building for Production | 生产构建

Electron Build | Electron 构建

# Build for all platforms | 为所有平台构建
npm run build

# Build for Windows | 为 Windows 构建
npm run build:win

# Build NSIS installer | 构建 NSIS 安装程序
npm run build:nsis

Docker Build | Docker 构建

# Build Docker image | 构建 Docker 镜像
docker build -t cogito-agent:latest .

# Or with Docker Compose | 或使用 Docker Compose
docker-compose build

Contributing Guidelines | 贡献指南

Pull Request Process | Pull Request 流程

  1. Fork the repository

  2. Clone your fork locally

  3. Create a feature branch (feat/your-feature)

  4. Write code following the style guide

  5. Write tests for your changes

  6. Run tests to ensure everything passes

  7. Update documentation as needed

  8. Submit a Pull Request to the main branch

  9. Fork 仓库

  10. Clone 您的本地分支

  11. 创建功能分支(feat/your-feature)

  12. 编写代码,遵循风格指南

  13. 为您的更改编写测试

  14. 运行测试确保一切通过

  15. 根据需要更新文档

  16. 向主分支提交 Pull Request

Code Review Checklist | 代码审查清单

  • 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 | 无安全漏洞

Next Steps | 下一步


Previous: FAQ →

上一篇: 常见问题 →

Clone this wiki locally