Skill: scotthuang/graceful-restart (version 1.0.4)

--- name: graceful-restart description: 优雅重启 Gateway。解决重启后丢失会话上下文的问题，重启前设置一次性 cron 任务，重启后自动发送消息到主会话恢复任务。默认 10 秒后唤醒。依赖 openclaw CLI。触发词：重启、restart。 --- # graceful-restart skill ## 触发条件 当用户要求重启 Gateway 时，自动触发此 skill。 ## 问题背景 Gateway 重启后，会丢失上一轮会话的任务上下文，导致： - 主会话被中断，无法自动恢复 - 需要用户手动发送消息才能继续 ## 功能 自动执行"重启后自唤醒"流程： 1. 设置一次性 cron 任务（默认 10 秒后触发） 2. 执行 Gateway 重启 3. 重启后自动发送消息到主会话 ## English Description **Problem:** After Gateway restarts, OpenClaw loses the previous session context - the main session is interrupted and cannot resume automatically. **Solution:** Auto-restart Gateway with self-wakeup. Sets a one-time cron task (default 10s) before restart, then sends a message to main session after Gateway recovers to resume tasks. **⚠️ Important: Must use this skill, NOT exec:** ```bash # ✅ Correct node ~/.openclaw/workspace/skills/graceful-restart/graceful-restart.js --task "config changed" # ❌ Wrong exec openclaw gateway restart # Don't do this! ``` **Trigger:** "重启", "restart Gateway" ## 使用方式 用户说"重启"时，自动执行： ``` [自动触发 graceful-restart skill] ``` 或者用户可以指定任务： ``` 重启 Gateway，继续之前的任务：安装 Python 包 ``` ## 命令行调用 ```bash node ~/.openclaw/workspace/skills/graceful-restart/graceful-restart.js node ~/.openclaw/workspace/skills/graceful-restart/graceful-restart.js --task "继续安装 Python 包" node ~/.openclaw/workspace/skills/graceful-restart/graceful-restart.js --task "继续安装 Python 包" --delay 60 ``` ## 实现原理 使用 `--session main` + `--system-event`： - Cron 在主会话里注入一个 system event - Gateway 重启后，heartbeat 轮询到并交付给主会话 - 主会话收到消息后回复用户 ## 注意事项 - Cron 任务时间可调整（默认 10 秒） - 使用 `--delete-after-run` 确保一次性任务自动清理 ## 📝 更新 SOUL.md 使用此 skill 后，建议在 `SOUL.md` 中添加自动触发规则（见上方）。 ## ⚠️ 重要：禁止使用 exec Gateway 重启**必须使用此 skill**，禁止直接用 exec 执行： ✅ **正确：** ```bash node ~/.openclaw/workspace/skills/graceful-restart/graceful-restart.js --task "配置已修改，需要重启后生效" ``` ❌ **错误：** ```bash exec openclaw gateway restart # 禁止！ ``` 这样写

path: _meta.json
content: {
  "name": "graceful-restart",
  "version": "1.0.4",
  "description": "优雅重启 Gateway - 重启后自唤醒",
  "author": "Scott",
  "created": "2026-02-22",
  "updated": "2026-02-22",
  "runtime": "node",
  "permissions": ["gateway-restart", "cron"],
  "requiredBinaries": ["openclaw"],
  "requiredEnvironment": [],
  "capabilities": ["gateway-restart"]
}


path: CHANGELOG.md
content: # Changelog - graceful-restart

## English

### v1.0.3 (2026-02-22)

#### 🔧 Fix
- Add more metadata fields: runtime, permissions, capabilities, requiredEnvironment

---

### v1.0.4 (2026-02-22)

#### 🔧 Fix
- Add more metadata fields: runtime, permissions, capabilities, requiredEnvironment

---

### v1.0.3 (2026-02-22)

#### 🔧 Fix
- Add more metadata fields: runtime, permissions, capabilities, requiredEnvironment

---

### v1.0.2 (2026-02-22)

#### 🔧 Fix
- Fix SKILL.md: default delay 30s → 10s (matches code)
- Add `requiredBinaries` field to metadata

---

### v1.0.1 (2026-02-22)

#### 🔒 Security Fix
- Use `execFile` with argument arrays to prevent command injection
- Add input validation for `--task` parameter
- Declare `openclaw CLI` dependency in metadata

---

### v1.0.0 (2026-02-22)

#### 🎉 Initial Release
- **Problem:** Gateway restart loses session context
- **Solution:** Auto-restart with self-wakeup using cron + system-event
- **Default delay:** 10 seconds

---

## 中文

### v1.0.2 (2026-02-22)

#### 🔧 修复
- 修复 SKILL.md：默认延迟 30 秒改为 10 秒（与代码一致）
- 添加 `requiredBinaries` 字段到 metadata

---

### v1.0.1 (2026-02-22)

#### 🔒 安全修复
- 使用 `execFile` + 参数数组防止命令注入
- 添加 `--task` 参数输入验证
- 在 metadata 中声明 `openclaw CLI` 依赖

---

### v1.0.0 (2026-02-22)

#### 🎉 初始版本
- **问题**：Gateway 重启后会丢失会话上下文
- **方案**：使用 cron + system-event 实现重启后自唤醒
- **默认延迟**：10 秒


path: graceful-restart.js
content: #!/usr/bin/env node
/**
 * Gateway Restart with Self-Wakeup
 * 
 * Usage:
 *   node graceful-restart.js [--task "任务描述"] [--delay seconds]
 * 
 * Examples:
 *   node graceful-restart.js
 *   node graceful-restart.js --task "继续安装 Python 包"
 *   node graceful-restart.js --task "继续安装 Python包" --delay 60
 * 
 * Security: Uses execFile with argument arrays to prevent command injection
 */

import { execFileSync } from 'node:child_process';
import os from 'node:os';

const HOME = os.homedir();

// Parse arguments
const args = process.argv.slice(2);
let taskDescription = null;
let delaySeconds = 10;

for (let i = 0; i < args.length; i++) {
  if (args[i] === '--task' && args[i + 1]) {
    taskDescription = args[i + 1];
    i++;
  } else if (args[i] === '--delay' && args[i + 1]) {
    delaySeconds = parseInt(args[i + 1], 10);
    i++;
  }
}

// If no task specified, use default
if (!taskDescription) {
  taskDescription = "继续之前的任务";
}

// Validate task description - only allow safe characters
const safeTaskDesc = taskDescription.replace(/[^\w\u4e00-\u9fa5\s\d\-_,，。！？、]/g, '').slice(0, 200);

console.log('🔄 Gateway Restart with Self-Wakeup');
console.log('================================');
console.log(`📝 Task: ${safeTaskDesc}`);
console.log(`⏱️  Delay: ${delaySeconds} seconds`);
console.log('');

// Step 1: Calculate cron time
console.log('⏰ Setting up cron job...');
const futureTime = new Date(Date.now() + delaySeconds * 1000);
const cronTime = futureTime.toISOString().replace('.000Z', 'Z');

// Step 2: Create cron job with system-event (using execFile to prevent injection)
console.log('🔄 Restarting Gateway...');
try {
  execFileSync('openclaw', [
    'cron', 'add',
    '--at', cronTime,
    '--session', 'main',
    '--system-event', `🔔 Gateway 已重启！有待处理任务：${safeTaskDesc}`,
    '--name', 'auto-wakeup',
    '--delete-after-run'
  ], { encoding: 'utf-8' });
  console.log('   ✅ Cron job created');
} catch (error) {
  console.error('   ❌ Failed to create cron job:', error.message);
  process.exit(1);
}

// Step 3: Restart Gateway (using execFile)
try {
  execFileSync('openclaw', ['gateway', 'restart'], { encoding: 'utf-8', timeout: 30000 });
  console.log('   ✅ Gateway restart initiated');
} catch (error) {
  console.error('   ❌ Failed to restart Gateway:', error.message);
  process.exit(1);
}

console.log('');
console.log('================================');
console.log('✅ All done! Gateway will restart and notify you after wakeup.');


Security scan verdicts — ClawScan: suspicious | static analysis: clean | VirusTotal: clean | SkillSpector: suspicious (HIGH)