OpenClaw 自愈Agent设计与故障恢复

更新时间:2026-04-24 | 预计阅读:13分钟

凌晨4点,我的Agent挂了——进程还在,但脑子已经不转了。它卡在某个API调用上,超时了也不知道重试,像一个迷路的送餐员站在路灯下发呆。于是我决定,下一个Agent必须学会自己站起来。

什么是自愈Agent

自愈Agent(Self-healing Agent)是一种具备故障检测、自动恢复和优雅降级能力的AI智能体。它不只是"出错重试",而是像一个有经验的运维工程师——知道什么错了、怎么修、修不好怎么办。

核心能力矩阵

  • 故障检测:识别API超时、网络断连、内存溢出、无限循环
  • 自我诊断:分析错误日志,定位问题根因
  • 自动恢复:重试、切换备用方案、释放资源、重启服务
  • 优雅降级:核心功能可用,非核心功能关闭
  • 告警升级:无法自愈时及时通知人类

故障检测策略

心跳监测

// Agent心跳机制
const heartbeat = {
  interval: 30000,  // 30秒心跳
  timeout: 60000,   // 60秒无响应视为离线
  actions: {
    onMiss: (count) => {
      if (count >= 3) {
        // 连续3次心跳丢失,触发恢复流程
        triggerRecovery('heartbeat_miss');
      }
    }
  }
};

// 守护进程检测
setInterval(() => {
  const lastBeat = getLastHeartbeat();
  if (Date.now() - lastBeat > heartbeat.timeout) {
    heartbeat.actions.onMiss(getMissCount());
  }
}, heartbeat.interval);

资源监控

// 资源阈值检测
const resourceThresholds = {
  memory: {
    warning: 0.7,   // 70%内存使用率警告
    critical: 0.9,  // 90%触发清理
    action: 'cleanup' // 清理缓存、关闭非必要连接
  },
  cpu: {
    warning: 0.8,
    critical: 0.95,
    action: 'throttle' // 降速处理
  },
  tasks: {
    maxConcurrent: 10,
    maxQueued: 100,
    action: 'reject' // 拒绝新任务
  }
};

任务超时检测

// 任务执行监控
async function executeWithTimeout(task, timeout) {
  const controller = new AbortController();
  const timeoutId = setTimeout(() => controller.abort(), timeout);

  try {
    const result = await task(controller.signal);
    clearTimeout(timeoutId);
    return result;
  } catch (err) {
    if (err.name === 'AbortError') {
      // 超时处理
      await handleTimeout(task);
    }
    throw err;
  }
}

async function handleTimeout(task) {
  // 1. 记录超时
  logError('task_timeout', { task: task.name });

  // 2. 尝试重试
  if (task.retries < task.maxRetries) {
    return retry(task);
  }

  // 3. 升级到备用方案
  return fallbackPlan(task);
}

自动恢复机制

重试策略

// 智能重试:指数退避 + 抖动
async function smartRetry(fn, options = {}) {
  const { maxRetries = 3, baseDelay = 1000, maxDelay = 30000 } = options;

  for (let i = 0; i < maxRetries; i++) {
    try {
      return await fn();
    } catch (err) {
      if (i === maxRetries - 1) throw err;

      // 指数退避 + 随机抖动
      const delay = Math.min(
        baseDelay * Math.pow(2, i) + Math.random() * 1000,
        maxDelay
      );
      await sleep(delay);
    }
  }
}

故障转移

// 多节点故障转移
const nodes = [
  { url: 'https://api.openclaw.com', priority: 1 },
  { url: 'https://api.openclaw-backup.com', priority: 2 },
  { url: 'https://api.openclaw-dr.com', priority: 3 }
];

async function callWithFailover(endpoint, data) {
  for (const node of sortBy(nodes, 'priority')) {
    try {
      return await fetch(`${node.url}${endpoint}`, {
        method: 'POST',
        body: JSON.stringify(data),
        timeout: 10000
      });
    } catch (err) {
      logError('node_failed', { node: node.url, error: err.message });
      // 尝试下一个节点
    }
  }
  throw new Error('All nodes failed');
}

状态恢复

// 从检查点恢复
async function recoverFromCheckpoint(sessionId) {
  // 1. 加载最后已知状态
  const checkpoint = await loadCheckpoint(sessionId);

  // 2. 验证检查点完整性
  if (!validateCheckpoint(checkpoint)) {
    // 检查点损坏,从头开始
    return startFresh(sessionId);
  }

  // 3. 恢复上下文
  await restoreContext(checkpoint.context);

  // 4. 从中断点继续
  return resumeFrom(checkpoint.lastStep);
}

优雅降级设计

功能分级

// 功能优先级定义
const featureLevels = {
  critical: ['chat', 'basic_tools'],      // 必须
  important: ['web_search', 'memory'],     // 重要
  optional: ['image_gen', 'advanced_rag']  // 可选
};

// 根据系统状态降级
function degradeBasedOnStatus(status) {
  if (status.memoryUsage > 0.9) {
    // 内存紧张,关闭可选功能
    disableFeatures(featureLevels.optional);
  }
  if (status.apiErrorRate > 0.3) {
    // API错误率高,降级到本地模式
    switchToLocalModel();
  }
}

熔断器模式

// 熔断器:防止级联故障
class CircuitBreaker {
  constructor(threshold = 5, resetTime = 60000) {
    this.failures = 0;
    this.threshold = threshold;   // 失败阈值
    this.resetTime = resetTime;   // 重置时间
    this.state = 'closed';        // closed | open | half-open
  }

  async execute(fn) {
    if (this.state === 'open') {
      throw new Error('Circuit breaker is open');
    }

    try {
      const result = await fn();
      this.onSuccess();
      return result;
    } catch (err) {
      this.onFailure();
      throw err;
    }
  }

  onFailure() {
    this.failures++;
    if (this.failures >= this.threshold) {
      this.state = 'open';
      setTimeout(() => {
        this.state = 'half-open';
        this.failures = 0;
      }, this.resetTime);
    }
  }

  onSuccess() {
    this.failures = 0;
    this.state = 'closed';
  }
}

监控与告警

// 自愈监控仪表盘
const healthMetrics = {
  uptime: '99.7%',
  mttr: '45 seconds',        // 平均恢复时间
  selfHealed: 23,            // 自愈次数
  escalated: 2,              // 升级次数
  lastIncident: '2026-04-23T20:15:00Z',
  currentStatus: 'healthy'
};

// 告警规则
const alertRules = [
  {
    condition: 'consecutive_failures >= 3',
    severity: 'warning',
    action: 'notify_feishu'
  },
  {
    condition: 'recovery_failed',
    severity: 'critical',
    action: 'notify_human + disable_agent'
  },
  {
    condition: 'memory_usage > 95%',
    severity: 'critical',
    action: 'emergency_cleanup + notify'
  }
];

最佳实践总结

  1. 设计时假设一切都会失败——网络、API、磁盘、内存
  2. 自愈不是万能的——定义清晰的"无法自愈"边界
  3. 记录所有自愈动作——审计需要,调试需要
  4. 定期演练故障——确保恢复机制真的能用
  5. 保持简单——复杂的自愈机制本身可能成为故障点

相关资源