mcpField
C
cli

cli

github.com/lobehub开发84.0k179 次安装1 天前更新
代码仓库

关于 cli

LobeHub CLI 是用于管理和使用 LobeHub 服务的命令行工具,提供 Agent、工作区、内容、模型、设备等命令,并处理身份验证与范围选择。

主要功能

  1. 01管理 Agent、任务与项目
  2. 02连接和管理设备
  3. 03处理文档与知识库
  4. 04配置模型、提供商和插件
  5. 05选择并查看工作区范围
  6. 06输出 JSON 与 Shell 补全

适用场景

  1. 01运行和检查 Agent 任务
  2. 02切换工作区范围
  3. 03从外部工具导入内容
  4. 04检查网关连接和设备就绪状态

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/lobehub/lobehub --skill cli

安装后在 Claude Code 中输入/cli确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

agents/
openai.yaml
references/
agent.md
conversation.md
generate.md
goal.md
knowledge.md
memory.md
models-providers.md
search-config.md
skills-plugins.md

详细介绍

LobeHub CLI 开发指南

概述

LobeHub CLI(@lobehub/cli)是一个用于管理和使用 LobeHub 服务的命令行工具,基于 Commander.js + TypeScript 构建。

  • 软件包:apps/cli/
  • 入口:apps/cli/src/index.ts
  • 可执行文件:lh、lobe、lobehub(都是同一 CLI 的别名)
  • 构建工具:tsup
  • 运行时:Node.js / Bun

架构

apps/cli/src/
├── index.ts                  # Entry point — parses argv, invokes program.ts
├── program.ts                # Builds the Commander program, registers every command
├── api/
│   ├── acceptance/           # `lh acceptance`: review loop, rounds (run/), plans, criteria, rubrics; `lh verify` aliases
│   ├── client.ts             # tRPC client (type-safe backend API)
│   └── http.ts               # Raw HTTP utilities
├── auth/
│   ├── credentials.ts        # Encrypted credential storage (AES-256-GCM)
│   ├── identity.ts           # Account fingerprint for machine-local state
│   ├── refresh.ts            # Token auto-refresh
│   └── resolveToken.ts       # Token resolution (flag > stored)
├── commands/                 # All CLI commands (one file per command group)
│   ├── agent.ts              # Agent CRUD + run
│   ├── agent-group.ts        # Agent group CRUD
│   ├── agent-signal/         # Inspect and trigger Agent Signal source events
│   ├── artifact.ts           # Publish local HTML pages as artifacts
│   ├── bot.ts                # Bot integrations (channels, access policies, messengers)
│   ├── completion.ts         # Shell completion script output
│   ├── config.ts             # whoami, usage
│   ├── connect.ts            # Device gateway connection + daemon
│   ├── device.ts             # Manage connected devices
│   ├── doc.ts                # Document management
│   ├── doctor.ts             # Machine diagnostics (runtime, endpoints, credentials, readiness)
│   ├── eval.ts               # Evaluation workflows & benchmarks
│   ├── file.ts               # File management
│   ├── generate/             # Content generation (text/image/video/tts/asr)
│   ├── goal.ts               # Long-horizon Goal Graphs
│   ├── hetero.ts             # Run heterogeneous agent CLIs, stream their output
│   ├── kb.ts                 # Knowledge base management
│   ├── login.ts              # OIDC Device Code Flow / API key auth
│   ├── logout.ts             # Clear credentials
│   ├── man.ts                # CLI manual pages
│   ├── memory.ts             # User memory management
│   ├── message.ts            # Message management
│   ├── migrate/              # Import data from external tools (OpenClaw, ChatGPT, Claude, etc.)
│   ├── model.ts              # AI model management
│   ├── notification.ts       # Notification delivery settings (personal / workspace)
│   ├── notify.ts             # Send a callback message to a topic to trigger the agent
│   ├── plugin.ts             # Plugin management
│   ├── project.ts            # Goal-oriented project management
│   ├── provider.ts           # AI provider management
│   ├── search.ts             # Global search
│   ├── session-group.ts      # Agent session group management
│   ├── skill.ts              # Agent skill management
│   ├── status.ts             # Gateway connectivity check
│   ├── task/                 # Agent task management (assignees, checkpoints, deps, review)
│   ├── thread.ts             # Message thread management
│   ├── topic.ts              # Conversation topic management
│   ├── trace/                # Inspect and replay recorded agent execution traces
│   ├── update.ts             # Self-update to the latest published version
│   ├── user.ts               # User account & settings
│   └── workspace.ts          # Workspace list/scope/members/usage/audit
├── daemon/
│   └── manager.ts            # Background daemon process management
├── tools/
│   ├── shell.ts              # Shell command execution (for gateway)
│   └── file.ts               # File operations (for gateway)
├── settings/
│   └── index.ts              # Persistent settings (~/.lobehub/)
├── utils/
│   ├── logger.ts             # Logging (verbose mode)
│   ├── format.ts             # Table output, JSON, timeAgo/timeUntil, truncate
│   └── agentStream.ts        # WebSocket streaming for agent runs and task follow
└── constants/
    └── urls.ts               # Official server & gateway URLs

命令组

CommandAliasDescription
lh login-通过 OIDC Device Code Flow 或 API key 进行身份验证
lh logout-清除已存储的凭据
lh connect-设备网关连接与守护进程管理
lh device-管理已连接的设备
lh status-快速检查网关连接状态
lh doctor-诊断机器就绪状态(运行时、端点、凭据、范围、设备、Agent)
lh agent-Agent 的增删改查、运行和状态查看
lh agent-group-Agent 组的增删改查
lh agent-signal-检查并触发 Agent Signal 源事件
lh hetero-运行异构 Agent CLI(Claude Code、Codex 等),并流式输出其内容
lh goal-运行长周期 Goal Graphs
lh project-管理目标导向型项目
lh task-管理 Agent 任务(受指派人、检查点、依赖项、审核)
lh thread-管理消息线程
lh trace-检查并重放已记录的 Agent 执行跟踪
lh acceptance-交付验收:审核循环、轮次、每次运行的检查计划、标准、评分细则
lh verify-lh acceptance 命令的弃用别名
lh eval-管理评估工作流和基准测试
lh generategen内容生成(文本、图像、视频、tts、asr、下载)
lh doc-文档增删改查、批量创建、解析、主题关联
lh file-文件列表、查看、删除、最近文件
lh artifact-将本地 HTML 页面发布为制品
lh kb-知识库增删改查、文件夹、文档、上传、树状视图
lh memory-用户记忆增删改查与提取
lh message-消息列表、搜索、删除、计数、热度图
lh topic-主题增删改查、搜索、最近主题
lh notify-向主题发送回调消息并触发 Agent 进行处理
lh notification-通知设置:查看、启用/禁用渠道、即时通信平台和类型
lh migrate-从外部工具导入数据(OpenClaw、ChatGPT、Claude 等)
lh bot-管理机器人集成(渠道、访问策略、消息应用)
lh skill-Skill 增删改查与导入(GitHub/URL/市场)
lh model-模型增删改查、切换、批量切换、清除
lh provider-Provider 增删改查、配置、测试、切换
lh plugin-插件安装、卸载、更新
lh search-跨所有类型的全局搜索
lh session-group-管理 Agent 会话组
lh workspacews工作区列表、范围切换、成员、邀请、用量
lh user-管理用户账户和设置
lh whoami-当前用户信息(包括解析出的工作区范围)
lh usage-月度/每日用量统计
lh man-显示 CLI 或子命令的手册页
lh completion-输出 Shell 补全脚本
lh update-将 CLI 更新到最新发布版本
工作区作用域

每条命令都在一个作用域中运行,按以下顺序解析:

  1. 在支持该选项的 workspace、device 和 topic 命令中显式指定 --workspace <id|slug>(slug 会根据 lh workspace list 进行解析;如果没有匹配项,则操作失败)。如果凭据无法调用 workspace.list(没有 workspace:read,例如绑定到工作区的 API 密钥),则会跳过解析,并在警告后将该值作为 id 发送,因此必须传入 id。 lh connect --workspace 只接受 id。
  2. LOBEHUB_WORKSPACE_ID 环境变量(仅接受 id)
  3. 通过 lh workspace use <id|slug> 保存的作用域
  4. 个人内容(无工作区)

保存的作用域绑定到选择它时使用的账户和服务。如果其中任一项发生变化(例如使用不同的 lh login,或切换 --server),则会忽略该作用域,并将其报告为过期,而不会向新身份附加其不属于的工作区标头。lh logout 会清除该作用域。lh whoami 和 lh workspace current 都会显示当前生效的四种来源之一。

API 密钥身份验证不携带本地账户身份,因此无法将已保存的作用域绑定到任何账户——此类调用方应改为传入 LOBEHUB_WORKSPACE_ID。

添加新命令

1. 创建命令文件

创建 apps/cli/src/commands/<name>.ts:

import type { Command } from 'commander';
import { getTrpcClient } from '../api/client';
import { outputJson, printTable, truncate } from '../utils/format';

export function register<Name>Command(program: Command) {
  const cmd = program.command('<name>').description('...');

  // Subcommands
  cmd
    .command('list')
    .description('List items')
    .option('-L, --limit <n>', 'Maximum number of items', '30')
    .option('--json [fields]', 'Output JSON, optionally specify fields')
    .action(async (options) => {
      const client = await getTrpcClient();
      const result = await client.<router>.<procedure>.query({ ... });
      // Handle output
    });
}
2. 在入口文件中注册

在 apps/cli/src/index.ts 中:

import { registerNewCommand } from './commands/new';
// ...
registerNewCommand(program);
3. 添加测试

在命令文件旁创建 apps/cli/src/commands/<name>.test.ts。

约定

输出模式

所有列表和查看命令都遵循一致的模式:

  • --json [fields] - 输出 JSON,可选按字段筛选
  • --yes - 对破坏性操作跳过确认
  • -L, --limit <n> - 分页上限(默认为 30)
  • -v, --verbose - 详细日志
表格输出
const rows = items.map((item) => [item.id, truncate(item.title, 40), timeAgo(item.updatedAt)]);
printTable(rows, ['ID', 'TITLE', 'UPDATED']);
JSON 输出
if (options.json !== undefined) {
  const fields = typeof options.json === 'string' ? options.json : undefined;
  outputJson(items, fields);
  return;
}
身份验证

需要身份验证的命令使用 getTrpcClient() 自动解析令牌:

const client = await getTrpcClient();
// client.router.procedure.query/mutate(...)
确认提示
import { confirm } from '../utils/format';
if (!options.yes) {
  const ok = await confirm('Are you sure?');
  if (!ok) return;
}

存储位置

文件路径用途
凭据~/.lobehub/credentials.json加密令牌(AES-256-GCM)
设置~/.lobehub/settings.json自定义服务/网关 URL
工作区~/.lobehub/active-workspace活跃作用域 + 绑定到该作用域的账户/服务
守护进程 PID~/.lobehub/daemon.pid后台进程 PID
守护进程状态~/.lobehub/daemon.status.json连接状态 JSON
守护进程日志~/.lobehub/daemon.log守护进程输出日志

可通过 LOBEHUB_CLI_HOME 环境变量覆盖基础目录(~/.lobehub/)(例如,在开发模式下使用 LOBEHUB_CLI_HOME=.lobehub-dev 实现隔离)。

关键依赖项

  • commander - CLI 框架
  • @trpc/client + superjson - 类型安全的 API 客户端
  • @lobechat/device-gateway-client - WebSocket 网关连接
  • @lobechat/local-file-shell - 本地 shell/文件工具执行
  • picocolors - 终端颜色
  • ws - WebSocket
  • diff - 文本差异比较
  • fast-glob - 文件模式匹配

开发

在开发模式下运行

开发模式使用 LOBEHUB_CLI_HOME=.lobehub-dev 将凭据与全局 ~/.lobehub/ 目录隔离,因此开发和生产配置不会互相冲突。

# Run a command in dev mode (from apps/cli/)
cd apps/cli && bun run dev -- <command>

# This is equivalent to:
LOBEHUB_CLI_HOME=.lobehub-dev bun src/index.ts <command>
连接本地开发服务器

若要使用本地开发服务器(例如 localhost:3011)测试 CLI:

步骤 1:启动本地服务器

# From cloud repo root
bun run dev
# Server starts on http://localhost:3011 (or configured port)

步骤 2:通过设备码流程登录本地服务器

cd apps/cli && bun run dev -- login --server http://localhost:3011

此操作将:

  1. 调用 POST http://localhost:3011/oidc/device/auth 获取设备码
  2. 输出类似 http://localhost:3011/oidc/device?user_code=XXXX-YYYY 的 URL
  3. 在浏览器中打开该 URL,登录并授权
  4. 将凭据保存到 apps/cli/.lobehub-dev/credentials.json
  5. 将服务器 URL 保存到 apps/cli/.lobehub-dev/settings.json

登录后,后续所有 bun run dev -- <command> 调用都会使用本地服务器。

步骤 3:对本地服务器运行命令

cd apps/cli && bun run dev -- task list
cd apps/cli && bun run dev -- task create -i "Test task" -n "My Task"
cd apps/cli && bun run dev -- agent list

故障排除:

  • 如果登录返回 invalid_grant,请确保本地 OIDC 提供商已正确配置(检查 .env 中的 OIDC_* 环境变量)
  • 如果 API 调用出现 UNAUTHORIZED,你的令牌可能已过期 — 请再次运行 bun run dev -- login --server http://localhost:3011
  • 开发凭据存储在 apps/cli/.lobehub-dev/(已被 git 忽略),而非 ~/.lobehub/
在本地环境和生产环境之间切换
# Dev mode (local server) — uses .lobehub-dev/
cd apps/cli && bun run dev -- <command>

# Production (app.lobehub.com) — uses ~/.lobehub/
lh <command>

两个环境的凭据目录不同,彼此完全隔离。

构建与测试
# Build CLI
cd apps/cli && bun run build

# Unit tests
cd apps/cli && bun run test

# E2E tests (requires authenticated CLI)
cd apps/cli && bunx vitest run e2e/kb.e2e.test.ts

# Link globally for testing (installs lh/lobe/lobehub commands)
cd apps/cli && bun run cli:link

命令详细参考

各命令组的详细信息请参阅 references/:

  • Agent:references/agent.md(CRUD、运行、状态)
  • 目标:references/goal.md(规划轮次、状态、事件、生命周期、决策)
  • 内容生成:references/generate.md(文本、图像、视频、tts、asr、下载)
  • 知识与文件:references/knowledge.md(kb、文件、文档)
  • 对话:references/conversation.md(主题、消息)
  • 记忆:references/memory.md(记忆管理、提取)
  • 技能与插件:references/skills-plugins.md(技能、插件)
  • 模型与提供商:references/models-providers.md(模型、提供商)
  • 搜索与配置:references/search-config.md(搜索、whoami、用量、工作区)

评论

支持 Markdown