> ## Documentation Index
> Fetch the complete documentation index at: https://ppio.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# On-Demand 模式

> PPClaw On-Demand 沙箱模式：空闲自动暂停、访问自动恢复，搭配飞书机器人集成，打造低成本、高可用的 AI 助手。

<Warning>
  本文档中的功能需要 PPClaw v1.8.0 及以上版本，请先升级 CLI：

  **macOS / Linux：**

  ```bash theme={null}
  curl -fsSL https://ppclaw.ppio.com/install.sh | bash
  ```

  **Windows (PowerShell)：**

  ```powershell theme={null}
  irm https://ppclaw.ppio.com/install.ps1 | iex
  ```

  **或通过 pipx：**

  ```bash theme={null}
  pipx install ppclaw
  ```
</Warning>

<Tip>
  还没部署过 OpenClaw？请先阅读[新手快速部署](/sandbox/openclaw-quickstart)完成首次安装和启动。
</Tip>

## On-Demand 模式

On-Demand 是一种按需运行的沙箱模式——空闲时自动暂停以节省资源，有请求时自动恢复。适合低频使用的 AI 助手、Webhook 类 IM 集成和定时任务场景。

### 启动 On-Demand 沙箱

```bash theme={null}
# 默认空闲超时 300 秒
ppclaw launch --api-key <你的 API Key> --type on-demand

# 自定义空闲超时（60–86400 秒）
ppclaw launch --api-key <你的 API Key> --type on-demand --idle-timeout 600
```

<Warning>
  On-Demand 模式不支持 `--mode node`，两者不可组合使用。
</Warning>

### 手动暂停与恢复

```bash theme={null}
# 暂停沙箱（暂停期间零计费）
ppclaw pause <sandbox_id>

# 恢复沙箱（约 1 秒恢复至暂停前状态）
ppclaw resume <sandbox_id>
```

### 运行时修改配置

沙箱创建后，仍可动态调整超时参数，变更即时生效：

```bash theme={null}
# 修改空闲超时（60–86400 秒）
ppclaw config set <sandbox_id> idle-timeout 600

# 修改沙箱生命周期超时（300–2592000 秒）
ppclaw config set <sandbox_id> timeout 3600
```

### 查看沙箱状态

```bash theme={null}
# 查看沙箱状态（paused 状态下不会触发恢复）
ppclaw status <sandbox_id>

# 列表中显示 sandbox_type 和 state
ppclaw list --api-key <你的 API Key>
```

<Note>
  暂停状态下 `status` 命令仍返回完整的 URL 信息（从数据库读取，不连接沙箱），方便脚本保存地址。
</Note>

### 工作原理

On-Demand 模式通过以下机制实现自动暂停与恢复：

1. **空闲检测** — 沙箱内 agent 守护进程定期检查 OpenClaw 会话活跃状态，写入 `/tmp/.ppclaw-status.json`
2. **自动暂停** — 服务端 idle monitor 读取 agent 状态，连续 2 次检测到空闲后自动暂停沙箱
3. **自动恢复** — Webhook 请求或 Web UI 访问时，沙箱自动恢复
4. **Cron 预唤醒** — 调度器扫描已暂停沙箱的 cron 计划，在定时任务触发前约 120 秒自动恢复沙箱，确保 cron job 准时执行

## 飞书机器人集成

PPClaw 支持将 OpenClaw 实例连接到飞书机器人，实现在飞书中直接与 AI 助手对话。支持两种连接模式：**Webhook（HTTP 推送）** 和 **Event（WebSocket 长连接）**。

### 前置准备：创建飞书应用

1. 打开[飞书开放平台](https://open.feishu.cn/app)，登录后点击**创建企业自建应用**

2. 在**凭证与基础信息**页面复制以下信息：
   * **App ID**（格式：`cli_xxx`）
   * **App Secret**

3. 进入**权限管理**，点击**批量导入**，粘贴以下权限：

```json theme={null}
{
  "scopes": {
    "tenant": [
      "im:message", "im:message:send_as_bot", "im:message:readonly",
      "im:message.p2p_msg:readonly", "im:message.group_at_msg:readonly",
      "im:resource", "im:chat.access_event.bot_p2p_chat:read",
      "im:chat.members:bot_access"
    ],
    "user": ["im:chat.access_event.bot_p2p_chat:read"]
  }
}
```

4. 进入**应用能力 > 机器人**，开启机器人能力

5. 创建版本并发布应用

### 模式一：Webhook 模式（推荐）

Webhook 模式通过 HTTP 推送接收飞书消息。On-Demand 沙箱推荐使用此模式——Webhook 请求会自动触发暂停沙箱恢复，不会丢失消息。

**额外获取凭证**：在飞书开放平台，进入**开发配置 > 事件与回调 > 加密策略**，复制：

* **Verification Token**
* **Encrypt Key**

```bash theme={null}
ppclaw pair feishu <sandbox_id> \
  --app-id cli_xxx \
  --app-secret secret_xxx \
  --mode webhook \
  --verification-token tok_xxx \
  --encrypt-key key_xxx
```

在飞书开放平台**事件订阅**页面：

1. 选择**请求地址配置**
2. 填入 Webhook URL — 通过 `ppclaw status` 获取：
   ```bash theme={null}
   ppclaw status <sandbox_id> --json | jq -r '.feishu_webhook_url'
   ```
3. 添加事件：`im.message.receive_v1`

#### Webhook 可选参数

| 参数               | 默认值              | 说明              |
| ---------------- | ---------------- | --------------- |
| `--webhook-host` | `0.0.0.0`        | Webhook 服务器绑定地址 |
| `--webhook-port` | `3000`           | Webhook 监听端口    |
| `--webhook-path` | `/feishu/events` | Webhook URL 路径  |

### 模式二：Event 模式

Event 模式通过飞书 WebSocket 长连接接收消息，无需公网 URL，配置最简单：

```bash theme={null}
ppclaw pair feishu <sandbox_id> \
  --app-id cli_xxx \
  --app-secret secret_xxx
```

配置完成后，在飞书开放平台**事件订阅**页面：

1. 选择**使用长连接接收事件**
2. 添加事件：`im.message.receive_v1`

<Note>
  保存前确保 gateway 已在运行（`ppclaw status <sandbox_id>`），否则飞书可能无法保存长连接配置。
</Note>

<Warning>
  Event 模式不建议用于 On-Demand 类型的沙箱。沙箱被自动暂停后，飞书的 WebSocket 长连接会断开，消息将丢失且无法触发自动恢复。如需使用 On-Demand 沙箱，请选择 Webhook 模式。
</Warning>

### 两种模式对比

|                | Webhook 模式（推荐）        | Event 模式              |
| -------------- | --------------------- | --------------------- |
| 连接方式           | HTTP 推送（入站）           | WebSocket 长连接（出站）     |
| 公网端口           | 需要（默认 3000）           | 不需要                   |
| 配置复杂度          | 中（额外需要 Token + Key）   | 低（只需 App ID + Secret） |
| On-Demand 自动恢复 | 支持（Webhook 触发自动恢复）    | 不支持（长连接在暂停时断开）        |
| 推荐场景           | On-Demand 沙箱、生产 IM 集成 | Always-on 沙箱、开发调试     |

### 配对流程

飞书默认使用 `pairing` 策略：首次对话时机器人会回复一个配对码，需要在 CLI 中批准：

```bash theme={null}
# 查看待配对请求
ppclaw pair list <sandbox_id> feishu

# 批准配对
ppclaw pair approve <sandbox_id> feishu <CODE>
```

配对完成后即可在飞书中正常对话。

## 命令速查

| 命令                                                      | 说明                  |
| ------------------------------------------------------- | ------------------- |
| `ppclaw launch --type on-demand`                        | 启动 On-Demand 沙箱     |
| `ppclaw launch --idle-timeout <秒>`                      | 指定空闲超时（仅 On-Demand） |
| `ppclaw pause <id>`                                     | 暂停沙箱（零计费）           |
| `ppclaw resume <id>`                                    | 恢复暂停的沙箱             |
| `ppclaw config set <id> idle-timeout <秒>`               | 修改空闲超时              |
| `ppclaw config set <id> timeout <秒>`                    | 修改生命周期超时            |
| `ppclaw pair feishu <id> --app-id ... --app-secret ...` | 配对飞书（Event 模式）      |
| `ppclaw pair feishu <id> --mode webhook ...`            | 配对飞书（Webhook 模式）    |
| `ppclaw pair list <id> feishu`                          | 查看待配对请求             |
| `ppclaw pair approve <id> feishu <CODE>`                | 批准配对                |
