Skip to content

🔧 AgentCore

AgentCore 是 VTeamOS 的核心引擎,负责工具执行、消息路由、插件管理和决策追踪。


🎯 核心职责

1. 工具执行

AgentCore 管理 12 工具基座,提供统一的执行接口:

go
// 工具执行接口
type ToolExecutor interface {
    Execute(ctx context.Context, tool string, input map[string]any) (map[string]any, error)
    ListTools(ctx context.Context) []ToolDef
    GetToolSchema(ctx context.Context, tool string) (*JSONSchema, error)
}

基座工具列表:

工具功能示例
shell命令执行ls -la, git status
filesystem文件操作read, write, list
web网络请求fetch, search
httpHTTP 客户端get, post
datetime时间处理now, format
memory_store记忆存储save, update
memory_recall记忆召回search, query

2. 消息路由

AgentCore 负责将消息路由到正确的 AgentClaw:

go
// 消息路由接口
type MessageRouter interface {
    Route(ctx context.Context, msg *UnifiedMessage) error
    RegisterChannel(ctx context.Context, channel Channel) error
    GetChannel(ctx context.Context, name string) (Channel, error)
}

路由策略:

  • 🎯 用户绑定: 用户 → AgentClaw 映射
  • 📡 渠道分发: 不同渠道不同处理逻辑
  • 🔄 负载均衡: 多实例间的请求分发

3. 插件管理

AgentCore 管理 WASM/Go/MCP 插件的生命周期:

go
// 插件管理接口
type PluginManager interface {
    Load(ctx context.Context, plugin Plugin) error
    Unload(ctx context.Context, name string) error
    GetPlugin(ctx context.Context, name string) (Plugin, error)
    ListPlugins(ctx context.Context) []PluginInfo
}

插件类型:

  • 🔧 WASM 插件: Rust/TinyGo 编译,安全隔离
  • Go 插件: 原生性能,深度集成
  • 🌐 MCP 插件: 外部服务,JSON-RPC 通信

4. 决策追踪

AgentCore 记录每个任务的执行路径:

go
// 决策追踪接口
type DecisionTracer interface {
    StartTrace(ctx context.Context, taskID string) *TraceContext
    RecordStep(ctx context.Context, step *DecisionStep) error
    GetTrace(ctx context.Context, taskID string) (*DecisionTrace, error)
}

追踪内容:

  • 📊 工具调用: 哪个工具、什么输入、什么输出
  • 🧠 决策过程: 为什么选择这个工具
  • ⏱️ 时间线: 每步的执行时间
  • 错误记录: 失败的调用和原因

🏗️ 架构设计

核心结构

go
// AgentCore 核心结构
type AgentCore struct {
    mu          sync.RWMutex
    tools       map[string]ToolExecutor
    router      MessageRouter
    plugins     PluginManager
    tracer      DecisionTracer
    logger      *slog.Logger
    
    // 配置
    config      *CoreConfig
    llm         LLMProvider
    memory      MemorySystem
}

工具注册

go
// 注册工具
func (c *AgentCore) registerTools() {
    c.tools["shell"] = NewShellTool()
    c.tools["filesystem"] = NewFilesystemTool()
    c.tools["web"] = NewWebTool()
    c.tools["http"] = NewHTTPTool()
    c.tools["datetime"] = NewDateTimeTool()
    c.tools["memory_store"] = NewMemoryStoreTool()
    c.tools["memory_recall"] = NewMemoryRecallTool()
    // ... 更多工具
}

消息处理流程

go
// 处理消息
func (c *AgentCore) HandleMessage(ctx context.Context, msg *UnifiedMessage) error {
    // 1. 开始追踪
    trace := c.tracer.StartTrace(ctx, msg.TaskID)
    
    // 2. 路由到 AgentClaw
    claw, err := c.router.GetClaw(ctx, msg.UserID)
    if err != nil {
        return err
    }
    
    // 3. 执行任务
    result, err := claw.Execute(ctx, msg, trace)
    if err != nil {
        trace.RecordError(err)
        return err
    }
    
    // 4. 记录结果
    trace.RecordResult(result)
    
    // 5. 回复消息
    return c.router.Reply(ctx, msg, result)
}

🔌 插件系统

WASM 插件

WASM 插件提供最高级别的安全隔离:

rust
// Rust WASM 插件示例
#[no_mangle]
pub extern "C" fn execute(input_ptr: *const u8, input_len: usize) -> *mut u8 {
    // 读取输入
    let input = unsafe { std::slice::from_raw_parts(input_ptr, input_len) };
    let input_str = std::str::from_utf8(input).unwrap();
    
    // 执行逻辑
    let result = process_input(input_str);
    
    // 返回结果
    let output = result.as_bytes();
    let ptr = output.as_ptr() as *mut u8;
    std::mem::forget(output);
    ptr
}

Go 插件

Go 插件提供原生性能:

go
// Go 插件接口
type GoPlugin interface {
    Name() string
    Version() string
    Init(ctx context.Context, config map[string]any) error
    Execute(ctx context.Context, input map[string]any) (map[string]any, error)
    Shutdown(ctx context.Context) error
}

MCP 插件

MCP 插件集成外部服务:

json
// MCP 工具定义
{
  "name": "web_search",
  "description": "Search the web",
  "inputSchema": {
    "type": "object",
    "properties": {
      "query": {
        "type": "string",
        "description": "Search query"
      }
    }
  }
}

📊 决策追踪

追踪示例

json
{
  "task_id": "task_123",
  "user_message": "帮我查一下今天的天气",
  "steps": [
    {
      "step": 1,
      "tool": "sop_search",
      "input": {"query": "天气查询"},
      "output": {"sop": "weather_query_sop"},
      "duration_ms": 45,
      "reason": "匹配到天气查询 SOP"
    },
    {
      "step": 2,
      "tool": "skill_view",
      "input": {"name": "weather"},
      "output": {"skill": "weather_skill"},
      "duration_ms": 32,
      "reason": "加载天气技能"
    },
    {
      "step": 3,
      "tool": "web",
      "input": {"url": "https://api.weather.com/..."},
      "output": {"temp": "25°C", "condition": "晴"},
      "duration_ms": 156,
      "reason": "调用天气 API"
    }
  ],
  "result": "今天天气晴朗,气温 25°C",
  "total_duration_ms": 233
}

追踪分析

  • 📈 性能分析: 哪些工具调用耗时最长
  • 🔍 决策审查: Agent 的推理过程是否合理
  • 🐛 问题诊断: 失败任务的根本原因
  • 📊 优化建议: 如何改进 SOP 和工具

🔧 配置

核心配置

yaml
# agentcore.yaml
agentcore:
  # LLM 配置
  llm:
    provider: "claude"
    model: "claude-3-5-sonnet"
    max_tokens: 4096
  
  # 工具配置
  tools:
    shell:
      enabled: true
      timeout: 30s
    filesystem:
      enabled: true
      root_dir: "/workspace"
  
  # 插件配置
  plugins:
    wasm_dir: "./plugins/wasm"
    go_dir: "./plugins/go"
    mcp_servers:
      - name: "web_search"
        url: "https://mcp.example.com"
  
  # 追踪配置
  tracing:
    enabled: true
    storage: "sqlite"
    retention_days: 30

🚀 快速开始

1. 初始化 AgentCore

go
core, err := agentcore.New(&agentcore.Config{
    LLM: &llm.Config{
        Provider: "claude",
        Model:    "claude-3-5-sonnet",
    },
    Tools: defaultToolConfig(),
    Plugins: defaultPluginConfig(),
})
if err != nil {
    log.Fatal(err)
}

2. 注册渠道

go
feishu := feishu.NewChannel(&feishu.Config{
    AppID:     "your_app_id",
    AppSecret: "your_app_secret",
})
core.RegisterChannel(feishu)

3. 启动服务

go
ctx := context.Background()
if err := core.Start(ctx); err != nil {
    log.Fatal(err)
}
defer core.Shutdown(ctx)

📚 下一步