<p align="center">
  <a href="https://github.com/openclaw/openclaw"><img src="./doc/openclaw-logo.svg" width="96" height="96" alt="OpenClaw" style="vertical-align: middle"></a>
  &nbsp;&nbsp;&nbsp;&nbsp;
  <a href="https://cursor.sh"><img src="./doc/cursor-logo.svg" width="80" height="80" alt="Cursor" style="vertical-align: middle"></a>
  <h1 align="center">openclaw-cursor-brain</h1>
  <p align="center">
    将 <a href="https://cursor.sh">Cursor</a> 作为 <a href="https://github.com/openclaw/openclaw">OpenClaw</a> 的 AI 大脑 — 原生调用所有插件工具
  </p>
  <p align="center">
    <a href="https://www.npmjs.com/package/openclaw-cursor-brain"><img src="https://img.shields.io/npm/v/openclaw-cursor-brain.svg" alt="npm version"></a>
    <a href="https://www.npmjs.com/package/openclaw-cursor-brain"><img src="https://img.shields.io/npm/dm/openclaw-cursor-brain.svg" alt="npm downloads"></a>
    <a href="https://github.com/openclaw/openclaw"><img src="https://img.shields.io/badge/OpenClaw-Plugin-orange.svg" alt="OpenClaw Plugin"></a>
    <a href="https://cursor.sh"><img src="https://img.shields.io/badge/Cursor-Agent%20CLI-purple.svg" alt="Cursor"></a>
    <a href="https://nodejs.org"><img src="https://img.shields.io/badge/Node.js-%3E%3D18-green.svg" alt="Node.js >= 18"></a>
    <a href="https://opensource.org/licenses/MIT"><img src="https://img.shields.io/badge/License-MIT-blue.svg" alt="License: MIT"></a>
    <br/>
    <a href="./README.md">English</a> | 中文 · <a href="./doc/technical-guide-zh.md">技术设计文档</a> · <a href="./doc/technical-guide-en.md">Technical Guide</a>
  </p>
</p>

---

**openclaw-cursor-brain** 是一个 [OpenClaw](https://github.com/openclaw/openclaw) 插件，将 [Cursor Agent CLI](https://cursor.sh) 作为实时流式 AI 后端，通过 [MCP](https://modelcontextprotocol.io) 连接所有插件工具，让 AI 原生调用飞书、Slack、GitHub 等能力。

## 前置条件

- [Cursor IDE](https://cursor.sh) 已安装并至少启动过一次
- Cursor Agent CLI 已启用：打开 Cursor → `Cmd+Shift+P` → 输入 **Install 'cursor' command** → 回车。或执行命令 `curl https://cursor.com/install -fsS | bash`。（安装后终端可用 `cursor-agent` 或 `agent` 命令）

- [OpenClaw](https://github.com/openclaw/openclaw) 已全局安装（`npm i -g openclaw`）
- Node.js ≥ 18

## 快速开始

```bash
openclaw plugins install openclaw-cursor-brain # 安装与默认配置
openclaw gateway restart                       # 重启服务
openclaw cursor-brain doctor                   # 验证
```

**主/备模型选择**（可选）：在终端为 TTY 时，**`openclaw plugins install`** 完成后会自动进入交互式选择；若非 TTY 或未弹出，可手动执行：

```bash
openclaw cursor-brain setup   # 可选：选择主模型与备用模型
openclaw gateway restart      # 若改了配置需重启
```

**setup** 和 **upgrade** 时自动从 `cursor-agent --list-models` 发现可用模型。主模型单选，备用模型多选（空格切换），默认按 cursor 原始顺序全选：

```
◆  Select primary model (↑↓ navigate, enter confirm)
│  ● auto              Auto
│  ○ opus-4.6-thinking Claude 4.6 Opus (thinking, cursor default)
│  ○ opus-4.6          Claude 4.6 Opus
│  ○ sonnet-4.6        Claude 4.6 Sonnet
│  ○ gpt-5.3-codex     GPT-5.3 Codex
│  …
└

◆  Select fallback models (space toggle, enter confirm, order follows list)
│  ◼ opus-4.6-thinking Claude 4.6 Opus (thinking, cursor default)
│  ◼ opus-4.6          Claude 4.6 Opus
│  ◼ sonnet-4.6        Claude 4.6 Sonnet
│  …
└
```

## 工作原理

<img src="README_ZH-mermaid/Untitled-1.png" alt="双向桥接架构" width="746" />

<details>
<summary>查看流程图源码</summary>

```mermaid
flowchart TD
    subgraph Channels ["📱 消息通道"]
        direction LR
        Feishu["飞书"]
        Slack["Slack"]
        Web["Web / API"]
    end

    GW["OpenClaw Gateway"]

    subgraph Bridge ["🔄 双向桥接"]
        direction LR
        subgraph ProxyBox ["⚡ Streaming Proxy :18790"]
            Proxy["OpenAI 兼容 API<br/>Session 自动推导<br/>即时结果 · 脚本哈希自动重启"]
        end
        subgraph MCPBox ["🔌 MCP Server (stdio)"]
            MCP["工具网关<br/>丰富描述 · 超时重试<br/>自动发现"]
        end
    end

    Agent["🧠 cursor-agent CLI<br/>--stream-partial-output --resume"]

    subgraph Tools ["🛠️ 插件工具"]
        direction LR
        T1["feishu_doc"]
        T2["feishu_wiki"]
        T3["GitHub · DB · …"]
    end

    Channels -->|"用户消息"| GW
    GW -->|"POST /v1/chat/completions"| Proxy
    Proxy -->|"spawn + stdin"| Agent
    Agent -->|"SSE 实时流"| Proxy
    Proxy -->|"响应"| GW
    GW -->|"回复"| Channels

    Agent <-->|"MCP stdio"| MCP
    MCP -->|"POST /tools/invoke"| GW
    GW --> Tools

```

</details>

两条自动配置的路径：

1. **Streaming Proxy** — 本地 OpenAI 兼容服务器（`/v1/chat/completions`）启动 `cursor-agent`，通过 `--stream-partial-output` 实时推送文本增量。包含工具调用日志、批量结果即时发送、可选推理过程转发、脚本哈希自动重启。
2. **MCP Server** — Cursor IDE 通过 stdio 调用 OpenClaw 工具，转发到 Gateway REST API（带超时/重试）。服务器指令包含丰富的工具描述（token 提取规则、action 键、参数示例），减少不必要的 `openclaw_skill` 调用。

会话自动从消息元数据中推导 session key（如 `sender_id` 用于私聊，`group_channel` + `topic_id` 用于群聊），持久化到磁盘，通过 `--resume` 复用（重启不丢上下文）。也支持通过 body 字段（`_openclaw_session_id`、`session_id`）或 HTTP 头（`X-OpenClaw-Session-Id`、`X-Session-Id`）显式传递。新插件重启 Gateway 后自动发现。

## 双向增强

- **OpenClaw 获得 Cursor AI** — 所有通道（Slack、飞书、Web 等）获得 Cursor 前沿模型作为 AI 后端
- **Cursor IDE 获得 OpenClaw 工具** — 所有插件工具自动注册为 MCP 工具，Cursor 可原生调用飞书、Slack、GitHub、数据库等
- **复合效应** — 单个 Agent 会话可读取 Slack、编写代码、推送 GitHub、通知飞书 — 无需切换上下文

## 功能特性

- **零配置** — 安装重启即可，一切自动配置
- **交互式模型选择** — `setup`/`upgrade` 通过 `@clack/prompts` 展示所有发现的模型（主模型单选，备用模型按顺序多选）
- **动态模型发现** — 自动从 `cursor-agent --list-models` 获取模型列表，每次 Gateway 启动时同步
- **实时流式** — `--stream-partial-output` 逐字输出；批量结果默认即时发送（插件 config `instantResult`），可选智能分块回退
- **推理过程转发** — 可选流式输出 LLM 推理过程（插件 config `forwardThinking`）：`"off"` 不转发；`"content"`（默认）以 markdown 引用嵌入正文（兼容 OpenClaw 飞书/Slack 等流式卡片）；`"reasoning_content"` 通过标准字段
- **丰富工具描述** — MCP 服务器指令包含 token 提取规则、精确 action 键和参数示例（来自 SKILL.md），减少不必要的 `openclaw_skill` 调用
- **工具调用日志** — proxy 记录每个工具调用的名称、参数摘要、耗时和 call ID，便于诊断
- **工具自动发现** — 启动时从磁盘 SKILL.md 直接注册（不依赖 Gateway）；后台异步验证用于诊断；60s TTL 缓存
- **Session 自动推导** — 自动从消息元数据（sender/group/topic）推导 session key，Gateway 无需显式传递 session ID
- **会话持久化** — cursor-agent 会话持久化到磁盘（`~/.openclaw/cursor-sessions.json`）；也支持通过 body 字段或 HTTP 头（`X-OpenClaw-Session-Id`、`X-Session-Id`）显式传递
- **升级自动重启** — proxy 在 `/v1/health` 暴露 `scriptHash`；Gateway 比较哈希值，代码变更后自动重启
- **三层容错** — 请求级：stale session 自动清除并重试一次；进程级：连续失败达阈值后 proxy 自退出触发重启；网关级：崩溃后指数退避自动重启（2s → 10s → 60s，稳定 5min 后重置）
- **版本保护** — `upgrade` 命令检测版本大小，降级或同版本需确认
- **独立代理** — `streaming-proxy.mjs` 可独立运行为 OpenAI 兼容 API（自动检测、API Key、CORS）
- **可靠性** — 工具调用超时（60s）、重试（2 次）、结构化错误（`isError: true`）
- **请求安全** — 请求体大小限制（10 MB）、单请求超时、客户端断连优雅处理
- **代理管理** — `proxy status/stop/restart/log` 命令独立管控代理生命周期，无需重启 Gateway
- **诊断** — `doctor`（10+ 检查项）、`status` 和 `proxy log` 命令
- **跨平台** — macOS、Linux、Windows（端口管理、健康检查）

## 配置

在 `openclaw.json` 的 `plugins.entries.openclaw-cursor-brain.config` 下：

| 参数           | 类型   | 默认值   | 说明                        |
| -------------- | ------ | -------- | --------------------------- |
| `cursorPath`   | string | 自动探测 | cursor-agent 路径           |
| `outputFormat` | string | 自动探测 | `"stream-json"` 或 `"json"` |
| `proxyPort`    | number | `18790`  | Streaming proxy 端口        |

主模型与备用模型**不**写在插件 config 里，而是存在 `agents.defaults.model`（primary + fallbacks 数组）和 `models.providers.cursor-local`。通过 `openclaw cursor-brain setup` 或升级流程交互设置。

<details>
<summary><strong>插件配置与环境变量</strong></summary>

**单一数据源：** Proxy 调优项**仅**在 **openclaw.json** 的 `plugins.entries.openclaw-cursor-brain.config` 中配置。Proxy 始终只读 openclaw.json：由 gateway 启动时使用 `OPENCLAW_CONFIG_PATH`；**独立运行**（`node streaming-proxy.mjs`）时默认读 `~/.openclaw/openclaw.json`，无需单独配置文件。**卸载**会停止 proxy 并删除可能存在的旧版 `cursor-proxy.json`；**升级**会保留 openclaw.json 中的插件配置。

| 变量                        | 默认值   | 说明                     |
| --------------------------- | -------- | ------------------------ |
| `OPENCLAW_TOOL_TIMEOUT_MS`  | `60000`  | MCP 工具调用超时（毫秒） |
| `OPENCLAW_TOOL_RETRY_COUNT` | `2`      | MCP 瞬态错误重试次数     |
| `CURSOR_PROXY_PORT`         | `18790`  | 独立运行 proxy 时的端口  |
| `CURSOR_PROXY_API_KEY`      | _（无）_ | 独立模式 API Key 认证    |

</details>

## CLI 命令

| 命令                                     | 说明                              |
| ---------------------------------------- | --------------------------------- |
| `openclaw cursor-brain setup`            | 配置 MCP + 交互选择模型           |
| `openclaw cursor-brain doctor`           | 健康检查（10+ 项）                |
| `openclaw cursor-brain status`           | 版本、配置、模型、工具数量        |
| `openclaw cursor-brain upgrade <source>` | 一键升级 + 模型选择               |
| `openclaw cursor-brain uninstall`        | 完整卸载（配置 + 文件）           |
| `openclaw cursor-brain proxy`            | 显示代理状态（PID、端口、会话数） |
| `openclaw cursor-brain proxy stop`       | 停止流式代理                      |
| `openclaw cursor-brain proxy restart`    | 重启代理（独立进程）              |
| `openclaw cursor-brain proxy log [-n N]` | 显示最近 N 行代理日志（默认 30）  |

## 独立 Streaming Proxy

无需 OpenClaw，将任何 Cursor 变为 OpenAI 兼容 API：

```bash
node mcp-server/streaming-proxy.mjs
# 带配置：
CURSOR_PROXY_PORT=8080 CURSOR_PROXY_API_KEY=secret node mcp-server/streaming-proxy.mjs
```

```bash
curl http://127.0.0.1:18790/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{"model":"auto","stream":true,"messages":[{"role":"user","content":"你好！"}]}'
```

端点：`POST /v1/chat/completions`、`GET /v1/models`、`GET /v1/health`（返回 `scriptHash` 用于版本检测）。支持 API Key 认证、CORS、会话自动推导与复用。

<details>
<summary><strong>自动配置的文件</strong></summary>

### ~/.cursor/mcp.json

```json
{
  "mcpServers": {
    "openclaw-gateway": {
      "command": "node",
      "args": ["<插件路径>/mcp-server/server.mjs"],
      "env": {
        "OPENCLAW_GATEWAY_URL": "http://127.0.0.1:<port>",
        "OPENCLAW_GATEWAY_TOKEN": "<token>",
        "OPENCLAW_CONFIG_PATH": "~/.openclaw/openclaw.json"
      }
    }
  }
}
```

### openclaw.json（交互选择后）

```json
{
  "agents": {
    "defaults": {
      "model": {
        "primary": "cursor-local/auto",
        "fallbacks": ["cursor-local/opus-4.6", "cursor-local/sonnet-4.6", "..."]
      }
    }
  },
  "models": {
    "providers": {
      "cursor-local": {
        "api": "openai-completions",
        "baseUrl": "http://127.0.0.1:18790/v1",
        "apiKey": "local",
        "models": [
          { "id": "auto", "name": "Auto" },
          { "id": "opus-4.6", "name": "Claude 4.6 Opus" },
          "..."
        ]
      }
    }
  }
}
```

</details>

<details>
<summary><strong>故障排查</strong></summary>

| 问题                                                               | 解决                                                                                                                                                                                                                                                                                                                                                                                      |
| ------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **WARNING: dangerous code patterns (child_process / env+network)** | OpenClaw 安装时会扫描插件并可能显示此告警。本插件需使用 `child_process` 运行 Cursor agent 与 proxy，并读取环境变量（如 `CURSOR_PATH`）进行配置。插件仅向子进程传递最小化白名单环境变量，不会传递完整 `process.env`。可放心忽略此告警。                                                                                                                                                    |
| **卡在「Provider synced」后不退出**                                | 旧版在 `plugins install` 时会启动 proxy/定时器导致进程不退出；新版已修复，安装会正常结束。请升级到最新版。                                                                                                                                                                                                                                                                                |
| **安装时没有主/备模型选择**                                        | 需在 TTY 终端下安装才会自动弹出；否则安装后执行 `openclaw cursor-brain setup` 即可。                                                                                                                                                                                                                                                                                                      |
| **Invalid config … source / unknown command 'cursor-brain'**       | 旧版曾写入非法 `source: "tarball"`。新版会在 register 时自动修正。若仍报错，请打开 `~/.openclaw/openclaw.json`，把 `plugins.installs.openclaw-cursor-brain.source` 改为 `"archive"`（或 `"path"` 若为本地安装），保存后再执行一次 `openclaw plugins install ./`。                                                                                                                         |
| **plugins.allow / plugins.entries: plugin not found**              | 配置里残留了已卸载插件的引用，且 `openclaw doctor --fix` 可能不会清除。在项目目录执行 **`npm run uninstall`** 清理后，再执行 `openclaw plugins install ./`。或手动编辑 `~/.openclaw/openclaw.json`，从 `plugins.allow` 中删掉 `openclaw-cursor-brain`，并删掉 `plugins.entries.openclaw-cursor-brain`。                                                                                   |
| **No API key found for provider "anthropic"**                      | 当前默认模型不是 cursor-local，而是 anthropic（需 API key）。改用本机 Cursor：执行 `openclaw config set agents.defaults.model.primary "cursor-local/auto"`，或运行 `openclaw cursor-brain setup` 选择主模型为 cursor-local/auto，然后 `openclaw gateway restart`。若某 agent 单独指定了 anthropic，用 `openclaw config get agents.list` 查看并改其 `model.primary` 或删/改该 agent 配置。 |
| "Cursor Agent CLI not found"                                       | 安装 Cursor 并运行一次，或设置 `config.cursorPath`                                                                                                                                                                                                                                                                                                                                        |
| Gateway 错误                                                       | 确认 Gateway 运行中（`openclaw gateway status`），检查 token                                                                                                                                                                                                                                                                                                                              |
| 工具未出现                                                         | 重启 Gateway，在 Cursor 中调用 `openclaw_discover`                                                                                                                                                                                                                                                                                                                                        |
| 工具超时                                                           | 设置 `OPENCLAW_TOOL_TIMEOUT_MS=120000`                                                                                                                                                                                                                                                                                                                                                    |
| Proxy 未启动                                                       | `openclaw cursor-brain proxy log` 查看日志；`proxy restart` 强制启动                                                                                                                                                                                                                                                                                                                      |
| **Cursor 限速 / 504 超时 / proxy 频繁退出**                        | 限速时单次请求变慢。默认：请求超时 5 分钟、降级后仍 5 分钟；仅当连续失败 ≥4 或连续超时 ≥2 时 health 才报 degraded，Gateway 才会重启 proxy，避免一次超时就重启。非流式请求会累积 agent 的 text 输出，超时前已有内容会正常返回。飞书等渠道约 50–60 秒回复超时，若 Cursor 经常超过则需减少并发或等限速恢复。                                                                                 |
| 升级后 Proxy 未更新                                                | Gateway 自动检测 `scriptHash` 变化并重启；用 `curl http://127.0.0.1:18790/v1/health` 验证                                                                                                                                                                                                                                                                                                 |
| 消息间上下文丢失                                                   | 查看 `~/.openclaw/logs/cursor-proxy.log` 中 `session=auto:dm:…(meta.auto)` — 若为 `none(none)` 说明消息中未嵌入元数据                                                                                                                                                                                                                                                                     |
| 重启后上下文丢失                                                   | 会话已自动持久化；用 `proxy restart`（而非 `gateway restart`）可保留会话                                                                                                                                                                                                                                                                                                                  |
| 批量响应延迟                                                       | 在插件 config 中设置 `instantResult: false`，则按 ~200 字符/秒分块                                                                                                                                                                                                                                                                                                                        |
| 调试工具调用                                                       | 查看 `~/.openclaw/logs/cursor-proxy.log` 中 `tool:start` / `tool:done` 条目                                                                                                                                                                                                                                                                                                               |
| 调试 MCP                                                           | `OPENCLAW_GATEWAY_URL=... node mcp-server/server.mjs`                                                                                                                                                                                                                                                                                                                                     |

</details>

<details>
<summary><strong>项目结构</strong></summary>

```
openclaw-cursor-brain/
  index.ts                  # 插件入口（register + CLI 命令）
  openclaw.plugin.json      # 插件元数据 + 配置 schema
  src/
    constants.ts            # 路径、ID、输出格式类型
    setup.ts                # 幂等安装、模型发现、格式检测
    doctor.ts               # 健康检查（11 项）
  scripts/
    uninstall.mjs           # 卸载：配置 + MCP + 扩展目录
  mcp-server/
    server.mjs              # MCP 服务器（工具发现、超时/重试）
    streaming-proxy.mjs     # OpenAI 兼容流式代理
```

</details>

## 许可证

[MIT](./LICENSE)
