CLI-Anything 深度学习笔记

学习时间:2026-04-23
项目地址:https://github.com/HKUDS/CLI-Anything
本地路径:./cli-anything/
核心定位:让所有软件变成 Agent 原生 (Making ALL Software Agent-Native)

一、项目概述 / Project Overview

1.1 核心理念 / Core Vision

Today's Software Serves Humans👨‍💻. Tomorrow's Users will be Agents🤖.

CLI-Anything 是香港大学数据科学实验室(HKU DS Lab)开源的项目,旨在为任何软件自动生成有状态的 CLI 接口,使其可以被 AI Agent 驱动。

英文原文:
CLI-Anything: Bridging the Gap Between AI Agents and the World's Software
中文翻译:
CLI-Anything:弥合 AI Agent 与世界软件之间的鸿沟

1.2 核心价值 / Core Values

特性 / Feature说明 / Description
结构化 & 可组合文本命令天然匹配 LLM 的输入格式,可自由串联成复杂工作流
轻量且通用几乎零开销,跨平台运行,不依赖额外环境
自描述一个 --help 就能让 Agent 自动发现所有功能
久经验证Claude Code 每天通过 CLI 执行数以千计的真实任务
Agent 友好结构化 JSON 输出,Agent 无需任何额外解析
确定且可靠输出稳定一致,Agent 行为可预测

1.3 技术栈 / Tech Stack

Python 3.10+  |  Click 8.0+  |  pytest 7.0+
输出格式: JSON + Human-readable  |  测试: Unit + E2E

二、核心架构 / Core Architecture

2.1 七阶段构建流程 / 7-Phase Build Pipeline

┌─────────────────────────────────────────────────────────────────────┐
│                    CLI-Anything 构建流程                            │
├─────────────────────────────────────────────────────────────────────┤
│                                                                     │
│  Phase 1: 🔍 分析 (Analyze)                                         │
│  ────────────────────────────────────────────────────────────────  │
│  • 识别后端引擎 (MLT for Shotcut, GEGL for GIMP...)                │
│  • 将 GUI 操作映射到 API 调用                                        │
│  • 确定数据模型 (XML, JSON, Binary, Database)                        │
│  • 查找现有 CLI 工具 (melt, ffmpeg, convert)                         │
│  • 梳理命令/撤销系统                                                │
│                                                                     │
│  Phase 2: 📐 设计 (Design)                                          │
│  ────────────────────────────────────────────────────────────────  │
│  • 选择交互模型: Stateful REPL / Subcommand CLI / Both              │
│  • 定义命令分组: Project, Core, I/O, Config, Session                │
│  • 设计状态模型: 内存/文件/JSON                                      │
│  • 规划输出格式: --json / Human-readable                            │
│                                                                     │
│  Phase 3: 🔨 实现 (Implement)                                       │
│  ────────────────────────────────────────────────────────────────  │
│  • 数据层: XML/JSON 操作                                            │
│  • Info 命令: 让 Agent 先检查再修改                                  │
│  • 变更命令: 每个逻辑操作一个命令                                     │
│  • 后端集成: utils/_backend.py                            │
│  • 会话管理: Undo/Redo                                              │
│  • REPL 界面: 使用 ReplSkin                                         │
│                                                                     │
│  Phase 4: 📋 规划测试 (Plan Tests)                                  │
│  ────────────────────────────────────────────────────────────────  │
│  • 创建 TEST.md 测试计划文档                                         │
│                                                                     │
│  Phase 5: 🧪 编写测试 (Write Tests)                                 │
│  ────────────────────────────────────────────────────────────────  │
│  • 单元测试 (test_core.py) - 无外部依赖                              │
│  • E2E 测试 (test_full_e2e.py) - 调用真实软件                        │
│                                                                     │
│  Phase 6: 📝 文档 (Document)                                        │
│  ────────────────────────────────────────────────────────────────  │
│  • 更新 TEST.md 写入测试结果                                         │
│  • 生成 SKILL.md AI 可发现的技能定义                                 │
│                                                                     │
│  Phase 7: 📦 发布 (Publish)                                         │
│  ────────────────────────────────────────────────────────────────  │
│  • setup.py + PyPI 发布                                             │
│  • registry.json 注册                                               │
│                                                                     │
└─────────────────────────────────────────────────────────────────────┘

2.2 目录结构 / Directory Structure

cli-anything/
├── /                    # 每个软件的子目录
│   └── agent-harness/            # Agent 适配层
│       ├── cli_anything/         # Python 包
│       │   └── /
│       │       ├── __init__.py
│       │       ├── _cli.py    # Click CLI 主文件
│       │       ├── core/                 # 核心模块
│       │       │   ├── __init__.py
│       │       │   ├── session.py        # 会话管理 + Undo/Redo
│       │       │   ├── project.py        # 项目管理
│       │       │   ├── layers.py         # 图层管理
│       │       │   └── ...
│       │       ├── utils/
│       │       │   ├── _backend.py  # 后端集成
│       │       │   └── repl_skin.py      # REPL 皮肤
│       │       └── tests/
│       │           ├── test_core.py      # 单元测试
│       │           └── test_full_e2e.py  # E2E 测试
│       ├── .md           # SOP 文档
│       └── setup.py                 # 发布配置
│
├── cli-anything-plugin/           # Claude Code 插件
│   ├── commands/                  # /cli-anything 命令
│   ├── HARNESS.md                 # 方法论文档
│   ├── repl_skin.py               # REPL 样式
│   └── skill_generator.py         # SKILL.md 生成器
│
├── cli-hub/                       # CLI 包管理器
│   └── cli_anything_hub/
│       └── hub.py
│
├── skills/                        # 技能定义目录
│   ├── cli-anything-/
│   │   └── SKILL.md              # AI 可发现的技能定义
│   └── ...
│
├── registry.json                  # CLI 注册表
└── public_registry.json          # 公共 CLI 注册表

2.3 CLI 命名规范 / CLI Naming Convention

cli-anything-
  ├── cli-anything-gimp       # 图像处理
  ├── cli-anything-blender   # 3D 建模
  ├── cli-anything-kdenlive   # 视频编辑
  ├── cli-anything-audacity   # 音频处理
  └── ... (49+ CLIs)

三、会话系统 / Session System

3.1 状态管理 / State Management

class Session:
    """Manages project state with undo/redo history."""
    
    MAX_UNDO = 50  # 最大撤销步数
    
    def __init__(self):
        self.project: Optional[Dict[str, Any]] = None
        self.project_path: Optional[str] = None
        self._undo_stack: List[Dict[str, Any]] = []
        self._redo_stack: List[Dict[str, Any]] = []
        self._modified: bool = False
    
    def snapshot(self, description: str = "") -> None:
        """Save current state before mutation."""
        
    def undo(self) -> Optional[str]:
        """Undo the last operation."""
        
    def redo(self) -> Optional[str]:
        """Redo the last undone operation."""

3.2 文件锁定保存 / File Locking

python def _locked_save_json(path, data, **dump_kwargs) -> None: """Atomically write JSON with exclusive file locking.""" f = open(path, "r+") with f: fcntl.flock(f.fileno(), fcntl.LOCK_EX) # 独占锁 f.seek(0) f.truncate() json.dump(data, f, **dump_kwargs) fcntl.flock(f.fileno(), fcntl.LOCK_UN) # 解锁

四、CLI-Hub 包管理器 / CLI-Hub Package Manager

4.1 安装命令 / Installation

bash

安装 CLI-Hub

pip install cli-anything-hub

安装后获得 cli-hub 命令

4.2 使用方法 / Usage

bash

浏览所有可用 CLI

cli-hub list

按分类筛选 (image, 3d, video, audio, office, ai, ...)

cli-hub list -c image

搜索 CLI

cli-hub search "3d modeling"

查看 CLI 详情

cli-hub info gimp

安装 CLI

cli-hub install gimp

更新 CLI

cli-hub update gimp

卸载 CLI

cli-hub uninstall gimp

JSON 输出

cli-hub list --json cli-hub search blender --json

4.3 Web Hub / 网页版

访问地址: https://hkuds.github.io/CLI-Anything/

五、已有 CLI 清单 / CLI Inventory

5.1 完整列表 (49+ CLIs)

分类CLI 名称说明
图像 / Imagegimp栅格图像处理 (Pillow)
inkscape矢量图形编辑
krita数字绘画
sketchUI 设计工具
3D / 3Dblender3D 建模、动画、渲染
freecad参数化 3D 建模
视频 / Videokdenlive视频编辑
shotcut跨平台视频编辑
openscreen屏幕录制编辑
obs-studio直播/录制
videocaptionerAI 字幕生成
renderdocGPU 帧捕获分析
音频 / Audioaudacity音频编辑 (sox)
音乐 / Musicmusescore乐谱编辑
办公 / Officelibreoffice办公套件
zotero文献管理
mubu数据分析工具
AIcomfyuiAI 图像生成工作流
notebooklmAI 研究助手
ollama本地 LLM
novitaOpenAI 兼容 API
dify-workflow工作流自动化
n8n工作流自动化
数据库 / Databasechromadb向量数据库
科学 / ScienceqgisGIS/地图制作
unimol_tools分子建模
cloudcompare3D 点云处理
intelwatchOSINT 工具
图表 / Diagramsdrawio图表创建
mermaid流程图/时序图
开发 / DevOpseth2-quickstart以太坊节点部署
pm2进程管理
iterm2终端控制
cloudanalyzer云成本分析
网络 / NetworkadguardhomeDNS 广告拦截
rms远程管理
通信 / Communicationzoom视频会议
知识管理 / Knowledgeobsidian知识库
游戏 / Gameslay_the_spire_ii卡牌肉鸽游戏
游戏开发 / GameDevgodt游戏引擎
unrealinsightsUnreal 调试
搜索 / SearchexaAI 搜索引擎
测试 / TestingwiremockHTTP 模拟服务器
WebbrowserDOMShell 浏览器自动化
safariSafari 自动化
生成 / Generationanygen文档/幻灯片生成

5.2 分类统计 / Category Statistics

图像处理 (Image): 4 CLIs 3D建模 (3D): 2 CLIs 视频编辑 (Video): 5 CLIs AI工具 (AI): 6 CLIs 办公软件 (Office): 3 CLIs 科学计算 (Science): 4 CLIs DevOps: 4 CLIs 图表 (Diagrams): 2 CLIs 其他 (Others): 19+ CLIs ───────────────────────────────── 总计 (Total): 49+ CLIs

六、技术实现 / Technical Implementation

6.1 Click 框架核心模式 / Click Framework Core Patterns

python import click import json from typing import Optional

── 全局状态 ──────────────────────────────────────

_session: Optional[Session] = None _json_output = False

── 输出函数 ──────────────────────────────────────

def output(data, message: str = ""): if _json_output: click.echo(json.dumps(data, indent=2, default=str)) else: click.echo(message) _print_dict(data)

── 错误处理装饰器 ─────────────────────────────────

def handle_error(func): def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except FileNotFoundError as e: if _json_output: click.echo(json.dumps({"error": str(e), "type": "file_not_found"})) else: click.echo(f"Error: {e}", err=True) if not _repl_mode: sys.exit(1) return wrapper

── 主命令组 ──────────────────────────────────────

@click.group(invoke_without_command=True) @click.option("--json", "use_json", is_flag=True, help="Output as JSON") @click.option("--project", "project_path", type=str, default=None) @click.pass_context def cli(ctx, use_json, project_path): global _json_output _json_output = use_json if ctx.invoked_subcommand is None: ctx.invoke(repl, project_path=None) # 默认进入 REPL

── 子命令组示例 ──────────────────────────────────

@cli.group() def project(): """Project management.""" pass

@project.command("new") @click.option("-o", "--output", required=True) def project_new(output): """Create a new project.""" proj = {"name": "untitled"} output(proj, f"Project created: {output}")

6.2 JSON 项目格式 / JSON Project Format

json { "version": "1.0", "name": "my_project", "canvas": { "width": 1920, "height": 1080, "color_mode": "RGB", "background": "#ffffff", "dpi": 300 }, "layers": [ { "id": 0, "name": "Background", "type": "image", "source": "/path/to/image.png", "visible": true, "opacity": 1.0, "blend_mode": "normal", "filters": [ {"name": "brightness", "params": {"factor": 1.2}} ] } ], "selection": null, "metadata": {} }

6.3 REPL 皮肤系统 / REPL Skin System

python from cli_anything..utils.repl_skin import ReplSkin

初始化 REPL 皮肤

skin = ReplSkin("", version="1.0.0")

显示启动横幅

skin.print_banner()

创建交互会话

pt_session = skin.create_prompt_session() line = skin.get_input(pt_session, project_name="my_project", modified=True)

格式化输出

skin.help(commands_dict) # 帮助信息 skin.success("Saved") # ✓ 成功消息 (绿色) skin.error("Not found") # ✗ 错误消息 (红色) skin.warning("Unsaved") # ⚠ 警告消息 (黄色) skin.info("Processing...") # ● 信息消息 (蓝色) skin.status("Key", "value") # 状态行 skin.table(headers, rows) # 格式化表格 skin.progress(3, 10, "...") # 进度条

退出消息

skin.print_goodbye()

七、与 Agent 平台集成 / Agent Platform Integration

7.1 支持的平台 / Supported Platforms

平台安装方式命令
Claude Code插件市场/cli-anything
Pi Coding Agent扩展安装/cli-anything
OpenClawSKILL.md@cli-anything build a CLI for...
OpenCode命令复制/cli-anything
CodexSkill 安装Use CLI-Anything to...
Qodercli插件注册/cli-anything:cli-anything
GitHub Copilot CLI插件安装/cli-anything:cli-anything

7.2 Claude Code 集成示例 / Claude Code Integration

bash

Step 1: 添加插件市场

/plugin marketplace add HKUDS/CLI-Anything

Step 2: 安装插件

/plugin install cli-anything

Step 3: 生成 CLI

/cli-anything ./gimp

Step 4: 优化 CLI

/cli-anything:refine ./gimp /cli-anything:refine ./gimp "batch processing and filters"

7.3 Pi Coding Agent 集成 / Pi Integration

bash

安装扩展

git clone https://github.com/HKUDS/CLI-Anything.git cd CLI-Anything bash .pi-extension/cli-anything/install.sh

卸载扩展

bash .pi-extension/cli-anything/install.sh --uninstall

可用命令

/cli-anything # 构建 CLI /cli-anything:refine # 优化 CLI /cli-anything:test # 运行测试 /cli-anything:validate # 验证 CLI /cli-anything:list [options] # 列出工具

八、贡献机制 / Contribution Guide

8.1 贡献类型 / Contribution Types

类型说明影响
A) 新软件 CLI为未支持的软件创建 CLI⭐⭐⭐⭐⭐ 最高
B) 新功能扩展现有 CLI 功能⭐⭐⭐⭐
C) Bug 修复修复现有问题⭐⭐⭐

8.2 仓库内 CLI 结构 / In-Repo Harness Structure

/ └── agent-harness/ ├── cli_anything/ │ └── / │ ├── __init__.py │ ├── _cli.py │ ├── core/ # 核心模块 │ ├── utils/ # 工具函数 │ │ ├── repl_skin.py # 复制自 plugin │ │ └── _backend.py │ └── tests/ │ ├── test_core.py # 单元测试 │ └── test_full_e2e.py # E2E 测试 ├── .md # SOP 文档 └── setup.py # 发布配置

8.3 registry.json 字段说明 / Registry Fields

json { "name": "my-software", // 唯一标识符 (小写) "display_name": "My Software", // 显示名称 "version": "1.0.0", // 语义版本 "description": "Short description of what the CLI does", "requires": "backend software or null", // 运行时依赖 "homepage": "https://my-software.org", // 官方主页 "source_url": null, // 独立仓库 URL,仓库内为 null "install_cmd": "pip install git+https://github.com/HKUDS/CLI-Anything.git#subdirectory=my-software/agent-harness", "entry_point": "cli-anything-my-software", // CLI 命令名 "skill_md": "skills/cli-anything-my-software/SKILL.md", // 技能定义路径 "category": "category-name", // 分类 "contributors": [ // 贡献者列表 {"name": "github-username", "url": "https://github.com/github-username"} ] }

8.4 SKILL.md 生成 / SKILL.md Generation

yaml
name: "cli-anything-gimp" description: >- Command-line interface for Gimp - A stateful command-line interface for image editing, built on Pillow. Designed for AI agents...

cli-anything-gimp

Installation

pip install cli-anything-gimp

Usage

cli-anything-gimp project new -o project.json cli-anything-gimp --json project info -p project.json

Command Groups

Project

CommandDescription
newCreate a new project
openOpen an existing project
| ...

Layer

...

九、使用示例 / Usage Examples

9.1 GIMP CLI 示例 / GIMP CLI Examples

bash

创建新项目

cli-anything-gimp project new -o myproject.json

交互式 REPL

cli-anything-gimp

添加图层

cli-anything-gimp layer add-from-file photo.jpg --name "Background"

应用滤镜

cli-anything-gimp filter add brightness --layer 0 --param factor=1.3

导出项目

cli-anything-gimp --project myproject.json export render output.png --overwrite

JSON 输出

cli-anything-gimp --json project info -p myproject.json

9.2 Blender CLI 示例 / Blender CLI Examples

bash

创建场景

cli-anything-blender scene new --name "MyScene"

添加对象

cli-anything-blender object add cube --name "MyCube"

创建材质

cli-anything-blender material create --name "Red" --color 1,0,0,1

渲染输出

cli-anything-blender render output --format PNG --engine EEVEE

9.3 Shotcut CLI 示例 / Shotcut CLI Examples

bash

创建项目

cli-anything-shotcut project new -o myvideo.mlt

添加视频

cli-anything-shotcut clip add video.mp4 --track 1

应用滤镜

cli-anything-shotcut filter add brightness --clip 0 --param value=20

导出

cli-anything-shotcut export output.mp4 --preset youtube_1080p

十、学习总结 / Learning Summary

10.1 核心突破 / Key Innovations

  • Agent 原生设计 - CLI-Anything 不仅仅生成 CLI,而是为 Agent 构建了完整的工作流系统
  • 七阶段方法论 - 系统化的 GUI-to-CLI 转换流程,确保高质量输出
  • 状态持久化 - Session + Undo/Redo 让复杂任务可中断、可回滚
  • 多平台支持 - 统一的接口,适配 Claude Code、Pi、OpenClaw 等主流 Agent
  • 10.2 应用价值 / Application Value

    场景价值
    自动化工作流Agent 可驱动任何 GUI 软件完成复杂任务
    批量处理告别重复性 GUI 操作,实现命令行批量处理
    CI/CD 集成软件自动化测试、渲染、打包
    跨平台兼容统一接口,屏蔽底层差异
    Agent 生态为 AI Agent 打开所有软件的大门

    10.3 未来展望 / Future Outlook

    ┌─────────────────────────────────────────────────────────────────┐ │ CLI-Anything 生态系统 │ ├─────────────────────────────────────────────────────────────────┤ │ │ │ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ │ │ 用户 │────▶│ Agent │────▶│ CLI │ │ │ │ 意图 │ │ 理解 │ │ 执行 │ │ │ └──────────┘ └──────────┘ └──────────┘ │ │ │ │ │ ┌──────────────┼──────────────┐ │ │ ▼ ▼ ▼ │ │ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ │ │ GIMP │ │ Blender │ │ 任何 │ │ │ │ CLIs │ │ CLIs │ │ 软件 │ │ │ └──────────┘ └──────────┘ └──────────┘ │ │ │ │ 愿景 (Vision): 让每个软件都成为 Agent 的工具 │ │ │ └─────────────────────────────────────────────────────────────────┘

    参考链接 / References

  • GitHub: https://github.com/HKUDS/CLI-Anything
  • CLI-Hub Web: https://hkuds.github.io/CLI-Anything/
  • 中文文档: ./cli-anything/README_CN.md
  • 日语文档: ./cli-anything/README_JA.md
  • 方法论文档: ./cli-anything/cli-anything-plugin/HARNESS.md
  • 贡献指南: ./cli-anything/CONTRIBUTING.md