Code Reader
首页
帮助
设计文档
首页
帮助
设计文档
  • 工具系统架构

工具系统架构

Moltbot 的 Agent 工具注册、过滤和执行机制

概述

工具系统是 Moltbot Agent 的核心能力层,通过工具(Tools)给 AI 模型提供执行外部操作的能力。支持工具注册、细粒度权限控制、沙箱适配和流式结果返回。

设计目标

  • 模块化工具: 每个工具作为独立模块定义
  • 细粒度控制: 多层级的工具权限策略
  • 沙箱适配: 工具可在 Docker 沙箱中运行
  • 流式执行: 支持长时间运行工具的进度反馈
  • 类型安全: 使用 TypeBox/Zod 定义工具 Schema

核心工具类型

内置工具列表

工具类别工具名说明
文件操作read读取文件内容
write写入文件
edit编辑文件(应用补丁)
apply_patch应用补丁文件
执行bash执行 Shell 命令
process启动后台进程
浏览器browser.*浏览器控制
Canvascanvas.*Canvas 操作
会话sessions_list列出会话
sessions_history获取会话历史
sessions_send发送消息到其他会话
sessions_spawn启动子代理
通道send发送消息到渠道
节点node.*远程节点操作
Croncron.*定时任务管理
Discorddiscord.*Discord API 操作
Webweb.*Web 请求
Gmailgmail.*Gmail 操作

工具注册流程

工具创建

文件: src/agents/pi-tools.ts

export function createMoltbotCodingTools(params: {
  exec: ExecFunction;
  sandbox: SandboxContext | null;
  messageProvider?: string;
  ...}): ToolCollection {
  // 1. 解析工具策略
  // 2. 构建基础工具
  // 3. 应用策略过滤
  // 4. 包装 Abort Signal
  // 5. 返回工具集合
}

工具构建流程

工具策略过滤

策略层次

优先级(从高到低):

策略配置

{
  agents: {
    defaults: {
      // 全局工具策略
      tools: {
        profile: {
          allow: ["*"],
          deny: ["system.run", "system.notify"]
        }
      }
    },
    list: {
      work: {
        // Agent 特定策略
        tools: {
          allow: ["bash", "read", "write", "edit"],
          deny: ["process", "browser"]
        }
      }
    }
  },

  // Provider 特定策略
  tools: {
    byProvider: {
      anthropic: {
        profile: {
          deny: ["cron.*", "discord.*"]
        }
      }
    }
  },

  // Sandbox 策略
  tools: {
    sandbox: {
      tools: {
        allow: ["bash", "process", "read", "write"],
        deny: ["browser", "canvas", "nodes"]
      }
    }
  }
}

Glob 匹配

// 匹配所有 bash 相关工具
"bash*"

// 匹配 sessions 开头的工具
"sessions_*"

// 匹配除了 session 开头的所有工具
"!sessions_*"

// 多个模式
["bash*", "read", "write"]

工具执行

执行流程

沙箱工具适配

文件: src/agents/sandbox/context.ts

// 沙箱工具包装器
function wrapSandboxTool(tool: AnyAgentTool, ctx: SandboxContext): AnyAgentTool {
  return {
    name: tool.name,
    description: tool.description,
    parameters: tool.parameters,
    handler: async (args, signal) => {
      if (!ctx.enabled) {
        throw new Error("Sandbox not enabled");
      }

      // 在沙箱容器中执行
      return await executeInSandbox({
        containerName: ctx.containerName,
        toolName: tool.name,
        args,
        signal,
      });
    },
  };
}

工具超时

// 工具执行超时控制
const TOOL_TIMEOUT_MS = 120_000; // 2 分钟

async function executeToolWithTimeout(
  tool: AnyAgentTool,
Handler,
  args: unknown,
  signal: AbortSignal,
): Promise<ToolResult> {
  const timeoutSignal = AbortSignal.timeout(TOOL_TIMEOUT_MS);

  // 组合多个信号
  const combinedSignal = combineSignals([signal, timeoutSignal]);

  return await toolHandler(args, combinedSignal);
}

插件工具

工具注册

文件: src/plugins/types.ts

// 插件注册工具
api.registerTool({
  name: "my_tool",
  description: "My custom tool",
  parameters: {
    type: "object",
    properties: {
      input: {
        type: "string",
        description: "Input string"
      }
    },
    required: ["input"]
  },
}, {
  name: "my_tool",      // 工具名(用于引用)
  names: ["alias1"],   // 别名列表
  optional: true,        // 是否可选
});

工具工厂

// 工具工厂函数
export type MoltbotPluginToolFactory = (
  ctx: MoltbotPluginToolContext,
) => AnyAgentTool | AnyAgentTool[] | null | undefined;

// Channel 插件提供 Agent 工具
export type ChannelPlugin<ResolvedAccount = any> = {
  agentTools?: ChannelAgentToolFactory | ChannelAgentTool[];
  // ...
};

工具类型定义

AnyAgentTool

export type AnyAgentTool = {
  name: string;
  description: string;
  parameters?: {
    type: "object";
    properties?: Record<string, ToolParameter>;
    required?: string[];
    additionalProperties?: boolean;
  };
  handler: (args: unknown, signal: AbortSignal) => Promise<ToolResult>;
  // 可选字段
  category?: string;
  hidden?: boolean;
  experimental?: boolean;
};

ToolParameter

export type ToolParameter = {
  type: "string" | "number" | "boolean" | "array" | "object";
  description?: string;
  enum?: string[];
  default?: unknown;
  format?: string;
  minimum?: number;
  maximum?: number;
  // 可选字段
  hidden?: boolean;
};

ToolResult

export type ToolResult = {
  content: string;
  is_error?: boolean;
  data?: Record<string, unknown>;
  // 可选字段
  attachments?: MediaAttachment[];
};

工具元数据

工具分组

文件: src/agents/pi-tools.ts

// 工具按类别分组
export const TOOL_CATEGORIES = {
  "file-system": "文件系统操作",
  "execution": "命令执行",
  "browser": "浏览器控制",
  "canvas": "Canvas 操作",
  "sessions": "会话管理",
  "channels": "渠道消息",
  "nodes": "远程节点",
  "cron": "定时任务",
  "discord": "Discord API",
  "web": "Web 请求",
};

工具描述生成

// 动态生成工具描述
function generateToolDescription(tool: AnyAgentTool, ctx: ToolContext): string {
  let desc = tool.description;

  // 添加 Sandbox 信息
  if (ctx.inSandbox) {
    desc += " (在沙箱容器中运行)";
  }

  // 添加权限信息
  if (ctx.requiresApproval) {
    desc += " (需要执行批准)";
  }

  return desc;
}

代码路径引用

功能文件路径
工具创建src/agents/pi-tools.ts
工具策略src/agents/tool-policy.ts
沙箱适配src/agents/sandbox/context.ts
执行工具src/agents/sandbox/docker.ts
Bash 工具src/agents/bash-tools.ts
Process 工具src/agents/process-tools.ts
Channel 工具src/agents/channel-tools.ts
插件工具src/plugins/types.ts