CLAWIST.
🟡 中级阅读时间 11 分钟••作者:Lin6

使用 OpenClaw's 心跳系统构建主动式 AI 助手

笔记本电脑上的分析仪表板——示意图

大多数 AI 助手都是被动的——它们会等你开口提问才会行动。但如果你的助手能够在你察觉之前,就帮你检查紧急邮件、提醒即将召开的会议,或者提示系统问题,会怎么样呢?这就是主动式 AI,而 OpenClaw 的心跳系统让这一切成为可能。

在本指南中,您将学习如何配置心跳监控、设计智能检查流程,并打造一个能够预判您需求的 AI 助手。

什么是心跳监控?

A 心跳 是定期发送给 AI 助手的轮询。OpenClaw 无需等待用户输入,而是可以按固定间隔(每 30 分钟、每小时等)向您的代理发送询问:"有什么需要关注的事项吗?"

然后,代理可以:

  • 检查邮件中的紧急消息
  • 查看日历中即将发生的事件
  • 监控系统状态
  • 查看通知
  • 运行后台维护任务

如果有需要关注的事项,代理会主动联系您。如果没有,它会回复 HEARTBEAT_OK 并保持安静。

设置心跳

1. 在配置中启用心跳

编辑 ~/.openclaw/config/gateway.json:

{
  "heartbeat": {
    "enabled": true,
    "intervalMinutes": 30,
    "prompt": "Read HEARTBEAT.md if it exists (workspace context). Follow it strictly. Do not infer or repeat old tasks from prior chats. If nothing needs attention, reply HEARTBEAT_OK.",
    "channels": ["discord"]
  }
}

参数:

  • intervalMinutes:轮询频率(建议 15-60)
  • prompt:发送给代理的指令
  • channels:心跳发送的位置(例如 Discord 频道 ID,或使用 "main" 表示主会话)

2. 创建 HEARTBEAT.md

在您的工作区中(~/.openclaw/workspace/HEARTBEAT.md):

# HEARTBEAT.md - Proactive Monitoring Rules

## What to Check (Rotate Through These)

### Email (Check every 4 hours)
- Look for unread emails with "urgent", "important", or "ASAP"
- Check for calendar invites requiring response
- Flag messages from VIPs

### Calendar (Check twice daily: 8am, 6pm)
- Upcoming events in next 4 hours
- Events requiring preparation
- Conflicts or overlapping meetings

### System Status (Every 2 hours)
- Check disk usage: `df -h /`
- Check memory: `free -h`
- Review recent error logs: `journalctl -p err --since "30 minutes ago"`

### GitHub (Every 3 hours)
- Check for PR reviews requested
- Look for critical issues assigned to me

### Weather (Once daily: 7am)
- Check forecast for the day
- Alert if rain/snow/extreme temps expected

## State Tracking

Keep track of last checks in `memory/heartbeat-state.json`:

```json
{
  "lastChecks": {
    "email": 1708975200,
    "calendar": 1708970000,
    "system": 1708978800,
    "github": 1708972400,
    "weather": 1708945200
  }
}

何时主动联系

需要通知的情况:

  • 紧急邮件已到达
  • 会议将在 < 2 小时内开始
  • 磁盘使用率 > 85%
  • 日志中出现严重错误
  • 有 PR 请求审核

不要通知:

  • 深夜(晚上11点至早上7点),除非确实紧急
  • 今天已发送过相同的通知
  • 低优先级的例行事项

回复格式

如果有需要关注的事项:

📧 John 发来的紧急邮件:"需要在今天下班前提交季度报告"
📅 90 分钟后有会议:"下午2点团队站会"

如果没有需要关注的事项:

HEARTBEAT_OK

### 3. 重启 OpenClaw

```bash
openclaw restart

您的代理现在将每 30 分钟收到一次心跳提示。

设计智能检查流程

原则 1:轮换检查以降低成本

不要每次都检查所有内容。轮流进行不同的检查:

const checks = ['email', 'calendar', 'system', 'github'];
let currentCheckIndex = 0;

function getNextCheck() {
  const check = checks[currentCheckIndex];
  currentCheckIndex = (currentCheckIndex + 1) % checks.length;
  return check;
}

心跳 1: 检查邮件
心跳 2: 检查日历
心跳 3: 检查系统
心跳 4: 检查 GitHub
心跳 5: 回到邮件

原则 2:基于时间的检查

有些检查仅在特定时间才有意义:

function shouldCheck(checkType) {
  const hour = new Date().getHours();
  
  if (checkType === 'weather' && hour !== 7) {
    return false; // Only check weather at 7am
  }
  
  if (checkType === 'calendar' && hour < 8) {
    return false; // Don't check calendar before 8am
  }
  
  return true;
}

原则 3:频率限制

不要过于频繁地检查同一件事:

function needsCheck(checkType) {
  const state = loadState();
  const lastCheck = state.lastChecks[checkType] || 0;
  const now = Date.now();
  
  const intervals = {
    email: 4 * 60 * 60 * 1000,    // 4 hours
    calendar: 12 * 60 * 60 * 1000, // 12 hours
    system: 2 * 60 * 60 * 1000,    // 2 hours
    github: 3 * 60 * 60 * 1000     // 3 hours
  };
  
  return (now - lastCheck) > intervals[checkType];
}

邮件监控示例

通过 CLI 使用 Gmail

# Install gmail-cli or use API
npm install -g gmail-cli

# Check unread emails
gmail unread --label INBOX --max 10

邮件过滤逻辑

async function checkEmail() {
  const unread = await exec("gmail unread --label INBOX --max 20");
  const emails = parseEmails(unread);
  
  const urgent = emails.filter(email => {
    const subject = email.subject.toLowerCase();
    const sender = email.from.toLowerCase();
    
    // Flag urgent keywords
    if (subject.includes('urgent') || subject.includes('asap')) {
      return true;
    }
    
    // Flag VIP senders
    const vips = ['boss@company.com', 'client@important.com'];
    if (vips.some(vip => sender.includes(vip))) {
      return true;
    }
    
    return false;
  });
  
  if (urgent.length > 0) {
    return formatEmailAlert(urgent);
  }
  
  return null; // No urgent emails
}

function formatEmailAlert(emails) {
  return emails.map(email => 
    `📧 ${email.from}: "${email.subject}"`
  ).join('\n');
}

日历集成

通过 CLI 使用 Google 日历

# 安装 gcalcli
pip install gcalcli

# 查看即将到来的事件
gcalcli agenda --calendar "Personal" --tsv

日历检查逻辑

async function checkCalendar() {
  const now = new Date();
  const fourHoursFromNow = new Date(now.getTime() + 4 * 60 * 60 * 1000);
  
  const events = await exec(`gcalcli agenda --tsv --start "${now.toISOString()}" --end "${fourHoursFromNow.toISOString()}"`);
  const parsed = parseCalendarEvents(events);
  
  const upcoming = parsed.filter(event => {
    const timeUntil = event.start - now;
    const hoursUntil = timeUntil / (1000 * 60 * 60);
    
    // 提醒未来 2 小时内的事件
    return hoursUntil <= 2 && hoursUntil > 0;
  });
  
  if (upcoming.length > 0) {
    return formatCalendarAlert(upcoming);
  }
  
  return null;
}

function formatCalendarAlert(events) {
  return events.map(event => {
    const timeUntil = Math.round((event.start - Date.now()) / (1000 * 60));
    return `📅 In ${timeUntil} minutes: "${event.title}"`;
  }).join('\n');
}

系统监控

磁盘使用率

df -h / | awk 'NR==2 {print $5}' | sed 's/%//'

内存使用率

free | awk 'NR==2 {printf "%.0f", $3/$2 * 100}'

错误日志

journalctl -p err --since "1 hour ago" --no-pager | tail -20

系统检查逻辑

async function checkSystem() {
  const alerts = [];
  
  // 检查磁盘使用率
  const diskUsage = await exec("df -h / | awk 'NR==2 {print $5}' | sed 's/%//'");
  const diskPercent = parseInt(diskUsage.trim());
  
  if (diskPercent > 85) {
    alerts.push(`💾 Disk usage at ${diskPercent}% - consider cleanup`);
  }
  
  // 检查内存
  const memUsage = await exec("free | awk 'NR==2 {printf \"%.0f\", $3/$2 * 100}'");
  const memPercent = parseInt(memUsage.trim());
  
  if (memPercent > 90) {
    alerts.push(`🧠 Memory usage at ${memPercent}% - may need restart`);
  }
  
  // 检查错误日志
  const errors = await exec("journalctl -p err --since '1 hour ago' --no-pager | tail -20");
  const errorCount = errors.trim().split('\n').length;
  
  if (errorCount > 10) {
    alerts.push(`⚠️ ${errorCount} errors in last hour - check logs`);
  }
  
  return alerts.length > 0 ? alerts.join('\n') : null;
}

GitHub 集成

使用 GitHub CLI

# 安装 gh CLI
gh pr list --assignee @me
gh issue list --assignee @me

GitHub 检查逻辑

async function checkGitHub() {
  const alerts = [];
  
  // 检查被请求审查的 PR
  const prs = await exec("gh pr list --search 'review-requested:@me' --json number,title");
  const prList = JSON.parse(prs);
  
  if (prList.length > 0) {
    alerts.push(`🔍 ${prList.length} PR(s) awaiting your review`);
  }
  
  // 检查分配给自己的 issue
  const issues = await exec("gh issue list --assignee @me --state open --json number,title");
  const issueList = JSON.parse(issues);
  
  const criticalIssues = issueList.filter(issue => 
    issue.title.toLowerCase().includes('critical') ||
    issue.title.toLowerCase().includes('urgent')
  );
  
  if (criticalIssues.length > 0) {
    alerts.push(`🚨 ${criticalIssues.length} critical issue(s) assigned`);
  }
  
  return alerts.length > 0 ? alerts.join('\n') : null;
}

高级模式

条件通知

仅在清醒时段发送通知:

function shouldNotify() {
  const hour = new Date().getHours();
  
  // 静音时段:晚上 11 点 - 早上 7 点
  if (hour >= 23 || hour < 7) {
    return false;
  }
  
  return true;
}

通知去重

不要多次发送相同的提醒:

const sentAlerts = new Set();

function sendAlert(message) {
  const hash = hashString(message);
  
  if (sentAlerts.has(hash)) {
    console.log("Duplicate alert, skipping");
    return;
  }
  
  sentAlerts.add(hash);
  
  // 24 小时后清除哈希值
  setTimeout(() => sentAlerts.delete(hash), 24 * 60 * 60 * 1000);
  
  // 发送通知
  notifyUser(message);
}

优先级

按紧急程度对提醒进行分类:

const PRIORITY = {
  LOW: 1,
  MEDIUM: 2,
  HIGH: 3,
  CRITICAL: 4
};

function classifyAlert(alert) {
  if (alert.includes('critical') || alert.includes('urgent')) {
    return PRIORITY.CRITICAL;
  }
  if (alert.includes('important') || alert.includes('soon')) {
    return PRIORITY.HIGH;
  }
  // ... 等等
}

function shouldNotifyImmediately(priority) {
  // 在静音时段,仅通知关键提醒
  if (!isWakingHours() && priority < PRIORITY.CRITICAL) {
    return false;
  }
  return true;
}

主动维护任务

Heartbeat 不仅仅用于通知——还可以用它执行后台任务:

自动清理

async function performMaintenance() {
  // 清理旧日志文件
  await exec("find ~/.openclaw/logs -type f -mtime +7 -delete");
  
  // 归档旧的记忆文件
  await exec("tar -czf memory-archive-$(date +%Y%m).tar.gz memory/*.md");
  
  // 更新依赖
  if (Math.random() < 0.1) { // 10% 的心跳
    await exec("npm update -g openclaw");
  }
}

Git 自动提交

async function autoCommit() {
  const status = await exec("git status --porcelain");
  
  if (status.trim().length > 0) {
    await exec("git add memory/");
    await exec("git commit -m 'Auto-commit: memory update'");
    console.log("Auto-committed memory changes");
  }
}

Heartbeat 的成本优化

如果不加以优化,Heartbeat 的成本可能会很高:

使用低成本模型

{
  "heartbeat": {
    "model": "claude-haiku-3.5"  // 最便宜的模型
  }
}

保持上下文最小化

在 HEARTBEAT.md中,明确将上下文降至最低:

## 心跳上下文规则

- 仅加载 SOUL.md(身份信息)
- 不要加载 MEMORY.md(文件过大)
- 不要加载对话历史
- 将心跳逻辑控制在 1000 个 token 以内

批量检查

不要每次心跳只检查一件事:

## 批量检查计划

每 2 小时:
- 邮件 + 日历 + 系统(全部在一次心跳中完成)

每 6 小时:
- GitHub + 天气

监控心跳健康状况

记录心跳活动

# 查看心跳日志
grep "HEARTBEAT" ~/.openclaw/logs/gateway.log

跟踪响应时间

function logHeartbeat(durationMs, result) {
  const entry = {
    timestamp: new Date().toISOString(),
    durationMs,
    result: result === "HEARTBEAT_OK" ? "ok" : "alert",
    cost: estimateCost(result)
  };
  
  appendToFile("heartbeat-stats.jsonl", JSON.stringify(entry) + "\n");
}

真实案例

以下是来自生产环境 OpenClaw 部署的完整心跳工作流:

# HEARTBEAT.md

## 计划

- 邮件:每 4 小时一次(上午9点、下午1点、下午5点)
- 日历:每天两次(上午8点、下午6点)
- 系统:每 2 小时一次
- GitHub:工作时间内每 3 小时一次

## 逻辑

1. 从 memory/heartbeat-state.json 加载状态
2. 判断哪项检查到期
3. 运行检查
4. 如果发现警报:
   - 格式化消息
   - 检查今天是否已发送
   - 如果是新警报则发送
5. 使用 lastCheck 时间戳更新状态
6. 如果没有需要报告的内容,则返回 HEARTBEAT_OK

## 示例输出

典型的心跳周期:
- 90% 的时间:HEARTBEAT_OK
- 8% 的时间:单个警报
- 2% 的时间:多个警报

成本:约 $2/月(心跳使用 Haiku)

结论

心跳监控让您的 AI 助手从被动响应转变为主动出击。通过定期检查邮件、日历、系统状态和其他来源,您的智能体可以在您自己发现问题之前就向您发出警报。

核心原则:

  • 轮换检查以降低成本
  • 使用基于时间和频率的逻辑
  • 保持最小的上下文(使用 Haiku 模型)
  • 实施通知去重
  • 遵守免打扰时段
  • 跟踪状态以避免重复检查

通过精心配置,心跳功能可以在不增加大量成本的情况下带来巨大价值。


后续步骤: 探索 自托管 AI 助手的成本优化 以及 OpenClaw 自动化定时任务指南 来构建高效的自动化系统。