CLI-Anything:让所有软件都能被 AI Agent 驱动

CLI-Anything:让所有软件都能被 Agent 驱动

<p align="center">
<strong>今天的软件为人而生:man_technologist:,明天的用户是 Agent:robot:

CLI-Anything:连接 AI Agent 与全世界软件的桥梁</strong>
</p>

:globe_with_meridians: CLI-Hub:在 CLI-Hub 探索社区已构建的所有 CLI,一条命令即可安装。想贡献你的 CLI?提交 PR — Hub 会即时更新。

<p align="center">
<a href="#-快速上手"><img src="https://img.shields.io/badge/快速上手-5_分钟-blue?style=for-the-badge" alt="Quick Start"></a>
<a href="#-实测展示"><img src="https://img.shields.io/badge/Demo-13_款软件-green?style=for-the-badge" alt="Demos"></a>
<a href="#-测试结果"><img src="https://img.shields.io/badge/测试-1%2C741_通过-brightgreen?style=for-the-badge" alt="Tests"></a>
<a href="LICENSE"><img src="https://img.shields.io/badge/License-Apache_2.0-yellow?style=for-the-badge" alt="License"></a>
</p>

<p align="center">
<img src="https://img.shields.io/badge/python-≥3.10-blue?logo=python&logoColor=white" alt="Python">
<img src="https://img.shields.io/badge/click-≥8.0-green" alt="Click">
<img src="https://img.shields.io/badge/pytest-100%25_pass-brightgreen" alt="Pytest">
<img src="https://img.shields.io/badge/coverage-unit_%2B_e2e-orange" alt="Coverage">
<img src="https://img.shields.io/badge/output-JSON_%2B_Human-blueviolet" alt="Output">
</p>

一行命令,让任意软件接入 OpenClaw、nanobot、Cursor、Claude Code 等 Agent 框架。

:sparkles: 功能特性

  • 为 AI Agent 而生:将 Blender、GIMP、Audacity、Chrome 等软件的 GUI 操作转化为结构化 CLI 命令,让 Agent 能够像调用 API 一样驱动复杂软件
  • 统一的 CLI 架构:基于 Click 框架构建,所有软件 CLI 遵循一致的命令结构(子命令 + 选项 + JSON 输出),降低 Agent 学习成本
  • 状态管理与会话:支持项目状态持久化(JSON 格式)、撤销/重做(50 级历史)、REPL 交互模式,Agent 可在长会话中保持上下文
  • JSON 输出模式:所有命令支持 --json 标志,输出结构化数据供 Agent 程序化消费
  • CLI-Hub 一站式管理:社区驱动的 CLI 仓库,pip install cli-anything-hub 后通过 cli-hub install <name> 安装任意 CLI
  • 开箱即用的软件覆盖:
    • Blender:3D 场景创建、对象管理、材质/修改器配置、渲染脚本生成
    • Audacity:音频项目编辑、轨道/片段操作、效果链、WAV 渲染
    • AdGuardHome:DNS 过滤规则、客户端管理、DHCP、统计查询
    • Chrome 浏览器:通过 DOMShell MCP 服务器实现基于无障碍树的文件系统式自动化
    • AnyGen:云端内容生成(PPT、文档、图表、网站等)

:rocket: 快速上手

安装 CLI-Hub(推荐)

# 安装 CLI-Hub
pip install cli-anything-hub

# 浏览可用软件
cli-hub list

# 安装指定软件 CLI
cli-hub install blender
cli-hub install audacity
cli-hub install adguardhome

直接从源码安装

# 克隆项目
git clone https://github.com/HKUDS/CLI-Anything.git
cd CLI-Anything

# 进入目标软件的 agent-harness 目录
cd cli_anything/blender/agent-harness

# 开发模式安装
pip install -e .

# 验证安装
cli-anything-blender --help

:open_book: 使用指南

交互式 REPL(推荐 Agent 使用)

# 进入 REPL 会话
cli-anything-blender

# 在 REPL 中执行命令
scene new --name "MyScene" -o scene.json
object add cube --name "Box"
render execute render.png --overwrite
help              # 查看所有可用命令
undo / redo       # 撤销/重做
quit              # 退出

单次命令模式

# 带 JSON 输出(Agent 程序化消费)
cli-anything-blender --json scene new -o scene.json

# 3D 场景操作
cli-anything-blender object add sphere --name "Ball" -l 3,0,1
cli-anything-blender material create --name "Red" --color 1,0,0,1
cli-anything-blender material assign 0 0

# 音频编辑(Audacity)
cli-anything-audacity project new --name "Podcast" -o project.json
cli-anything-audacity track add --name "Voice"
cli-anything-audacity clip add 0 recording.wav
cli-anything-audacity effect add normalize --track 0 -p target_db=-3.0
cli-anything-audacity export render output.wav

# 浏览器自动化
cli-anything-browser page open https://example.com
cli-anything-browser fs ls /
cli-anything-browser fs grep "Login"
cli-anything-browser act click /main/button[0]

命令结构规范

所有 CLI 遵循统一的命令结构:

cli-anything-<software> [--json] [--host HOST] <command-group> <subcommand> [OPTIONS]
  • --json:启用机器可读的 JSON 输出
  • --host / --port:连接目标服务(如 AdGuardHome、ChromaDB)
  • <command-group>:功能分组(scene、track、page、collection 等)
  • <subcommand>:具体操作(new、add、open、list 等)

:microscope: 核心代码

以下是 CLI-Anything 各软件 CLI 的核心实现模块展示:

1. Blender CLI 核心模块 - 场景管理 (scene.py)

"""Blender CLI - Scene/project management module."""

import json
import os
import copy
from datetime import datetime
from typing import Optional, Dict, Any, List

PROJECT_VERSION = "1.0"

# 场景预设配置
PROFILES = {
    "default": {"resolution_x": 1920, "resolution_y": 1080, "engine": "CYCLES", "samples": 128},
    "preview": {"resolution_x": 960, "resolution_y": 540, "engine": "EEVEE", "samples": 16},
    "4k": {"resolution_x": 3840, "resolution_y": 2160, "engine": "CYCLES", "samples": 256},
}

def create_scene(
    name: str = "untitled",
    profile: Optional[str] = None,
    resolution_x: int = 1920,
    resolution_y: int = 1080,
    engine: str = "CYCLES",
    samples: int = 128,
    fps: int = 24,
) -> Dict[str, Any]:
    """创建新的 Blender 场景(JSON 项目)"""
    if profile and profile in PROFILES:
        p = PROFILES[profile]
        resolution_x = p.get("resolution_x", resolution_x)
        resolution_y = p.get("resolution_y", resolution_y)
        engine = p.get("engine", engine)
        samples = p.get("samples", samples)
        fps = p.get("fps", fps)

    scene = {
        "version": PROJECT_VERSION,
        "name": name,
        "settings": {
            "resolution_x": resolution_x,
            "resolution_y": resolution_y,
            "engine": engine,
            "samples": samples,
            "fps": fps,
        },
        "objects": [],
        "materials": [],
        "cameras": [],
        "lights": [],
        "animation": {"frame_start": 1, "frame_end": 250, "current_frame": 1},
        "render": {"output_path": "", "format": "PNG", "use_transparent": False},
        "metadata": {
            "created": datetime.now().isoformat(),
            "modified": datetime.now().isoformat(),
            "software": "cli-anything-blender 1.0",
        },
    }
    return scene

def save_project(project: Dict[str, Any], path: str) -> None:
    """将场景项目保存为 JSON 文件"""
    project["metadata"]["modified"] = datetime.now().isoformat()
    with open(path, "w", encoding="utf-8") as f:
        json.dump(project, f, indent=2, default=str)

def open_project(path: str) -> Dict[str, Any]:
    """从 JSON 文件加载场景项目"""
    if not os.path.exists(path):
        raise FileNotFoundError(f"Project file not found: {path}")
    with open(path, "r", encoding="utf-8") as f:
        return json.load(f)

2. Audacity CLI 核心模块 - 效果注册表 (effects.py)

"""Audacity CLI - Effect registry and management module."""

from typing import Dict, Any, List, Optional

# 效果注册表:效果名 -> 参数规格说明
EFFECT_REGISTRY = {
    "amplify": {
        "category": "volume",
        "description": "按 dB 值放大或衰减音频",
        "params": {
            "gain_db": {"type": "float", "default": 0.0, "min": -60, "max": 60,
                        "description": "增益(分贝)"},
        },
    },
    "normalize": {
        "category": "volume",
        "description": "将音频归一化到目标峰值电平",
        "params": {
            "target_db": {"type": "float", "default": -1.0, "min": -60, "max": 0,
                          "description": "目标峰值电平(dB)"},
        },
    },
    "fade_in": {
        "category": "fade",
        "description": "在开头应用淡入效果",
        "params": {
            "duration": {"type": "float", "default": 1.0, "min": 0.01, "max": 300,
                         "description": "淡入持续时间(秒)"},
        },
    },
    "reverse": {
        "category": "transform",
        "description": "反转音频",
        "params": {},
    },
}

def add_effect(
    project: Dict[str, Any],
    effect_name: str,
    track_index: int,
    params: Optional[Dict[str, Any]] = None,
) -> Dict[str, Any]:
    """向指定轨道添加效果"""
    if effect_name not in EFFECT_REGISTRY:
        raise ValueError(f"未知效果: {effect_name}")

    tracks = project.get("tracks", [])
    if track_index < 0 or track_index >= len(tracks):
        raise IndexError(f"轨道索引 {track_index} 超出范围")

    effect_spec = EFFECT_REGISTRY[effect_name]
    validated_params = {}
    for key, spec in effect_spec["params"].items():
        value = params.get(key, spec["default"]) if params else spec["default"]
        if "min" in spec and value < spec["min"]:
            raise ValueError(f"参数 {key} 不能小于 {spec['min']}")
        if "max" in spec and value > spec["max"]:
            raise ValueError(f"参数 {key} 不能大于 {spec['max']}")
        validated_params[key] = value

    effect = {
        "name": effect_name,
        "category": effect_spec["category"],
        "params": validated_params,
    }
    tracks[track_index].setdefault("effects", []).append(effect)
    return effect

def list_effects(project: Dict[str, Any], track_index: int) -> List[Dict[str, Any]]:
    """列出轨道上的所有效果"""
    tracks = project.get("tracks", [])
    if track_index < 0 or track_index >= len(tracks):
        return []
    return tracks[track_index].get("effects", [])

3. 浏览器自动化 CLI - DOMShell 后端 (domshell_backend.py)

"""DOMShell MCP 后端 - 通过 MCP 协议与 DOMShell 服务器通信"""

import json
import subprocess
from typing import Dict, Any, Optional

class DOMShellBackend:
    """DOMShell MCP 服务器后端封装"""

    def __init__(self):
        self._process = None
        self._daemon_mode = False

    def _run_command(self, command: str, args: Optional[list] = None) -> Dict[str, Any]:
        """执行 DOMShell 命令"""
        cmd = ["npx", "@apireno/domshell", command]
        if args:
            cmd.extend(args)

        try:
            result = subprocess.run(
                cmd,
                capture_output=True,
                text=True,
                timeout=30,
            )
            if result.returncode != 0:
                return {
                    "error": f"DOMShell 命令失败: {result.stderr}",
                    "isError": True,
                }
            try:
                return json.loads(result.stdout)
            except json.JSONDecodeError:
                return {"output": result.stdout}
        except subprocess.TimeoutExpired:
            return {"error": "命令超时", "isError": True}

    def open_url(self, url: str) -> Dict[str, Any]:
        """在 Chrome 中打开 URL"""
        return self._run_command("open", [url])

    def ls(self, path: str = "/") -> Dict[str, Any]:
        """列出无障碍树中的元素"""
        return self._run_command("ls", [path])

    def cd(self, path: str) -> Dict[str, Any]:
        """更改工作目录"""
        return self._run_command("cd", [path])

    def cat(self, path: str) -> Dict[str, Any]:
        """读取元素内容"""
        return self._run_command("cat", [path])

    def grep(self, pattern: str) -> Dict[str, Any]:
        """搜索文本模式"""
        return self._run_command("grep", [pattern])

    def click(self, path: str) -> Dict[str, Any]:
        """点击元素"""
        return self._run_command("click", [path])

    def type_text(self, path: str, text: str) -> Dict[str, Any]:
        """向输入框输入文本"""
        return self._run_command("type", [path, text])

4. ChromaDB CLI 核心 - 集合管理 (collections.py)

"""ChromaDB 集合管理命令"""

import json as json_mod
import click
from ..utils.chromadb_backend import ChromaDBBackend

@click.group("collection")
@click.pass_context
def collection_group(ctx):
    """管理 ChromaDB 集合"""
    pass

@collection_group.command("list")
@click.pass_context
def list_collections(ctx):
    """列出所有集合"""
    backend: ChromaDBBackend = ctx.obj["backend"]
    use_json = ctx.obj.get("json", False)

    try:
        collections = backend.list_collections()
        if use_json:
            click.echo(json_mod.dumps(collections, indent=2))
        else:
            if not collections:
                click.echo("未找到集合")
                return
            click.echo(f"{'名称':<20} {'ID':<40}")
            click.echo("-" * 62)
            for c in collections:
                click.echo(f"{c.get('name', '?'):<20} {c.get('id', '?'):<40}")
    except Exception as e:
        click.echo(f"错误: {e}", err=True)
        raise SystemExit(1)

@collection_group.command("create")
@click.option("--name", required=True, help="集合名称")
@click.option("--metadata", default=None, help="元数据 JSON 字符串")
@click.pass_context
def create_collection(ctx, name, metadata):
    """创建新集合"""
    backend: ChromaDBBackend = ctx.obj["backend"]
    use_json = ctx.obj.get("json", False)

    try:
        meta = json_mod.loads(metadata) if metadata else None
        result = backend.create_collection(name, metadata=meta)
        if use_json:
            click.echo(json_mod.dumps(result, indent=2))
        else:
            click.echo(f"✓ 集合 '{name}' 已创建 (ID: {result.get('id')})")
    except Exception as e:
        click.echo(f"错误: {e}", err=True)
        raise SystemExit(1)

5. 会话管理基类 - 撤销/重做 (Session)

"""会话管理 - 带撤销/重做功能的状态管理"""

import json
import os
import copy
from typing import Dict, Any, Optional, List

class Session:
    """管理项目状态,支持撤销/重做"""

    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 has_project(self) -> bool:
        return self.project is not None

    def get_project(self) -> Dict[str, Any]:
        if self.project is None:
            raise RuntimeError("没有加载项目")
        return self.project

    def set_project(self, project: Dict[str, Any], path: Optional[str] = None) -> None:
        """设置当前项目并清空历史"""
        self.project = project
        self.project_path = path
        self._undo_stack.clear()
        self._redo_stack.clear()
        self._modified = False

    def snapshot(self, description: str = "") -> None:
        """在执行变更前保存当前状态到撤销栈"""
        if self.project is None:
            return
        state = {
            "project": copy.deepcopy(self.project),
            "description": description,
            "timestamp": datetime.now().isoformat(),
        }
        self._undo_stack.append(state)
        if len(self._undo_stack) > self.MAX_UNDO:
            self._undo_stack.pop(0)
        self._redo_stack.clear()
        self._modified = True

    def undo(self) -> Optional[Dict[str, Any]]:
        """撤销上次操作"""
        if not self._undo_stack:
            return None
        # 保存当前状态到重做栈
        self._redo_stack.append({
            "project": copy.deepcopy(self.project),
            "timestamp": datetime.now().isoformat(),
        })
        state = self._undo_stack.pop()
        self.project = state["project"]
        self._modified = True
        return state

    def redo(self) -> Optional[Dict[str, Any]]:
        """重做上次撤销的操作"""
        if not self._redo_stack:
            return None
        self._undo_stack.append({
            "project": copy.deepcopy(self.project),
            "timestamp": datetime.now().isoformat(),
        })
        state = self._redo_stack.pop()
        self.project = state["project"]
        self._modified = True
        return state

:test_tube: 测试结果

CLI-Anything 项目包含完善的单元测试和端到端测试(E2E)体系:

软件 单元测试 E2E 测试 通过率
Blender 380+ 90+ :check_mark_button: 100%
Audacity 290+ 75+ :check_mark_button: 100%
AdGuardHome 140+ 35+ :check_mark_button: 100%
浏览器 210+ 55+ :check_mark_button: 100%
AnyGen 160+ 40+ :check_mark_button: 100%
ChromaDB 120+ 30+ :check_mark_button: 100%
# 运行所有测试
cd cli_anything/<software>/agent-harness
python -m pytest tests/ -v

# 仅运行单元测试(无需后端)
python -m pytest tests/test_core.py -v

# 运行端到端测试(需要后端运行)
python -m pytest tests/test_full_e2e.py -v

:handshake: 为 CLI-Anything 贡献新的软件 CLI

CLI-Anything 欢迎社区贡献!你可以选择以下两种方式之一:

方式一:在 Monorepo 中添加新 CLI

  1. 在 cli_anything/<software>/ 下创建 agent-harness/ 目录
  2. 编写 <SOFTWARE>.md SOP 文档描述架构
  3. 实现 CLI 代码(遵循 Click 框架 + 统一的命令结构)
  4. 编写单元测试和 E2E 测试
  5. 在 cli_anything/<software>/skills/SKILL.md 中添加 AI 可发现的技能定义
  6. 更新 registry.json 添加新软件条目

方式二:独立仓库(推荐)

  1. 在自有 GitHub 仓库中实现 CLI
  2. 发布到 PyPI 或支持 pip install git+https://...
  3. 向本仓库提交 仅含 registry 条目 的 PR

:scroll: 许可证

CLI-Anything 采用 Apache License 2.0 许可证。


<p align="center">
<strong>:globe_with_meridians: <a href="https://hkuds.github.io/CLI-Anything/">CLI-Hub</a> · <a href="https://github.com/HKUDS/CLI-Anything">GitHub</a></strong>
</p>
BUR6Mw9NoEj9m1nnXLq1vDeKHJ2gVMZ/23y6PK5qIR4=

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容