核心架构

系统层次结构

┌─────────────────────────────────────────────────────────────┐
│                    通道层 (Channels)                        │
│    Discord / Slack / Telegram / QQ / Web / etc.             │
└─────────────────────────────────────────────────────────────┘
                           │
                           ▼
┌─────────────────────────────────────────────────────────────┐
│                   消息路由层 (Routing)                       │
│              会话管理 / 消息分发 / 上下文路由                 │
└─────────────────────────────────────────────────────────────┘
                           │
                           ▼
┌─────────────────────────────────────────────────────────────┐
│                   Agent 运行时核心                          │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────────────┐  │
│  │ CLI Runner  │  │ Embedded PI │  │ Subagent Registry   │  │
│  └─────────────┘  └─────────────┘  └─────────────────────┘  │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────────────┐  │
│  │  Skills     │  │ Tool Policy │  │ Session Management │  │
│  └─────────────┘  └─────────────┘  └─────────────────────┘  │
└─────────────────────────────────────────────────────────────┘
                           │
                           ▼
┌─────────────────────────────────────────────────────────────┐
│                   工具执行引擎                               │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────────────┐  │
│  │ Bash/Exec   │  │  Sandbox    │  │ Tool Policy Engine  │  │
│  └─────────────┘  └─────────────┘  └─────────────────────┘  │
└─────────────────────────────────────────────────────────────┘
                           │
                           ▼
┌─────────────────────────────────────────────────────────────┐
│                   模型提供商层                              │
│  Claude / OpenAI / MiniMax / Bedrock / Venice / etc.       │
└─────────────────────────────────────────────────────────────┘

Agent 生命周期状态机

系统启动

收到消息

加载会话上下文

构建系统提示词

调用模型

模型请求工具

工具执行完成

流式输出响应

处理流式块

需要更多工具调用

继续流式输出

消息结束

上下文压缩

压缩完成

错误处理

重试

放弃并返回错误

会话结束

Idle

Initializing

LoadingContext

PreparingPrompt

RunningAgent

ToolExecution

Streaming

Processing

MessageEnd

Compacting

Error

Recovering

Terminating

工具调用机制

工具执行引擎架构

安全层

工具包装层

工具类型

Bash/Exec 工具

沙箱执行

Read 工具

沙箱化读取

Write 工具

沙箱化写入

Edit 工具

沙箱化编辑

ApplyPatch 工具

补丁工具

工具调用入口

normalizeToolName

filterToolsByPolicy

isToolAllowedByPolicies

AbortSignal 包装

调用前钩子

参数规范化

策略检查

沙箱策略

主机环境验证

危险变量检测

工具策略引擎

策略应用

策略解析

工具策略配置

工具组

group:fs

文件系统工具

group:runtime

运行时工具

group:web

Web 工具

group:memory

内存工具

工具配置

工具策略

工具组定义

resolveSubagentToolPolicy

resolveGroupToolPolicy

resolveEffectiveToolPolicy

filterToolsByPolicy

collectExplicitAllowlist

expandPolicyWithPluginGroups

Skills 渐进式披露机制

OpenClaw 的 Skills 系统采用**渐进式披露(Progressive Disclosure)**设计,通过分层加载策略优化上下文使用,在保证功能完整性的同时最小化 token 消耗。

1. 三层加载系统

Layer 3: Bundled Resources 层

Layer 2: SKILL.md Body 层

Layer 1: Metadata 层

Frontmatter

name

description

metadata

完整文档内容

使用说明

示例代码

参数定义

scripts/

可执行脚本

工具脚本

references/

参考文档

assets/

静态资源

1.1 Metadata 层(总是加载)

加载时机:Agent 启动时立即加载所有已安装 Skills 的 frontmatter

Frontmatter 解析流程

// src/agents/skills/frontmatter.ts
export function parseFrontmatter(content: string): ParsedSkillFrontmatter {
  return parseFrontmatterBlock(content);
}

export function resolveOpenClawMetadata(
  frontmatter: ParsedSkillFrontmatter,
): OpenClawSkillMetadata | undefined {
  // 解析 metadata JSON5 块
  // 提取 requires、install、os 等配置
}

export function resolveSkillInvocationPolicy(
  frontmatter: ParsedSkillFrontmatter,
): SkillInvocationPolicy {
  return {
    userInvocable: parseFrontmatterBool(getFrontmatterValue(frontmatter, "user-invocable"), true),
    disableModelInvocation: parseFrontmatterBool(
      getFrontmatterValue(frontmatter, "disable-model-invocation"),
      false,
    ),
  };
}

触发条件

  • always: true → 总是包含在 prompt 中
  • 依赖检查通过 → requires.binsrequires.envrequires.config
  • 操作系统匹配 → metadata.os
  • 远程平台支持 → eligibility.remote.platforms

匹配逻辑

// src/agents/skills/config.ts
export function shouldIncludeSkill(params: {
  entry: SkillEntry;
  config?: OpenClawConfig;
  eligibility?: SkillEligibilityContext;
}): boolean {
  const { entry, config, eligibility } = params;
  
  // 1. 配置启用检查
  if (skillConfig?.enabled === false) {
    return false;
  }
  
  // 2. Bundled allowlist 检查
  if (!isBundledSkillAllowed(entry, allowBundled)) {
    return false;
  }
  
  // 3. 操作系统匹配
  if (osList.length > 0 && !osList.includes(resolveRuntimePlatform())) {
    return false;
  }
  
  // 4. always: true 强制包含
  if (entry.metadata?.always === true) {
    return true;
  }
  
  // 5. 依赖检查
  const requiredBins = entry.metadata?.requires?.bins ?? [];
  for (const bin of requiredBins) {
    if (!hasBinary(bin) && !eligibility?.remote?.hasBin?.(bin)) {
      return false;
    }
  }
  
  return true;
}
1.2 SKILL.md Body 层(条件加载)

加载时机:当某个 Skill 被模型识别为可能需要使用时

Prompt 构建流程

// src/agents/skills/workspace.ts
export function buildWorkspaceSkillsPrompt(
  workspaceDir: string,
  opts?: {
    config?: OpenClawConfig;
    managedSkillsDir?: string;
    bundledSkillsDir?: string;
    entries?: SkillEntry[];
    skillFilter?: string[];
    eligibility?: SkillEligibilityContext;
  },
): string {
  const skillEntries = opts?.entries ?? loadSkillEntries(workspaceDir, opts);
  
  // 过滤适用的 Skills
  const eligible = filterSkillEntries(
    skillEntries,
    opts?.config,
    opts?.skillFilter,
    opts?.eligibility,
  );
  
  // 排除 disableModelInvocation 的 Skills
  const promptEntries = eligible.filter(
    (entry) => entry.invocation?.disableModelInvocation !== true,
  );
  
  // 生成提示词
  return formatSkillsForPrompt(promptEntries.map((entry) => entry.skill));
}

条件加载触发条件

  • Skill name 出现在用户 query 中
  • Skill description 与用户意图语义匹配
  • Skill 已被显式命令调用(如 /skill-name

上下文管理策略

// 使用 formatSkillsForPrompt 生成精简的 skill 列表
// 只包含 name 和 description,不包含完整 SKILL.md 内容
1.3 Bundled Resources 层(按需加载)

资源类型

  • scripts/ → 可执行脚本和工具脚本
  • references/ → 参考文档和技术资料
  • assets/ → 静态资源文件

执行时的动态加载

// scripts/ 加载示例
// 脚本在工具执行时由工具定义动态加载
// 不是预先加载到上下文,而是在需要时直接执行

// references/ 引用
// 当工具执行需要特定文档时,按需读取
// 例如:外部 API 文档、配置文件模板等

2. 触发与匹配机制

2.1 技能匹配算法

用户 Query

解析 Frontmatter

提取 name 和 description

提取 keywords/tags

匹配算法

关键词精确匹配

模糊匹配

语义相似度

优先级排序

Top-K Skills

加载 SKILL.md

匹配策略

  1. 关键词匹配:Skill name、description 中的关键词
  2. 命令匹配/skill-name 格式的显式调用
  3. 语义匹配:基于 embedding 的相似度计算
2.2 条件加载决策树
渲染错误: Mermaid 渲染失败: Lexical error on line 3. Unrecognized text. ...} B --> C[/命令开头?] C -->|是| D[加载对 ----------------------^
2.3 多技能优先级排序
// 优先级规则
const SKILL_PRIORITY = [
  // 1. 显式命令调用(最高优先级)
  { type: "explicit_command", score: 100 },
  
  // 2. 精确关键词匹配
  { type: "exact_match", score: 80 },
  
  // 3. 前缀匹配
  { type: "prefix_match", score: 60 },
  
  // 4. 模糊匹配
  { type: "fuzzy_match", score: 40 },
  
  // 5. 语义相似度
  { type: "semantic_similarity", score: 20 },
];

3. 上下文优化策略

3.1 上下文膨胀控制

文件大小阈值

// 限制单个 SKILL.md 加载大小
const MAX_SKILL_CONTENT_SIZE = 50 * 1024; // 50KB

// 超过阈值的 Skill 摘要处理
function summarizeSkillContent(content: string): string {
  if (content.length > MAX_SKILL_CONTENT_SIZE) {
    return extractSummary(content);
  }
  return content;
}

加载顺序优化

// 优先级加载策略
const LOAD_ORDER = [
  "bundled/",    // 内置 Skills(最先加载)
  "managed/",    // 管理 Skills
  "workspace/",  // 工作区 Skills(最后加载,优先级最高)
];

缓存机制

// Skill Snapshot 缓存
export function buildWorkspaceSkillSnapshot(
  workspaceDir: string,
  opts?: {
    snapshotVersion?: number;
  },
): SkillSnapshot {
  // 缓存构建结果
  // 版本变化时重新构建
}
3.2 渐进式披露流程图
LLM 模型 Prompt 构建器 Snapshot 缓存 Skills 加载器 Agent 运行时 LLM 模型 Prompt 构建器 Snapshot 缓存 Skills 加载器 Agent 运行时 alt [缓存有效] [缓存过期] 模型分析用户意图 alt [需要执行 Skill] 加载 Skills 检查缓存 返回缓存 返回缓存 Snapshot 重新扫描 Skills 解析 Frontmatter 过滤适用 Skills 构建 Skills Prompt 返回 Prompt 更新缓存 返回 Snapshot 构建完整 Prompt 发送请求 返回响应 解析 Skill 调用 加载完整 SKILL.md 读取 SKILL.md 内容 加载 scripts/ 资源 执行 Skill 发送 Skill 执行结果 返回最终响应
Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐