Repository navigation
Architecture Overview
Understanding How CogitoAgent Works
理解 CogitoAgent 的工作原理
CogitoAgent is built on a modular, event-driven architecture that separates concerns into distinct layers. This guide provides a comprehensive overview of the system architecture, including component relationships, data flow, and the core thinking loop.
CogitoAgent 构建在模块化、事件驱动的架构之上,将关注点分离到不同的层次。本指南提供了系统架构的全面概述,包括组件关系、数据流和核心思考循环。
The diagram below shows the overall architecture of CogitoAgent, from the user interface layer down to the core agent engine.
下图展示了 CogitoAgent 的整体架构,从用户界面层到核心 Agent 引擎。
flowchart TB
subgraph UI["User Interface Layer | 用户界面层"]
CLI["CLI Terminal<br/>命令行终端"]
DESKTOP["Desktop Mode<br/>桌面模式"]
DASHBOARD["Dashboard Mode<br/>仪表盘模式"]
MONITOR["Monitor Panel<br/>监控面板"]
end
subgraph IPC["IPC & WebSocket Layer | 通信层"]
PRELOAD["preload.cjs<br/>IPC Bridge"]
MAIN["main.js<br/>Window Manager"]
BRIDGE["agent-bridge.js<br/>Message Router"]
WSS["ws-server.ts<br/>WebSocket :9527"]
end
subgraph CORE["Core Agent Engine | 核心引擎"]
AGENT["Agent.ts<br/>Think Cycle"]
STATE["state.ts<br/>State Machine"]
SESSION["session.ts<br/>Session Manager"]
COMMANDS["commands.ts<br/>Command Handler"]
end
subgraph TOOLS["Tool System | 工具系统"]
REGISTRY["registry.ts<br/>Tool Registry"]
PARSER["tool-parser.ts<br/>Tool Parser"]
EXECUTOR["executeTool()<br/>Tool Executor"]
TOOL_MODULES["28 Tool Modules<br/>160+ Tools"]
end
subgraph EXTENSIONS["Extensions | 扩展"]
PLUGIN["plugin.ts<br/>Plugin System"]
MCP["mcp.ts<br/>MCP Server :3001"]
CLUSTER["orchestrator.ts<br/>Agent Cluster"]
WECHAT["wechat-manager.ts<br/>WeChat Channel"]
RETRY["retry.ts<br/>Circuit Breaker"]
end
subgraph LLM["LLM Layer | 模型层"]
CLIENT["client.ts<br/>API Client"]
PROVIDERS["OpenAI / Moark / Anthropic / Google"]
end
CLI --> WSS
DESKTOP --> PRELOAD
DASHBOARD --> PRELOAD
MONITOR --> PRELOAD
PRELOAD --> MAIN
MAIN --> BRIDGE
BRIDGE --> WSS
WSS --> AGENT
AGENT --> STATE
AGENT --> SESSION
AGENT --> COMMANDS
AGENT --> PARSER
AGENT --> EXECUTOR
AGENT --> CLIENT
PARSER --> REGISTRY
EXECUTOR --> REGISTRY
REGISTRY --> TOOL_MODULES
REGISTRY --> PLUGIN
AGENT --> CLUSTER
AGENT --> WECHAT
AGENT --> RETRY
REGISTRY --> MCP
CLIENT --> PROVIDERS
classDef ui fill:#1a2332,stroke:#5eead4,color:#5eead4
classDef ipc fill:#1a2332,stroke:#5eead4,color:#5eead4
classDef core fill:#1a2332,stroke:#fbbf24,color:#fbbf24
classDef tools fill:#1a2332,stroke:#38bdf8,color:#38bdf8
classDef ext fill:#1a2332,stroke:#a78bfa,color:#a78bfa
classDef llm fill:#1a2332,stroke:#94a3b8,color:#94a3b8
class CLI,DESKTOP,DASHBOARD,MONITOR ui
class PRELOAD,MAIN,BRIDGE,WSS ipc
class AGENT,STATE,SESSION,COMMANDS core
class REGISTRY,PARSER,EXECUTOR,TOOL_MODULES tools
class PLUGIN,MCP,CLUSTER,WECHAT,RETRY ext
class CLIENT,PROVIDERS llm
| Component | File | Responsibility |
|---|---|---|
| Agent Engine | Agent.ts |
Main think loop controller — orchestrates thinking, tool execution, and state transitions |
| State Machine | state.ts |
Manages agent lifecycle states: THINKING, AWAITING_INPUT, AWAITING_CONFIRMATION
|
| Session Manager | session.ts |
Multi-session isolation, history persistence, auto-compression, token estimation |
| Command Handler | commands.ts |
Parses and executes slash commands (/help, /status, /new, etc.) |
| 组件 | 文件 | 职责 |
|---|---|---|
| Agent 引擎 | Agent.ts |
主思考循环控制器——编排思考、工具执行和状态转换 |
| 状态机 | state.ts |
管理 Agent 生命周期状态:THINKING、AWAITING_INPUT、AWAITING_CONFIRMATION
|
| 会话管理器 | session.ts |
多会话隔离、历史持久化、自动压缩、Token 估算 |
| 命令处理器 | commands.ts |
解析并执行斜杠命令(/help、/status、/new 等) |
| Component | File | Responsibility |
|---|---|---|
| Tool Registry | registry.ts |
Central registry of all 160+ tools with metadata and execution handlers |
| Tool Parser | tool-parser.ts |
Extracts [TOOL]...[/TOOL] calls from LLM responses |
| Tool Executor | Agent.ts |
Executes tools via the registry with confirmation and error handling |
| Tool Modules | tools/*.ts |
28 modules covering file, web, code, git, database, GIS, bio, medicine, etc. |
| 组件 | 文件 | 职责 |
|---|---|---|
| 工具注册表 | registry.ts |
所有 160+ 个工具及其元数据和执行处理器的中央注册表 |
| 工具解析器 | tool-parser.ts |
从 LLM 响应中提取 [TOOL]...[/TOOL] 调用 |
| 工具执行器 | Agent.ts |
通过注册表执行工具,包含确认和错误处理 |
| 工具模块 | tools/*.ts |
28 个模块,覆盖文件、网络、代码、Git、数据库、GIS、生物、医学等 |
| Component | File | Responsibility |
|---|---|---|
| Plugin System | plugin.ts |
Dynamically load custom tool plugins from plugins/ directory |
| MCP Server | mcp.ts |
Expose tools as MCP protocol (JSON-RPC 2.0) on port 3001 |
| Agent Cluster | orchestrator.ts |
Spawn and manage sub-agents for multi-agent collaboration |
| WeChat Channel | wechat-manager.ts |
WeChat iLink integration for message receiving and replying |
| Circuit Breaker | retry.ts |
Reliable network requests with retry and circuit breaker |
| 组件 | 文件 | 职责 |
|---|---|---|
| 插件系统 | plugin.ts |
从 plugins/ 目录动态加载自定义工具插件 |
| MCP 服务器 | mcp.ts |
将工具暴露为 MCP 协议(JSON-RPC 2.0),端口 3001 |
| 智能体集群 | orchestrator.ts |
生成和管理子智能体,实现多智能体协作 |
| 微信通道 | wechat-manager.ts |
微信 iLink 集成,用于消息收发 |
| 熔断器 | retry.ts |
带重试和熔断的可靠网络请求 |
The Think Cycle is the heart of CogitoAgent. It follows an Observe-Think-Act iterative paradigm.
思考循环是 CogitoAgent 的核心。它遵循观察-思考-行动的迭代范式。
flowchart TD
START(["Start | 开始"]) --> STEP1["Step 1: Observe | 观察<br/>• User input / System event<br/>• Tool results<br/>• Session context"]
STEP1 --> STEP2["Step 2: Build Prompt | 构建提示<br/>• System prompt (persona)<br/>• Conversation history<br/>• Tool schemas"]
STEP2 --> STEP3["Step 3: Invoke LLM | 调用 LLM<br/>• streamChat() via client.ts<br/>• SSE streaming response"]
STEP3 --> STEP4["Step 4: Parse Response | 解析响应<br/>• Extract reasoning<br/>• Detect tool calls<br/>• Detect [WAIT] tag"]
STEP4 --> DECIDE1{"Tool call detected?<br/>检测到工具调用?"}
DECIDE1 -->|"Yes | 是"| STEP5["Step 5: Execute Tool | 执行工具<br/>• Parse [TOOL] syntax<br/>• Look up in registry<br/>• Execute with sandbox<br/>• Record stats"]
STEP5 --> STEP6["Step 6: Inject Result | 注入结果<br/>• Format tool output<br/>• Add as user message<br/>• Update session"]
STEP6 --> STEP2
DECIDE1 -->|"No | 否"| DECIDE2{"[WAIT] detected?<br/>检测到 [WAIT]?"}
DECIDE2 -->|"Yes | 是"| OUTPUT(["Output | 输出<br/>Return to user<br/>返回给用户"])
DECIDE2 -->|"No | 否"| DECIDE3{"Tools executed?<br/>已执行工具?"}
DECIDE3 -->|"Yes | 是"| STEP2
DECIDE3 -->|"No | 否"| DECIDE4{"Max cycles reached?<br/>达到最大循环次数?"}
DECIDE4 -->|"Yes | 是"| OUTPUT
DECIDE4 -->|"No | 否"| STEP2
style START fill:#5eead4,color:#0b0e14
style OUTPUT fill:#5eead4,color:#0b0e14
style DECIDE1 fill:#fbbf24,color:#0b0e14
style DECIDE2 fill:#fbbf24,color:#0b0e14
style DECIDE3 fill:#fbbf24,color:#0b0e14
style DECIDE4 fill:#fbbf24,color:#0b0e14
style STEP3 fill:#a78bfa,color:#fff
style STEP5 fill:#38bdf8,color:#fff
| Step | Description | 说明 |
|---|---|---|
| Observe | Perceive input from user messages, system events, or tool results | 感知来自用户消息、系统事件或工具结果的输入 |
| Build Prompt | Construct the full prompt with system persona, history, and tool schemas | 使用系统人设、历史和工具模式构建完整的提示词 |
| Invoke LLM | Send the request to the LLM via streamChat() with SSE streaming |
通过 streamChat() 向 LLM 发送请求,使用 SSE 流式传输 |
| Parse Response | Extract reasoning, content, tool calls, and [WAIT] markers |
提取推理、内容、工具调用和 [WAIT] 标记 |
| Execute Tool | Parse [TOOL] syntax, look up in registry, execute with sandbox |
解析 [TOOL] 语法,在注册表中查找,使用沙箱执行 |
| Inject Result | Format output and inject as a user message for the next cycle | 格式化输出并作为用户消息注入下一轮循环 |
CogitoAgent uses a simple but powerful state machine to manage its behavior.
CogitoAgent 使用一个简单但强大的状态机来管理其行为。
stateDiagram-v2
[*] --> IDLE: Initialize | 初始化
IDLE --> AWAITING_INPUT: Ready | 就绪
AWAITING_INPUT --> THINKING: User input / Event<br/>用户输入 / 事件
state THINKING {
[*] --> BUILDING_PROMPT
BUILDING_PROMPT --> CALLING_LLM
CALLING_LLM --> PARSING_RESPONSE
PARSING_RESPONSE --> EXECUTING_TOOL: Tool call detected<br/>检测到工具调用
PARSING_RESPONSE --> FINALIZING: Final answer detected<br/>检测到最终答案
EXECUTING_TOOL --> BUILDING_PROMPT: Tool result ready<br/>工具结果就绪
FINALIZING --> [*]
}
THINKING --> AWAITING_INPUT: Output response<br/>输出响应
THINKING --> AWAITING_CONFIRMATION: Dangerous operation<br/>危险操作
AWAITING_CONFIRMATION --> THINKING: Confirm / Reject<br/>确认 / 拒绝
AWAITING_CONFIRMATION --> AWAITING_INPUT: Cancel / Timeout<br/>取消 / 超时
AWAITING_INPUT --> [*]: Session ends<br/>会话结束
classDef idle fill:#94a3b8,color:#0b0e14
classDef input fill:#fbbf24,color:#0b0e14
classDef thinking fill:#5eead4,color:#0b0e14
classDef confirm fill:#f87171,color:#0b0e14
class IDLE idle
class AWAITING_INPUT input
class THINKING thinking
class AWAITING_CONFIRMATION confirm
| State | Description | 说明 |
|---|---|---|
IDLE |
Initial state, waiting for input | 初始状态,等待输入 |
AWAITING_INPUT |
Ready to receive user input | 准备接收用户输入 |
THINKING |
Agent is actively thinking — building prompts, calling LLM, executing tools | Agent 正在积极思考——构建提示、调用 LLM、执行工具 |
AWAITING_CONFIRMATION |
Waiting for user to confirm or reject a dangerous operation | 等待用户确认或拒绝危险操作 |
The sequence diagram below shows the detailed flow of a tool call from the LLM response to the final result.
下面的时序图展示了从 LLM 响应到最终结果的工具调用详细流程。
sequenceDiagram
participant User as User | 用户
participant Agent as Agent.ts
participant Parser as tool-parser.ts
participant Registry as registry.ts
participant Executor as executeTool()
participant Sandbox as sandbox.ts
participant Tool as Tool Module
participant Stats as stats.ts
participant Trace as tracing.ts
User->>Agent: Send message | 发送消息
Agent->>Agent: thinkCycle()
Agent->>LLM: streamChat()
LLM-->>Agent: Response with [TOOL] | 包含 [TOOL] 的响应
Agent->>Parser: parseAllToolCalls()
Parser-->>Agent: Tool call list | 工具调用列表
loop For each tool call | 对每个工具调用
Agent->>Registry: getToolRegistry(name)
Registry-->>Agent: Tool entry | 工具条目
Agent->>Trace: traceToolExec()
Agent->>Executor: executeTool(tool, args)
alt Dangerous operation | 危险操作
Executor->>Agent: requestConfirmation()
Agent->>User: Ask for confirmation | 请求确认
User-->>Agent: Confirm / Reject | 确认 / 拒绝
alt Rejected | 拒绝
Executor-->>Agent: Return error | 返回错误
end
end
Executor->>Sandbox: Execute safely | 安全执行
Sandbox->>Tool: fn(...args)
alt Success | 成功
Tool-->>Sandbox: Result | 结果
Sandbox-->>Executor: Formatted result | 格式化结果
Executor->>Stats: recordToolCall(success)
Executor-->>Agent: { success: true, data }
Agent->>Trace: updateTraceStep(success)
else Failure | 失败
Tool-->>Sandbox: Error | 错误
Sandbox-->>Executor: Format error | 格式化错误
Executor->>Stats: recordToolCall(failure)
Executor-->>Agent: { success: false, error }
Agent->>Trace: updateTraceStep(failure)
end
Agent->>Agent: Inject result as user message | 注入结果作为用户消息
Agent->>Agent: Schedule next cycle | 调度下一轮循环
end
Agent->>User: Final response | 最终回复
CogitoAgent uses WebSocket (port 9527) for real-time communication between Electron windows and the Agent subprocess.
CogitoAgent 使用 WebSocket(端口 9527)在 Electron 窗口和 Agent 子进程之间进行实时通信。
sequenceDiagram
participant Renderer as Electron Renderer<br/>UI Window
participant Preload as preload.cjs
participant Main as main.js
participant Bridge as agent-bridge.js
participant WS as ws-server.ts<br/>Port 9527
participant Agent as Agent.ts
Renderer->>Preload: electronAPI.sendMessage(text)
Preload->>Main: ipcRenderer.send()
Main->>Bridge: forward to bridge
Bridge->>WS: ws.send(JSON message)
WS->>Agent: on('message')
Agent->>Agent: handleUserInput()
Agent->>Agent: thinkCycle()
loop Streaming Response | 流式响应
Agent->>WS: broadcast('agent-reply', chunk)
WS->>Bridge: on('message')
Bridge->>Main: forward
Main->>Preload: event.sender.send()
Preload->>Renderer: ipcRenderer.on()
Renderer->>Renderer: Render chunk | 渲染数据块
end
Agent->>WS: broadcast('agent-reply', { type: 'end' })
WS->>Bridge: on('message')
Bridge->>Main: forward
Main->>Preload: event.sender.send()
Preload->>Renderer: ipcRenderer.on()
Renderer->>Renderer: Finalize message | 完成消息
| Direction | Type | Description |
|---|---|---|
| Renderer → Agent | user-message |
User input text |
| Renderer → Agent | stats-request |
Request statistics data |
| Agent → Renderer |
agent-reply (chunk) |
Streaming content chunk |
| Agent → Renderer |
agent-reply (tool-start) |
Tool execution started |
| Agent → Renderer |
agent-reply (tool-result) |
Tool execution result |
| Agent → Renderer |
agent-reply (end) |
End of response |
| Agent → Renderer | agent-state |
State change notification |
| Agent → Renderer | thought-trace |
Thought chain update |
| Agent → Renderer | cluster-state |
Cluster status update |
| Agent → Renderer | token-usage |
Token usage statistics |
| Agent → Renderer | wechat-* |
WeChat-related messages |
| 方向 | 类型 | 说明 |
|---|---|---|
| 渲染进程 → Agent | user-message |
用户输入文本 |
| 渲染进程 → Agent | stats-request |
请求统计数据 |
| Agent → 渲染进程 |
agent-reply (chunk) |
流式内容块 |
| Agent → 渲染进程 |
agent-reply (tool-start) |
工具执行开始 |
| Agent → 渲染进程 |
agent-reply (tool-result) |
工具执行结果 |
| Agent → 渲染进程 |
agent-reply (end) |
响应结束 |
| Agent → 渲染进程 | agent-state |
状态变更通知 |
| Agent → 渲染进程 | thought-trace |
思维链更新 |
| Agent → 渲染进程 | cluster-state |
集群状态更新 |
| Agent → 渲染进程 | token-usage |
Token 使用统计 |
| Agent → 渲染进程 | wechat-* |
微信相关消息 |
CogitoAgent stores data in the data/ directory:
CogitoAgent 将数据存储在 data/ 目录中:
flowchart LR
subgraph DATA["data/ | 数据目录"]
SESSIONS["sessions/<br/>会话历史"]
MEMORY["memory.json<br/>记忆系统"]
TASKS["tasks.json<br/>任务管理"]
STATS["stats.json<br/>使用统计"]
WECHAT["wechat/<br/>微信消息"]
LOGS["logs/<br/>追踪日志"]
end
AGENT["Agent.ts"] --> SESSIONS
AGENT --> MEMORY
AGENT --> TASKS
AGENT --> STATS
WECHAT["wechat-manager.ts"] --> WECHAT
TRACE["tracing.ts"] --> LOGS
classDef data fill:#1a2332,stroke:#5eead4,color:#5eead4
classDef comp fill:#1a2332,stroke:#fbbf24,color:#fbbf24
class SESSIONS,MEMORY,TASKS,STATS,WECHAT,LOGS data
class AGENT,WECHAT,TRACE comp
| Directory | Contents | 内容 |
|---|---|---|
data/sessions/ |
Session history and metadata | 会话历史和元数据 |
data/memory.json |
Long-term memory entries | 长期记忆条目 |
data/tasks.json |
Task management data | 任务管理数据 |
data/stats.json |
Tool usage statistics | 工具使用统计 |
data/wechat/ |
WeChat messages and state | 微信消息和状态 |
data/logs/ |
Tracing logs | 追踪日志 |
cogito-agent/
├── src/ # TypeScript source code | TypeScript 源码
│ ├── agent/ # Core agent engine | 核心 Agent 引擎
│ │ ├── Agent.ts # Main think loop | 主思考循环
│ │ ├── state.ts # State machine | 状态机
│ │ ├── registry.ts # Tool registry | 工具注册表
│ │ ├── session.ts # Session manager | 会话管理
│ │ ├── commands.ts # Command handler | 命令处理
│ │ ├── stats.ts # Usage statistics | 使用统计
│ │ ├── tracing.ts # Observability | 可观测性
│ │ ├── retry.ts # Circuit breaker | 熔断器
│ │ ├── mcp.ts # MCP Server | MCP 服务器
│ │ ├── plugin.ts # Plugin system | 插件系统
│ │ ├── orchestrator.ts # Agent cluster | Agent 集群
│ │ ├── wechat-manager.ts # WeChat channel | 微信通道
│ │ ├── tool-parser.ts # [TOOL] parser | 工具解析器
│ │ ├── tool-utils.ts # Tool utilities | 工具工具函数
│ │ ├── thought-trace.ts # Thought chain | 思维链
│ │ └── tools/ # 28 tool modules | 28 个工具模块
│ │ ├── file.ts # File operations | 文件操作
│ │ ├── web.ts # Web tools | 网络工具
│ │ ├── browser.ts # Browser automation | 浏览器自动化
│ │ ├── code.ts # Code execution | 代码执行
│ │ ├── git.ts # Git operations | Git 操作
│ │ ├── db.ts # Database | 数据库
│ │ ├── gis.ts # GIS tools | 地理信息
│ │ ├── bio.ts # Bioinformatics | 生命科学
│ │ ├── med.ts # Medicine | 医学
│ │ ├── chem.ts # Chemistry | 化学
│ │ ├── finance.ts # Finance | 金融
│ │ ├── math.ts # Math & Stats | 数学统计
│ │ └── ... # And more | 以及更多
│ ├── 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 server | WebSocket 服务器
│ ├── config.ts # Configuration loader | 配置加载器
│ ├── types/ # TypeScript types | TypeScript 类型定义
│ └── index.ts # Entry point | 入口点
├── electron/ # Electron desktop app | Electron 桌面应用
│ ├── main.js # Main process | 主进程
│ ├── preload.cjs # IPC bridge | IPC 桥接
│ ├── agent-bridge.js # Agent communication | Agent 通信
│ ├── desktop/ # Desktop mode UI | 桌面模式 UI
│ ├── dashboard/ # Dashboard UI | 仪表盘 UI
│ ├── monitor/ # Monitor panel | 监控面板
│ └── setup/ # Setup wizard | 配置向导
├── personas/ # 22 preset personas | 22 个预设人设
├── data/ # Runtime data | 运行时数据
├── plugins/ # Custom plugins | 自定义插件
├── config.json # Configuration file | 配置文件
├── .env # Environment variables | 环境变量
├── package.json # Dependencies | 依赖
├── tsconfig.json # TypeScript config | TypeScript 配置
└── docker-compose.yml # Docker deployment | Docker 部署
| Principle | Description | 说明 |
|---|---|---|
| Modularity | Each component has a single, well-defined responsibility | 每个组件都有单一、明确的职责 |
| Event-Driven | Components communicate via events and messages | 组件通过事件和消息进行通信 |
| Observability | Full tracing, stats, and thought chain visualization | 完整的追踪、统计和思维链可视化 |
| Security | Sandboxed code execution, dangerous operation confirmation | 沙箱化代码执行、危险操作确认 |
| Extensibility | Plugin system, MCP protocol, custom personas | 插件系统、MCP 协议、自定义人设 |
| Privacy First | All data stays local; only context sent to LLM | 所有数据保留在本地;仅上下文发送给 LLM |
-
Tools — Explore all 160+ built-in tools
-
Extensions — Learn about plugins, MCP, and more
-
Deployment — Deploy to production
-
工具列表 — 探索所有 160+ 个内置工具
-
扩展功能 — 了解插件、MCP 等
-
部署指南 — 部署到生产环境
Previous: Configuration →
Next: Tools →
上一篇: 配置说明 →
下一篇: 工具列表 →