返回 DeepSeek-TUI-2026
ARCHITECTURE.md
根目录 / docs / ARCHITECTURE.md
1 # DeepSeek TUI Architecture
2
3 This document provides an overview of the DeepSeek TUI architecture for developers and contributors.
4
5 Current boundary note (v0.8.6):
6 - `crates/tui` is still the live end-user runtime for the TUI, runtime API, task manager, and tool execution loop.
7 - Other workspace crates are being split out incrementally, but they are not yet the sole runtime source of truth.
8 - The LSP subsystem (`crates/tui/src/lsp/`) is fully wired into the engine's post-tool-execution path
9 (`core/engine/lsp_hooks.rs`), providing inline diagnostics after every edit_file/apply_patch/write_file.
10 - The swarm agent system was removed in v0.8.5 in favour of sub-agents (agent_spawn) and RLM (rlm_query).
11 No model-visible swarm tool remains in the active codebase.
12
13 ## High-Level Overview
14
15 ```
16 ┌─────────────────────────────────────────────────────────────────┐
17 │ User Interface │
18 │ ┌─────────────────┐ ┌─────────────────┐ ┌────────────────┐ │
19 │ │ TUI (ratatui) │ │ One-shot Mode │ │ Config/CLI │ │
20 │ └────────┬────────┘ └────────┬────────┘ └────────┬───────┘ │
21 └───────────┼─────────────────────┼────────────────────┼──────────┘
22 │ │ │
23 ▼ ▼ ▼
24 ┌─────────────────────────────────────────────────────────────────┐
25 │ Core Engine │
26 │ ┌─────────────────────────────────────────────────────────┐ │
27 │ │ Agent Loop (core/engine.rs) │ │
28 │ │ ┌─────────┐ ┌─────────────┐ ┌──────────────────────┐ │ │
29 │ │ │ Session │ │ Turn Mgmt │ │ Tool Orchestration │ │ │
30 │ │ └─────────┘ └─────────────┘ └──────────────────────┘ │ │
31 │ └─────────────────────────────────────────────────────────┘ │
32 └─────────────────────────────────────────────────────────────────┘
33 │ │ │
34 ▼ ▼ ▼
35 ┌─────────────────────────────────────────────────────────────────┐
36 │ Tool & Extension Layer │
37 │ ┌──────────┐ ┌──────────┐ ┌─────────┐ ┌────────────────┐ │
38 │ │ Tools │ │ Skills │ │ Hooks │ │ MCP Servers │ │
39 │ │ (shell, │ │ (plugins)│ │ (pre/ │ │ (external) │ │
40 │ │ file) │ │ │ │ post) │ │ │ │
41 │ └──────────┘ └──────────┘ └─────────┘ └────────────────┘ │
42 └─────────────────────────────────────────────────────────────────┘
43 │ │ │
44 ▼ ▼ ▼
45 ┌─────────────────────────────────────────────────────────────────┐
46 │ Runtime API + Task Management │
47 │ ┌─────────────────────────────┐ ┌──────────────────────────┐ │
48 │ │ HTTP/SSE Runtime API │ │ Persistent Task Manager │ │
49 │ │ (runtime_api.rs) │ │ (task_manager.rs) │ │
50 │ └─────────────────────────────┘ └──────────────────────────┘ │
51 └─────────────────────────────────────────────────────────────────┘
52 │ │
53 ▼ ▼
54 ┌─────────────────────────────────────────────────────────────────┐
55 │ LLM Layer │
56 │ ┌──────────────────────────────────────────────────────────┐ │
57 │ │ LLM Client Abstraction (llm_client.rs) │ │
58 │ │ ┌─────────────────┐ ┌─────────────────────────────┐ │ │
59 │ │ │ DeepSeek Client │ │ Compatible Client (DeepSeek)│ │ │
60 │ │ │ (client.rs) │ │ (client.rs) │ │ │
61 │ │ └─────────────────┘ └─────────────────────────────┘ │ │
62 │ └──────────────────────────────────────────────────────────┘ │
63 └─────────────────────────────────────────────────────────────────┘
64 ```
65
66 ## Module Organization
67
68 ### Entry Point
69
70 - **`main.rs`** - CLI argument parsing (clap), configuration loading, entry point routing
71
72 ### Core Components
73
74 - **`core/`** - Main engine components
75 - `engine.rs` - Engine state, operation handling, message processing
76 - `engine/turn_loop.rs` - Streaming turn loop and tool execution orchestration
77 - `engine/capacity_flow.rs` - Capacity guardrail checkpoints and interventions
78 - `session.rs` - Session state management
79 - `turn.rs` - Turn-based conversation handling
80 - `events.rs` - Event system for UI updates
81 - `ops.rs` - Core operations
82
83 ### Configuration
84
85 - **`config.rs`** - Configuration loading, profiles, environment variables
86 - **`settings.rs`** - Runtime settings management
87
88 ### Workspace Crates
89
90 - **`crates/tools`** - Shared tool invocation primitives, including tool result/error/capability types used by the TUI runtime.
91 - **`crates/agent`** - Model/provider registry (ModelRegistry) for resolving model IDs to provider endpoints.
92 - **`crates/app-server`** - HTTP/SSE + JSON-RPC app server transport for headless agent workflows.
93 - **`crates/config`** - Config loading, profiles, environment variable precedence, CLI runtime overrides.
94 - **`crates/core`** - Agent loop, session management, turn orchestration, capacity flow guardrails.
95 - **`crates/execpolicy`** - Approval/sandbox policy engine for tool execution decisions.
96 - **`crates/hooks`** - Lifecycle hooks (stdout, jsonl, webhook) for pre/post tool events.
97 - **`crates/mcp`** - MCP client + stdio server for Model Context Protocol tool servers.
98 - **`crates/protocol`** - Request/response framing and protocol types.
99 - **`crates/secrets`** - OS keyring integration for API key storage.
100 - **`crates/state`** - SQLite thread/session persistence layer.
101 - **`crates/tui-core`** - Event-driven TUI state machine scaffold.
102
103 ### LLM Integration
104
105 - **`client.rs`** - HTTP client for DeepSeek's documented OpenAI-compatible Chat Completions API
106 - **`llm_client.rs`** - Abstract LLM client trait with retry logic
107 - **`models.rs`** - Data structures for API requests/responses
108
109 #### DeepSeek API Endpoints
110
111 DeepSeek exposes OpenAI-compatible endpoints. The CLI uses:
112 - `https://api.deepseek.com/v1/chat/completions` - normal and streaming model turns
113 - `https://api.deepseek.com/v1/models` - live model discovery and health checks
114
115 `https://api.deepseek.com/v1` is accepted for OpenAI SDK compatibility, and
116 `https://api.deepseek.com/beta` can be configured for beta-only features such as
117 strict tool mode, chat prefix completion, and FIM completion. The public
118 DeepSeek docs do not document a Responses API path for this workflow; the engine
119 drives turns through Chat Completions.
120
121 ### Tool System
122
123 - **`tools/`** - Built-in tool implementations
124 - `mod.rs` - Tool registry and common types
125 - `shell.rs` - Shell command execution
126 - `file.rs` - File read/write operations
127 - `todo.rs` - Checklist tools plus legacy todo aliases
128 - `tasks.rs` - Model-visible durable task, gate, background shell, and PR-attempt tools
129 - `github.rs` - Read-only GitHub context and guarded comment/closure tools backed by `gh`
130 - `automation.rs` - Model-visible scheduling tools over `AutomationManager`
131 - `plan.rs` - Planning tools
132 - `subagent.rs` - Sub-agent spawning (replaces the removed `agent_swarm` surface)
133 - `spec.rs` - Tool specifications
134 - `rlm.rs` - Recursive Language Model (RLM) tool — sandboxed Python REPL with `llm_query()` helpers
135
136 ### Extension Systems
137
138 - **`mcp.rs`** - Model Context Protocol client for external tool servers
139 - **`skills.rs`** - Plugin/skill loading and execution
140 - **`hooks.rs`** - Pre/post execution hooks with conditions
141
142 ### User Interface
143
144 - **`tui/`** - Terminal UI components (ratatui-based)
145 - `app.rs` - Application state and message handling
146 - `ui.rs` - Event handling, streaming state, and rendering logic
147 - `approval.rs` - Tool approval dialog
148 - `clipboard.rs` - Clipboard handling
149 - `streaming.rs` - Streaming text collector
150
151 - **`ui.rs`** - Legacy/simple UI utilities
152
153 ### LSP Integration
154
155 - **`lsp/`** - Post-edit diagnostics injection (#136)
156 - `mod.rs` - `LspManager` — lazy per-language transport pool + config
157 - `client.rs` - `StdioLspTransport` — JSON-RPC over stdio with `didOpen`/`didChange`/`publishDiagnostics`
158 - `diagnostics.rs` - Diagnostic types, severity, and HTML-block renderer
159 - `registry.rs` - Language detection and default server map (rust-analyzer, pyright, gopls, clangd, typescript-language-server)
160 - Wired into the engine via `core/engine/lsp_hooks.rs` — called after every successful edit
161
162 ### Security
163
164 - **`sandbox/`** - macOS sandboxing support
165 - `mod.rs` - Sandbox type definitions
166 - `policy.rs` - Sandbox policy configuration
167 - `seatbelt.rs` - macOS Seatbelt profile generation
168
169 ### Utilities
170
171 - **`utils.rs`** - Common utilities
172 - **`logging.rs`** - Logging infrastructure
173 - **`compaction.rs`** - Context compaction for long conversations
174 - **`pricing.rs`** - Cost estimation
175 - **`prompts.rs`** - System prompt templates
176 - **`project_doc.rs`** - Project documentation handling
177 - **`session.rs`** - Session serialization
178 - **`runtime_api.rs`** - HTTP/SSE runtime API (`deepseek serve --http`)
179 - **`runtime_threads.rs`** - Durable thread/turn/item store + replayable event timeline
180 - **`task_manager.rs`** - Durable queue, worker pool, task timelines and artifacts
181
182 ## Data Flow
183
184 ### Interactive Session
185
186 1. User input received in TUI
187 2. Input processed by `core/engine.rs`
188 3. Message sent to LLM via `llm_client.rs`
189 4. Response streamed back, parsed in `client.rs`
190 5. Tool calls extracted and executed via `tools/`
191 6. Hooks triggered before/after tool execution
192 7. Results aggregated and sent back to LLM
193 8. Final response rendered in TUI
194
195 ### Crash Recovery + Offline Queue
196
197 1. Before sending user input, the TUI writes a checkpoint snapshot to `~/.deepseek/sessions/checkpoints/latest.json`
198 2. Startup remains fresh by default; prior sessions are resumed explicitly via `--resume`/`--continue` (or `Ctrl+R` in TUI)
199 3. While degraded/offline, new prompts are queued in-memory and mirrored to `~/.deepseek/sessions/checkpoints/offline_queue.json`
200 4. Queue edits (`/queue ...`) are persisted continuously so drafts and queued prompts survive restarts
201 5. Successful turn completion clears the active checkpoint and writes a durable session snapshot
202 6. Agent/Yolo turns also take pre/post-turn side-git workspace snapshots under `~/.deepseek/snapshots/<project_hash>/<worktree_hash>/.git`; `/restore N` and `revert_turn` restore file state without changing conversation history or the user's `.git`
203
204 ### Tool Execution
205
206 1. LLM requests tool via `tool_use` content block
207 2. Tool registry looks up handler
208 3. Pre-execution hooks run
209 4. Approval requested if needed (non-yolo mode)
210 5. Tool executed (possibly sandboxed on macOS)
211 6. Post-execution hooks run
212 7. Result metadata is retained on runtime item records
213 8. **LSP post-edit hook** (v0.8.6): if the tool was `edit_file`/`apply_patch`/`write_file` and LSP is enabled, the engine runs `run_post_edit_lsp_hook()` to collect diagnostics
214 9. **Diagnostics flush** (v0.8.6): before the next API request, `flush_pending_lsp_diagnostics()` injects any collected errors as a synthetic user message
215 10. Result returned to agent loop
216
217 ### Background Tasks
218
219 1. Client enqueues task (`/task add ...` or `POST /v1/tasks`)
220 2. `task_manager.rs` persists task + queue entry under `~/.deepseek/tasks`
221 3. Worker picks queued task (bounded pool), transitions to `running`
222 4. Task creates/uses a runtime thread and starts a runtime turn
223 5. `runtime_threads.rs` persists thread/turn/item records + monotonic event sequence
224 6. Timeline/tool summaries/artifact references are persisted incrementally
225 7. Checklist state, verifier gates, PR attempts, and guarded GitHub events are applied from tool metadata to the active task
226 8. Final state (`completed|failed|canceled`) is durable and queryable via TUI/API
227
228 Model-visible durable task tools are a surface over this same manager. They do
229 not introduce a parallel work system: `task_create` enqueues normal tasks,
230 `checklist_*` updates task-local progress, `task_gate_run` and completed
231 `task_shell_wait` attach verification evidence, and automation runs enqueue
232 ordinary durable tasks.
233
234 ### Runtime Thread/Turn Timeline
235
236 1. API/TUI creates or resumes a thread (`/v1/threads*`)
237 2. Turn starts on the thread (`/v1/threads/{id}/turns`)
238 3. Engine events are mapped to item lifecycle events (`item.started|item.delta|item.completed`)
239 4. Interrupt/steer operations apply to the active turn only
240 5. Compaction (auto/manual) is emitted as `context_compaction` item lifecycle
241 6. Clients replay history and resume with `/v1/threads/{id}/events?since_seq=<n>`
242
243 ### Durable Schema Gates
244
245 - `session_manager.rs`, `runtime_threads.rs`, and `task_manager.rs` embed `schema_version` on persisted records.
246 - On load, newer schema versions are rejected with explicit errors instead of silently truncating/overwriting data.
247 - This allows safe forward migrations and prevents corruption when binaries and stored state are out of sync.
248
249 ## Extension Points
250
251 ### Adding a New Tool
252
253 1. Create handler in `tools/`
254 2. Register in `tools/registry.rs`
255 3. Add tool specification (name, description, input schema)
256
257 ### Adding an MCP Server
258
259 1. Configure in `~/.deepseek/mcp.json`
260 2. Server auto-discovered at startup
261 3. Tools exposed to LLM automatically
262
263 ### Creating a Skill
264
265 1. Create skill directory with `SKILL.md`
266 2. Define skill prompt and optional scripts
267 3. Place in `~/.deepseek/skills/`
268
269 ### Adding Hooks
270
271 Configure in `~/.deepseek/config.toml`:
272
273 ```toml
274 [[hooks]]
275 event = "tool_call_before"
276 command = "echo 'Running tool: $TOOL_NAME'"
277 ```
278
279 ## Key Design Decisions
280
281 1. **Streaming-first**: All LLM responses stream for responsiveness
282 2. **Tool safety**: Non-YOLO mode requires approval for destructive operations, including side-effectful MCP tools
283 3. **Extensibility**: MCP, skills, and hooks allow customization without code changes
284 4. **Cross-platform**: Core works on Linux/macOS/Windows, sandboxing macOS-only
285 5. **Minimal dependencies**: Careful dependency selection for build speed
286 6. **Local-first runtime API**: HTTP/SSE endpoints are intended for trusted localhost access and are served by the `crates/tui` runtime today
287
288 ## Configuration Files
289
290 - `~/.deepseek/config.toml` - Main configuration
291 - `/etc/deepseek/managed_config.toml` - Optional managed defaults layer (Unix)
292 - `/etc/deepseek/requirements.toml` - Optional allowed-policy constraints (Unix)
293 - `~/.deepseek/mcp.json` - MCP server configuration
294 - `~/.deepseek/skills/` - User skills directory
295 - `~/.deepseek/sessions/` - Session history
296 - `~/.deepseek/sessions/checkpoints/` - Crash checkpoint + offline queue persistence
297 - `~/.deepseek/snapshots/` - Side-git pre/post-turn workspace snapshots for `/restore` and `revert_turn`
298 - `~/.deepseek/tasks/` - Background task records, queue, timelines, artifacts
299 - `~/.deepseek/audit.log` - Append-only audit events for credential + approval/elevation actions
300
300 lines MARKDOWN