介绍

架构设计

深入理解aster的三层架构设计

架构设计

aster采用灵感来自DeepAgents的三层可扩展架构,通过清晰的分层和抽象实现高度可扩展性。

🏗️ 整体架构

三层架构

┌─────────────────────────────────────────────────────────┐
│                      Agent Layer                        │
│  ┌──────────────────────────────────────────────────┐  │
│  │             Middleware Stack                     │  │
│  │  ┌────────────────────────────────────────────┐  │  │
│  │  │  SummarizationMiddleware (priority: 40)   │  │  │
│  │  │  - Auto summarize (>170k tokens)         │  │  │
│  │  │  - Keep recent 6 messages                 │  │  │
│  │  └────────────────────────────────────────────┘  │  │
│  │  ┌────────────────────────────────────────────┐  │  │
│  │  │  FilesystemMiddleware (priority: 100)     │  │  │
│  │  │  - Tools: [fs_*, bash_*]                  │  │  │
│  │  │  - Auto eviction (>20k tokens)            │  │  │
│  │  └────────────────────────────────────────────┘  │  │
│  │  ┌────────────────────────────────────────────┐  │  │
│  │  │  SubAgentMiddleware (priority: 200)       │  │  │
│  │  │  - Tools: [task]                          │  │  │
│  │  │  - Context isolation                      │  │  │
│  │  └────────────────────────────────────────────┘  │  │
│  │  ┌────────────────────────────────────────────┐  │  │
│  │  │  CustomMiddleware (priority: 500+)        │  │  │
│  │  └────────────────────────────────────────────┘  │  │
│  └──────────────────────────────────────────────────┘  │
│         │ WrapModelCall      │ WrapToolCall            │
│         ▼                    ▼                         │
│  ┌─────────────┐      ┌──────────────┐                │
│  │  Provider   │      │ Tool Executor│                │
│  │  (Stream)   │      │  (Execute)   │                │
│  └─────────────┘      └──────────────┘                │
└─────────────────────────────────────────────────────────┘
                         │
                         ▼
┌─────────────────────────────────────────────────────────┐
│                    Backend Layer                        │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐  │
│  │ StateBackend │  │ StoreBackend │  │FilesystemBE  │  │
│  │  (临时内存)  │  │  (持久化)    │  │  (真实FS)    │  │
│  └──────────────┘  └──────────────┘  └──────────────┘  │
│                ┌──────────────────┐                     │
│                │ CompositeBackend │                     │
│                │   (路由组合)     │                     │
│                └──────────────────┘                     │
└─────────────────────────────────────────────────────────┘

第一层:Agent层

负责Agent的核心运行时逻辑:

  • 中间件栈:洋葱模型的中间件组合
  • Provider:大模型API调用
  • 工具执行器:工具调用和结果处理
  • 事件分发:Progress/Control/Monitor三通道

第二层:Backend层

提供统一的存储抽象:

  • StateBackend:内存临时存储
  • StoreBackend:持久化存储
  • FilesystemBackend:真实文件系统
  • VectorBackend:向量存储与语义记忆(可选)
  • CompositeBackend:路由组合

第三层:基础设施层

  • Sandbox:代码执行环境(本地/云端)
  • Scheduler:任务调度器
  • Permission:权限控制
  • MCP Client:MCP协议客户端

🧅 中间件系统

中间件系统是aster的核心设计,采用洋葱模型实现功能的灵活组合。

洋葱模型

Request → M1 → M2 → M3 → Handler → M3 → M2 → M1 → Response
          ↓    ↓    ↓              ↑    ↑    ↑
      Before Before Before       After After After

Middleware接口

type Middleware interface {
    // 基础信息
    Name() string
    Priority() int  // 0-100: 系统, 100-500: 功能, 500+: 用户

    // 提供工具
    Tools() []tools.Tool

    // 双向拦截
    WrapModelCall(ctx, req, handler) (*ModelResponse, error)
    WrapToolCall(ctx, req, handler) (*ToolCallResponse, error)

    // 生命周期
    OnAgentStart(ctx, agentID) error
    OnAgentStop(ctx, agentID) error
}

内置中间件

1. SummarizationMiddleware

功能:自动管理上下文长度

  • 优先级:40
  • 触发条件:消息历史超过170k tokens
  • 处理方式
    1. 保留最近6条消息
    2. 总结更早的消息
    3. 用总结替换旧历史
// 启用自动总结
config := &types.AgentConfig{
    Middlewares: []string{"summarization"},
}

2. FilesystemMiddleware

功能:提供文件系统操作工具

  • 优先级:100
  • 工具Read, Write, Edit, Ls, Glob, Grep
  • 特性
    • 自动驱逐大结果(>20k tokens)
    • 系统提示词增强
    • Backend抽象支持
fsMiddleware := middleware.NewFilesystemMiddleware(&middleware.FilesystemMiddlewareConfig{
    Backend:        backend,
    EnableEviction: true,
    TokenLimit:     20000,
})

3. SubAgentMiddleware

功能:任务委派到子Agent

  • 优先级:200
  • 工具task
  • 特性
    • 上下文隔离
    • 并发执行支持
    • 可配置子Agent规格
subagentMiddleware := middleware.NewSubAgentMiddleware(&middleware.SubAgentMiddlewareConfig{
    Specs: []middleware.SubAgentSpec{
        {Name: "researcher", Description: "Research expert"},
        {Name: "coder", Description: "Coding expert"},
    },
    Factory:        subagentFactory,
    EnableParallel: true,
})

中间件栈管理

// 创建栈(自动按优先级排序)
stack := middleware.NewStack([]middleware.Middleware{
    fsMiddleware,       // priority: 100
    subagentMiddleware, // priority: 200
    customMiddleware,   // priority: 500
})

// 获取所有工具
tools := stack.Tools()

// 执行模型调用(经过所有中间件)
response := stack.WrapModelCall(ctx, request, finalHandler)

🗄️ Backend抽象层

Backend提供统一的存储接口,支持多种实现。

BackendProtocol接口

type BackendProtocol interface {
    // 文件操作
    Read(ctx, path, offset, limit) (string, error)
    Write(ctx, path, content) (*WriteResult, error)
    Edit(ctx, path, old, new, replaceAll) (*EditResult, error)

    // 目录操作
    ListInfo(ctx, path) ([]FileInfo, error)
    GlobInfo(ctx, pattern, path) ([]FileInfo, error)

    // 搜索
    GrepRaw(ctx, pattern, path, glob) ([]GrepMatch, error)
}

四种Backend实现

Backend生命周期使用场景特点
StateBackend会话级临时文件、中间结果内存存储,快速
StoreBackend跨会话知识库、记忆持久化,可恢复
FilesystemBackend永久工作空间文件真实文件系统
CompositeBackend-混合存储策略路由组合

使用示例

单一Backend

// 内存临时存储
backend := backends.NewStateBackend()
backend.Write(ctx, "/temp.txt", "content")

// 持久化存储
storeBackend := backends.NewStoreBackend(storeImpl, "agent-id")
storeBackend.Write(ctx, "/memory.txt", "persistent data")

// 真实文件系统
fsBackend := backends.NewFilesystemBackend(sandboxFS)
fsBackend.Write(ctx, "/workspace/output.txt", "result")

组合Backend

// 路由策略:不同路径使用不同后端
composite := backends.NewCompositeBackend(
    backends.NewStateBackend(), // 默认后端
    []backends.RouteConfig{
        {Prefix: "/memories/", Backend: storeBackend},
        {Prefix: "/workspace/", Backend: fsBackend},
    },
)

// /memories/* → 持久化存储
composite.Write(ctx, "/memories/user_profile.json", data)

// /workspace/* → 真实文件系统
composite.Write(ctx, "/workspace/output.py", code)

// 其他路径 → 内存临时存储
composite.Write(ctx, "/temp/cache.txt", temp)

🎯 事件驱动架构

aster采用事件驱动架构,通过三个独立通道分离不同类型的事件。

三通道设计

通道用途典型订阅者事件类型
Progress实时进度、UI展示前端、聊天界面文本流、工具执行
Control审批、人机交互审批服务、安全网关工具审批请求
Monitor监控、审计监控系统、日志平台错误、性能指标

事件订阅

// 订阅Progress通道
progressCh := ag.Subscribe([]types.AgentChannel{
    types.ChannelProgress,
}, nil)

for envelope := range progressCh {
    switch e := envelope.Event.(type) {
    case *types.ProgressTextChunkEvent:
        fmt.Print(e.Delta)  // 流式输出
    case *types.ProgressToolStartEvent:
        fmt.Printf("[Tool] %s\n", e.Call.Name)
    case *types.ProgressToolEndEvent:
        fmt.Printf("[Result] %v\n", e.Result)
    }
}

事件过滤

// 只订阅特定事件类型
eventCh := ag.Subscribe(
    []types.AgentChannel{types.ChannelProgress},
    &types.EventFilter{
        EventTypes: []string{
            "progress.text_chunk",
            "progress.tool_start",
        },
    },
)

🛠️ 工具系统

工具接口

type Tool interface {
    Name() string
    Description() string
    InputSchema() map[string]interface{}
    Execute(ctx context.Context, input map[string]interface{}) (interface{}, error)
}

工具注册

// 创建注册表
registry := tools.NewRegistry()

// 注册所有内置工具
builtin.RegisterAll(registry)

// 或选择性注册
registry.Register(builtin.NewFileSystemTool())
registry.Register(builtin.NewBashTool())

// 注册自定义工具
registry.Register(&MyCustomTool{})

工具分类

文件系统工具

  • Read:读取文件(支持分页)
  • Write:写入文件
  • Edit:精确编辑(字符串替换)
  • Ls:列出目录
  • Glob:Glob模式匹配
  • Grep:正则搜索

命令执行工具

  • Bash:执行Bash命令

任务管理工具

  • todo_list:列出待办事项
  • todo_add:添加待办
  • todo_update:更新待办状态

网络工具

  • http_fetch:HTTP请求
  • WebSearch:网络搜索

子Agent工具

  • task:任务委派

🏭 Provider系统

Provider接口

type Provider interface {
    // 流式API
    StreamMessages(ctx, request) (<-chan StreamEvent, error)

    // 非流式API
    Messages(ctx, request) (*Response, error)

    // 模型信息
    Name() string
    SupportedModels() []string
}

支持的Provider

Provider模型特点
AnthropicClaude 3/4系列长上下文、工具调用优秀
OpenAIGPT-4/GPT-3.5生态成熟
DeepSeekDeepSeek-V2性价比高
GLMChatGLM系列中文优化

使用示例

// Anthropic
p := provider.NewAnthropicProvider(apiKey)

// OpenAI
p := provider.NewOpenAIProvider(apiKey)

// DeepSeek
p := provider.NewDeepSeekProvider(apiKey)

// 统一接口调用
stream, _ := p.StreamMessages(ctx, request)
for event := range stream {
    // 处理流式事件
}

🔒 沙箱系统

沙箱类型

类型使用场景隔离级别配置
LocalSandbox开发测试进程级本地Docker
AliyunSandbox生产环境容器级AgentBay
VolcengineSandbox生产环境容器级火山引擎
MockSandbox单元测试无隔离模拟执行

配置示例

// 本地沙箱
Sandbox: &types.SandboxConfig{
    Kind:    types.SandboxKindLocal,
    WorkDir: "./workspace",
}

// 阿里云沙箱
Sandbox: &types.SandboxConfig{
    Kind:    types.SandboxKindAliyun,
    WorkDir: "/workspace",
    Config: map[string]interface{}{
        "region":    "cn-hangzhou",
        "accessKey": os.Getenv("ALIYUN_AK"),
        "secretKey": os.Getenv("ALIYUN_SK"),
    },
}

📊 性能指标

基于Apple M1, Go 1.21的性能测试:

操作性能内存分配吞吐量
Middleware Stack36.21 ns/op96 B/op~27M ops/s
Backend Write257.9 ns/op480 B/op~3.8M ops/s
Tool Execution< 1ms1-5 KB1000+ ops/s

🎨 设计模式

1. Protocol + Factory模式

// 定义协议
type BackendProtocol interface { ... }

// 工厂函数
type BackendFactory func(ctx) (BackendProtocol, error)

// 延迟初始化
backend := factory(ctx)

2. 洋葱模型

type Middleware interface {
    WrapModelCall(ctx, req, next) (*Response, error)
}

// 自动组合
stack.WrapModelCall(ctx, req, finalHandler)

3. 观察者模式

// 订阅事件
ch := ag.Subscribe(channels, filter)

// 发布事件
ag.Emit(event)

🔄 与DeepAgents对比

特性DeepAgents (Python)aster (Go)
Backend Protocol✅ 4种✅ 4种
Middleware栈✅ 洋葱模型✅ 洋葱模型
文件工具✅ 6个✅ 6个
自动驱逐
子代理
性能中等极高
内存
并发GIL限制真正并发
类型安全动态静态

📚 下一步

🔗 相关资源