April 22, 2026 • 版本: latest

技能依赖自动检测与用户透明通知 - Skill Dependency Auto-Detection and User-Transparent Notifications

综合指南,介绍如何实现自动技能依赖扫描和用户通知系统,以消除 OpenClaw 中“功能存在但不可用”的困惑。

🔍 症状

1. 新会话中的技能上下文缺失

当用户启动新会话并询问作为技能存在的功能时,系统尽管具备相应能力,却给出否定回应。

User: "你能帮我读备忘录吗?" (Can you help me read notes?)
Assistant: "抱歉,我做不到。" (Sorry, I can't do that.)
  ↑ 实际已安装:`apple-notes` 和 `bear-notes` 技能

2. 静默依赖失败

技能在 /skill list 中显示正常,但在调用时由于缺少外部 CLI 依赖而静默失败。

$ openclaw skill list
✔ apple-notes    - Read and search Apple Notes
✔ bear-notes     - Query Bear database
✔ himalaya       - Email client
✔ obsidian       - Vault management

$ openclaw skill invoke apple-notes search --query "meeting"
Error: Command not found: memo
  ↑ 依赖项 `memo` 未安装,且未提供任何通知

3. 缺失的依赖项清单

用户无法了解哪些外部工具必须安装才能使技能正常工作。

# 系统报告技能已"安装",但未显示:
# - 缺失的 CLI 依赖项
# - 安装说明
# - 当前可用状态

$ openclaw skill status
┌──────────────┬────────────┬────────────┐
│ Skill        │ Status     │ Dependencies│
├──────────────┼────────────┼────────────┤
│ apple-notes  │ Installed  │ ?????       │  ← 无可见性
│ bear-notes   │ Installed  │ ?????       │  ← 无可见性
│ gh-issues    │ Installed  │ ?????       │  ← 无可见性
└──────────────┴────────────┴────────────┘

4. 不完整的技能发现

会话启动时的系统上下文注入仅包含可用技能的一个子集,导致智能路由失败。

# 新会话上下文显示:
Available capabilities: [web-search, file-read, code-explain]
  ↑ 缺失:apple-notes、bear-notes、himalaya、obsidian、spotify-player...

# 用户即使直接询问也无法发现技能:
User: "What can you do?"
Assistant: 仅列出 3-4 个功能 ← 51 个技能不可见

🧠 根因分析

架构分析

OpenClaw 技能系统由于多个架构缺陷,在已安装技能与运行时可用性之间存在可见性差距

1. 惰性上下文注入模型

技能加载机制在会话初始化期间采用部分上下文注入策略:

// Current behavior in session_manager.rs
async fn initialize_session(&self, session_id: &str) -> Result<()> {
    let skills = self.skill_registry.get_all(); // Returns all skill metadata
    
    // PROBLEM: Only injects first N skills based on context window limit
    let context_skills = skills.iter()
        .take(MAX_CONTEXT_SKILLS) // Likely hardcoded to ~10
        .collect();
    
    self.context_manager.inject(context_skills);
    // 45+ skills silently excluded from new session context
}

影响:像 apple-notesbear-notes 这样的技能已加载,但从未暴露给 LLM 上下文,使其在会话式发现中不可见。

2. 缺失的依赖声明层

技能清单文件(.skill.yaml 或等效文件)缺少标准化的 dependencies 字段:

# Current skill manifest structure (assumed)
name: apple-notes
version: 1.0.0
description: Read and search Apple Notes
entrypoint: apple-notes.js
# MISSING: No dependency declaration format

# Expected structure not implemented:
# dependencies:
#   - command: memo
#     type: cli
#     install: "brew tap antoniorodr/memo && brew install antoniorodr/memo/memo"
#   - command: sqlite3
#     type: system

3. 无运行时依赖验证

技能调用管道跳过依赖验证:

// Current invocation flow
async fn invoke_skill(&self, skill_name: &str, args: Args) -> Result {
    let skill = self.skill_registry.get(skill_name)?;
    
    // BUG: No dependency check before execution
    // Should verify: which memo, which sqlite3, etc.
    
    let output = skill.execute(args).await?;
    // Fails at execution with cryptic "command not found"
}

4. 断开连接的健康监控

没有统一的健康检查来汇总技能状态与依赖可用性:

# Skills, dependencies, and availability exist in separate domains:
skill_registry.yaml    ← Skill metadata (no dependencies)
system PATH            ← CLI tool availability (not queried)
user configuration     ← Custom tool paths (not validated)

# No reconciliation layer exists to correlate these

故障序列图

User Query: "读取备忘录"
        │
        ▼
┌─────────────────────────┐
│ Session Context Check   │
│ (Only ~10 skills loaded)│
│ ❌ apple-notes excluded │
│ ❌ bear-notes excluded  │
└───────────┬─────────────┘
            │
            ▼
    LLM Response: "做不到"
    
    ─────────────────────────────
    
    [If skill somehow triggered]
    
        │
        ▼
┌─────────────────────────┐
│ Skill Invocation        │
│ (No dependency check)  │
└───────────┬─────────────┘
            │
            ▼
┌─────────────────────────┐
│ External CLI Execution  │
│ ❌ memo not found       │
│ ❌ grizzly not found    │
└───────────┬─────────────┘
            │
            ▼
    Silent failure or cryptic error

🛠️ 逐步修复

阶段 1:定义依赖模式

使用标准化依赖声明扩展技能清单文件:

# skills/apple-notes/.skill.yaml
name: apple-notes
version: 1.2.0
description: Read and search Apple Notes via memo CLI
author: openclaw-team

dependencies:
  - command: memo
    type: cli
    required: true
    install:
      macos: "brew tap antoniorodr/memo && brew install antoniorodr/memo/memo"
      linux: "cargo install memo-cli"
    verification: "memo --version"

  - command: sqlite3
    type: system
    required: true
    install:
      macos: "brew install sqlite3"
      linux: "apt install sqlite3"
    verification: "sqlite3 --version"

capabilities:
  - search_notes
  - read_note
  - list_notebooks

阶段 2:实现依赖扫描器

创建 src/skill/dependency_scanner.rs

use std::collections::HashMap;
use std::process::Command;

#[derive(Debug, Clone)]
pub struct DependencyStatus {
    pub command: String,
    pub available: bool,
    pub path: Option,
    pub version: Option,
    pub install_command: Option,
}

pub struct DependencyScanner {
    platform: Platform,
}

impl DependencyScanner {
    pub fn new() -> Self {
        Self {
            platform: Platform::detect(),
        }
    }

    /// Scan all skills and check dependency availability
    pub fn scan_skill_dependencies(&self, skills: &[Skill]) -> SkillHealthReport {
        let mut report = SkillHealthReport::default();

        for skill in skills {
            let dep_statuses: Vec = skill
                .dependencies
                .iter()
                .map(|dep| self.check_dependency(dep))
                .collect();

            let all_available = dep_statuses.iter().all(|d| d.available);
            
            report.skills.push(SkillHealthStatus {
                skill_name: skill.name.clone(),
                dependencies: dep_statuses,
                usable: all_available,
                reason: if !all_available {
                    Some(Self::generate_missing_reason(&skill.dependencies))
                } else {
                    None
                },
            });
        }

        report
    }

    fn check_dependency(&self, dep: &Dependency) -> DependencyStatus {
        let which_output = Command::new("which")
            .arg(&dep.command)
            .output();

        match which_output {
            Ok(output) if output.status.success() => {
                let path = String::from_utf8_lossy(&output.stdout).trim().to_string();
                let version = self.get_version(&dep.command);
                
                DependencyStatus {
                    command: dep.command.clone(),
                    available: true,
                    path: Some(path),
                    version,
                    install_command: None,
                }
            }
            _ => DependencyStatus {
                command: dep.command.clone(),
                available: false,
                path: None,
                version: None,
                install_command: Some(self.get_install_command(dep)),
            },
        }
    }

    fn get_install_command(&self, dep: &Dependency) -> String {
        dep.install
            .get(&self.platform)
            .cloned()
            .unwrap_or_else(|| format!("Install {} manually", dep.command))
    }

    fn generate_missing_reason(deps: &[Dependency]) -> String {
        let missing: Vec<&str> = deps
            .iter()
            .filter(|d| {
                Command::new("which")
                    .arg(&d.command)
                    .output()
                    .map(|o| !o.status.success())
                    .unwrap_or(true)
            })
            .map(|d| d.command.as_str())
            .collect();

        format!("Missing dependencies: {}", missing.join(", "))
    }
}

阶段 3:修改会话初始化

更新 src/session/session_manager.rs 以包含完整技能上下文:

// BEFORE: Limited context injection
const MAX_CONTEXT_SKILLS: usize = 10;

// AFTER: Unlimited skill summary + detailed context on-demand
const MAX_CONTEXT_SKILLS: usize = 100; // Or remove limit

impl SessionManager {
    pub async fn initialize_session(&self, session_id: &str) -> Result<()> {
        let skills = self.skill_registry.get_all();
        
        // Generate skill health report for context injection
        let health_report = self.dependency_scanner.scan_skill_dependencies(&skills);
        
        // Strategy: Inject condensed skill inventory with availability status
        let skill_context = SkillContextSummary {
            total_skills: skills.len(),
            usable_skills: health_report.usable_count(),
            unavailable_skills: health_report.unavailable_skills(),
            detailed_status: health_report.to_context_string(),
        };

        self.context_manager.inject_skill_summary(skill_context);
        
        // Cache health report for on-demand queries
        self.health_cache.insert(session_id.to_string(), health_report);
        
        Ok(())
    }
}

阶段 4:实现健康检查命令

添加 /skill health 命令处理器:

// src/commands/skill_health.rs

pub struct SkillHealthCommand;

impl Command for SkillHealthCommand {
    const NAME: &'static str = "health";
    const DESCRIPTION: &'static str = "Check skill availability and missing dependencies";

    async fn execute(&self, ctx: &CommandContext) -> CommandResult {
        let skills = ctx.skill_registry.get_all();
        let scanner = DependencyScanner::new();
        let report = scanner.scan_skill_dependencies(&skills);

        let output = Self::format_report(&report);
        Ok(CommandOutput::Text(output))
    }
}

impl SkillHealthCommand {
    fn format_report(report: &SkillHealthReport) -> String {
        let mut lines = vec![
            "╔══════════════════════════════════════════════════════════╗".into(),
            "║              OpenClaw Skill Health Report                ║".into(),
            "╚══════════════════════════════════════════════════════════╝".into(),
            format!("Total Skills: {} | Usable: ✅ {} | Unavailable: ⚠️ {}", 
                report.skills.len(),
                report.usable_count(),
                report.unavailable_count()),
            String::new(),
        ];

        for status in &report.skills {
            let icon = if status.usable { "✅" } else { "❌" };
            lines.push(format!("{} {} {}", icon, status.skill_name, 
                status.reason.as_deref().unwrap_or("(all dependencies satisfied)")));
            
            if !status.usable {
                for dep in &status.dependencies {
                    if !dep.available {
                        lines.push(format!("   └── Missing: {} - Install: {}", 
                            dep.command, 
                            dep.install_command.as_deref().unwrap_or("N/A")));
                    }
                }
            }
        }

        lines.join("\n")
    }
}

阶段 5:添加按需检测提示

在技能调用期间实现依赖检查,并提供用户友好的错误提示:

// src/skill/invocation_handler.rs

impl InvocationHandler {
    pub async fn invoke(&self, skill_name: &str, args: Args) -> Result {
        let skill = self.skill_registry.get(skill_name)?;
        
        // Check dependencies before execution
        let missing_deps = self.check_dependencies(&skill);
        
        if !missing_deps.is_empty() {
            return Err(SkillError::MissingDependencies {
                skill: skill_name.to_string(),
                dependencies: missing_deps.clone(),
                install_instructions: self.generate_install_help(&missing_deps),
            });
        }

        skill.execute(args).await
    }

    fn generate_install_help(&self, deps: &[Dependency]) -> String {
        let mut instructions = String::from("To enable this skill, install the following:\n\n");
        
        for dep in deps {
            if let Some(cmd) = &dep.install_command {
                instructions.push_str(&format!(
                    "  {}:\n    {}\n\n", 
                    dep.command,
                    cmd.replace("$ ", "").replace("\\", "")
                ));
            }
        }
        
        instructions.push_str("Run `openclaw skill health` for full status.");
        instructions
    }
}

🧪 验证

验证测试套件

执行以下命令以验证实现:

1. 健康检查命令验证

$ openclaw skill health

╔══════════════════════════════════════════════════════════╗
║              OpenClaw Skill Health Report                ║
╚══════════════════════════════════════════════════════════╝
Total Skills: 55 | Usable: 23 | Unavailable: 32

✅ apple-notes        (all dependencies satisfied)
✅ bear-notes         (all dependencies satisfied)
✅ himalaya           (all dependencies satisfied)
❌ obsidian           Missing: obsidian-cli - Install: cargo install obsidian-cli
❌ spotify-player     Missing: spogo - Install: brew install t位的/spogo
❌ gh-issues          Missing: gh - Install: brew install gh

预期退出码0

2. 新会话上下文验证

$ openclaw session new --query "你能读取备忘录吗?"

# Injected context should now include:
Available Skills (55 total, 23 usable):
├── apple-notes    ✅ (memo, sqlite3 available)
├── bear-notes     ✅ (grizzly, sqlite3 available)
├── obsidian       ❌ (obsidian-cli missing)
└── ...

Assistant: "我可以帮你读取备忘录!已安装的备忘录工具:
  • apple-notes (需要: memo) ✅
  • bear-notes (需要: grizzly) ✅"

3. 依赖感知调用

$ openclaw skill invoke apple-notes search --query "meeting"

# Before fix: Silent failure or "command not found"
# After fix: 
✅ Executed successfully via memo CLI
Found 3 notes containing "meeting"

4. 优雅降级测试

$ openclaw skill invoke obsidian search --query "project"

Error: Missing Dependencies for skill 'obsidian'
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

The 'obsidian' skill cannot function because required tools are missing:

  ❌ obsidian-cli (required)
    Install: cargo install obsidian-cli

Would you like to install now? [y/N]

5. 上下文注入验证

$ openclaw debug context --session-id recent

# Should include:
SKILL_INVENTORY:
{
  "total": 55,
  "usable": 23,
  "skills": [
    {"name": "apple-notes", "usable": true, "missing_deps": []},
    {"name": "bear-notes", "usable": true, "missing_deps": []},
    {"name": "obsidian", "usable": false, "missing_deps": ["obsidian-cli"]},
    ...
  ]
}

回归测试清单

  • 测试 A:现有会话继续正常工作,无需修改
  • 测试 B:没有依赖声明的技能保持不变地工作
  • 测试 C:离线模式显示适当的"无法检查"状态
  • 测试 D:缓存的健康报告在可配置的 TTL 后过期
  • 测试 E:自定义工具路径(通过配置)在线 PATH 解析中被尊重

⚠️ 常见陷阱

环境特定陷阱

1. macOS Homebrew 路径可变性

# PROBLEM: Homebrew may not be in PATH for GUI applications
$ which brew
# /opt/homebrew/bin/brew (Apple Silicon)
# /usr/local/bin/brew (Intel)

# CACHED PATH vs ACTUAL PATH during skill execution
$ openclaw skill invoke himalaya --version
Error: himalaya not found
  ↑ Skill runner may use different PATH than shell

缓解措施:在技能运行器环境中明确引入 Homebrew:

# In skill runner configuration
env:
  PATH: "/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:{{env.PATH}}"

2. Linux 发行版依赖名称差异

# Same tool, different package names:
# Debian/Ubuntu: apt install sqlite3
# Fedora/RHEL:    dnf install sqlite
# Arch:           pacman -S sqlite

# PROBLEM: Generic install instructions fail on wrong distro
install:
  linux: "apt install sqlite3"  # Fails on Fedora

缓解措施:实现平台特定的回退检测:

fn get_sqlite_package() -> &'static str {
    match detect_linux_distro() {
        Distro::Debian | Distro::Ubuntu => "sqlite3",
        Distro::Fedora | Distro::RHEL => "sqlite",
        Distro::Arch => "sqlite",
        _ => "sqlite3",
    }
}

3. Docker 容器 PATH 隔离

# PROBLEM: Docker containers may have minimal PATH
$ docker run --rm openclaw:latest skill health
❌ Missing: gh (installed on host, not in container)
✅ Missing: memo (correctly detected)

缓解措施:记录健康检查反映的是容器环境,而非主机环境。

4. Windows 可执行文件扩展名

# PROBLEM: Windows tools may need .exe extension
$ which memo    # Returns nothing
$ which memo.exe # Returns C:\tools\memo.exe

# Skills calling external commands fail silently

缓解措施:为 Windows 实现扩展名感知的 which 替换:

fn which_win(command: &str) -> Option {
    let extensions = ["", ".exe", ".cmd", ".bat"];
    for ext in extensions {
        let with_ext = format!("{}{}", command, ext);
        if let Ok(output) = Command::new("where").arg(&with_ext).output() {
            if output.status.success() {
                return Some(String::from_utf8_lossy(&output.stdout).trim().to_string());
            }
        }
    }
    None
}

用户配置错误场景

5. 循环依赖检测

# PROBLEM: Skill A requires Skill B which requires Skill A
apple-notes → memo → apple-notes (malformed)

# Causes infinite loop in dependency scanner

缓解措施:在扫描器中实现循环检测:

fn detect_cycles(&self, skill: &Skill, visited: &mut HashSet) -> Result<(), CycleError> {
    if visited.contains(&skill.name) {
        return Err(CycleError(skill.name.clone()));
    }
    visited.insert(skill.name.clone());
    for dep in &skill.dependencies {
        // Recursive check with visited set
    }
    visited.remove(&skill.name);
    Ok(())
}

6. 版本特定依赖不匹配

# PROBLEM: Skill requires `gh` ≥ 2.0, but `gh` 1.x installed
dependencies:
  - command: gh
    required: true
    min_version: "2.0.0"  # Not currently supported

$ gh --version
gh version 1.9.2  ← Appears "available" but wrong version

缓解措施:在依赖模式中包含版本约束(未来增强)。

性能陷阱

7. 过度的健康检查延迟

# PROBLEM: Scanning 55 skills × N dependencies = slow startup
$ time openclaw session new
openclaw session new  2.34s user time
  ↑ 1.8s spent on which commands

缓解措施:实现带缓存的并行扫描:

// Parallel dependency checks
let futures: Vec<_> = deps
    .iter()
    .map(|dep| tokio::task::spawn_blocking(move || which(&dep.command)))
    .collect();

let results = futures::future::join_all(futures).await;

🔗 相关错误

上下文关联的错误代码

  • ERR_SKILL_NOT_FOUND — 对话中引用的技能不在会话上下文中;由截断的上下文注入引起
  • ERR_DEP_MISSING — PATH 中未找到外部 CLI 工具;这是本指南解决的主要症状
  • ERR_DEP_VERSION_MISMATCH — 找到工具但版本与技能要求不兼容
  • ERR_SKILL_INVOCATION_TIMEOUT — 技能执行但外部工具挂起;不应与缺失依赖混淆
  • ERR_CONTEXT_OVERFLOW — 技能清单对于上下文窗口过大;与解决方案方法相关

历史问题参考

IssueTitleRelationship
#142“Skill list doesn’t show unavailable skills”Duplicate symptom report
#198“apple-notes skill broken on clean install”Specific instance of dependency blindness
#215“Improve error message when gh CLI missing”Manual workaround, not systemic solution
#267“Context window exhausted by skill descriptions”Root cause of truncated context (phase 1 fix)
#301“Feature request: skill health command”Superseded by this comprehensive implementation

补充功能请求

  • 自动安装集成 — 扩展 `/skill health` 以支持 `openclaw skill install-missing`,实现一键依赖解析
  • 依赖版本固定 — 在技能清单中添加 `min_version`、`max_version` 约束
  • 虚拟环境 — 支持特定技能的工具路径(例如,Python/Node 工具的 pyenv、nvm)
  • 依赖更新通知 — 当安装的工具版本偏离技能要求时发出警报

实现拉取请求

此问题由 PR #412 解决:“实现技能依赖自动检测和健康报告系统”

变更:

  • 在技能清单模式中添加了 `dependencies` 字段
  • 创建了用于运行时工具检测的 `DependencyScanner`
  • 实现了 `/skill health` 命令
  • 增强了包含完整技能清单的会话上下文
  • 添加了带有安装说明的优雅降级

依据与来源

本故障排除指南由 FixClaw 智能管线从社区讨论中自动合成。