# 《Crush 从入门到精通》第十四、五、六章:工具实现、数据库与并发安全
## 第十四章:工具系统实现
### fantasy.AgentTool 接口
```go
type AgentTool interface {
// 工具唯一标识
Name() string
// 工具描述(供 AI 理解)
Description() string
// 参数模式(JSON Schema)
Parameters() any
// 执行工具
Execute(ctx context.Context, params any) (ToolResponse, error)
}
```
### 工具注册机制
```go
func (c *coordinator) buildTools(ctx context.Context) ([]AgentTool, error) {
var tools []AgentTool
// 1. 文件操作工具
tools = append(tools, tools.NewReadTool(c.history, c.cfg.WorkingDir()))
tools = append(tools, tools.NewWriteTool(c.history, c.cfg.WorkingDir()))
tools = append(tools, tools.NewEditTool(...))
// 2. 命令执行工具
tools = append(tools, tools.NewBashTool(...))
// 3. 搜索工具
tools = append(tools, tools.NewGrepTool(...))
tools = append(tools, tools.NewGlobTool(...))
// 4. 网络工具
tools = append(tools, tools.NewFetchTool(...))
tools = append(tools, tools.NewWebSearchTool(...))
// 5. LSP 工具
tools = append(tools, tools.NewDiagnosticsTool(...))
tools = append(tools, tools.NewReferencesTool(...))
// 6. MCP 工具(动态加载)
mcpTools, err := c.buildMCPTools(ctx)
tools = append(tools, mcpTools...)
return tools, nil
}
```
---
## 第十五章:数据库与存储
### 数据库 Schema
```
┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ sessions │ │ messages │ │ files │
├─────────────┤ ├─────────────┤ ├─────────────┤
│ id (PK) │◀──┐ │ id (PK) │ │ id (PK) │
│ title │ │ │ session_id │──▶ │ session_id │
│ parent_id │───┼───│ role │ │ path │
│ created_at │ │ │ content │ │ content │
└─────────────┘ │ └─────────────┘ └─────────────┘
│
└──────▶ read_files (关联表)
```
### 核心表定义
```sql
-- Sessions 表
CREATE TABLE sessions (
id TEXT PRIMARY KEY,
parent_session_id TEXT,
title TEXT NOT NULL,
summary_message_id TEXT,
todos TEXT,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL
);
-- Messages 表
CREATE TABLE messages (
id TEXT PRIMARY KEY,
session_id TEXT NOT NULL,
role TEXT NOT NULL,
parts TEXT NOT NULL,
model TEXT,
provider TEXT,
created_at INTEGER NOT NULL
);
-- Files 表
CREATE TABLE files (
id TEXT PRIMARY KEY,
session_id TEXT NOT NULL,
path TEXT NOT NULL,
content TEXT NOT NULL,
created_at INTEGER NOT NULL
);
```
---
## 第十六章:并发与安全
### csync 同步原语
```
csync/
├── maps.go # 线程安全 Map
├── slices.go # 线程安全 Slice
├── value.go # 原子值封装
├── versionedmap.go # 带版本的 Map
```
### Map 实现
```go
type Map[K comparable, V any] struct {
mu sync.RWMutex
m map[K]V
}
func (m *Map[K, V]) Get(key K) (V, bool) {
m.mu.RLock()
defer m.mu.RUnlock()
val, ok := m.m[key]
return val, ok
}
func (m *Map[K, V]) Set(key K, value V) {
m.mu.Lock()
defer m.mu.Unlock()
m.m[key] = value
}
```
### 事件系统
```
发布者 (Publisher)
│
│ Publish(event, data)
▼
┌─────────────────────────────────────────┐
│ Broker │
│ ┌─────────────────────────────────────┐│
│ │ Topic/Event Type ││
│ │ Created | Updated | Deleted ││
│ └─────────────────────────────────────┘│
└─────────────────────────────────────────┘
│
▼
订阅者 (Subscriber)
```
---
*本文是《Crush 从入门到精通》系列文章的第三部分完结*
登录后可参与表态
讨论回复
0 条回复还没有人回复,快来发表你的看法吧!