OpenClaw CLI 命令全解析:不只是启动服务器
对应文章:《OpenClaw CLI 命令全解析:不只是启动服务器》
学习目标:掌握 CLI 工具的使用,理解命令系统设计,学会用命令高效管理 OpenClaw
一、CLI 入口:从 `openclaw` 命令说起
当你在任何终端输入 openclaw 时,背后发生了一系列精心设计的启动流程。理解这个入口,是掌握 CLI 的第一步。
1.1 双层入口架构
OpenClaw 的 CLI 采用双层入口设计:
openclaw.mjs(包装器)
↓
entry.ts(入口点)
↓
cli/run-main.ts(命令分发)
↓
各命令模块(gateway/config/plugins/...)
第一层:CLI 包装器 [openclaw.mjs](file:///openclaw-main/openclaw.mjs#L1)
这是用户直接执行的文件,负责最基础的运行时检查:
// 第 11-12 行:Node.js 版本要求
const MIN_NODE_MAJOR = 22;
const MIN_NODE_MINOR = 19;
// 第 25-37 行:版本检查
const ensureSupportedNodeVersion = () => {
if (isSupportedNodeVersion(parseNodeVersion(process.versions.node))) {
return;
}
process.stderr.write(
`openclaw: Node.js v${MIN_NODE_VERSION}+ is required...`
);
process.exit(1);
};
为什么需要包装器?
- 版本守卫:确保 Node.js 版本符合要求(≥ v22.19)
- 编译缓存:管理 Node.js 编译缓存,加速后续启动
- 信号处理:优雅处理 SIGTERM、SIGINT 等进程信号
- 源码检出检测:区分开发模式(源码)和发布模式(npm 包)
第二层:入口点 [src/entry.ts](file:///openclaw-main/src/entry.ts#L1)
这是真正启动 CLI 逻辑的地方:
// 第 90-100 行:主模块检查
if (!isMainModule({...})) {
// 作为依赖被导入时跳过入口逻辑
} else {
process.title = "openclaw";
ensureOpenClawExecMarkerOnProcess();
installProcessWarningFilter();
normalizeEnv();
// ... 继续启动
}
关键设计:isMainModule 检查防止了当 entry.js 被 bundler 作为共享依赖导入时重复执行入口逻辑。
1.2 启动流程的 5 个阶段
从 entry.ts 可以看到启动的完整流程:
| 阶段 | 功能 | 对应代码 |
|---|---|---|
| 1. 环境标准化 | 规范化环境变量、过滤警告 | `normalizeEnv()` |
| 2. 编译缓存 | 启用 Node.js 编译缓存加速 | `enableOpenClawCompileCache()` |
| 3. 参数解析 | 解析容器目标、配置文件 | `parseCliContainerArgs()` |
| 4. 快速路径 | 处理 `–version`、根帮助等 | `tryHandleRootVersionFastPath()` |
| 5. 主运行 | 调用 `runMainOrRootHelp()` | `runCli()` |
二、核心命令详解
OpenClaw 提供了 20+ 个核心命令,覆盖从安装到运维的完整生命周期。
2.1 命令全景图
从 core-command-descriptors.ts 可以看到所有核心命令的定义:
const coreCliCommandCatalog = defineCommandDescriptorCatalog([
{ name: "crestodian", description: "交互式设置和修复助手" },
{ name: "setup", description: "初始化本地配置和 Agent 工作区" },
{ name: "onboard", description: "Gateway、工作区和技能的交互式引导" },
{ name: "configure", description: "凭证、通道、Gateway 和 Agent 的交互式配置" },
{ name: "config", description: "非交互式配置助手(get/set/unset/validate)", hasSubcommands: true },
{ name: "doctor", description: "诊断和修复配置、Gateway、插件和通道问题" },
{ name: "dashboard", description: "用当前 token 打开 Control UI" },
{ name: "gateway", description: "运行、检查和查询 WebSocket Gateway", hasSubcommands: true },
{ name: "channels", description: "管理已连接的聊天通道和账户", hasSubcommands: true },
{ name: "plugins", description: "管理 OpenClaw 插件和扩展", hasSubcommands: true },
{ name: "models", description: "管理模型提供商和配置", hasSubcommands: true },
{ name: "agents", description: "管理隔离的 Agent(工作区、认证、路由)", hasSubcommands: true },
{ name: "status", description: "显示 Gateway、通道、模型和最近会话状态" },
{ name: "health", description: "从运行中的 Gateway 获取详细健康信息" },
// ... 更多命令
]);
2.2 `openclaw gateway` — 网关管理
这是最重要的命令,负责启动和管理 OpenClaw 的核心服务。
快速启动路径
从 run-main.ts 可以看到 gateway run 有专门的快速路径:
export function isGatewayRunFastPathArgv(argv: string[]): boolean {
const invocation = resolveCliArgvInvocation(argv);
if (invocation.hasHelpOrVersion) {
return false;
}
const args = argv.slice(2);
let sawGateway = false;
let sawRun = false;
for (let index = 0; index < args.length; index += 1) {
const arg = args[index];
if (!sawGateway) {
if (arg !== "gateway") return false;
sawGateway = true;
continue;
}
if (!sawRun && arg === "run") {
sawRun = true;
continue;
}
return false;
}
return sawGateway;
}
为什么需要快速路径?
- 跳过完整的 Commander 程序构建,直接加载 Gateway 运行命令
- 减少启动时间(对守护进程模式尤为重要)
- 避免加载不必要的插件命令注册
常用子命令
# 前台启动 Gateway
openclaw gateway run
# 后台启动(守护进程)
openclaw gateway run --daemon
# 检查 Gateway 状态
openclaw gateway status
# 停止 Gateway
openclaw gateway stop
2.3 `openclaw doctor` — 健康诊断
doctor 命令是 OpenClaw 的”体检医生”,自动检测并修复常见问题。
# 运行全面诊断
openclaw doctor
# 自动修复发现的问题
openclaw doctor --fix
# 检查特定组件
openclaw doctor --config # 仅检查配置
openclaw doctor --channels # 仅检查通道
openclaw doctor --plugins # 仅检查插件
设计哲学:借鉴了 brew doctor 的设计理念,让问题诊断变得简单直观。
2.4 `openclaw config` — 配置管理
这是非交互式的配置管理工具,适合脚本和自动化场景。
从 config-cli.ts 可以看到支持的完整操作:
# 读取配置值
openclaw config get models.providers.openai.apiKey
# 设置配置值
openclaw config set models.providers.openai.apiKey "sk-xxx"
# 批量设置(JSON5 格式)
openclaw config set --json '{ models: { providers: { openai: { apiKey: "sk-xxx" } } } }'
# 删除配置项
openclaw config unset models.providers.openai.apiKey
# 验证配置
openclaw config validate
# 查看配置文件路径
openclaw config file
配置变更的幂等性:config set 命令支持 --merge 和 --replace 模式,确保配置更新是安全的。
2.5 `openclaw channels` — 通道管理
管理 OpenClaw 与外部聊天平台的连接。
从 channels-cli.ts 可以看到支持的子命令:
# 列出已配置的通道
openclaw channels list
# 查看所有可用通道(包括未安装的)
openclaw channels list --all
# 添加通道(交互式引导)
openclaw channels add
# 非交互式添加(适合脚本)
openclaw channels add --channel telegram --token <your-bot-token>
# 检查通道状态
openclaw channels status
# 深度检查(包括本地探针)
openclaw channels status --deep
# 通道认证
openclaw channels login --channel whatsapp
openclaw channels logout --channel whatsapp
懒加载设计:通道特定的设置选项只在 channels add 时加载,避免不必要的启动开销:
// channels-cli.ts 第 75-80 行
function shouldRegisterChannelSetupOptions(argv: string[]): boolean {
const { commandPath } = resolveCliArgvInvocation(normalizeWindowsArgv(argv));
return commandPath[0] === "channels" && commandPath[1] === "add";
}
2.6 `openclaw plugins` — 插件管理
OpenClaw 的扩展性核心,管理插件的安装、启用、禁用和卸载。
从 plugins-cli.ts 可以看到完整功能:
# 列出已发现的插件
openclaw plugins list
# 仅显示已启用的插件
openclaw plugins list --enabled
# 搜索 ClawHub 插件市场
openclaw plugins search telegram
# 查看插件详情
openclaw plugins inspect <plugin-id>
# 安装插件(支持多种来源)
openclaw plugins install <npm-package>
openclaw plugins install <local-path>
openclaw plugins install <git-repo-url>
openclaw plugins install clawhub:<package-name>
# 启用/禁用插件
openclaw plugins enable <plugin-id>
openclaw plugins disable <plugin-id>
# 卸载插件
openclaw plugins uninstall <plugin-id>
# 更新插件
openclaw plugins update <plugin-id>
openclaw plugins update --all
插件来源的灵活性:支持 npm 包、本地路径、Git 仓库、ClawHub 市场,甚至直接安装压缩包。
三、命令解析流程深度解析
3.1 从输入到执行的完整路径
当你输入 openclaw gateway run --port 8080 时,发生了什么?
1. 输入解析
argv = ["node", "openclaw", "gateway", "run", "--port", "8080"]
2. 容器目标检查
parseCliContainerArgs() → 是否有 --container 标志?
3. 配置文件检查
parseCliProfileArgs() → 是否有 --profile/--dev 标志?
4. 快速路径判断
isGatewayRunFastPathArgv() → true(匹配 gateway run 模式)
5. 快速路径执行
直接加载 gateway-cli/run-command.js,跳过完整程序构建
6. 命令解析
Commander 解析 --port 8080
7. 执行
启动 Gateway 服务器,绑定到端口 8080
3.2 路由机制
如果快速路径不匹配,CLI 会进入完整的路由流程。从 run-main.ts 可以看到:
const { tryRouteCli } = await import("./route.js");
if (await tryRouteCli(normalizedArgv)) {
return;
}
route.js 负责处理子 CLI(subcli)的路由——某些命令可能由独立的子进程处理。
3.3 插件命令动态注册
OpenClaw 的一个强大特性是插件可以注册自己的 CLI 命令。
从 run-main.ts 可以看到注册流程:
if (!shouldSkipPluginRegistration) {
const config = await startupTrace.measure("register-plugin-commands", async () => {
const { registerPluginCliCommandsFromValidatedConfig } =
await import("../plugins/cli.js");
return await registerPluginCliCommandsFromValidatedConfig(program, ..., {
mode: "lazy", // 懒加载模式
primary,
});
});
}
懒加载模式:插件命令只在实际使用时加载,避免启动时加载所有插件代码。
3.4 未知命令处理
当输入不存在的命令时,OpenClaw 提供了智能的错误提示:
// run-main.ts 第 450-470 行
const unownedPrimary = await resolveUnownedCliPrimary({ argv: normalizedArgv, config });
if (unownedPrimary) {
throw new Error(await resolveUnownedCliPrimaryMessage({ primary: unownedPrimary, config }));
}
系统会检查:
- 是否是内置命令的拼写错误?
- 是否是某个插件的命令但插件未安装?
- 是否是某个工具的别名?
然后给出针对性的提示,比如:
Unknown command: openclaw telegrm. Did you mean "telegram"?
四、CLI 参数传递机制
4.1 环境变量集成
OpenClaw CLI 深度集成了环境变量系统:
# 方式1:命令行参数
openclaw gateway run --port 8080
# 方式2:环境变量
OPENCLAW_GATEWAY_PORT=8080 openclaw gateway run
# 方式3:配置文件
# 在 openclaw.json 中设置 gateway.port
优先级:命令行参数 > 环境变量 > 配置文件 > 默认值
4.2 配置文件热加载
CLI 命令在运行时会自动加载 .env 文件:
// run-main.ts 第 520-530 行
if (!isHelpOrVersionInvocation && shouldLoadCliDotEnv()) {
const { loadCliDotEnv } = await import("./dotenv.js");
loadCliDotEnv({ quiet: true });
}
支持两个位置的 .env:
- 当前工作目录:
./.env
- OpenClaw 状态目录:
~/.openclaw/.env
4.3 代理支持
对于需要网络访问的命令,OpenClaw 自动配置 HTTP 代理:
// run-main.ts 第 560-570 行
if (!isHelpOrVersionInvocation && shouldStartProxyForCli(normalizedArgv)) {
const config = await readBestEffortCliConfig();
const { startProxy } = await loadProxyLifecycleModule();
proxyHandle = await startProxy(config?.proxy ?? undefined);
}
支持的环境变量:
HTTP_PROXY/http_proxy
HTTPS_PROXY/https_proxy
ALL_PROXY/all_proxy
五、实用命令速查表
5.1 安装与配置
| 命令 | 作用 |
|---|---|
| `openclaw onboard` | 交互式首次配置 |
| `openclaw setup` | 初始化配置和工作区 |
| `openclaw configure` | 交互式配置管理 |
| `openclaw config validate` | 验证配置有效性 |
5.2 Gateway 管理
| 命令 | 作用 |
|---|---|
| `openclaw gateway run` | 前台启动 Gateway |
| `openclaw gateway run –daemon` | 后台启动 |
| `openclaw gateway status` | 查看状态 |
| `openclaw gateway stop` | 停止 Gateway |
| `openclaw dashboard` | 打开 Web UI |
5.3 通道管理
| 命令 | 作用 |
|---|---|
| `openclaw channels list` | 列出通道 |
| `openclaw channels add` | 添加通道 |
| `openclaw channels status` | 通道状态 |
| `openclaw channels login` | 通道认证 |
5.4 插件管理
| 命令 | 作用 |
|---|---|
| `openclaw plugins list` | 列出插件 |
| `openclaw plugins search <query>` | 搜索插件 |
| `openclaw plugins install <spec>` | 安装插件 |
| `openclaw plugins enable/disable <id>` | 启用/禁用 |
| `openclaw plugins uninstall <id>` | 卸载插件 |
5.5 诊断与维护
| 命令 | 作用 |
|---|---|
| `openclaw doctor` | 全面诊断 |
| `openclaw doctor –fix` | 自动修复 |
| `openclaw status` | 快速状态 |
| `openclaw health` | 详细健康 |
| `openclaw backup create` | 创建备份 |
| `openclaw reset` | 重置状态 |
六、进阶技巧
6.1 JSON 输出模式
几乎所有命令都支持 --json 标志,方便脚本处理:
openclaw channels list --json | jq '.[] | select(.status == "connected")'
openclaw plugins list --json | jq '.[].id'
openclaw status --json | jq '.gateway.version'
6.2 配置文件批量操作
# 从文件批量导入配置
cat config.json5 | openclaw config set --stdin
# 导出当前配置
openclaw config get --all > backup.json5
6.3 调试模式
# 启用启动跟踪
OPENCLAW_GATEWAY_STARTUP_TRACE=1 openclaw gateway run
# 启用代理调试
OPENCLAW_DEBUG_PROXY_ENABLED=1 openclaw plugins search telegram
# 禁用颜色输出
openclaw --no-color status
6.4 容器支持
# 在 Docker 容器中运行命令
openclaw --container my-container gateway status
七、总结
核心要点回顾
- 双层入口:
openclaw.mjs做运行时检查,entry.ts做逻辑启动
- 快速路径:
gateway run等常用命令有专门的快速启动路径
- 20+ 核心命令:覆盖安装、配置、运行、诊断、维护全生命周期
- 插件扩展:插件可以动态注册自己的 CLI 命令
- 智能错误:未知命令时给出针对性提示,而非简单的 “not found”
下篇预告
第 4 篇将深入 OpenClaw 的架构全景,解析 Gateway 是如何工作的——WebSocket 服务器、HTTP 服务器、通道管理器、插件系统是如何协同工作的。我们将从 src/gateway/server.impl.ts 开始,逐层拆解这个多通道 AI 网关的核心架构。
互动时间:你最常用的 OpenClaw CLI 命令是什么?有没有发现什么隐藏的实用功能?欢迎在评论区留言分享!
夜雨聆风