Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a7f64cd797 | ||
|
|
115ce38370 | ||
|
|
357cd0958f | ||
|
|
bfefbef475 | ||
|
|
fb41c79b14 | ||
|
|
038fbe24c8 | ||
|
|
fe79f0e5d4 | ||
|
|
af9fffc4a6 | ||
|
|
7ada90ac27 | ||
|
|
407ecc0f47 | ||
|
|
78b74d1bb1 | ||
|
|
bef3fe560d | ||
|
|
0b19ec64a4 | ||
|
|
6f13d41c11 | ||
|
|
0d27f2b774 | ||
|
|
03685ab5e7 | ||
|
|
7a72a5c69e | ||
|
|
baa2cbc49a | ||
|
|
f41d5d5a7c | ||
|
|
8865084905 | ||
|
|
da9cfb6c9d | ||
|
|
f142e3bae8 | ||
|
|
e3b2d56686 | ||
|
|
aa37ec0e44 | ||
|
|
2bd8ca0fba | ||
|
|
530a255091 | ||
|
|
e6fddf14f8 | ||
|
|
a00396b4fd | ||
|
|
c2dfa284d1 | ||
|
|
614b081364 | ||
|
|
245413b2cd | ||
|
|
3fa1d56632 | ||
|
|
68d085df28 | ||
|
|
62c761b7d8 | ||
|
|
62aa5ed128 |
No files matched your search
@@ -1,117 +0,0 @@
|
|||||||
# Gitee Go CI 流水线
|
|
||||||
|
|
||||||
triggers:
|
|
||||||
push:
|
|
||||||
branches:
|
|
||||||
- master
|
|
||||||
- main
|
|
||||||
pull_request:
|
|
||||||
branches:
|
|
||||||
- master
|
|
||||||
- main
|
|
||||||
|
|
||||||
stages:
|
|
||||||
- lint
|
|
||||||
- test
|
|
||||||
- structure
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
py-compile:
|
|
||||||
name: 语法检查
|
|
||||||
stage: lint
|
|
||||||
image: python:3.12
|
|
||||||
script:
|
|
||||||
- python -c "
|
|
||||||
import py_compile, os, sys;
|
|
||||||
errors = 0;
|
|
||||||
for root, dirs, files in os.walk('.'):
|
|
||||||
dirs[:] = [d for d in dirs if d not in {'.git', '__pycache__', 'node_modules', 'embedded_python'}];
|
|
||||||
for f in files:
|
|
||||||
if f.endswith('.py'):
|
|
||||||
path = os.path.join(root, f);
|
|
||||||
try:
|
|
||||||
py_compile.compile(path, doraise=True);
|
|
||||||
except py_compile.PyCompileError as e:
|
|
||||||
print(f'ERROR: {e}');
|
|
||||||
errors += 1;
|
|
||||||
if errors:
|
|
||||||
print(f'{errors} 个文件有语法错误');
|
|
||||||
sys.exit(1);
|
|
||||||
print('所有文件语法正确')
|
|
||||||
"
|
|
||||||
|
|
||||||
ruff-lint:
|
|
||||||
name: Ruff lint
|
|
||||||
stage: lint
|
|
||||||
image: python:3.12
|
|
||||||
script:
|
|
||||||
- pip install ruff -q
|
|
||||||
- ruff check . --select E,F,W --ignore E501,E402 --exclude .git,__pycache__,embedded_python
|
|
||||||
|
|
||||||
pytest-310:
|
|
||||||
name: 插件测试 (Python 3.10)
|
|
||||||
stage: test
|
|
||||||
image: python:3.10
|
|
||||||
script:
|
|
||||||
- pip install pytest colorama -q
|
|
||||||
- pytest tests/ -v --tb=short
|
|
||||||
|
|
||||||
pytest-311:
|
|
||||||
name: 插件测试 (Python 3.11)
|
|
||||||
stage: test
|
|
||||||
image: python:3.11
|
|
||||||
script:
|
|
||||||
- pip install pytest colorama -q
|
|
||||||
- pytest tests/ -v --tb=short
|
|
||||||
|
|
||||||
pytest-312:
|
|
||||||
name: 插件测试 (Python 3.12)
|
|
||||||
stage: test
|
|
||||||
image: python:3.12
|
|
||||||
script:
|
|
||||||
- pip install pytest colorama -q
|
|
||||||
- pytest tests/ -v --tb=short
|
|
||||||
|
|
||||||
structure:
|
|
||||||
name: 项目结构检查
|
|
||||||
stage: structure
|
|
||||||
image: python:3.12
|
|
||||||
script:
|
|
||||||
- echo "检查项目结构..."
|
|
||||||
- |
|
|
||||||
files=(
|
|
||||||
"ai_cli.py"
|
|
||||||
"launcher.py"
|
|
||||||
"xcli_core/cli_core.py"
|
|
||||||
"xcli_core/cli_base.py"
|
|
||||||
"xcli_core/config.py"
|
|
||||||
"xcli_core/constants.py"
|
|
||||||
"ai_engines/ollama_engine.py"
|
|
||||||
"ai_engines/openai_engine.py"
|
|
||||||
"plugins/code_editor.py"
|
|
||||||
"plugins/cmd_executor.py"
|
|
||||||
"plugins/file_manager.py"
|
|
||||||
"plugins/auto_engineer.py"
|
|
||||||
)
|
|
||||||
missing=0
|
|
||||||
for f in "${files[@]}"; do
|
|
||||||
if [ -f "$f" ]; then
|
|
||||||
echo " ✓ $f"
|
|
||||||
else
|
|
||||||
echo " ✗ $f (缺失!)"
|
|
||||||
missing=$((missing + 1))
|
|
||||||
fi
|
|
||||||
done
|
|
||||||
if [ $missing -gt 0 ]; then
|
|
||||||
echo "${missing} 个文件缺失"
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
echo "项目结构完整"
|
|
||||||
- |
|
|
||||||
engines=$(ls ai_engines/*_engine.py 2>/dev/null | wc -l)
|
|
||||||
echo "AI 引擎数量: $engines"
|
|
||||||
if [ "$engines" -gt 2 ]; then
|
|
||||||
echo "警告: 引擎数量超过 2 个"
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
echo "引擎数量正常"
|
|
||||||
@@ -1,148 +0,0 @@
|
|||||||
name: CI
|
|
||||||
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
branches: [master, main]
|
|
||||||
pull_request:
|
|
||||||
branches: [master, main]
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
lint:
|
|
||||||
name: 代码检查
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
|
|
||||||
- name: 安装 Python
|
|
||||||
uses: actions/setup-python@v5
|
|
||||||
with:
|
|
||||||
python-version: "3.12"
|
|
||||||
|
|
||||||
- name: 安装依赖
|
|
||||||
run: pip install ruff
|
|
||||||
|
|
||||||
- name: 语法检查 (py_compile)
|
|
||||||
run: |
|
|
||||||
python -c "
|
|
||||||
import py_compile, os, sys
|
|
||||||
errors = 0
|
|
||||||
for root, dirs, files in os.walk('.'):
|
|
||||||
dirs[:] = [d for d in dirs if d not in {'.git', '__pycache__', 'node_modules', 'embedded_python'}]
|
|
||||||
for f in files:
|
|
||||||
if f.endswith('.py'):
|
|
||||||
path = os.path.join(root, f)
|
|
||||||
try:
|
|
||||||
py_compile.compile(path, doraise=True)
|
|
||||||
except py_compile.PyCompileError as e:
|
|
||||||
print(f'ERROR: {e}')
|
|
||||||
errors += 1
|
|
||||||
if errors:
|
|
||||||
print(f'\n{errors} 个文件有语法错误')
|
|
||||||
sys.exit(1)
|
|
||||||
print('所有文件语法正确')
|
|
||||||
"
|
|
||||||
|
|
||||||
- name: Ruff lint
|
|
||||||
run: ruff check . --select E,F,W --ignore E501,E402,W503 --exclude .git,__pycache__,embedded_python
|
|
||||||
|
|
||||||
test:
|
|
||||||
name: 插件测试
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
strategy:
|
|
||||||
matrix:
|
|
||||||
python-version: ["3.10", "3.11", "3.12"]
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
|
|
||||||
- name: 安装 Python ${{ matrix.python-version }}
|
|
||||||
uses: actions/setup-python@v5
|
|
||||||
with:
|
|
||||||
python-version: ${{ matrix.python-version }}
|
|
||||||
|
|
||||||
- name: 安装测试依赖
|
|
||||||
run: pip install pytest colorama
|
|
||||||
|
|
||||||
- name: 运行测试
|
|
||||||
run: pytest tests/ -v --tb=short
|
|
||||||
|
|
||||||
structure:
|
|
||||||
name: 项目结构检查
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
|
|
||||||
- name: 安装 Python
|
|
||||||
uses: actions/setup-python@v5
|
|
||||||
with:
|
|
||||||
python-version: "3.12"
|
|
||||||
|
|
||||||
- name: 检查必要文件
|
|
||||||
run: |
|
|
||||||
echo "检查项目结构..."
|
|
||||||
files=(
|
|
||||||
"ai_cli.py"
|
|
||||||
"launcher.py"
|
|
||||||
"xcli_core/cli_core.py"
|
|
||||||
"xcli_core/cli_base.py"
|
|
||||||
"xcli_core/config.py"
|
|
||||||
"xcli_core/constants.py"
|
|
||||||
"ai_engines/ollama_engine.py"
|
|
||||||
"ai_engines/openai_engine.py"
|
|
||||||
"plugins/code_editor.py"
|
|
||||||
"plugins/git_tools.py"
|
|
||||||
"plugins/cmd_executor.py"
|
|
||||||
"plugins/file_manager.py"
|
|
||||||
"plugins/auto_engineer.py"
|
|
||||||
)
|
|
||||||
missing=0
|
|
||||||
for f in "${files[@]}"; do
|
|
||||||
if [ -f "$f" ]; then
|
|
||||||
echo " $f"
|
|
||||||
else
|
|
||||||
echo " $f (缺失!)"
|
|
||||||
missing=$((missing + 1))
|
|
||||||
fi
|
|
||||||
done
|
|
||||||
if [ $missing -gt 0 ]; then
|
|
||||||
echo "\n${missing} 个文件缺失"
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
echo "\n项目结构完整"
|
|
||||||
|
|
||||||
- name: 检查旧文件已清理
|
|
||||||
run: |
|
|
||||||
old_files=(
|
|
||||||
"ai_engines/mimo_engine.py"
|
|
||||||
"ai_engines/GLM_http_engine.py"
|
|
||||||
"ai_engines/qwq_engine.py"
|
|
||||||
"ai_engines/xfyun_spark_engine.py"
|
|
||||||
"ai_engines/iflow_api_engine.py"
|
|
||||||
"ai_engines/maas_http_engine.py"
|
|
||||||
"ai_engines/SDK_openAI.py"
|
|
||||||
"plugins/git_workflow.py"
|
|
||||||
"plugins/code_search.py"
|
|
||||||
"plugins/project_analyzer.py"
|
|
||||||
"plugins/scheduler.py"
|
|
||||||
)
|
|
||||||
found=0
|
|
||||||
for f in "${old_files[@]}"; do
|
|
||||||
if [ -f "$f" ]; then
|
|
||||||
echo " 旧文件未清理: $f"
|
|
||||||
found=$((found + 1))
|
|
||||||
fi
|
|
||||||
done
|
|
||||||
if [ $found -gt 0 ]; then
|
|
||||||
echo "\n${found} 个旧文件未清理"
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
echo "旧文件已全部清理"
|
|
||||||
|
|
||||||
- name: 检查无重复引擎
|
|
||||||
run: |
|
|
||||||
engines=$(ls ai_engines/*_engine.py 2>/dev/null | wc -l)
|
|
||||||
echo "AI 引擎数量: $engines"
|
|
||||||
if [ "$engines" -gt 2 ]; then
|
|
||||||
echo "警告: 引擎数量超过 2 个 (ollama + openai)"
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
echo "引擎数量正常"
|
|
||||||
@@ -36,6 +36,14 @@ Thumbs.db
|
|||||||
# 嵌入式 Python
|
# 嵌入式 Python
|
||||||
embedded_python/
|
embedded_python/
|
||||||
|
|
||||||
|
# 记忆系统数据(运行时生成)
|
||||||
|
MEMORY.md
|
||||||
|
memory/
|
||||||
|
|
||||||
|
# 生成的图片
|
||||||
|
generated_*.png
|
||||||
|
screenshots/gen_*.png
|
||||||
|
|
||||||
# 临时文件
|
# 临时文件
|
||||||
*.tmp
|
*.tmp
|
||||||
*.bak
|
*.bak
|
||||||
@@ -4,6 +4,105 @@
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
## v5.2.0 (2026-05-08)
|
||||||
|
|
||||||
|
### ✨ 新增功能
|
||||||
|
|
||||||
|
- **插件内存管理器** (`plugin_memory_manager.py`) — TTL 自动淘汰 + 懒加载机制
|
||||||
|
- 后台线程定期扫描空闲插件,超过 TTL(默认 5 分钟)自动从内存卸载,释放资源
|
||||||
|
- AI 调用已卸载的插件时自动重新加载(懒加载),对用户完全透明
|
||||||
|
- 核心插件(`tool_search`)可钉住永不淘汰,保障基础功能可用
|
||||||
|
- 可配置参数:TTL 时间、最大空闲插件数、扫描间隔、钉住列表
|
||||||
|
- `/status` 命令和 TUI 侧栏实时显示内存管理状态(已加载/已卸载/统计)
|
||||||
|
- `search_tools` 支持搜索已卸载插件(使用缓存的元数据,无需加载实例)
|
||||||
|
|
||||||
|
### 统一插件格式
|
||||||
|
|
||||||
|
- **统一自研插件入口类名为 `Liugin`** — 18 个插件从 `class Plugin` 统一为 `class Liugin`
|
||||||
|
- 加载器保留 `Plugin` 回退兼容,第三方插件仍可用旧格式
|
||||||
|
- 测试块中 `Plugin()` 调用同步更新为 `Liugin()`
|
||||||
|
|
||||||
|
### TUI 修复
|
||||||
|
|
||||||
|
- **修复消息分类失效** — `_write_raw` 中空字符串 `'' in msg` 永远为 True,导致所有消息显示为工具成功样式;替换为正确的 emoji 标记(✅/❌/🤖)
|
||||||
|
- **修复侧栏切换失效** — Textual 无 `.visible` 布尔属性,改用 `has_class("hidden")` + CSS 类控制显隐
|
||||||
|
- **修复侧栏隐藏动画** — CSS `display: none` 阻止过渡动画,改用 `width: 0` + `opacity: 0` 方案
|
||||||
|
- **修复 TextArea 导入缺失** — `constants.py` 可用性检查未导入 `TextArea`、`Rule`
|
||||||
|
- **修复 `set_timer(0)` 崩溃** — 欢迎动画首行延迟为 0.0 导致 Textual 8.x 除零错误(`ZeroDivisionError`),使用 `max(0.01, delay)` 修复
|
||||||
|
|
||||||
|
### 改进
|
||||||
|
|
||||||
|
- `UnifiedToolManager` 重构:集成 `PluginMemoryManager`,所有工具访问统一走 `_ensure_loaded` 路径
|
||||||
|
- 新增 `get_all_tools_info()` 方法,系统提示词可列出所有注册工具(含已卸载)
|
||||||
|
- 新增 `get_tool_by_name()` / `memory_manager` 属性,兼容旧 `LiuginManager` 接口
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## v5.1.4 (2026-04-29)
|
||||||
|
|
||||||
|
### 新增功能
|
||||||
|
|
||||||
|
- **桌面GUI自动化插件** (`gui_auto`, 20 操作) — 基于 Windows UI Automation (UIA) API,AI 可识别和操控桌面应用
|
||||||
|
- 元素树获取 (`snapshot`) — 获取整个屏幕或指定窗口的 UI 元素树,支持自定义遍历深度
|
||||||
|
- 元素交互 — 点击/右键/双击(名称模糊匹配 + 坐标点击),文本输入(中文 Unicode)、清空、发送按键
|
||||||
|
- 窗口管理 — 列出所有窗口 (`windows`)、聚焦指定窗口 (`focus`)
|
||||||
|
- 元素查询 — 查找/查找所有/详情/值/子树/存在检查/状态,共 8 个查询操作
|
||||||
|
- 高级功能 — 等待元素出现(带超时)、高亮闪烁元素(GDI 红色边框)、滚动
|
||||||
|
- MCP/FC 完整定义,AI 通过 Function Calling 直接调用,非 Windows 环境优雅降级
|
||||||
|
|
||||||
|
- **AI 生图插件** (`ai_image`) — 基于 ai.2x.nz 自然语言生图接口
|
||||||
|
- 自然语言描述 + 直接 Tag 双模式
|
||||||
|
- 工作流切换、画风选择、分辨率调整
|
||||||
|
- 异步生成 + WebSocket 进度推送
|
||||||
|
- 生成历史记录
|
||||||
|
|
||||||
|
- **Web UI 后端** (`webui_server.py`) — WebSocket 实时通信 + 静态文件服务
|
||||||
|
- 纯 Python 实现,基于 `websockets` 库
|
||||||
|
- 支持命令行参数 (`--port` / `--host`)
|
||||||
|
- 与前端 `webui.html` 配合,提供完整的浏览器端 AI 交互体验
|
||||||
|
|
||||||
|
### 改进
|
||||||
|
|
||||||
|
- **Web UI 前端重写** (`webui.html`) — 从纯静态页面升级为 WebSocket 实时交互
|
||||||
|
- 大厂设计感 UI,响应式布局
|
||||||
|
- 实时消息流、打字机效果
|
||||||
|
- 支持工具调用结果展示
|
||||||
|
|
||||||
|
### 文档
|
||||||
|
|
||||||
|
- 更新 README.md: 插件列表、项目结构、badge 版本号
|
||||||
|
- 更新 CHANGELOG.md: v5.1.4 完整变更记录
|
||||||
|
- 更新 HELP.md: 新增 GUI 自动化使用说明
|
||||||
|
|
||||||
|
### 测试
|
||||||
|
|
||||||
|
- 新增 gui_auto 插件 30 个单元测试(工具信息、MCP 定义、参数转换、错误处理、操作路由)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## v5.1.3 (2026-04-28)
|
||||||
|
|
||||||
|
### 新增功能
|
||||||
|
- **图像生成插件** (`image_generator`) — 基于 ai.2x.nz 的 ComfyUI 在线服务,自然语言/Tag 双模式,支持中文描述,28 个角色工作流可选,分辨率可调(最大 1344×1344)
|
||||||
|
- **记忆系统插件** (`memory_plugin`) — 包装 `xcli_core/memory.py` 的完整记忆工具,AI 可写日记、读日记、搜索记忆、管理聊天记录、操作长期记忆 MEMORY.md
|
||||||
|
- **AI 编程助手横评页面** (`compare.html`) — 7 款工具(Claude Code / Codex CLI / Gemini CLI / Aider / Copilot CLI / 小狸 / TG HELPER)25+ 维度同口径对比
|
||||||
|
|
||||||
|
### 修复
|
||||||
|
- 修复记忆系统插件(`Liugin` 类在 `xcli_core/memory.py` 中定义但未被插件管理器加载)导致 AI 无法调用记忆工具的问题,新增 `plugins/memory_plugin.py` 包装层
|
||||||
|
|
||||||
|
### 文档
|
||||||
|
- 全面更新 README.md 至 v5.1.3
|
||||||
|
- 新增记忆系统、Clawli 远程模式、MCP 协议支持、定时任务、系统通知等功能说明
|
||||||
|
- 更新插件列表:15 个 → 17 个(+image_generator, +memory_plugin)
|
||||||
|
- 更新操作数:141 → 141+
|
||||||
|
- 补充 MCP 协议支持说明(17 个插件全部实现 MCP 定义)
|
||||||
|
- 补充插件开发文档中 `Liugin` / `Plugin` 双协议说明
|
||||||
|
|
||||||
|
### 贡献者
|
||||||
|
- 感谢 **艾轮 卧壳** 对本版本的贡献 🖤
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## v5.1.2 (2026-04-26)
|
## v5.1.2 (2026-04-26)
|
||||||
|
|
||||||
### 新增功能
|
### 新增功能
|
||||||
|
|||||||
@@ -154,6 +154,26 @@ run make build --timeout 60 # 60秒超时
|
|||||||
| `pdf page.pdf` | 保存 PDF |
|
| `pdf page.pdf` | 保存 PDF |
|
||||||
| `stop` | 关闭浏览器 |
|
| `stop` | 关闭浏览器 |
|
||||||
|
|
||||||
|
### 桌面GUI自动化 (`gui_auto`) ⭐ NEW
|
||||||
|
|
||||||
|
> 仅支持 Windows,基于 UI Automation API
|
||||||
|
|
||||||
|
| 操作 | 说明 |
|
||||||
|
|------|------|
|
||||||
|
| `snapshot [深度]` | 获取屏幕 UI 元素树 |
|
||||||
|
| `snapshot --window 记事本` | 获取指定窗口元素树 |
|
||||||
|
| `screenshot [路径]` | 全屏截图 |
|
||||||
|
| `windows` | 列出所有窗口 |
|
||||||
|
| `focus 记事本` | 聚焦窗口 |
|
||||||
|
| `click 确定` | 点击元素(模糊匹配) |
|
||||||
|
| `click --xy 500 300` | 点击坐标 |
|
||||||
|
| `type 搜索框 Hello` | 在元素中输入文本 |
|
||||||
|
| `keys ctrl+s` | 发送按键 |
|
||||||
|
| `find 保存` | 查找元素 |
|
||||||
|
| `exists 确定` | 检查元素是否存在 |
|
||||||
|
| `wait 加载完成 10` | 等待元素出现 |
|
||||||
|
| `highlight 确定` | 高亮闪烁元素 |
|
||||||
|
|
||||||
### 子 Agent (`sub_agent`)
|
### 子 Agent (`sub_agent`)
|
||||||
|
|
||||||
| 操作 | 说明 |
|
| 操作 | 说明 |
|
||||||
@@ -202,6 +222,54 @@ tool_search 浏览器 # 搜索浏览器相关工具
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
## 插件市场
|
||||||
|
|
||||||
|
通过 `/plugin` 命令管理插件,支持从远程仓库一键安装。
|
||||||
|
|
||||||
|
### 查看可用插件
|
||||||
|
|
||||||
|
```
|
||||||
|
/plugin list # 列出所有可用插件(自动同步远程源)
|
||||||
|
/plugin search 郊狼 # 搜索关键词
|
||||||
|
/plugin info dglab # 查看插件详情
|
||||||
|
```
|
||||||
|
|
||||||
|
### 安装插件
|
||||||
|
|
||||||
|
```
|
||||||
|
/plugin install dglab # 通过插件码安装
|
||||||
|
/plugin install https://example.com/my_plugin.py # 从 URL 安装
|
||||||
|
```
|
||||||
|
|
||||||
|
安装后自动:
|
||||||
|
- 下载插件文件到 `plugins/` 目录
|
||||||
|
- 在 `plugins_config.py` 中启用
|
||||||
|
- 尝试动态加载(无需重启)
|
||||||
|
|
||||||
|
### 卸载插件
|
||||||
|
|
||||||
|
```
|
||||||
|
/plugin remove dglab_ws # 卸载指定插件
|
||||||
|
```
|
||||||
|
|
||||||
|
### 更新插件
|
||||||
|
|
||||||
|
```
|
||||||
|
/plugin update dglab # 重新下载更新
|
||||||
|
```
|
||||||
|
|
||||||
|
### 添加插件源
|
||||||
|
|
||||||
|
```
|
||||||
|
/plugin add-source https://example.com/registry.json # 同步远程插件源
|
||||||
|
```
|
||||||
|
|
||||||
|
### 插件码注册表
|
||||||
|
|
||||||
|
插件码是插件的唯一标识,映射到下载地址。注册表文件:`plugin_registry.json`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## 聊天记录
|
## 聊天记录
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|||||||
+1
-1
@@ -5,7 +5,7 @@
|
|||||||
</p>
|
</p>
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<img src="https://img.shields.io/badge/version-5.1.2-blue" alt="version">
|
<img src="https://img.shields.io/badge/version-5.2.0-blue" alt="version">
|
||||||
<img src="https://img.shields.io/badge/python-3.10+-green" alt="python">
|
<img src="https://img.shields.io/badge/python-3.10+-green" alt="python">
|
||||||
<img src="https://img.shields.io/badge/license-MIT-orange" alt="license">
|
<img src="https://img.shields.io/badge/license-MIT-orange" alt="license">
|
||||||
<img src="https://img.shields.io/badge/tests-113%20passed-brightgreen" alt="tests">
|
<img src="https://img.shields.io/badge/tests-113%20passed-brightgreen" alt="tests">
|
||||||
|
|||||||
@@ -1,29 +1,43 @@
|
|||||||
# 小狸 Pro-CLI
|
# 小狸 Pro-CLI
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<strong>智能编程助手 — 代码编辑 · Git 集成 · 浏览器自动化 · 多 Agent 协作</strong>
|
<img src="logo.png" width="120" alt="xiaoli-cli logo">
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<img src="https://img.shields.io/badge/version-5.1.2-blue" alt="version">
|
<strong>智能编程助手 — 代码编辑 · Git 集成 · 浏览器自动化 · 多 Agent 协作 · 图像生成 · 记忆系统</strong>
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<p align="center">
|
||||||
|
<img src="https://img.shields.io/badge/version-5.2.0-blue" alt="version">
|
||||||
<img src="https://img.shields.io/badge/python-3.10+-green" alt="python">
|
<img src="https://img.shields.io/badge/python-3.10+-green" alt="python">
|
||||||
<img src="https://img.shields.io/badge/license-MIT-orange" alt="license">
|
<img src="https://img.shields.io/badge/license-MIT-orange" alt="license">
|
||||||
<img src="https://img.shields.io/badge/tests-113%20passed-brightgreen" alt="tests">
|
<img src="https://img.shields.io/badge/tests-150+%20passed-brightgreen" alt="tests">
|
||||||
|
<img src="https://img.shields.io/badge/plugins-19-blueviolet" alt="plugins">
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
## 简介
|
||||||
|
|
||||||
|
小狸 Pro-CLI 是一款基于 Python 的智能编程助手,集成了代码编辑、版本控制、浏览器自动化、图像生成、记忆系统等功能,支持多种 AI 引擎,帮助开发者提升工作效率。
|
||||||
|
|
||||||
## 特性
|
## 特性
|
||||||
|
|
||||||
- **双 AI 引擎** — Ollama 本地模型 + OpenAI 兼容格式(DeepSeek、Grok、硅基流动等)
|
- **双 AI 引擎** — Ollama 本地模型 + OpenAI 兼容格式(DeepSeek、Grok、硅基流动等)
|
||||||
- **代码编辑与搜索** — 精准替换、批量编辑、符号提取、依赖分析、正则搜索、**自动语法检查**
|
- **代码编辑与搜索** — 精准替换、批量编辑、符号提取、依赖分析、正则搜索、自动语法检查
|
||||||
- **Git 版本控制** — 完整 Git 操作 + 工作流自动化(smart-commit、changelog)
|
- **Git 版本控制** — 完整 Git 操作 + 工作流自动化(smart-commit、changelog)
|
||||||
- **浏览器自动化** — Playwright 驱动,导航/交互/截图/JS 执行/PDF
|
- **浏览器自动化** — Playwright 驱动,导航、交互、截图、JS 执行、PDF 导出
|
||||||
- **子 Agent 系统** — 多 Agent 并行协作,独立任务分配与结果回收
|
- **子 Agent 系统** — 多 Agent 并行协作,独立任务分配与结果回收
|
||||||
- **统一安全层** — AI 风险识别 + 三模式切换(普通/人工/无限制)
|
- **图像生成** — 基于 ComfyUI 在线服务,自然语言/Tag 双模式,支持中文描述
|
||||||
- **15 个插件 141 个操作** — 代码编辑、Git、浏览器、工程化、文件管理、任务管理等
|
- **记忆系统** — 长期记忆 + 每日日记 + AI 写日记 + 全局搜索 + 自动保存对话
|
||||||
- **三模式界面** — TUI 图形化 + 传统命令行 + **Web UI 浏览器界面**
|
- **远程通信** — PC 与手机 WebSocket 双向通信
|
||||||
- **113 个自动化测试** — pytest 覆盖全部插件和核心模块
|
- **定时任务** — 支持相对时间、绝对时间、重复任务,到期自动激活 AI
|
||||||
|
- **系统通知** — 跨平台任务完成通知(Windows / macOS / Linux)
|
||||||
|
- **MCP 协议** — 19 个插件全部实现 MCP 定义,支持 Function Calling 原生调用
|
||||||
|
- **19 个插件 161+ 个操作** — 代码编辑、Git、浏览器、工程化、文件管理、图像生成、记忆等
|
||||||
|
- **三模式界面** — TUI 图形化 + 传统命令行 + Web UI 浏览器界面
|
||||||
|
- **150+ 个自动化测试** — pytest 覆盖全部插件和核心模块
|
||||||
|
|
||||||
## 快速开始
|
## 快速开始
|
||||||
|
|
||||||
@@ -43,6 +57,9 @@ python ai_cli.py
|
|||||||
|
|
||||||
# 指定引擎
|
# 指定引擎
|
||||||
python ai_cli.py --engine openai
|
python ai_cli.py --engine openai
|
||||||
|
|
||||||
|
# Windows 一键启动
|
||||||
|
launcher.exe
|
||||||
```
|
```
|
||||||
|
|
||||||
## AI 引擎
|
## AI 引擎
|
||||||
@@ -76,17 +93,19 @@ python ai_cli.py --engine openai
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
## 插件列表 (15 个)
|
## 插件列表 (19 个)
|
||||||
|
|
||||||
|
> 更多社区插件请访问 [xiaoli-cli-plugins](https://gitee.com/shuiyu1123/xiaoli-cli-plugins),使用 `/plugin install <插件码>` 一键安装。
|
||||||
|
|
||||||
### 核心生产力
|
### 核心生产力
|
||||||
|
|
||||||
| 插件 | 操作数 | 说明 |
|
| 插件 | 操作数 | 说明 |
|
||||||
|------|--------|------|
|
|------|--------|------|
|
||||||
| `code_editor` | 23 | 代码编辑+搜索。精准替换、批量编辑、find/regex/symbols/imports/callers/todo/structure + 自动语法检查 |
|
| `code_editor` | 24 | 代码编辑+搜索。精准替换、批量编辑、find/regex/symbols/imports/callers/todo/structure + 自动语法检查 |
|
||||||
| `git_tools` | 20 | Git 版本控制。status/diff/log/commit/branch + smart-commit/changelog/contributors |
|
| `git_tools` | 17 | Git 版本控制。status/diff/log/commit/branch + smart-commit/changelog/contributors/stale |
|
||||||
| `cmd_executor` | 1 | Shell 命令执行。跨平台,超时控制,危险命令拦截 |
|
| `cmd_executor` | 1 | Shell 命令执行,跨平台,超时控制 |
|
||||||
| `file_manager` | 11 | 文件系统。list/read/write/copy/move/delete/search/info/mkdir |
|
| `file_manager` | 10 | 文件系统。list/read/write/copy/move/delete/search/info/mkdir/append |
|
||||||
| `auto_engineer` | 16 | 工程化。lint/format/test/build/deps + 复杂度/安全扫描/质量指标 |
|
| `auto_engineer` | 12 | 工程化。lint/format/test/build/deps + 复杂度/安全扫描/质量指标/项目初始化 |
|
||||||
| `task_manager` | 7 | 任务管理。add/list/complete/delete/clear,JSON 持久化 |
|
| `task_manager` | 7 | 任务管理。add/list/complete/delete/clear,JSON 持久化 |
|
||||||
|
|
||||||
### 高级功能
|
### 高级功能
|
||||||
@@ -94,8 +113,13 @@ python ai_cli.py --engine openai
|
|||||||
| 插件 | 操作数 | 说明 |
|
| 插件 | 操作数 | 说明 |
|
||||||
|------|--------|------|
|
|------|--------|------|
|
||||||
| `sub_agent` | 8 | 子 Agent 系统。spawn/list/status/result/send/kill,多 Agent 并行协作 |
|
| `sub_agent` | 8 | 子 Agent 系统。spawn/list/status/result/send/kill,多 Agent 并行协作 |
|
||||||
| `browser_auto` | 31 | 浏览器自动化。导航/点击/填写/截图/JS执行/PDF/cookies(基于 Playwright) |
|
| `browser_auto` | 28 | 浏览器自动化。导航/点击/填写/截图/JS执行/PDF/cookies(基于 Playwright) |
|
||||||
| `tool_search` | — | 工具搜索。按关键词发现可用插件(供 AI 按需调用) |
|
| `gui_auto` | 20 | 桌面 GUI 自动化。基于 Windows UIA,屏幕元素识别/点击/输入/截图(仅 Windows) |
|
||||||
|
| `ai_image` | — | AI 生图。基于 ai.2x.nz 自然语言生图,异步生成 + WebSocket 进度推送 |
|
||||||
|
| `image_generator` | 7 | 图像生成。基于 ComfyUI 在线服务,自然语言/Tag 双模式,28 个角色工作流 |
|
||||||
|
| `memory_plugin` | 11 | 记忆系统。AI 写日记/搜索记忆/管理聊天记录/长期记忆 |
|
||||||
|
| `scheduler` | 4 | 定时任务。支持相对时间/绝对时间/重复任务,到期自动激活 AI |
|
||||||
|
| `tool_search` | — | 工具搜索。按关键词发现可用插件 |
|
||||||
|
|
||||||
### 辅助工具
|
### 辅助工具
|
||||||
|
|
||||||
@@ -104,19 +128,50 @@ python ai_cli.py --engine openai
|
|||||||
| `network_tools` | 网络工具。ping/get/status/headers/ip |
|
| `network_tools` | 网络工具。ping/get/status/headers/ip |
|
||||||
| `ai_search` | AI 搜索。jina.ai 智能搜索 + 网页内容提取 |
|
| `ai_search` | AI 搜索。jina.ai 智能搜索 + 网页内容提取 |
|
||||||
| `frontend_tester` | 前端测试。HTML/CSS/JS 语法检查、响应式验证 |
|
| `frontend_tester` | 前端测试。HTML/CSS/JS 语法检查、响应式验证 |
|
||||||
| `speech_recognition` | 语音识别。录音 + 语音转文字 |
|
| `speech_recognition` | 语音识别。录音 + 语音转文字(Whisper) |
|
||||||
| `audio_player` | 音频播放 |
|
| `audio_player` | 音频播放 |
|
||||||
| `send_image` | Clawli 模式下发图片到手机 |
|
| `send_image` | 远程模式下发图片到手机 |
|
||||||
|
|
||||||
|
## 记忆系统
|
||||||
|
|
||||||
|
内置持久化记忆系统,AI 可以记住之前的工作:
|
||||||
|
|
||||||
|
| 功能 | 说明 |
|
||||||
|
|------|------|
|
||||||
|
| 长期记忆 | `MEMORY.md` — AI 自己维护的精华记忆 |
|
||||||
|
| 每日日记 | `memory/YYYY-MM-DD.md` — 带时间戳和标签 |
|
||||||
|
| AI 写日记 | `memory_plugin diary_ai` — 自动标记 [AI观察] |
|
||||||
|
| 自动保存对话 | 每轮对话后自动存 JSON |
|
||||||
|
| 上下文压缩 | 超过 50 条自动 AI 总结,保留最近 10 条 |
|
||||||
|
| 全局搜索 | 搜索 MEMORY + 日记 + 聊天记录 |
|
||||||
|
|
||||||
|
```
|
||||||
|
memory_plugin diary 今天完成了API对接
|
||||||
|
memory_plugin search 定时任务
|
||||||
|
memory_plugin remember 用户偏好深色主题
|
||||||
|
memory_plugin chat_search 图像生成
|
||||||
|
```
|
||||||
|
|
||||||
|
## 远程通信
|
||||||
|
|
||||||
|
通过 WebSocket 实现 PC 与手机双向通信:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
/remote start 9079 mypassword # 启动本地服务
|
||||||
|
/remote stop # 停止服务
|
||||||
|
/remote status # 查看状态
|
||||||
|
```
|
||||||
|
|
||||||
|
功能:手机发消息给 AI、AI 回复推到手机、文件传输、图片识别。
|
||||||
|
|
||||||
## 安全机制
|
## 安全机制
|
||||||
|
|
||||||
### 三模式切换 (`/safe`)
|
### 模式切换 (`/safe`)
|
||||||
|
|
||||||
| 模式 | 图标 | 说明 |
|
| 模式 | 说明 |
|
||||||
|------|------|------|
|
|------|------|
|
||||||
| **普通模式** (默认) | | AI 识别风险,有风险才请求确认 |
|
| **普通模式** (默认) | AI 识别风险,有风险才请求确认 |
|
||||||
| **人工确认** | | 所有指令都需要用户确认 |
|
| **人工确认** | 所有指令都需要用户确认 |
|
||||||
| **无限制** | | 直接执行,不检查 |
|
|
||||||
|
|
||||||
### 检查流程
|
### 检查流程
|
||||||
|
|
||||||
@@ -124,105 +179,115 @@ python ai_cli.py --engine openai
|
|||||||
工具调用 → safety.check()
|
工具调用 → safety.check()
|
||||||
├─ 快速预检(读取/查询类)→ 直接放行
|
├─ 快速预检(读取/查询类)→ 直接放行
|
||||||
├─ 普通模式 → AI 独立分析风险
|
├─ 普通模式 → AI 独立分析风险
|
||||||
│ ├─ safe=true → 放行
|
│ ├─ safe → 放行
|
||||||
│ └─ safe=false → 展示风险等级+影响,y/n 确认
|
│ └─ unsafe → 展示风险等级+影响,y/n 确认
|
||||||
└─ 特殊指令(rm/delete/chmod)→ 始终确认
|
└─ 特殊指令(rm/delete/chmod)→ 始终确认
|
||||||
```
|
```
|
||||||
|
|
||||||
### 代码沙箱
|
### 代码执行
|
||||||
|
|
||||||
独立的安全代码执行环境:
|
独立的安全代码执行环境:
|
||||||
- AST 级危险代码检测
|
- AST 级危险代码检测
|
||||||
- 模块白名单(阻断 os/subprocess/socket 等 25 个模块)
|
- 模块白名单(阻断 25 个高危模块)
|
||||||
- 子进程隔离执行
|
- 子进程隔离执行
|
||||||
- 内存限制
|
- 内存限制
|
||||||
|
|
||||||
|
## MCP 协议支持
|
||||||
|
|
||||||
|
所有 19 个插件均实现 MCP (Model Context Protocol) 定义,支持三种工具调用协议:
|
||||||
|
|
||||||
|
| 协议 | 说明 |
|
||||||
|
|------|------|
|
||||||
|
| **MCP** | Model Context Protocol 标准定义 |
|
||||||
|
| **FC** | OpenAI Function Calling 原生调用 |
|
||||||
|
| **JSON** | 传统 `{"action": "use_tool", ...}` 格式 |
|
||||||
|
|
||||||
## 命令列表
|
## 命令列表
|
||||||
|
|
||||||
| 命令 | 说明 |
|
| 命令 | 说明 |
|
||||||
|------|------|
|
|------|------|
|
||||||
| `/help` | 显示帮助 |
|
| `/help` | 显示帮助 |
|
||||||
| `/safe` | 切换安全模式(普通→人工→无限制) |
|
| `/safe` | 切换安全模式 |
|
||||||
| `/safe off` | 直接切换到无限制模式 |
|
|
||||||
| `/safe manual` | 直接切换到人工确认模式 |
|
|
||||||
| `/engine list` | 列出可用引擎 |
|
| `/engine list` | 列出可用引擎 |
|
||||||
| `/engine switch <引擎>` | 切换引擎 |
|
| `/engine switch <引擎>` | 切换引擎 |
|
||||||
| `/engine.openai models` | 列出 OpenAI 引擎模型 |
|
| `/engine.openai models` | 列出 OpenAI 引擎模型 |
|
||||||
| `/chat save/list/open` | 聊天记录管理 |
|
| `/chat save/list/open` | 聊天记录管理 |
|
||||||
| `/file.read <路径>` | 读取文件 |
|
| `/file.read <路径>` | 读取文件 |
|
||||||
|
| `/remote` | 远程连接帮助 |
|
||||||
|
| `/notify` | 切换任务完成通知 |
|
||||||
|
| `/scheduler` / `/remind` | 管理定时任务 |
|
||||||
|
| `/memory` | 管理记忆系统 |
|
||||||
| `/tui` | 切换 TUI 模式 |
|
| `/tui` | 切换 TUI 模式 |
|
||||||
| `/quit` | 退出 |
|
| `/quit` | 退出 |
|
||||||
|
|
||||||
## Web UI
|
## Web UI
|
||||||
|
|
||||||
纯静态 HTML 界面,无需后端,浏览器直接打开。
|
WebSocket 实时交互界面,支持完整的 AI 对话体验。
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# 直接用浏览器打开
|
# 方式 1: 启动 WebSocket 后端(推荐)
|
||||||
|
python webui_server.py --port 8080
|
||||||
|
# 浏览器访问 http://localhost:8080
|
||||||
|
|
||||||
|
# 方式 2: 直接打开静态页面
|
||||||
|
start webui.html # Windows
|
||||||
open webui.html # macOS
|
open webui.html # macOS
|
||||||
xdg-open webui.html # Linux
|
xdg-open webui.html # Linux
|
||||||
start webui.html # Windows
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### 功能
|
|
||||||
|
|
||||||
| 功能 | 说明 |
|
|
||||||
|------|------|
|
|
||||||
| 对话界面 | 聊天气泡、快捷指令、打字动画 |
|
|
||||||
| 代码编辑器 | 行号显示、Tab 缩进、Ctrl+S 保存、语法高亮 |
|
|
||||||
| 文件浏览 | 侧栏项目文件树,点击查看 |
|
|
||||||
| ️ 系统状态 | 插件/操作/引擎/测试统计 |
|
|
||||||
| 引擎面板 | Ollama / OpenAI 引擎一览 |
|
|
||||||
| 工具面板 | 15 个插件及操作数一览 |
|
|
||||||
| 日志面板 | 系统操作实时记录 |
|
|
||||||
|
|
||||||
## 项目结构
|
## 项目结构
|
||||||
|
|
||||||
```
|
```
|
||||||
xiaoli-cli/
|
xiaoli-cli/
|
||||||
├── ai_cli.py # 主入口
|
├── ai_cli.py # 主入口
|
||||||
├── webui.html # Web UI 界面 (纯静态 HTML)
|
├── webui.html # Web UI 界面
|
||||||
|
├── webui_server.py # Web UI 后端
|
||||||
├── launcher.py # 智能启动器
|
├── launcher.py # 智能启动器
|
||||||
├── config.json.example # 配置模板
|
├── config.json.example # 配置模板
|
||||||
│
|
├── easter_egg.py # 彩蛋
|
||||||
├── xcli_core/ # 核心模块
|
├── xcli_core/ # 核心模块
|
||||||
│ ├── cli_core.py # 主循环 + 提示词构建
|
│ ├── cli_core.py # 主循环 + 提示词构建
|
||||||
│ ├── cli_base.py # 初始化 + 引擎/插件加载
|
│ ├── cli_base.py # 初始化 + 引擎/插件加载
|
||||||
│ ├── cli_tools.py # 工具调用执行
|
│ ├── cli_tools.py # 工具调用执行
|
||||||
|
│ ├── cli_clawli.py # 远程模式
|
||||||
|
│ ├── cli_code_exec.py # 代码执行
|
||||||
│ ├── cli_display.py # 显示输出
|
│ ├── cli_display.py # 显示输出
|
||||||
│ ├── cli_history.py # 聊天记录
|
│ ├── cli_history.py # 聊天记录
|
||||||
│ ├── cli_code_exec.py # 代码执行
|
|
||||||
│ ├── config.py # 配置管理
|
│ ├── config.py # 配置管理
|
||||||
│ ├── constants.py # 常量定义
|
│ ├── constants.py # 常量定义
|
||||||
|
│ ├── fc_tools.py # MCP → FC 格式转换
|
||||||
|
│ ├── memory.py # 记忆系统
|
||||||
|
│ ├── notification.py # 跨平台系统通知
|
||||||
|
│ ├── plugin_manager.py # 插件管理器
|
||||||
│ ├── safety.py # 统一安全层
|
│ ├── safety.py # 统一安全层
|
||||||
│ ├── sandbox.py # 代码安全沙箱
|
│ ├── sandbox.py # 代码安全沙箱
|
||||||
│ ├── plugin_manager.py # 插件管理器
|
|
||||||
│ └── tui.py # TUI 界面
|
│ └── tui.py # TUI 界面
|
||||||
│
|
|
||||||
├── ai_engines/ # AI 引擎
|
├── ai_engines/ # AI 引擎
|
||||||
│ ├── ollama_engine.py # Ollama 本地模型
|
│ ├── ollama_engine.py
|
||||||
│ └── openai_engine.py # OpenAI 兼容格式
|
│ └── openai_engine.py
|
||||||
│
|
├── plugins/ # 插件 (19 个)
|
||||||
├── plugins/ # 插件 (15 个)
|
│ ├── code_editor.py
|
||||||
│ ├── code_editor.py # 代码编辑+搜索
|
│ ├── git_tools.py
|
||||||
│ ├── git_tools.py # Git 版本控制
|
│ ├── cmd_executor.py
|
||||||
│ ├── cmd_executor.py # Shell 命令执行
|
│ ├── file_manager.py
|
||||||
│ ├── file_manager.py # 文件管理
|
│ ├── auto_engineer.py
|
||||||
│ ├── auto_engineer.py # 工程化自动化
|
│ ├── task_manager.py
|
||||||
│ ├── task_manager.py # 任务管理
|
│ ├── sub_agent.py
|
||||||
│ ├── sub_agent.py # 子 Agent 系统
|
│ ├── browser_auto.py
|
||||||
│ ├── browser_auto.py # 浏览器自动化
|
│ ├── gui_auto.py
|
||||||
│ ├── tool_search.py # 工具搜索
|
│ ├── ai_image.py
|
||||||
│ ├── network_tools.py # 网络工具
|
│ ├── image_generator.py
|
||||||
│ ├── ai_search.py # AI 搜索
|
│ ├── memory_plugin.py
|
||||||
│ ├── frontend_tester.py # 前端测试
|
│ ├── scheduler.py
|
||||||
│ ├── speech_recognition.py # 语音识别
|
│ ├── tool_search.py
|
||||||
│ ├── audio_player.py # 音频播放
|
│ ├── network_tools.py
|
||||||
│ └── send_image.py # 图片发送
|
│ ├── ai_search.py
|
||||||
│
|
│ ├── frontend_tester.py
|
||||||
├── skills/ # 技能 (Skill 协议)
|
│ ├── speech_recognition.py
|
||||||
|
│ └── send_image.py
|
||||||
|
├── skills/ # 技能
|
||||||
├── image_engine/ # 图像识别引擎
|
├── image_engine/ # 图像识别引擎
|
||||||
├── tests/ # 测试套件 (113 用例)
|
├── tests/ # 测试套件 (150+ 用例)
|
||||||
├── love.txt # 彩蛋情话
|
├── love.txt # 彩蛋情话
|
||||||
└── about.txt # 关于信息
|
└── about.txt # 关于信息
|
||||||
```
|
```
|
||||||
@@ -230,7 +295,7 @@ xiaoli-cli/
|
|||||||
## 测试
|
## 测试
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# 运行全部测试 (113 用例)
|
# 运行全部测试
|
||||||
python -m pytest tests/ -v
|
python -m pytest tests/ -v
|
||||||
|
|
||||||
# 语法检查
|
# 语法检查
|
||||||
@@ -239,6 +304,8 @@ python -c "import py_compile; py_compile.compile('ai_cli.py', doraise=True)"
|
|||||||
|
|
||||||
## 插件开发
|
## 插件开发
|
||||||
|
|
||||||
|
小狸支持 `Liugin`(自研协议)和 `Plugin`(通用协议)两种类名,均可被插件管理器自动识别:
|
||||||
|
|
||||||
```python
|
```python
|
||||||
class Plugin:
|
class Plugin:
|
||||||
"""我的插件"""
|
"""我的插件"""
|
||||||
@@ -258,6 +325,18 @@ class Plugin:
|
|||||||
"usage": self.usage
|
"usage": self.usage
|
||||||
}
|
}
|
||||||
|
|
||||||
|
def get_mcp_definition(self):
|
||||||
|
return {
|
||||||
|
"name": "my_tool",
|
||||||
|
"description": "工具描述",
|
||||||
|
"inputSchema": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"args": {"type": "string", "description": "参数"}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
def handle(self, args: str) -> str:
|
def handle(self, args: str) -> str:
|
||||||
return "处理结果"
|
return "处理结果"
|
||||||
```
|
```
|
||||||
@@ -269,5 +348,6 @@ class Plugin:
|
|||||||
## 链接
|
## 链接
|
||||||
|
|
||||||
- Gitee: https://gitee.com/shuiyu1123/xiaoli-cli
|
- Gitee: https://gitee.com/shuiyu1123/xiaoli-cli
|
||||||
|
- 插件仓库: https://gitee.com/shuiyu1123/xiaoli-cli-plugins
|
||||||
- [更新日志](CHANGELOG.md)
|
- [更新日志](CHANGELOG.md)
|
||||||
- [使用指南](HELP.md)
|
- [使用指南](HELP.md)
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
**产品标识**
|
**产品标识**
|
||||||
- **产品名称**:小狸智能体 增强-终端(Xiaoli Pro-CLI)
|
- **产品名称**:小狸智能体 增强-终端(Xiaoli Pro-CLI)
|
||||||
- **内部版本号**:20260426
|
- **内部版本号**:20260428
|
||||||
- **发布版本**:发行版5.1.1
|
- **发布版本**:发行版5.1.3
|
||||||
|
|
||||||
**技术规格**
|
**技术规格**
|
||||||
- **主要语言**:简体中文(UTF-8)
|
- **主要语言**:简体中文(UTF-8)
|
||||||
|
|||||||
@@ -122,6 +122,13 @@ Ollama AI引擎插件帮助信息
|
|||||||
if not self.is_service_running:
|
if not self.is_service_running:
|
||||||
return "错误:Ollama服务未运行,请启动Ollama服务后再使用此引擎."
|
return "错误:Ollama服务未运行,请启动Ollama服务后再使用此引擎."
|
||||||
|
|
||||||
|
# 检查模型是否已配置
|
||||||
|
if not self.model or not self.model.strip():
|
||||||
|
return ("错误:Ollama模型未配置。请执行以下操作:\n"
|
||||||
|
" 1. /engine.ollama models → 查看本地可用模型\n"
|
||||||
|
" 2. /engine.ollama set <模型名> → 设置要使用的模型\n"
|
||||||
|
" 或编辑 config.json 中 api.engines.ollama.model 字段")
|
||||||
|
|
||||||
# 如果有工具结果,将其作为上下文返回给AI处理
|
# 如果有工具结果,将其作为上下文返回给AI处理
|
||||||
if tool_results:
|
if tool_results:
|
||||||
tool_result_text = f"工具执行结果: {tool_results.get('result', '无结果')}"
|
tool_result_text = f"工具执行结果: {tool_results.get('result', '无结果')}"
|
||||||
|
|||||||
@@ -0,0 +1,30 @@
|
|||||||
|
{
|
||||||
|
"version": 1,
|
||||||
|
"description": "小狸 CLI 插件码注册表 - 通过 /plugin install <插件码> 安装",
|
||||||
|
"plugins": {
|
||||||
|
"dglab": {
|
||||||
|
"name": "DG-Lab 郊狼 WebSocket 控制",
|
||||||
|
"description": "基于 DG-LAB-OPENSOURCE 官方 Socket V2 协议,支持郊狼 3.0 脉冲主机远程控制",
|
||||||
|
"author": "xiaoli-cli-plugins",
|
||||||
|
"version": "1.0.0",
|
||||||
|
"file": "dglab_ws.py",
|
||||||
|
"url": "https://gitee.com/shuiyu1123/xiaoli-cli-plugins/raw/master/dglab_ws/dglab_ws.py",
|
||||||
|
"docs": "https://gitee.com/shuiyu1123/xiaoli-cli-plugins/raw/master/dglab_ws/README.md",
|
||||||
|
"deps": ["websocket-client"],
|
||||||
|
"optional_deps": ["qrcode"],
|
||||||
|
"keywords": ["dg-lab", "dglab", "郊狼", "coyote", "websocket", "脉冲"]
|
||||||
|
},
|
||||||
|
"onebot": {
|
||||||
|
"name": "OneBot v11 QQ 机器人",
|
||||||
|
"description": "让 xiaoli-cli 成为 QQ 机器人,连接 go-cqhttp/Lagrange/LLOneBot 等 OneBot 实现",
|
||||||
|
"author": "xiaoli-cli-plugins",
|
||||||
|
"version": "1.0.0",
|
||||||
|
"file": "onebot.py",
|
||||||
|
"url": "https://gitee.com/shuiyu1123/xiaoli-cli-plugins/raw/master/onebot/onebot.py",
|
||||||
|
"docs": "https://gitee.com/shuiyu1123/xiaoli-cli-plugins/raw/master/onebot/README.md",
|
||||||
|
"deps": ["websocket-client"],
|
||||||
|
"optional_deps": [],
|
||||||
|
"keywords": ["onebot", "qq", "机器人", "bot", "go-cqhttp", "lagrange", "群聊", "私聊"]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,589 @@
|
|||||||
|
"""
|
||||||
|
AI 生图插件 - 基于 ai.2x.nz 自然语言生图接口
|
||||||
|
支持自然语言描述、直接 Tag、工作流切换、画风选择等
|
||||||
|
"""
|
||||||
|
|
||||||
|
import os
|
||||||
|
import json
|
||||||
|
import time
|
||||||
|
import threading
|
||||||
|
import hashlib
|
||||||
|
import re
|
||||||
|
from datetime import datetime
|
||||||
|
from urllib.parse import quote
|
||||||
|
|
||||||
|
try:
|
||||||
|
import requests
|
||||||
|
REQUESTS_AVAILABLE = True
|
||||||
|
except ImportError:
|
||||||
|
REQUESTS_AVAILABLE = False
|
||||||
|
|
||||||
|
try:
|
||||||
|
import websocket
|
||||||
|
WEBSOCKET_AVAILABLE = True
|
||||||
|
except ImportError:
|
||||||
|
WEBSOCKET_AVAILABLE = False
|
||||||
|
|
||||||
|
|
||||||
|
class Liugin:
|
||||||
|
"""AI 生图插件 - 调用 ai.2x.nz 接口生成图片"""
|
||||||
|
|
||||||
|
BASE_URL = "https://ai.2x.nz"
|
||||||
|
WS_URL = "wss://ai.2x.nz/ws/run"
|
||||||
|
API_URL = "https://ai.2x.nz/api"
|
||||||
|
|
||||||
|
# 保存目录
|
||||||
|
DEFAULT_SAVE_DIR = "generated_images"
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
self.usage = """AI 生图工具 - 基于自然语言描述生成图片
|
||||||
|
|
||||||
|
基本用法:
|
||||||
|
generate <描述> - 用自然语言描述生成图片
|
||||||
|
tag <直接Tag> - 用 Danbooru Tag 生成图片
|
||||||
|
both <Tag> <<<>>> <描述> - 同时使用 Tag 和自然语言
|
||||||
|
|
||||||
|
高级用法:
|
||||||
|
workflows - 列出所有可用工作流
|
||||||
|
switch <工作流名> - 切换工作流
|
||||||
|
width <数值> - 设置图片宽度 (最大1344)
|
||||||
|
height <数值> - 设置图片高度 (最大1344)
|
||||||
|
size <宽> <高> - 同时设置宽高
|
||||||
|
rewrite on|off - 改写模式开关
|
||||||
|
override on|off - 覆写模式开关
|
||||||
|
status - 查看当前状态和配置
|
||||||
|
|
||||||
|
示例:
|
||||||
|
ai_image generate 一个可爱的猫耳少女,樱花背景
|
||||||
|
ai_image tag 1girl, cat_ears, cherry_blossoms, smile
|
||||||
|
ai_image both 1girl, cat_ears <<<>>> 一个可爱的猫耳少女在樱花树下微笑
|
||||||
|
ai_image workflows
|
||||||
|
ai_image switch WAI - 37.json
|
||||||
|
ai_image size 1024 1024
|
||||||
|
ai_image rewrite on
|
||||||
|
"""
|
||||||
|
self.cli = None
|
||||||
|
self.save_dir = self.DEFAULT_SAVE_DIR
|
||||||
|
|
||||||
|
# 配置状态
|
||||||
|
self.current_workflow = None
|
||||||
|
self.direct_prompt = ""
|
||||||
|
self.nl_prompt = ""
|
||||||
|
self.rewrite = False
|
||||||
|
self.override = False
|
||||||
|
self.width = None
|
||||||
|
self.height = None
|
||||||
|
self.workflows_cache = None
|
||||||
|
self.is_generating = False
|
||||||
|
|
||||||
|
def set_cli(self, cli):
|
||||||
|
"""设置 CLI 实例引用"""
|
||||||
|
self.cli = cli
|
||||||
|
# 注册插件命令
|
||||||
|
if hasattr(cli, 'register_liugin_command'):
|
||||||
|
cli.register_liugin_command('ai_image', self.command_handler)
|
||||||
|
|
||||||
|
def get_tool_info(self):
|
||||||
|
return {
|
||||||
|
"name": "ai_image",
|
||||||
|
"description": "AI 生图工具 — 基于 ai.2x.nz 接口,支持自然语言描述和 Danbooru Tag 生成图片。当用户想要生成图片、画图、AI绘画、生图时使用此工具。",
|
||||||
|
"keywords": [
|
||||||
|
"生图", "画图", "图片", "AI绘画", "生成图片", "image", "generate",
|
||||||
|
"draw", "绘画", "插画", "二次元", "动漫", "Danbooru", "tag",
|
||||||
|
"工作流", "workflow", "ComfyUI"
|
||||||
|
],
|
||||||
|
"usage": self.usage
|
||||||
|
}
|
||||||
|
|
||||||
|
def get_mcp_definition(self):
|
||||||
|
return {
|
||||||
|
"name": "ai_image",
|
||||||
|
"description": "AI 生图工具,基于 ai.2x.nz 接口生成图片",
|
||||||
|
"inputSchema": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"operation": {
|
||||||
|
"type": "string",
|
||||||
|
"enum": ["generate", "tag", "both", "workflows", "switch", "size", "status"],
|
||||||
|
"description": "操作类型"
|
||||||
|
},
|
||||||
|
"prompt": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "生成提示词"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": ["operation"]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
def convert_mcp_args(self, arguments):
|
||||||
|
op = arguments.get("operation", "")
|
||||||
|
prompt = arguments.get("prompt", "")
|
||||||
|
return f"{op} {prompt}"
|
||||||
|
|
||||||
|
def command_handler(self, args):
|
||||||
|
"""处理 /ai_image 命令"""
|
||||||
|
return self.handle(args)
|
||||||
|
|
||||||
|
def handle(self, args):
|
||||||
|
"""处理 AI 生图请求"""
|
||||||
|
if not REQUESTS_AVAILABLE:
|
||||||
|
return "❌ 缺少 requests 库,请运行: pip install requests"
|
||||||
|
|
||||||
|
args = args.strip()
|
||||||
|
if not args:
|
||||||
|
return self.usage
|
||||||
|
|
||||||
|
# 解析操作
|
||||||
|
parts = args.split(maxsplit=1)
|
||||||
|
operation = parts[0].lower()
|
||||||
|
remaining = parts[1] if len(parts) > 1 else ""
|
||||||
|
|
||||||
|
try:
|
||||||
|
if operation in ["generate", "gen", "g"]:
|
||||||
|
return self._cmd_generate(remaining)
|
||||||
|
elif operation in ["tag", "t", "direct", "d"]:
|
||||||
|
return self._cmd_tag(remaining)
|
||||||
|
elif operation in ["both", "b"]:
|
||||||
|
return self._cmd_both(remaining)
|
||||||
|
elif operation in ["workflows", "wf", "list"]:
|
||||||
|
return self._cmd_workflows()
|
||||||
|
elif operation in ["switch", "sw"]:
|
||||||
|
return self._cmd_switch(remaining)
|
||||||
|
elif operation in ["width", "w"]:
|
||||||
|
return self._cmd_set_width(remaining)
|
||||||
|
elif operation in ["height", "h"]:
|
||||||
|
return self._cmd_set_height(remaining)
|
||||||
|
elif operation in ["size", "s"]:
|
||||||
|
return self._cmd_set_size(remaining)
|
||||||
|
elif operation in ["rewrite", "rw"]:
|
||||||
|
return self._cmd_set_rewrite(remaining)
|
||||||
|
elif operation in ["override", "ov"]:
|
||||||
|
return self._cmd_set_override(remaining)
|
||||||
|
elif operation in ["status", "st"]:
|
||||||
|
return self._cmd_status()
|
||||||
|
elif operation in ["help", "?"]:
|
||||||
|
return self.usage
|
||||||
|
else:
|
||||||
|
# 尝试当作自然语言描述处理
|
||||||
|
return self._cmd_generate(args)
|
||||||
|
except Exception as e:
|
||||||
|
return f"❌ 操作失败: {str(e)}"
|
||||||
|
|
||||||
|
# ── 命令实现 ──
|
||||||
|
|
||||||
|
def _cmd_generate(self, prompt):
|
||||||
|
"""自然语言生成图片"""
|
||||||
|
if not prompt.strip():
|
||||||
|
return "❌ 请提供描述内容。示例: ai_image generate 一个可爱的猫耳少女"
|
||||||
|
|
||||||
|
self.nl_prompt = prompt.strip()
|
||||||
|
self.direct_prompt = ""
|
||||||
|
self.override = False
|
||||||
|
return self._run_generation()
|
||||||
|
|
||||||
|
def _cmd_tag(self, tags):
|
||||||
|
"""使用直接 Tag 生成图片"""
|
||||||
|
if not tags.strip():
|
||||||
|
return "❌ 请提供 Tag 内容。示例: ai_image tag 1girl, cat_ears, smile"
|
||||||
|
|
||||||
|
self.direct_prompt = tags.strip()
|
||||||
|
self.nl_prompt = ""
|
||||||
|
self.override = True
|
||||||
|
return self._run_generation()
|
||||||
|
|
||||||
|
def _cmd_both(self, args):
|
||||||
|
"""同时使用 Tag 和自然语言"""
|
||||||
|
if "<<<>>>" in args:
|
||||||
|
parts = args.split("<<<>>>", 1)
|
||||||
|
self.direct_prompt = parts[0].strip()
|
||||||
|
self.nl_prompt = parts[1].strip()
|
||||||
|
else:
|
||||||
|
# 尝试用 || 分隔
|
||||||
|
if "||" in args:
|
||||||
|
parts = args.split("||", 1)
|
||||||
|
self.direct_prompt = parts[0].strip()
|
||||||
|
self.nl_prompt = parts[1].strip()
|
||||||
|
else:
|
||||||
|
return "❌ 格式错误。用法: ai_image both <Tag> <<<>>> <描述>"
|
||||||
|
|
||||||
|
self.override = False
|
||||||
|
return self._run_generation()
|
||||||
|
|
||||||
|
def _cmd_workflows(self):
|
||||||
|
"""列出所有工作流"""
|
||||||
|
workflows = self._fetch_workflows()
|
||||||
|
if not workflows:
|
||||||
|
return "❌ 获取工作流列表失败"
|
||||||
|
|
||||||
|
result = f"📂 共 {len(workflows)} 个工作流:\n\n"
|
||||||
|
for i, wf in enumerate(workflows, 1):
|
||||||
|
name = wf.get("path", "未知")
|
||||||
|
current = " ← [当前]" if name == self.current_workflow else ""
|
||||||
|
result += f" {i:2d}. {name}{current}\n"
|
||||||
|
|
||||||
|
result += f"\n💡 使用 'ai_image switch <工作流名>' 切换工作流"
|
||||||
|
return result
|
||||||
|
|
||||||
|
def _cmd_switch(self, name):
|
||||||
|
"""切换工作流"""
|
||||||
|
if not name.strip():
|
||||||
|
return "❌ 请提供工作流名称。先用 'ai_image workflows' 查看列表"
|
||||||
|
|
||||||
|
# 模糊匹配
|
||||||
|
workflows = self._fetch_workflows()
|
||||||
|
if not workflows:
|
||||||
|
return "❌ 获取工作流列表失败"
|
||||||
|
|
||||||
|
matched = None
|
||||||
|
name_lower = name.strip().lower()
|
||||||
|
for wf in workflows:
|
||||||
|
wf_path = wf.get("path", "")
|
||||||
|
if name_lower == wf_path.lower():
|
||||||
|
matched = wf_path
|
||||||
|
break
|
||||||
|
if name_lower in wf_path.lower():
|
||||||
|
matched = wf_path
|
||||||
|
|
||||||
|
if not matched:
|
||||||
|
# 尝试数字索引
|
||||||
|
try:
|
||||||
|
idx = int(name.strip()) - 1
|
||||||
|
if 0 <= idx < len(workflows):
|
||||||
|
matched = workflows[idx].get("path", "")
|
||||||
|
except ValueError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
if not matched:
|
||||||
|
return f"❌ 未找到匹配的工作流: {name}\n💡 先用 'ai_image workflows' 查看列表"
|
||||||
|
|
||||||
|
self.current_workflow = matched
|
||||||
|
return f"✅ 已切换工作流: {matched}"
|
||||||
|
|
||||||
|
def _cmd_set_width(self, val):
|
||||||
|
"""设置宽度"""
|
||||||
|
try:
|
||||||
|
w = int(val.strip())
|
||||||
|
if w < 64 or w > 1344:
|
||||||
|
return "❌ 宽度范围: 64 ~ 1344"
|
||||||
|
self.width = w
|
||||||
|
return f"✅ 宽度已设置为: {w}"
|
||||||
|
except ValueError:
|
||||||
|
return "❌ 请输入有效数字"
|
||||||
|
|
||||||
|
def _cmd_set_height(self, val):
|
||||||
|
"""设置高度"""
|
||||||
|
try:
|
||||||
|
h = int(val.strip())
|
||||||
|
if h < 64 or h > 1344:
|
||||||
|
return "❌ 高度范围: 64 ~ 1344"
|
||||||
|
self.height = h
|
||||||
|
return f"✅ 高度已设置为: {h}"
|
||||||
|
except ValueError:
|
||||||
|
return "❌ 请输入有效数字"
|
||||||
|
|
||||||
|
def _cmd_set_size(self, val):
|
||||||
|
"""同时设置宽高"""
|
||||||
|
parts = val.strip().split()
|
||||||
|
if len(parts) < 2:
|
||||||
|
return "❌ 用法: ai_image size <宽> <高>"
|
||||||
|
try:
|
||||||
|
w, h = int(parts[0]), int(parts[1])
|
||||||
|
if w < 64 or w > 1344 or h < 64 or h > 1344:
|
||||||
|
return "❌ 宽高范围: 64 ~ 1344"
|
||||||
|
self.width = w
|
||||||
|
self.height = h
|
||||||
|
return f"✅ 尺寸已设置为: {w} x {h}"
|
||||||
|
except ValueError:
|
||||||
|
return "❌ 请输入有效数字"
|
||||||
|
|
||||||
|
def _cmd_set_rewrite(self, val):
|
||||||
|
"""设置改写模式"""
|
||||||
|
val = val.strip().lower()
|
||||||
|
if val in ["on", "开", "1", "true", "yes"]:
|
||||||
|
self.rewrite = True
|
||||||
|
return "✅ 改写模式已开启 — LLM 将智能重写 prompt"
|
||||||
|
elif val in ["off", "关", "0", "false", "no"]:
|
||||||
|
self.rewrite = False
|
||||||
|
return "✅ 改写模式已关闭 — 普通翻译/追加模式"
|
||||||
|
else:
|
||||||
|
self.rewrite = not self.rewrite
|
||||||
|
status = "开启" if self.rewrite else "关闭"
|
||||||
|
return f"✅ 改写模式已{status}"
|
||||||
|
|
||||||
|
def _cmd_set_override(self, val):
|
||||||
|
"""设置覆写模式"""
|
||||||
|
val = val.strip().lower()
|
||||||
|
if val in ["on", "开", "1", "true", "yes"]:
|
||||||
|
self.override = True
|
||||||
|
return "✅ 覆写模式已开启 — 忽略工作流内置 prompt"
|
||||||
|
elif val in ["off", "关", "0", "false", "no"]:
|
||||||
|
self.override = False
|
||||||
|
return "✅ 覆写模式已关闭 — 保留工作流内置 prompt"
|
||||||
|
else:
|
||||||
|
self.override = not self.override
|
||||||
|
status = "开启" if self.override else "关闭"
|
||||||
|
return f"✅ 覆写模式已{status}"
|
||||||
|
|
||||||
|
def _cmd_status(self):
|
||||||
|
"""查看当前状态"""
|
||||||
|
result = " AI 生图状态:\n\n"
|
||||||
|
result += f" 工作流: {self.current_workflow or '(默认)'}\n"
|
||||||
|
result += f" 直接 Tag: {self.direct_prompt or '(未设置)'}\n"
|
||||||
|
result += f" 自然语言: {self.nl_prompt or '(未设置)'}\n"
|
||||||
|
result += f" 改写模式: {'✅ 开启' if self.rewrite else '❌ 关闭'}\n"
|
||||||
|
result += f" 覆写模式: {'✅ 开启' if self.override else '❌ 关闭'}\n"
|
||||||
|
result += f" 宽度: {self.width or '(默认)'}\n"
|
||||||
|
result += f" 高度: {self.height or '(默认)'}\n"
|
||||||
|
result += f" 保存目录: {self.save_dir}\n"
|
||||||
|
result += f" 生成中: {'是' if self.is_generating else '否'}\n"
|
||||||
|
return result
|
||||||
|
|
||||||
|
# ── 核心生图逻辑 ──
|
||||||
|
|
||||||
|
def _fetch_workflows(self):
|
||||||
|
"""获取工作流列表"""
|
||||||
|
if self.workflows_cache:
|
||||||
|
return self.workflows_cache
|
||||||
|
|
||||||
|
try:
|
||||||
|
resp = requests.get(f"{self.API_URL}/workflows", timeout=15)
|
||||||
|
if resp.status_code == 200:
|
||||||
|
data = resp.json()
|
||||||
|
self.workflows_cache = data.get("workflows", [])
|
||||||
|
return self.workflows_cache
|
||||||
|
except Exception as e:
|
||||||
|
pass
|
||||||
|
return []
|
||||||
|
|
||||||
|
def _run_generation(self):
|
||||||
|
"""执行图片生成"""
|
||||||
|
if self.is_generating:
|
||||||
|
return "⚠️ 已有生成任务在进行中,请等待完成"
|
||||||
|
|
||||||
|
if not self.direct_prompt and not self.nl_prompt:
|
||||||
|
return "❌ 请提供至少一种 prompt(直接 Tag 或自然语言描述)"
|
||||||
|
|
||||||
|
self.is_generating = True
|
||||||
|
result_lines = []
|
||||||
|
image_paths = []
|
||||||
|
|
||||||
|
try:
|
||||||
|
# 获取默认工作流(如果未指定则使用列表中第一个)
|
||||||
|
workflow = self.current_workflow
|
||||||
|
if not workflow:
|
||||||
|
workflows = self._fetch_workflows()
|
||||||
|
if workflows:
|
||||||
|
# 优先选 "无Lora" 工作流,否则用第一个
|
||||||
|
for wf in workflows:
|
||||||
|
if "无lora" in wf.get("path", "").lower():
|
||||||
|
workflow = wf["path"]
|
||||||
|
break
|
||||||
|
if not workflow:
|
||||||
|
workflow = workflows[0].get("path", "")
|
||||||
|
|
||||||
|
# 构建 payload
|
||||||
|
payload = {
|
||||||
|
"workflow_path": workflow or "",
|
||||||
|
"inline_workflow": None,
|
||||||
|
"direct_prompt": self.direct_prompt,
|
||||||
|
"nl_prompt": self.nl_prompt,
|
||||||
|
"rewrite": self.rewrite,
|
||||||
|
"override": self.override,
|
||||||
|
"width": self.width,
|
||||||
|
"height": self.height,
|
||||||
|
}
|
||||||
|
|
||||||
|
result_lines.append(" 正在连接 ai.2x.nz ...")
|
||||||
|
result_lines.append(f" 直接 Tag: {self.direct_prompt[:80] or '(无)'}")
|
||||||
|
result_lines.append(f" 自然语言: {self.nl_prompt[:80] or '(无)'}")
|
||||||
|
result_lines.append(f" 工作流: {workflow or '(默认)'}")
|
||||||
|
result_lines.append("")
|
||||||
|
|
||||||
|
# 使用同步方式通过 REST + 轮询获取结果
|
||||||
|
# 由于 websocket-client 可能未安装,提供降级方案
|
||||||
|
if WEBSOCKET_AVAILABLE:
|
||||||
|
images = self._generate_via_ws(payload, result_lines)
|
||||||
|
else:
|
||||||
|
# 降级:尝试使用 requests + SSE 或提示安装
|
||||||
|
result_lines.append("⚠️ websocket-client 未安装,尝试安装...")
|
||||||
|
images = self._generate_via_ws_fallback(payload, result_lines)
|
||||||
|
|
||||||
|
if images:
|
||||||
|
image_paths = images
|
||||||
|
result_lines.append(f"\n✅ 生成完成!共 {len(images)} 张图片")
|
||||||
|
for i, path in enumerate(images, 1):
|
||||||
|
result_lines.append(f" {i}. {path}")
|
||||||
|
else:
|
||||||
|
result_lines.append("\n❌ 未生成任何图片")
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
result_lines.append(f"\n❌ 生成失败: {str(e)}")
|
||||||
|
finally:
|
||||||
|
self.is_generating = False
|
||||||
|
|
||||||
|
return "\n".join(result_lines)
|
||||||
|
|
||||||
|
def _generate_via_ws(self, payload, result_lines):
|
||||||
|
"""通过 WebSocket 生成图片"""
|
||||||
|
images = []
|
||||||
|
final_prompt = ""
|
||||||
|
error_msg = None
|
||||||
|
|
||||||
|
ws_result = {"images": [], "error": None, "final_prompt": "", "done": False}
|
||||||
|
|
||||||
|
def on_message(ws, message):
|
||||||
|
try:
|
||||||
|
m = json.loads(message)
|
||||||
|
msg_type = m.get("type", "")
|
||||||
|
|
||||||
|
if msg_type == "log":
|
||||||
|
result_lines.append(f" {m.get('message', '')}")
|
||||||
|
elif msg_type == "llm_start":
|
||||||
|
result_lines.append(" LLM 正在处理 prompt...")
|
||||||
|
elif msg_type == "llm_chunk":
|
||||||
|
pass # 流式输出,不逐块显示
|
||||||
|
elif msg_type == "llm_done":
|
||||||
|
result_lines.append(" LLM 处理完成")
|
||||||
|
elif msg_type == "progress":
|
||||||
|
node = m.get("node", "")
|
||||||
|
value = m.get("value", 0)
|
||||||
|
max_val = m.get("max", 0)
|
||||||
|
if max_val and max_val > 1:
|
||||||
|
pct = int(value * 100 / max_val)
|
||||||
|
result_lines.append(f"⏳ 进度: {node} {value}/{max_val} ({pct}%)")
|
||||||
|
else:
|
||||||
|
result_lines.append(f"⏳ 执行: {node}")
|
||||||
|
elif msg_type == "prompt_id":
|
||||||
|
fp = m.get("final_prompt", "")
|
||||||
|
if fp:
|
||||||
|
ws_result["final_prompt"] = fp
|
||||||
|
result_lines.append(f"\n 最终 Prompt:\n{fp[:300]}{'...' if len(fp) > 300 else ''}\n")
|
||||||
|
elif msg_type == "image":
|
||||||
|
url = m.get("url", "")
|
||||||
|
filename = m.get("filename", "")
|
||||||
|
if url:
|
||||||
|
# 下载图片
|
||||||
|
saved = self._download_image(url, filename)
|
||||||
|
if saved:
|
||||||
|
ws_result["images"].append(saved)
|
||||||
|
result_lines.append(f" 收到图片: {filename}")
|
||||||
|
elif msg_type == "done":
|
||||||
|
count = m.get("count", 0)
|
||||||
|
result_lines.append(f"✅ 服务端完成,共 {count} 张")
|
||||||
|
ws_result["done"] = True
|
||||||
|
ws.close()
|
||||||
|
elif msg_type == "error":
|
||||||
|
ws_result["error"] = m.get("message", "未知错误")
|
||||||
|
result_lines.append(f"❌ 错误: {ws_result['error']}")
|
||||||
|
ws.close()
|
||||||
|
except Exception as e:
|
||||||
|
result_lines.append(f"⚠️ 解析消息出错: {e}")
|
||||||
|
|
||||||
|
def on_error(ws, error):
|
||||||
|
ws_result["error"] = str(error)
|
||||||
|
result_lines.append(f"❌ WebSocket 错误: {error}")
|
||||||
|
|
||||||
|
def on_close(ws, close_status_code, close_msg):
|
||||||
|
ws_result["done"] = True
|
||||||
|
|
||||||
|
def on_open(ws):
|
||||||
|
ws.send(json.dumps(payload))
|
||||||
|
|
||||||
|
try:
|
||||||
|
ws = websocket.WebSocketApp(
|
||||||
|
self.WS_URL,
|
||||||
|
on_message=on_message,
|
||||||
|
on_error=on_error,
|
||||||
|
on_close=on_close,
|
||||||
|
on_open=on_open
|
||||||
|
)
|
||||||
|
|
||||||
|
# 在独立线程中运行 WebSocket
|
||||||
|
ws_thread = threading.Thread(target=ws.run_forever, kwargs={"ping_timeout": 10})
|
||||||
|
ws_thread.daemon = True
|
||||||
|
ws_thread.start()
|
||||||
|
|
||||||
|
# 等待完成(最多 5 分钟)
|
||||||
|
timeout = 300
|
||||||
|
start = time.time()
|
||||||
|
while not ws_result["done"] and (time.time() - start) < timeout:
|
||||||
|
time.sleep(1)
|
||||||
|
|
||||||
|
if ws_result["error"]:
|
||||||
|
raise Exception(ws_result["error"])
|
||||||
|
|
||||||
|
if not ws_result["done"]:
|
||||||
|
ws.close()
|
||||||
|
raise Exception("生成超时(超过 5 分钟)")
|
||||||
|
|
||||||
|
return ws_result["images"]
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
raise Exception(f"WebSocket 连接失败: {e}")
|
||||||
|
|
||||||
|
def _generate_via_ws_fallback(self, payload, result_lines):
|
||||||
|
"""降级方案:尝试自动安装 websocket-client"""
|
||||||
|
try:
|
||||||
|
import subprocess
|
||||||
|
result_lines.append(" 正在安装 websocket-client ...")
|
||||||
|
subprocess.run(
|
||||||
|
["pip", "install", "websocket-client"],
|
||||||
|
capture_output=True, timeout=60
|
||||||
|
)
|
||||||
|
import importlib
|
||||||
|
global websocket
|
||||||
|
websocket = importlib.import_module("websocket")
|
||||||
|
global WEBSOCKET_AVAILABLE
|
||||||
|
WEBSOCKET_AVAILABLE = True
|
||||||
|
result_lines.append("✅ websocket-client 安装成功")
|
||||||
|
return self._generate_via_ws(payload, result_lines)
|
||||||
|
except Exception as e:
|
||||||
|
result_lines.append(f"❌ 无法安装 websocket-client: {e}")
|
||||||
|
result_lines.append("💡 请手动运行: pip install websocket-client")
|
||||||
|
return []
|
||||||
|
|
||||||
|
def _download_image(self, url, filename):
|
||||||
|
"""下载图片到本地"""
|
||||||
|
try:
|
||||||
|
# 确保 URL 是完整的
|
||||||
|
if url.startswith("/"):
|
||||||
|
url = f"{self.BASE_URL}{url}"
|
||||||
|
elif not url.startswith("http"):
|
||||||
|
url = f"{self.BASE_URL}/api/output/file?path={quote(url)}"
|
||||||
|
|
||||||
|
# 创建保存目录
|
||||||
|
os.makedirs(self.save_dir, exist_ok=True)
|
||||||
|
|
||||||
|
# 生成文件名
|
||||||
|
if not filename:
|
||||||
|
filename = f"img_{datetime.now().strftime('%Y%m%d_%H%M%S')}.png"
|
||||||
|
|
||||||
|
# 清理文件名
|
||||||
|
filename = re.sub(r'[<>:"/\\|?*]', '_', filename)
|
||||||
|
save_path = os.path.join(self.save_dir, filename)
|
||||||
|
|
||||||
|
# 如果文件已存在,添加序号
|
||||||
|
if os.path.exists(save_path):
|
||||||
|
name, ext = os.path.splitext(filename)
|
||||||
|
for i in range(1, 100):
|
||||||
|
new_path = os.path.join(self.save_dir, f"{name}_{i}{ext}")
|
||||||
|
if not os.path.exists(new_path):
|
||||||
|
save_path = new_path
|
||||||
|
break
|
||||||
|
|
||||||
|
# 下载
|
||||||
|
resp = requests.get(url, timeout=60, stream=True)
|
||||||
|
if resp.status_code == 200:
|
||||||
|
with open(save_path, 'wb') as f:
|
||||||
|
for chunk in resp.iter_content(chunk_size=8192):
|
||||||
|
f.write(chunk)
|
||||||
|
return save_path
|
||||||
|
else:
|
||||||
|
return None
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
# 兼容 Liugin 类名
|
||||||
@@ -10,7 +10,7 @@ import subprocess
|
|||||||
from typing import Tuple, List
|
from typing import Tuple, List
|
||||||
|
|
||||||
|
|
||||||
class Plugin:
|
class Liugin:
|
||||||
"""工程化工具 - lint/format/test/build + 代码分析"""
|
"""工程化工具 - lint/format/test/build + 代码分析"""
|
||||||
|
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
|
|||||||
@@ -0,0 +1,489 @@
|
|||||||
|
"""
|
||||||
|
书签管理器插件 - 管理开发相关链接和资源
|
||||||
|
支持分类、标签、搜索、导入导出,JSON 持久化
|
||||||
|
"""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import hashlib
|
||||||
|
import time
|
||||||
|
from datetime import datetime
|
||||||
|
from typing import List, Optional
|
||||||
|
|
||||||
|
|
||||||
|
class Liugin:
|
||||||
|
"""书签管理器 - 开发资源和链接管理"""
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
self.usage = """书签管理器
|
||||||
|
|
||||||
|
操作:
|
||||||
|
add <URL> -n <名称> [-c 分类] [-t 标签1,标签2] [-d 描述]
|
||||||
|
- 添加书签
|
||||||
|
list [-c 分类] [-t 标签] - 列出书签
|
||||||
|
open <名称或ID> - 获取书签 URL
|
||||||
|
search <关键词> - 搜索书签
|
||||||
|
delete <名称或ID> - 删除书签
|
||||||
|
edit <名称或ID> [-n 名称] [-d 描述] [-c 分类] [-t 标签]
|
||||||
|
- 编辑书签
|
||||||
|
categories - 列出所有分类
|
||||||
|
tags - 列出所有标签
|
||||||
|
export [文件] - 导出书签
|
||||||
|
import <文件> - 导入书签
|
||||||
|
stats - 统计信息
|
||||||
|
recent [-n 数量] - 最近添加的书签
|
||||||
|
check - 检查书签是否可访问
|
||||||
|
favicon <URL> - 获取网站 favicon URL
|
||||||
|
|
||||||
|
示例:
|
||||||
|
bookmark_manager add https://github.com -n GitHub -c 开发 -t 代码,托管 -d 代码托管平台
|
||||||
|
bookmark_manager list -c 开发
|
||||||
|
bookmark_manager search github
|
||||||
|
bookmark_manager open GitHub
|
||||||
|
bookmark_manager categories
|
||||||
|
"""
|
||||||
|
self.cli = None
|
||||||
|
self.bookmarks_file = "bookmarks.json"
|
||||||
|
self.bookmarks = []
|
||||||
|
self._load_bookmarks()
|
||||||
|
|
||||||
|
def set_cli(self, cli):
|
||||||
|
self.cli = cli
|
||||||
|
|
||||||
|
def get_tool_info(self):
|
||||||
|
return {
|
||||||
|
"name": "bookmark_manager",
|
||||||
|
"description": "书签管理器 - 管理开发相关链接和资源,支持分类、标签、搜索",
|
||||||
|
"keywords": ["书签", "链接", "收藏", "bookmark", "网址", "资源", "网站", "URL"],
|
||||||
|
"usage": self.usage
|
||||||
|
}
|
||||||
|
|
||||||
|
def get_mcp_definition(self):
|
||||||
|
return {
|
||||||
|
"name": "bookmark_manager",
|
||||||
|
"description": "书签管理器,支持添加、搜索、获取、删除书签",
|
||||||
|
"inputSchema": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"operation": {
|
||||||
|
"type": "string",
|
||||||
|
"enum": ["add", "list", "open", "search", "delete",
|
||||||
|
"edit", "categories", "tags", "export",
|
||||||
|
"import", "stats", "recent", "check"],
|
||||||
|
"description": "操作类型"
|
||||||
|
},
|
||||||
|
"url": {"type": "string", "description": "URL"},
|
||||||
|
"name": {"type": "string", "description": "书签名称"},
|
||||||
|
"category": {"type": "string", "description": "分类"},
|
||||||
|
"tags": {"type": "string", "description": "标签(逗号分隔)"},
|
||||||
|
"description": {"type": "string", "description": "描述"},
|
||||||
|
"keyword": {"type": "string", "description": "搜索关键词"},
|
||||||
|
"file": {"type": "string", "description": "文件路径"},
|
||||||
|
"count": {"type": "integer", "description": "数量"}
|
||||||
|
},
|
||||||
|
"required": ["operation"]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
def convert_mcp_args(self, arguments):
|
||||||
|
op = arguments.get("operation", "")
|
||||||
|
name = arguments.get("name", "")
|
||||||
|
return f"{op} {name}".strip()
|
||||||
|
|
||||||
|
def _load_bookmarks(self):
|
||||||
|
try:
|
||||||
|
if os.path.exists(self.bookmarks_file):
|
||||||
|
with open(self.bookmarks_file, 'r', encoding='utf-8') as f:
|
||||||
|
self.bookmarks = json.load(f)
|
||||||
|
except Exception:
|
||||||
|
self.bookmarks = []
|
||||||
|
|
||||||
|
def _save_bookmarks(self):
|
||||||
|
try:
|
||||||
|
with open(self.bookmarks_file, 'w', encoding='utf-8') as f:
|
||||||
|
json.dump(self.bookmarks, f, ensure_ascii=False, indent=2)
|
||||||
|
return None
|
||||||
|
except Exception as e:
|
||||||
|
return f"保存失败: {e}"
|
||||||
|
|
||||||
|
def _gen_id(self, url: str) -> str:
|
||||||
|
return hashlib.md5(f"{url}{time.time()}".encode()).hexdigest()[:8]
|
||||||
|
|
||||||
|
def handle(self, args: str) -> str:
|
||||||
|
try:
|
||||||
|
parts = self._parse_args(args)
|
||||||
|
if not parts:
|
||||||
|
return self._op_list([])
|
||||||
|
|
||||||
|
operation = parts[0].lower()
|
||||||
|
handlers = {
|
||||||
|
"add": self._op_add,
|
||||||
|
"list": self._op_list,
|
||||||
|
"open": self._op_open,
|
||||||
|
"search": self._op_search,
|
||||||
|
"delete": self._op_delete,
|
||||||
|
"edit": self._op_edit,
|
||||||
|
"categories": self._op_categories,
|
||||||
|
"tags": self._op_tags,
|
||||||
|
"export": self._op_export,
|
||||||
|
"import": self._op_import,
|
||||||
|
"stats": self._op_stats,
|
||||||
|
"recent": self._op_recent,
|
||||||
|
"check": self._op_check,
|
||||||
|
"favicon": self._op_favicon,
|
||||||
|
}
|
||||||
|
|
||||||
|
handler = handlers.get(operation)
|
||||||
|
if not handler:
|
||||||
|
return f"错误:不支持的操作 '{operation}'"
|
||||||
|
return handler(parts[1:])
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
return f"书签管理错误: {str(e)}"
|
||||||
|
|
||||||
|
def _parse_args(self, args: str) -> List[str]:
|
||||||
|
parts, current, in_quotes, qc = [], "", False, None
|
||||||
|
for ch in args:
|
||||||
|
if ch in ('"', "'") and not in_quotes:
|
||||||
|
in_quotes, qc = True, ch
|
||||||
|
elif ch == qc and in_quotes:
|
||||||
|
in_quotes, qc = False, None
|
||||||
|
elif ch == ' ' and not in_quotes:
|
||||||
|
if current:
|
||||||
|
parts.append(current)
|
||||||
|
current = ""
|
||||||
|
else:
|
||||||
|
current += ch
|
||||||
|
if current:
|
||||||
|
parts.append(current)
|
||||||
|
return parts
|
||||||
|
|
||||||
|
def _op_add(self, args: List[str]) -> str:
|
||||||
|
if not args:
|
||||||
|
return "错误:请提供 URL"
|
||||||
|
url = args[0]
|
||||||
|
name, category, tags, desc = "", "", [], ""
|
||||||
|
|
||||||
|
i = 1
|
||||||
|
while i < len(args):
|
||||||
|
if args[i] == "-n" and i + 1 < len(args):
|
||||||
|
name = args[i + 1]; i += 1
|
||||||
|
elif args[i] == "-c" and i + 1 < len(args):
|
||||||
|
category = args[i + 1]; i += 1
|
||||||
|
elif args[i] == "-t" and i + 1 < len(args):
|
||||||
|
tags = [t.strip() for t in args[i + 1].split(",") if t.strip()]; i += 1
|
||||||
|
elif args[i] == "-d" and i + 1 < len(args):
|
||||||
|
desc = args[i + 1]; i += 1
|
||||||
|
i += 1
|
||||||
|
|
||||||
|
if not name:
|
||||||
|
# 从 URL 推断名称
|
||||||
|
from urllib.parse import urlparse
|
||||||
|
parsed = urlparse(url if '://' in url else 'https://' + url)
|
||||||
|
name = parsed.netloc.replace('www.', '').split('.')[0].capitalize()
|
||||||
|
url = parsed.geturl()
|
||||||
|
|
||||||
|
# 检查重复
|
||||||
|
for b in self.bookmarks:
|
||||||
|
if b["url"] == url:
|
||||||
|
return f"错误:URL 已存在 (书签: {b['name']})"
|
||||||
|
|
||||||
|
bookmark = {
|
||||||
|
"id": self._gen_id(url),
|
||||||
|
"name": name,
|
||||||
|
"url": url,
|
||||||
|
"category": category,
|
||||||
|
"tags": tags,
|
||||||
|
"description": desc,
|
||||||
|
"created_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
|
||||||
|
"access_count": 0
|
||||||
|
}
|
||||||
|
self.bookmarks.append(bookmark)
|
||||||
|
err = self._save_bookmarks()
|
||||||
|
if err:
|
||||||
|
return err
|
||||||
|
return f"✅ 已添加书签 '{name}'\n URL: {url}\n 分类: {category or '未分类'}"
|
||||||
|
|
||||||
|
def _op_list(self, args: List[str]) -> str:
|
||||||
|
cat_filter, tag_filter = None, None
|
||||||
|
i = 0
|
||||||
|
while i < len(args):
|
||||||
|
if args[i] == "-c" and i + 1 < len(args):
|
||||||
|
cat_filter = args[i + 1].lower(); i += 1
|
||||||
|
elif args[i] == "-t" and i + 1 < len(args):
|
||||||
|
tag_filter = args[i + 1].lower(); i += 1
|
||||||
|
i += 1
|
||||||
|
|
||||||
|
filtered = self.bookmarks
|
||||||
|
if cat_filter:
|
||||||
|
filtered = [b for b in filtered if b.get("category", "").lower() == cat_filter]
|
||||||
|
if tag_filter:
|
||||||
|
filtered = [b for b in filtered if any(tag_filter in t.lower() for t in b.get("tags", []))]
|
||||||
|
|
||||||
|
if not filtered:
|
||||||
|
return "📭 没有找到书签"
|
||||||
|
|
||||||
|
# 按分类分组
|
||||||
|
grouped = {}
|
||||||
|
for b in filtered:
|
||||||
|
cat = b.get("category", "未分类")
|
||||||
|
grouped.setdefault(cat, []).append(b)
|
||||||
|
|
||||||
|
result = f"\n 书签列表 (共 {len(filtered)} 个)\n"
|
||||||
|
result += "═" * 55 + "\n"
|
||||||
|
|
||||||
|
for cat, items in sorted(grouped.items()):
|
||||||
|
result += f"\n {cat} ({len(items)} 个)\n"
|
||||||
|
result += "─" * 45 + "\n"
|
||||||
|
for b in items:
|
||||||
|
tags = ", ".join(b.get("tags", [])) if b.get("tags") else ""
|
||||||
|
result += f" [{b['id']}] {b['name']}\n"
|
||||||
|
result += f" {b['url']}\n"
|
||||||
|
if tags:
|
||||||
|
result += f" ️ {tags}\n"
|
||||||
|
if b.get("description"):
|
||||||
|
result += f" {b['description'][:50]}\n"
|
||||||
|
result += "\n"
|
||||||
|
|
||||||
|
return result.rstrip()
|
||||||
|
|
||||||
|
def _op_open(self, args: List[str]) -> str:
|
||||||
|
if not args:
|
||||||
|
return "错误:请提供书签名称或 ID"
|
||||||
|
key = args[0]
|
||||||
|
bookmark = self._find_bookmark(key)
|
||||||
|
if not bookmark:
|
||||||
|
return f"❌ 未找到书签: {key}"
|
||||||
|
|
||||||
|
bookmark["access_count"] = bookmark.get("access_count", 0) + 1
|
||||||
|
self._save_bookmarks()
|
||||||
|
|
||||||
|
return (f" {bookmark['name']}\n"
|
||||||
|
f" URL: {bookmark['url']}\n"
|
||||||
|
f" 访问次数: {bookmark.get('access_count', 0)}")
|
||||||
|
|
||||||
|
def _op_search(self, args: List[str]) -> str:
|
||||||
|
if not args:
|
||||||
|
return "错误:请提供搜索关键词"
|
||||||
|
keyword = " ".join(args).lower()
|
||||||
|
|
||||||
|
results = []
|
||||||
|
for b in self.bookmarks:
|
||||||
|
searchable = f"{b['name']} {b['url']} {b.get('description', '')} {' '.join(b.get('tags', []))} {b.get('category', '')}".lower()
|
||||||
|
if keyword in searchable:
|
||||||
|
results.append(b)
|
||||||
|
|
||||||
|
if not results:
|
||||||
|
return f" 未找到匹配 '{keyword}' 的书签"
|
||||||
|
|
||||||
|
output = f" 搜索结果 ({len(results)} 个):\n"
|
||||||
|
output += "─" * 50 + "\n"
|
||||||
|
for b in results:
|
||||||
|
output += f" [{b['id']}] {b['name']} - {b['url']}\n"
|
||||||
|
if b.get("description"):
|
||||||
|
output += f" {b['description'][:40]}\n"
|
||||||
|
return output.rstrip()
|
||||||
|
|
||||||
|
def _op_delete(self, args: List[str]) -> str:
|
||||||
|
if not args:
|
||||||
|
return "错误:请提供书签名称或 ID"
|
||||||
|
key = args[0]
|
||||||
|
for i, b in enumerate(self.bookmarks):
|
||||||
|
if b["name"].lower() == key.lower() or b["id"] == key:
|
||||||
|
removed = self.bookmarks.pop(i)
|
||||||
|
self._save_bookmarks()
|
||||||
|
return f" ️ 已删除书签: {removed['name']} ({removed['url']})"
|
||||||
|
return f"❌ 未找到书签: {key}"
|
||||||
|
|
||||||
|
def _op_edit(self, args: List[str]) -> str:
|
||||||
|
if not args:
|
||||||
|
return "错误:请提供书签名称或 ID"
|
||||||
|
key = args[0]
|
||||||
|
bookmark = self._find_bookmark(key)
|
||||||
|
if not bookmark:
|
||||||
|
return f"❌ 未找到书签: {key}"
|
||||||
|
|
||||||
|
i = 1
|
||||||
|
while i < len(args):
|
||||||
|
if args[i] == "-n" and i + 1 < len(args):
|
||||||
|
bookmark["name"] = args[i + 1]; i += 1
|
||||||
|
elif args[i] == "-d" and i + 1 < len(args):
|
||||||
|
bookmark["description"] = args[i + 1]; i += 1
|
||||||
|
elif args[i] == "-c" and i + 1 < len(args):
|
||||||
|
bookmark["category"] = args[i + 1]; i += 1
|
||||||
|
elif args[i] == "-t" and i + 1 < len(args):
|
||||||
|
bookmark["tags"] = [t.strip() for t in args[i + 1].split(",") if t.strip()]; i += 1
|
||||||
|
i += 1
|
||||||
|
|
||||||
|
bookmark["updated_at"] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||||||
|
self._save_bookmarks()
|
||||||
|
return f"✅ 已更新书签: {bookmark['name']}"
|
||||||
|
|
||||||
|
def _op_categories(self, args: List[str]) -> str:
|
||||||
|
cat_count = {}
|
||||||
|
for b in self.bookmarks:
|
||||||
|
cat = b.get("category", "未分类")
|
||||||
|
cat_count[cat] = cat_count.get(cat, 0) + 1
|
||||||
|
|
||||||
|
if not cat_count:
|
||||||
|
return " 暂无分类"
|
||||||
|
|
||||||
|
result = " 分类列表:\n"
|
||||||
|
for cat, count in sorted(cat_count.items(), key=lambda x: -x[1]):
|
||||||
|
bar = "█" * min(count, 20)
|
||||||
|
result += f" {cat:15s} {bar} ({count})\n"
|
||||||
|
return result.rstrip()
|
||||||
|
|
||||||
|
def _op_tags(self, args: List[str]) -> str:
|
||||||
|
tag_count = {}
|
||||||
|
for b in self.bookmarks:
|
||||||
|
for t in b.get("tags", []):
|
||||||
|
tag_count[t] = tag_count.get(t, 0) + 1
|
||||||
|
|
||||||
|
if not tag_count:
|
||||||
|
return " ️ 暂无标签"
|
||||||
|
|
||||||
|
result = " ️ 标签列表:\n"
|
||||||
|
for tag, count in sorted(tag_count.items(), key=lambda x: -x[1]):
|
||||||
|
result += f" {tag} ({count})\n"
|
||||||
|
return result.rstrip()
|
||||||
|
|
||||||
|
def _op_export(self, args: List[str]) -> str:
|
||||||
|
output_file = args[0] if args else "bookmarks_export.json"
|
||||||
|
try:
|
||||||
|
with open(output_file, 'w', encoding='utf-8') as f:
|
||||||
|
json.dump(self.bookmarks, f, ensure_ascii=False, indent=2)
|
||||||
|
return f"✅ 已导出 {len(self.bookmarks)} 个书签到: {output_file}"
|
||||||
|
except Exception as e:
|
||||||
|
return f"❌ 导出失败: {e}"
|
||||||
|
|
||||||
|
def _op_import(self, args: List[str]) -> str:
|
||||||
|
if not args:
|
||||||
|
return "错误:请提供导入文件路径"
|
||||||
|
file_path = args[0]
|
||||||
|
if not os.path.isfile(file_path):
|
||||||
|
return f"❌ 文件不存在: {file_path}"
|
||||||
|
try:
|
||||||
|
with open(file_path, 'r', encoding='utf-8') as f:
|
||||||
|
imported = json.load(f)
|
||||||
|
if not isinstance(imported, list):
|
||||||
|
return "❌ 文件格式错误:需要 JSON 数组"
|
||||||
|
|
||||||
|
existing_urls = {b["url"] for b in self.bookmarks}
|
||||||
|
added = 0
|
||||||
|
for b in imported:
|
||||||
|
if isinstance(b, dict) and b.get("url") and b["url"] not in existing_urls:
|
||||||
|
b["id"] = self._gen_id(b["url"])
|
||||||
|
self.bookmarks.append(b)
|
||||||
|
existing_urls.add(b["url"])
|
||||||
|
added += 1
|
||||||
|
|
||||||
|
self._save_bookmarks()
|
||||||
|
return f"✅ 已导入 {added} 个书签 (跳过 {len(imported) - added} 个重复)"
|
||||||
|
except Exception as e:
|
||||||
|
return f"❌ 导入失败: {e}"
|
||||||
|
|
||||||
|
def _op_stats(self, args: List[str]) -> str:
|
||||||
|
total = len(self.bookmarks)
|
||||||
|
if not total:
|
||||||
|
return "📊 暂无书签"
|
||||||
|
|
||||||
|
cat_count = {}
|
||||||
|
total_access = 0
|
||||||
|
for b in self.bookmarks:
|
||||||
|
cat = b.get("category", "未分类")
|
||||||
|
cat_count[cat] = cat_count.get(cat, 0) + 1
|
||||||
|
total_access += b.get("access_count", 0)
|
||||||
|
|
||||||
|
most_accessed = max(self.bookmarks, key=lambda b: b.get("access_count", 0))
|
||||||
|
|
||||||
|
result = f"📊 书签统计\n"
|
||||||
|
result += "─" * 35 + "\n"
|
||||||
|
result += f" 总数: {total}\n"
|
||||||
|
result += f" 总访问: {total_access} 次\n"
|
||||||
|
result += f" 分类数: {len(cat_count)}\n"
|
||||||
|
result += f" 最常访问: {most_accessed['name']} ({most_accessed.get('access_count', 0)} 次)\n"
|
||||||
|
result += f"\n 分类分布:\n"
|
||||||
|
for cat, count in sorted(cat_count.items(), key=lambda x: -x[1]):
|
||||||
|
result += f" {cat}: {count}\n"
|
||||||
|
return result.rstrip()
|
||||||
|
|
||||||
|
def _op_recent(self, args: List[str]) -> str:
|
||||||
|
count = 5
|
||||||
|
for i, a in enumerate(args):
|
||||||
|
if a == "-n" and i + 1 < len(args):
|
||||||
|
count = int(args[i + 1])
|
||||||
|
|
||||||
|
recent = sorted(self.bookmarks, key=lambda b: b.get("created_at", ""), reverse=True)[:count]
|
||||||
|
if not recent:
|
||||||
|
return "📭 暂无书签"
|
||||||
|
|
||||||
|
result = f"⏰ 最近 {len(recent)} 个书签:\n"
|
||||||
|
for b in recent:
|
||||||
|
result += f" [{b['id']}] {b['name']} - {b.get('created_at', '')}\n"
|
||||||
|
return result.rstrip()
|
||||||
|
|
||||||
|
def _op_check(self, args: List[str]) -> str:
|
||||||
|
import socket
|
||||||
|
from urllib.parse import urlparse
|
||||||
|
|
||||||
|
bookmarks = self.bookmarks
|
||||||
|
if args:
|
||||||
|
# 检查指定书签
|
||||||
|
bookmark = self._find_bookmark(args[0])
|
||||||
|
if not bookmark:
|
||||||
|
return f"❌ 未找到书签: {args[0]}"
|
||||||
|
bookmarks = [bookmark]
|
||||||
|
|
||||||
|
result = f" ️ 书签可访问性检查 ({len(bookmarks)} 个):\n"
|
||||||
|
result += "─" * 50 + "\n"
|
||||||
|
|
||||||
|
for b in bookmarks[:20]:
|
||||||
|
url = b["url"]
|
||||||
|
try:
|
||||||
|
parsed = urlparse(url)
|
||||||
|
host = parsed.netloc or parsed.path.split('/')[0]
|
||||||
|
socket.create_connection((host, 80), timeout=3)
|
||||||
|
result += f" {b['name']} ({host})\n"
|
||||||
|
except (socket.timeout, socket.error, OSError):
|
||||||
|
result += f" {b['name']} ({host}) - 不可达\n"
|
||||||
|
|
||||||
|
if len(bookmarks) > 20:
|
||||||
|
result += f" ... 仅检查前 20 个\n"
|
||||||
|
return result.rstrip()
|
||||||
|
|
||||||
|
def _op_favicon(self, args: List[str]) -> str:
|
||||||
|
if not args:
|
||||||
|
return "错误:请提供 URL"
|
||||||
|
url = args[0]
|
||||||
|
if '://' not in url:
|
||||||
|
url = 'https://' + url
|
||||||
|
|
||||||
|
from urllib.parse import urlparse
|
||||||
|
parsed = urlparse(url)
|
||||||
|
base = f"{parsed.scheme}://{parsed.netloc}"
|
||||||
|
favicon_url = f"{base}/favicon.ico"
|
||||||
|
|
||||||
|
return (f" Favicon:\n"
|
||||||
|
f" 网站: {base}\n"
|
||||||
|
f" Favicon: {favicon_url}\n"
|
||||||
|
f" Google: https://www.google.com/s2/favicons?domain={parsed.netloc}&sz=64")
|
||||||
|
|
||||||
|
def _find_bookmark(self, key: str) -> Optional[dict]:
|
||||||
|
for b in self.bookmarks:
|
||||||
|
if b["name"].lower() == key.lower() or b["id"] == key:
|
||||||
|
return b
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def test_plugin():
|
||||||
|
plugin = Liugin()
|
||||||
|
print("书签管理器测试:")
|
||||||
|
print(plugin.handle('add https://github.com -n GitHub -c 开发 -t 代码,托管 -d 代码托管平台'))
|
||||||
|
print(plugin.handle('add https://stackoverflow.com -n StackOverflow -c 学习 -t 问答,编程'))
|
||||||
|
print(plugin.handle('list'))
|
||||||
|
print(plugin.handle('search github'))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
test_plugin()
|
||||||
@@ -9,7 +9,7 @@ import time
|
|||||||
from typing import Optional
|
from typing import Optional
|
||||||
|
|
||||||
|
|
||||||
class Plugin:
|
class Liugin:
|
||||||
"""浏览器自动化 - 网页操控、表单填写、数据抓取、截图"""
|
"""浏览器自动化 - 网页操控、表单填写、数据抓取、截图"""
|
||||||
|
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ import subprocess
|
|||||||
import platform
|
import platform
|
||||||
|
|
||||||
|
|
||||||
class Plugin:
|
class Liugin:
|
||||||
"""Shell 命令执行器 - 跨平台命令行工具"""
|
"""Shell 命令执行器 - 跨平台命令行工具"""
|
||||||
|
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
|
|||||||
+138
-26
@@ -16,7 +16,7 @@ import threading
|
|||||||
from typing import Optional, Tuple, List
|
from typing import Optional, Tuple, List
|
||||||
|
|
||||||
|
|
||||||
class Plugin:
|
class Liugin:
|
||||||
"""代码编辑与搜索 - 精准编辑 + 代码理解"""
|
"""代码编辑与搜索 - 精准编辑 + 代码理解"""
|
||||||
|
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
@@ -37,9 +37,10 @@ class Plugin:
|
|||||||
编辑操作后自动执行,无需手动调用
|
编辑操作后自动执行,无需手动调用
|
||||||
|
|
||||||
Diff 弹窗:
|
Diff 弹窗:
|
||||||
diff_popup [on|off] - 开关 diff 弹窗 (别名: popup)
|
diff_popup [on|off|popup|inline] - 开关/切换 diff 显示模式 (别名: popup)
|
||||||
编辑操作后弹出新窗口显示修改前后对比(默认开启)
|
popup/弹窗 → 弹窗模式(新终端窗口)
|
||||||
on/开/enable → 开启 | off/关/disable → 关闭 | 无参数 → 切换
|
inline/ssh → 主终端内显示(SSH 兼容)
|
||||||
|
on/开 → 开启 | off/关 → 关闭 | 无参数 → 切换
|
||||||
|
|
||||||
查看操作:
|
查看操作:
|
||||||
read_range <文件> <起始行> [结束行] - 读取指定行范围
|
read_range <文件> <起始行> [结束行] - 读取指定行范围
|
||||||
@@ -59,7 +60,8 @@ Diff 弹窗:
|
|||||||
stats <目录> - 代码统计
|
stats <目录> - 代码统计
|
||||||
"""
|
"""
|
||||||
self.cli = None
|
self.cli = None
|
||||||
self.diff_popup_enabled = True # diff 弹窗开关,默认开启
|
self.diff_popup_enabled = True # diff 弹窗开关
|
||||||
|
self.diff_popup_mode = None # None=启动时询问, True=弹窗, False=主终端内显示
|
||||||
|
|
||||||
def set_cli(self, cli):
|
def set_cli(self, cli):
|
||||||
self.cli = cli
|
self.cli = cli
|
||||||
@@ -611,20 +613,26 @@ else:
|
|||||||
|
|
||||||
def _spawn_diff_popup(self, filepath: str, before: str, after: str):
|
def _spawn_diff_popup(self, filepath: str, before: str, after: str):
|
||||||
"""
|
"""
|
||||||
在新终端窗口中显示修改前后的对比。
|
显示修改前后的对比。
|
||||||
使用独立线程避免阻塞主流程。
|
根据 diff_popup_mode 决定弹窗还是主终端内显示。
|
||||||
"""
|
"""
|
||||||
if not self.diff_popup_enabled:
|
if not self.diff_popup_enabled:
|
||||||
return
|
return
|
||||||
if before == after:
|
if before == after:
|
||||||
return # 内容无变化,不弹窗
|
return # 内容无变化,不弹窗
|
||||||
|
|
||||||
|
# 启动时未选择模式,默认为主终端内显示(SSH 兼容)
|
||||||
|
popup = self.diff_popup_mode if self.diff_popup_mode is not None else False
|
||||||
|
|
||||||
|
if popup:
|
||||||
thread = threading.Thread(
|
thread = threading.Thread(
|
||||||
target=self._do_spawn_diff_popup,
|
target=self._do_spawn_diff_popup,
|
||||||
args=(filepath, before, after),
|
args=(filepath, before, after),
|
||||||
daemon=True
|
daemon=True
|
||||||
)
|
)
|
||||||
thread.start()
|
thread.start()
|
||||||
|
else:
|
||||||
|
self._show_inline_diff(filepath, before, after)
|
||||||
|
|
||||||
def _do_spawn_diff_popup(self, filepath: str, before: str, after: str):
|
def _do_spawn_diff_popup(self, filepath: str, before: str, after: str):
|
||||||
"""实际执行弹窗创建(在子线程中运行)"""
|
"""实际执行弹窗创建(在子线程中运行)"""
|
||||||
@@ -642,7 +650,6 @@ else:
|
|||||||
tofile=f"修改后: {basename}",
|
tofile=f"修改后: {basename}",
|
||||||
lineterm=''
|
lineterm=''
|
||||||
))
|
))
|
||||||
diff_text = '\n'.join(diff_lines)
|
|
||||||
|
|
||||||
# 统计变更
|
# 统计变更
|
||||||
added = sum(1 for l in diff_lines if l.startswith('+') and not l.startswith('+++'))
|
added = sum(1 for l in diff_lines if l.startswith('+') and not l.startswith('+++'))
|
||||||
@@ -655,7 +662,7 @@ else:
|
|||||||
display = self._build_diff_display(
|
display = self._build_diff_display(
|
||||||
basename, filepath,
|
basename, filepath,
|
||||||
before_numbered, after_numbered,
|
before_numbered, after_numbered,
|
||||||
diff_text, added, removed,
|
diff_lines, added, removed,
|
||||||
before_count, after_count
|
before_count, after_count
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -670,38 +677,62 @@ else:
|
|||||||
|
|
||||||
def _build_diff_display(self, basename, filepath,
|
def _build_diff_display(self, basename, filepath,
|
||||||
before_numbered, after_numbered,
|
before_numbered, after_numbered,
|
||||||
diff_text, added, removed,
|
diff_lines, added, removed,
|
||||||
before_count, after_count):
|
before_count, after_count):
|
||||||
"""构建完整的 diff 显示文本"""
|
"""构建完整的 diff 显示文本(带 ANSI 颜色)"""
|
||||||
sep = '═' * 70
|
sep = '═' * 70
|
||||||
thin_sep = '─' * 70
|
thin_sep = '─' * 70
|
||||||
|
|
||||||
|
# ANSI 颜色
|
||||||
|
R = '\033[31m' # 红
|
||||||
|
G = '\033[32m' # 绿
|
||||||
|
C = '\033[36m' # 青
|
||||||
|
B = '\033[1m' # 粗体
|
||||||
|
D = '\033[2m' # 暗
|
||||||
|
W = '\033[37m' # 白
|
||||||
|
N = '\033[0m' # 重置
|
||||||
|
|
||||||
|
# 构建带颜色的 diff
|
||||||
|
diff_colored_lines = []
|
||||||
|
for line in diff_lines:
|
||||||
|
if line.startswith('@@'):
|
||||||
|
diff_colored_lines.append(f"{C}{line}{N}")
|
||||||
|
elif line.startswith('+++') or line.startswith('---'):
|
||||||
|
diff_colored_lines.append(f"{B}{line}{N}")
|
||||||
|
elif line.startswith('+'):
|
||||||
|
diff_colored_lines.append(f"{G}{line}{N}")
|
||||||
|
elif line.startswith('-'):
|
||||||
|
diff_colored_lines.append(f"{R}{line}{N}")
|
||||||
|
else:
|
||||||
|
diff_colored_lines.append(line)
|
||||||
|
diff_colored = '\n'.join(diff_colored_lines) if diff_colored_lines else ' (无差异)'
|
||||||
|
|
||||||
display = f"""
|
display = f"""
|
||||||
{sep}
|
{W}{sep}{N}
|
||||||
文件变更对比: {basename}
|
{B} 文件变更对比: {basename}{N}
|
||||||
路径: {filepath}
|
{D} 路径: {filepath}{N}
|
||||||
{sep}
|
{W}{sep}{N}
|
||||||
|
|
||||||
统计: {before_count} 行 → {after_count} 行 | +{added} 新增 -{removed} 删除
|
统计: {before_count} 行 → {after_count} 行 | {G}+{added} 新增{N} {R}-{removed} 删除{N}
|
||||||
|
|
||||||
{thin_sep}
|
{W}{thin_sep}{N}
|
||||||
修改前 ({before_count} 行):
|
修改前 ({before_count} 行):
|
||||||
{thin_sep}
|
{W}{thin_sep}{N}
|
||||||
{before_numbered}
|
{before_numbered}
|
||||||
|
|
||||||
{thin_sep}
|
{W}{thin_sep}{N}
|
||||||
修改后 ({after_count} 行):
|
修改后 ({after_count} 行):
|
||||||
{thin_sep}
|
{W}{thin_sep}{N}
|
||||||
{after_numbered}
|
{after_numbered}
|
||||||
|
|
||||||
{thin_sep}
|
{W}{thin_sep}{N}
|
||||||
差异 (Diff):
|
差异 (Diff):
|
||||||
{thin_sep}
|
{W}{thin_sep}{N}
|
||||||
{diff_text if diff_text else ' (无差异)'}
|
{diff_colored}
|
||||||
|
|
||||||
{sep}
|
{W}{sep}{N}
|
||||||
按任意键关闭此窗口...
|
按任意键关闭此窗口...
|
||||||
{sep}
|
{W}{sep}{N}
|
||||||
"""
|
"""
|
||||||
return display
|
return display
|
||||||
|
|
||||||
@@ -775,8 +806,81 @@ else:
|
|||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"[Diff 弹窗] 创建失败: {e}")
|
print(f"[Diff 弹窗] 创建失败: {e}")
|
||||||
|
|
||||||
|
def _show_inline_diff(self, filepath: str, before: str, after: str):
|
||||||
|
"""在主终端内显示 diff(SSH 兼容模式),带颜色"""
|
||||||
|
basename = os.path.basename(filepath)
|
||||||
|
is_tui = self.cli and getattr(self.cli, 'tui_output_callback', None)
|
||||||
|
|
||||||
|
# 生成 diff
|
||||||
|
diff_lines = list(difflib.unified_diff(
|
||||||
|
before.splitlines(keepends=True),
|
||||||
|
after.splitlines(keepends=True),
|
||||||
|
fromfile=f"修改前: {basename}",
|
||||||
|
tofile=f"修改后: {basename}",
|
||||||
|
lineterm=''
|
||||||
|
))
|
||||||
|
|
||||||
|
# 统计
|
||||||
|
added = sum(1 for l in diff_lines if l.startswith('+') and not l.startswith('+++'))
|
||||||
|
removed = sum(1 for l in diff_lines if l.startswith('-') and not l.startswith('---'))
|
||||||
|
before_count = len(before.splitlines())
|
||||||
|
after_count = len(after.splitlines())
|
||||||
|
|
||||||
|
sep = '═' * 60
|
||||||
|
thin = '─' * 60
|
||||||
|
|
||||||
|
if is_tui:
|
||||||
|
# TUI 模式:使用 Rich 标记
|
||||||
|
output = self.cli._output
|
||||||
|
output(f"[dim]{sep}[/]")
|
||||||
|
output(f"[bold cyan] 文件变更: {basename}[/] [dim]{filepath}[/]")
|
||||||
|
output(f"[dim]{sep}[/]")
|
||||||
|
output(f"[bold] 统计: {before_count} 行 → {after_count} 行 | "
|
||||||
|
f"[green]+{added} 新增[/] [red]-{removed} 删除[/]")
|
||||||
|
output(f"[dim]{thin}[/]")
|
||||||
|
|
||||||
|
for line in diff_lines:
|
||||||
|
if line.startswith('@@'):
|
||||||
|
output(f"[cyan]{line}[/]")
|
||||||
|
elif line.startswith('+++') or line.startswith('---'):
|
||||||
|
output(f"[bold]{line}[/]")
|
||||||
|
elif line.startswith('+'):
|
||||||
|
output(f"[green]{line}[/]")
|
||||||
|
elif line.startswith('-'):
|
||||||
|
output(f"[red]{line}[/]")
|
||||||
|
else:
|
||||||
|
output(line)
|
||||||
|
|
||||||
|
output(f"[dim]{sep}[/]")
|
||||||
|
else:
|
||||||
|
# CLI 模式:使用 ANSI 颜色
|
||||||
|
from colorama import Fore, Style
|
||||||
|
_out = print
|
||||||
|
|
||||||
|
_out(f"{Fore.WHITE}{sep}{Style.RESET_ALL}")
|
||||||
|
_out(f"{Fore.CYAN} 文件变更: {basename}{Style.RESET_ALL} {filepath}")
|
||||||
|
_out(f"{Fore.WHITE}{sep}{Style.RESET_ALL}")
|
||||||
|
_out(f" 统计: {before_count} 行 → {after_count} 行 | "
|
||||||
|
f"{Fore.GREEN}+{added} 新增{Style.RESET_ALL} "
|
||||||
|
f"{Fore.RED}-{removed} 删除{Style.RESET_ALL}")
|
||||||
|
_out(f"{Fore.WHITE}{thin}{Style.RESET_ALL}")
|
||||||
|
|
||||||
|
for line in diff_lines:
|
||||||
|
if line.startswith('@@'):
|
||||||
|
_out(f"{Fore.CYAN}{line}{Style.RESET_ALL}")
|
||||||
|
elif line.startswith('+++') or line.startswith('---'):
|
||||||
|
_out(f"{Style.BRIGHT}{line}{Style.RESET_ALL}")
|
||||||
|
elif line.startswith('+'):
|
||||||
|
_out(f"{Fore.GREEN}{line}{Style.RESET_ALL}")
|
||||||
|
elif line.startswith('-'):
|
||||||
|
_out(f"{Fore.RED}{line}{Style.RESET_ALL}")
|
||||||
|
else:
|
||||||
|
_out(line)
|
||||||
|
|
||||||
|
_out(f"{Fore.WHITE}{sep}{Style.RESET_ALL}")
|
||||||
|
|
||||||
def _op_diff_popup(self, path: str, rest: str) -> str:
|
def _op_diff_popup(self, path: str, rest: str) -> str:
|
||||||
"""切换 diff 弹窗开关"""
|
"""切换 diff 弹窗开关 / 设置显示模式"""
|
||||||
arg = (path + ' ' + rest).strip().lower()
|
arg = (path + ' ' + rest).strip().lower()
|
||||||
if arg in ('on', '开', '开启', 'enable', '1', 'true'):
|
if arg in ('on', '开', '开启', 'enable', '1', 'true'):
|
||||||
self.diff_popup_enabled = True
|
self.diff_popup_enabled = True
|
||||||
@@ -784,6 +888,14 @@ else:
|
|||||||
elif arg in ('off', '关', '关闭', 'disable', '0', 'false'):
|
elif arg in ('off', '关', '关闭', 'disable', '0', 'false'):
|
||||||
self.diff_popup_enabled = False
|
self.diff_popup_enabled = False
|
||||||
return " Diff 弹窗已关闭"
|
return " Diff 弹窗已关闭"
|
||||||
|
elif arg in ('popup', '弹窗', '弹窗模式'):
|
||||||
|
self.diff_popup_enabled = True
|
||||||
|
self.diff_popup_mode = True
|
||||||
|
return " Diff 模式: 弹窗(新终端窗口)"
|
||||||
|
elif arg in ('inline', '内联', 'ssh', '终端', '主终端'):
|
||||||
|
self.diff_popup_enabled = True
|
||||||
|
self.diff_popup_mode = False
|
||||||
|
return " Diff 模式: 主终端内显示(SSH 兼容)"
|
||||||
else:
|
else:
|
||||||
# 无参数:切换状态
|
# 无参数:切换状态
|
||||||
self.diff_popup_enabled = not self.diff_popup_enabled
|
self.diff_popup_enabled = not self.diff_popup_enabled
|
||||||
|
|||||||
@@ -0,0 +1,459 @@
|
|||||||
|
"""
|
||||||
|
颜色工具插件 - 颜色格式转换、调色板、对比度检查
|
||||||
|
支持 HEX/RGB/HSL/HSV/CMYK 格式互转,WCAG 对比度检查
|
||||||
|
"""
|
||||||
|
|
||||||
|
import re
|
||||||
|
import colorsys
|
||||||
|
from typing import List, Tuple
|
||||||
|
|
||||||
|
|
||||||
|
class Liugin:
|
||||||
|
"""颜色工具 - 格式转换、调色板、对比度检查"""
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
self.usage = """颜色工具
|
||||||
|
|
||||||
|
操作:
|
||||||
|
convert <颜色> - 自动检测并转换为所有格式
|
||||||
|
hex <RGB或HSL> - 转换为 HEX
|
||||||
|
rgb <HEX或HSL> - 转换为 RGB
|
||||||
|
hsl <HEX或RGB> - 转换为 HSL
|
||||||
|
hsv <HEX或RGB> - 转换为 HSV
|
||||||
|
cmyk <HEX或RGB> - 转换为 CMYK
|
||||||
|
contrast <颜色1> <颜色2> - WCAG 对比度检查
|
||||||
|
palette <颜色> [-n 数量] - 生成调色板(明暗变体)
|
||||||
|
complementary <颜色> - 互补色
|
||||||
|
analogous <颜色> - 类似色
|
||||||
|
triadic <颜色> - 三色组
|
||||||
|
random [-n 数量] - 随机颜色
|
||||||
|
mix <颜色1> <颜色2> [-w 权重] - 混合两种颜色
|
||||||
|
blind <颜色> <类型> - 色盲模拟
|
||||||
|
named - 列出 CSS 命名颜色
|
||||||
|
|
||||||
|
颜色格式:
|
||||||
|
HEX: #FF6600, #F60, FF6600
|
||||||
|
RGB: rgb(255,102,0) 或 255,102,0
|
||||||
|
HSL: hsl(24,100%,50%)
|
||||||
|
HSV: hsv(24,100%,100%)
|
||||||
|
CMYK: cmyk(0,60,100,0)
|
||||||
|
|
||||||
|
示例:
|
||||||
|
color_picker convert "#3498db"
|
||||||
|
color_picker rgb "hsl(207,62%,54%)"
|
||||||
|
color_picker contrast "#FFFFFF" "#000000"
|
||||||
|
color_picker palette "#e74c3c" -n 9
|
||||||
|
color_picker complementary "#3498db"
|
||||||
|
"""
|
||||||
|
self.cli = None
|
||||||
|
|
||||||
|
def set_cli(self, cli):
|
||||||
|
self.cli = cli
|
||||||
|
|
||||||
|
def get_tool_info(self):
|
||||||
|
return {
|
||||||
|
"name": "color_picker",
|
||||||
|
"description": "颜色工具 - HEX/RGB/HSL/HSV/CMYK 转换、对比度检查、调色板生成",
|
||||||
|
"keywords": ["颜色", "color", "HEX", "RGB", "HSL", "调色板", "对比度", "色盲", "转换"],
|
||||||
|
"usage": self.usage
|
||||||
|
}
|
||||||
|
|
||||||
|
def get_mcp_definition(self):
|
||||||
|
return {
|
||||||
|
"name": "color_picker",
|
||||||
|
"description": "颜色工具,支持格式转换、对比度检查、调色板生成",
|
||||||
|
"inputSchema": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"operation": {
|
||||||
|
"type": "string",
|
||||||
|
"enum": ["convert", "hex", "rgb", "hsl", "hsv", "cmyk",
|
||||||
|
"contrast", "palette", "complementary", "analogous",
|
||||||
|
"triadic", "random", "mix", "blind"],
|
||||||
|
"description": "操作类型"
|
||||||
|
},
|
||||||
|
"color": {"type": "string", "description": "颜色值"},
|
||||||
|
"color2": {"type": "string", "description": "第二个颜色值"},
|
||||||
|
"count": {"type": "integer", "description": "数量"},
|
||||||
|
"weight": {"type": "number", "description": "混合权重 (0-1)"},
|
||||||
|
"blind_type": {"type": "string", "description": "色盲类型"}
|
||||||
|
},
|
||||||
|
"required": ["operation"]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
def convert_mcp_args(self, arguments):
|
||||||
|
op = arguments.get("operation", "")
|
||||||
|
color = arguments.get("color", "")
|
||||||
|
return f"{op} {color}".strip()
|
||||||
|
|
||||||
|
def handle(self, args: str) -> str:
|
||||||
|
try:
|
||||||
|
parts = self._parse_args(args)
|
||||||
|
if not parts:
|
||||||
|
return self._op_random(["1"])
|
||||||
|
|
||||||
|
operation = parts[0].lower()
|
||||||
|
handlers = {
|
||||||
|
"convert": self._op_convert,
|
||||||
|
"hex": self._op_hex,
|
||||||
|
"rgb": self._op_rgb,
|
||||||
|
"hsl": self._op_hsl,
|
||||||
|
"hsv": self._op_hsv,
|
||||||
|
"cmyk": self._op_cmyk,
|
||||||
|
"contrast": self._op_contrast,
|
||||||
|
"palette": self._op_palette,
|
||||||
|
"complementary": self._op_complementary,
|
||||||
|
"analogous": self._op_analogous,
|
||||||
|
"triadic": self._op_triadic,
|
||||||
|
"random": self._op_random,
|
||||||
|
"mix": self._op_mix,
|
||||||
|
"blind": self._op_blind,
|
||||||
|
}
|
||||||
|
|
||||||
|
handler = handlers.get(operation)
|
||||||
|
if not handler:
|
||||||
|
return f"错误:不支持的操作 '{operation}'"
|
||||||
|
return handler(parts[1:])
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
return f"颜色工具错误: {str(e)}"
|
||||||
|
|
||||||
|
def _parse_args(self, args: str) -> List[str]:
|
||||||
|
parts, current, in_quotes, qc = [], "", False, None
|
||||||
|
for ch in args:
|
||||||
|
if ch in ('"', "'") and not in_quotes:
|
||||||
|
in_quotes, qc = True, ch
|
||||||
|
elif ch == qc and in_quotes:
|
||||||
|
in_quotes, qc = False, None
|
||||||
|
elif ch == ' ' and not in_quotes:
|
||||||
|
if current:
|
||||||
|
parts.append(current)
|
||||||
|
current = ""
|
||||||
|
else:
|
||||||
|
current += ch
|
||||||
|
if current:
|
||||||
|
parts.append(current)
|
||||||
|
return parts
|
||||||
|
|
||||||
|
def _parse_opts(self, args: List[str]) -> dict:
|
||||||
|
opts = {}
|
||||||
|
i = 0
|
||||||
|
while i < len(args):
|
||||||
|
if args[i].startswith("-") and i + 1 < len(args):
|
||||||
|
key = args[i].lstrip("-")
|
||||||
|
opts[key] = args[i + 1]
|
||||||
|
i += 1
|
||||||
|
i += 1
|
||||||
|
return opts
|
||||||
|
|
||||||
|
def _parse_color(self, color_str: str) -> Tuple[int, int, int]:
|
||||||
|
"""解析颜色字符串为 RGB (0-255)"""
|
||||||
|
s = color_str.strip().lower()
|
||||||
|
|
||||||
|
# HEX
|
||||||
|
hex_match = re.match(r'^#?([0-9a-f]{3,8})$', s)
|
||||||
|
if hex_match:
|
||||||
|
h = hex_match.group(1)
|
||||||
|
if len(h) == 3:
|
||||||
|
h = h[0]*2 + h[1]*2 + h[2]*2
|
||||||
|
elif len(h) == 8:
|
||||||
|
h = h[:6] # ignore alpha
|
||||||
|
if len(h) == 6:
|
||||||
|
return (int(h[0:2], 16), int(h[2:4], 16), int(h[4:6], 16))
|
||||||
|
|
||||||
|
# RGB
|
||||||
|
rgb_match = re.match(r'rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)', s)
|
||||||
|
if rgb_match:
|
||||||
|
return (int(rgb_match.group(1)), int(rgb_match.group(2)), int(rgb_match.group(3)))
|
||||||
|
|
||||||
|
# plain r,g,b
|
||||||
|
plain_match = re.match(r'^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)$', s)
|
||||||
|
if plain_match:
|
||||||
|
return (int(plain_match.group(1)), int(plain_match.group(2)), int(plain_match.group(3)))
|
||||||
|
|
||||||
|
# HSL
|
||||||
|
hsl_match = re.match(r'hsl\s*\(\s*(\d+)\s*,\s*(\d+)%,\s*(\d+)%\s*\)', s)
|
||||||
|
if hsl_match:
|
||||||
|
h = int(hsl_match.group(1)) / 360
|
||||||
|
sl = int(hsl_match.group(2)) / 100
|
||||||
|
l = int(hsl_match.group(3)) / 100
|
||||||
|
r, g, b = colorsys.hls_to_rgb(h, l, sl)
|
||||||
|
return (int(r * 255), int(g * 255), int(b * 255))
|
||||||
|
|
||||||
|
# HSV/HSB
|
||||||
|
hsv_match = re.match(r'hsv\s*\(\s*(\d+)\s*,\s*(\d+)%,\s*(\d+)%\s*\)', s)
|
||||||
|
if hsv_match:
|
||||||
|
h = int(hsv_match.group(1)) / 360
|
||||||
|
sv = int(hsv_match.group(2)) / 100
|
||||||
|
v = int(hsv_match.group(3)) / 100
|
||||||
|
r, g, b = colorsys.hsv_to_rgb(h, sv, v)
|
||||||
|
return (int(r * 255), int(g * 255), int(b * 255))
|
||||||
|
|
||||||
|
# CMYK
|
||||||
|
cmyk_match = re.match(r'cmyk\s*\(\s*(\d+)%?\s*,\s*(\d+)%?\s*,\s*(\d+)%?\s*,\s*(\d+)%?\s*\)', s)
|
||||||
|
if cmyk_match:
|
||||||
|
c = int(cmyk_match.group(1)) / 100
|
||||||
|
m = int(cmyk_match.group(2)) / 100
|
||||||
|
y = int(cmyk_match.group(3)) / 100
|
||||||
|
k = int(cmyk_match.group(4)) / 100
|
||||||
|
r = int(255 * (1 - c) * (1 - k))
|
||||||
|
g = int(255 * (1 - m) * (1 - k))
|
||||||
|
b = int(255 * (1 - y) * (1 - k))
|
||||||
|
return (r, g, b)
|
||||||
|
|
||||||
|
raise ValueError(f"无法解析颜色: {color_str}")
|
||||||
|
|
||||||
|
def _rgb_to_hex(self, r: int, g: int, b: int) -> str:
|
||||||
|
return f"#{r:02X}{g:02X}{b:02X}"
|
||||||
|
|
||||||
|
def _rgb_to_hsl(self, r: int, g: int, b: int) -> Tuple[int, int, int]:
|
||||||
|
h, l, s = colorsys.rgb_to_hls(r / 255, g / 255, b / 255)
|
||||||
|
return (int(h * 360), int(s * 100), int(l * 100))
|
||||||
|
|
||||||
|
def _rgb_to_hsv(self, r: int, g: int, b: int) -> Tuple[int, int, int]:
|
||||||
|
h, s, v = colorsys.rgb_to_hsv(r / 255, g / 255, b / 255)
|
||||||
|
return (int(h * 360), int(s * 100), int(v * 100))
|
||||||
|
|
||||||
|
def _rgb_to_cmyk(self, r: int, g: int, b: int) -> Tuple[int, int, int, int]:
|
||||||
|
if r == g == b == 0:
|
||||||
|
return (0, 0, 0, 100)
|
||||||
|
c = 1 - r / 255
|
||||||
|
m = 1 - g / 255
|
||||||
|
y = 1 - b / 255
|
||||||
|
k = min(c, m, y)
|
||||||
|
c = int((c - k) / (1 - k) * 100)
|
||||||
|
m = int((m - k) / (1 - k) * 100)
|
||||||
|
y = int((y - k) / (1 - k) * 100)
|
||||||
|
k = int(k * 100)
|
||||||
|
return (c, m, y, k)
|
||||||
|
|
||||||
|
def _luminance(self, r: int, g: int, b: int) -> float:
|
||||||
|
"""计算相对亮度 (WCAG 2.0)"""
|
||||||
|
def linearize(c):
|
||||||
|
c = c / 255
|
||||||
|
return c / 12.92 if c <= 0.03928 else ((c + 0.055) / 1.055) ** 2.4
|
||||||
|
return 0.2126 * linearize(r) + 0.7152 * linearize(g) + 0.0722 * linearize(b)
|
||||||
|
|
||||||
|
def _format_color_block(self, r: int, g: int, b: int) -> str:
|
||||||
|
"""生成颜色预览块"""
|
||||||
|
return f" ■ RGB({r}, {g}, {b})"
|
||||||
|
|
||||||
|
def _op_convert(self, args: List[str]) -> str:
|
||||||
|
if not args:
|
||||||
|
return "错误:请提供颜色值"
|
||||||
|
r, g, b = self._parse_color(args[0])
|
||||||
|
h, s, l = self._rgb_to_hsl(r, g, b)
|
||||||
|
hh, sv, vv = self._rgb_to_hsv(r, g, b)
|
||||||
|
c, m, y, k = self._rgb_to_cmyk(r, g, b)
|
||||||
|
|
||||||
|
result = f" 颜色转换: {args[0]}\n"
|
||||||
|
result += self._format_color_block(r, g, b) + "\n"
|
||||||
|
result += "─" * 35 + "\n"
|
||||||
|
result += f" HEX: {self._rgb_to_hex(r, g, b)}\n"
|
||||||
|
result += f" RGB: rgb({r}, {g}, {b})\n"
|
||||||
|
result += f" HSL: hsl({h}, {s}%, {l}%)\n"
|
||||||
|
result += f" HSV: hsv({hh}, {sv}%, {vv}%)\n"
|
||||||
|
result += f" CMYK: cmyk({c}%, {m}%, {y}%, {k}%)\n"
|
||||||
|
return result.rstrip()
|
||||||
|
|
||||||
|
def _op_hex(self, args: List[str]) -> str:
|
||||||
|
if not args:
|
||||||
|
return "错误:请提供颜色值"
|
||||||
|
r, g, b = self._parse_color(args[0])
|
||||||
|
return f" HEX: {self._rgb_to_hex(r, g, b)}"
|
||||||
|
|
||||||
|
def _op_rgb(self, args: List[str]) -> str:
|
||||||
|
if not args:
|
||||||
|
return "错误:请提供颜色值"
|
||||||
|
r, g, b = self._parse_color(args[0])
|
||||||
|
return f" RGB: rgb({r}, {g}, {b})"
|
||||||
|
|
||||||
|
def _op_hsl(self, args: List[str]) -> str:
|
||||||
|
if not args:
|
||||||
|
return "错误:请提供颜色值"
|
||||||
|
r, g, b = self._parse_color(args[0])
|
||||||
|
h, s, l = self._rgb_to_hsl(r, g, b)
|
||||||
|
return f" HSL: hsl({h}, {s}%, {l}%)"
|
||||||
|
|
||||||
|
def _op_hsv(self, args: List[str]) -> str:
|
||||||
|
if not args:
|
||||||
|
return "错误:请提供颜色值"
|
||||||
|
r, g, b = self._parse_color(args[0])
|
||||||
|
h, s, v = self._rgb_to_hsv(r, g, b)
|
||||||
|
return f" HSV: hsv({h}, {s}%, {v}%)"
|
||||||
|
|
||||||
|
def _op_cmyk(self, args: List[str]) -> str:
|
||||||
|
if not args:
|
||||||
|
return "错误:请提供颜色值"
|
||||||
|
r, g, b = self._parse_color(args[0])
|
||||||
|
c, m, y, k = self._rgb_to_cmyk(r, g, b)
|
||||||
|
return f" CMYK: cmyk({c}%, {m}%, {y}%, {k}%)"
|
||||||
|
|
||||||
|
def _op_contrast(self, args: List[str]) -> str:
|
||||||
|
if len(args) < 2:
|
||||||
|
return "错误:请提供两种颜色"
|
||||||
|
r1, g1, b1 = self._parse_color(args[0])
|
||||||
|
r2, g2, b2 = self._parse_color(args[1])
|
||||||
|
|
||||||
|
l1 = self._luminance(r1, g1, b1)
|
||||||
|
l2 = self._luminance(r2, g2, b2)
|
||||||
|
lighter = max(l1, l2)
|
||||||
|
darker = min(l1, l2)
|
||||||
|
ratio = (lighter + 0.05) / (darker + 0.05)
|
||||||
|
|
||||||
|
aa_large = ratio >= 3
|
||||||
|
aa_normal = ratio >= 4.5
|
||||||
|
aaa_large = ratio >= 4.5
|
||||||
|
aaa_normal = ratio >= 7
|
||||||
|
|
||||||
|
result = f" WCAG 对比度检查\n"
|
||||||
|
result += "─" * 40 + "\n"
|
||||||
|
result += f" 颜色1: {self._rgb_to_hex(r1, g1, b1)} {self._format_color_block(r1, g1, b1)}\n"
|
||||||
|
result += f" 颜色2: {self._rgb_to_hex(r2, g2, b2)} {self._format_color_block(r2, g2, b1)}\n"
|
||||||
|
result += f" 对比度: {ratio:.2f}:1\n"
|
||||||
|
result += "─" * 40 + "\n"
|
||||||
|
result += f" {' ' if aa_normal else '❌'} AA 正文 (≥4.5:1)\n"
|
||||||
|
result += f" {' ' if aa_large else '❌'} AA 大字 (≥3:1)\n"
|
||||||
|
result += f" {' ' if aaa_normal else '❌'} AAA 正文 (≥7:1)\n"
|
||||||
|
result += f" {' ' if aaa_large else '❌'} AAA 大字 (≥4.5:1)\n"
|
||||||
|
return result.rstrip()
|
||||||
|
|
||||||
|
def _op_palette(self, args: List[str]) -> str:
|
||||||
|
if not args:
|
||||||
|
return "错误:请提供基础颜色"
|
||||||
|
r, g, b = self._parse_color(args[0])
|
||||||
|
opts = self._parse_opts(args[1:])
|
||||||
|
count = int(opts.get("n", 9))
|
||||||
|
count = max(3, min(count, 15))
|
||||||
|
|
||||||
|
h, l, s = colorsys.rgb_to_hls(r / 255, g / 255, b / 255)
|
||||||
|
|
||||||
|
result = f" 调色板 (基于 {args[0]}):\n"
|
||||||
|
result += "─" * 50 + "\n"
|
||||||
|
|
||||||
|
steps = count
|
||||||
|
for i in range(steps):
|
||||||
|
# 从暗到亮
|
||||||
|
new_l = 0.1 + (0.8 * i / (steps - 1))
|
||||||
|
nr, ng, nb = colorsys.hls_to_rgb(h, new_l, s)
|
||||||
|
nr, ng, nb = int(nr * 255), int(ng * 255), int(nb * 255)
|
||||||
|
hex_val = self._rgb_to_hex(nr, ng, nb)
|
||||||
|
bar = "█" * int(new_l * 20)
|
||||||
|
result += f" {hex_val} {bar} L:{int(new_l*100)}%\n"
|
||||||
|
|
||||||
|
return result.rstrip()
|
||||||
|
|
||||||
|
def _op_complementary(self, args: List[str]) -> str:
|
||||||
|
if not args:
|
||||||
|
return "错误:请提供颜色"
|
||||||
|
r, g, b = self._parse_color(args[0])
|
||||||
|
h, l, s = colorsys.rgb_to_hls(r / 255, g / 255, b / 255)
|
||||||
|
# 互补色: 色相旋转180°
|
||||||
|
comp_h = (h + 0.5) % 1.0
|
||||||
|
cr, cg, cb = colorsys.hls_to_rgb(comp_h, l, s)
|
||||||
|
cr, cg, cb = int(cr * 255), int(cg * 255), int(cb * 255)
|
||||||
|
|
||||||
|
result = f" 互补色:\n"
|
||||||
|
result += f" 原色: {self._rgb_to_hex(r, g, b)}\n"
|
||||||
|
result += f" 互补: {self._rgb_to_hex(cr, cg, cb)}\n"
|
||||||
|
return result
|
||||||
|
|
||||||
|
def _op_analogous(self, args: List[str]) -> str:
|
||||||
|
if not args:
|
||||||
|
return "错误:请提供颜色"
|
||||||
|
r, g, b = self._parse_color(args[0])
|
||||||
|
h, l, s = colorsys.rgb_to_hls(r / 255, g / 255, b / 255)
|
||||||
|
|
||||||
|
result = f" 类似色:\n"
|
||||||
|
for offset in [-30, -15, 0, 15, 30]:
|
||||||
|
ah = (h + offset / 360) % 1.0
|
||||||
|
ar, ag, ab = colorsys.hls_to_rgb(ah, l, s)
|
||||||
|
ar, ag, ab = int(ar * 255), int(ag * 255), int(ab * 255)
|
||||||
|
marker = " ◀" if offset == 0 else ""
|
||||||
|
result += f" {self._rgb_to_hex(ar, ag, ab)} ({offset:+d}°){marker}\n"
|
||||||
|
return result.rstrip()
|
||||||
|
|
||||||
|
def _op_triadic(self, args: List[str]) -> str:
|
||||||
|
if not args:
|
||||||
|
return "错误:请提供颜色"
|
||||||
|
r, g, b = self._parse_color(args[0])
|
||||||
|
h, l, s = colorsys.rgb_to_hls(r / 255, g / 255, b / 255)
|
||||||
|
|
||||||
|
result = f" 三色组:\n"
|
||||||
|
for i, offset in enumerate([0, 120, 240]):
|
||||||
|
th = (h + offset / 360) % 1.0
|
||||||
|
tr, tg, tb = colorsys.hls_to_rgb(th, l, s)
|
||||||
|
tr, tg, tb = int(tr * 255), int(tg * 255), int(tb * 255)
|
||||||
|
result += f" {i+1}. {self._rgb_to_hex(tr, tg, tb)} ({offset}°)\n"
|
||||||
|
return result.rstrip()
|
||||||
|
|
||||||
|
def _op_random(self, args: List[str]) -> str:
|
||||||
|
opts = self._parse_opts(args)
|
||||||
|
count = int(opts.get("n", 5))
|
||||||
|
count = min(count, 20)
|
||||||
|
|
||||||
|
result = f" 随机颜色 ({count} 个):\n"
|
||||||
|
for _ in range(count):
|
||||||
|
r, g, b = __import__('random').randint(0, 255), __import__('random').randint(0, 255), __import__('random').randint(0, 255)
|
||||||
|
result += f" {self._rgb_to_hex(r, g, b)} rgb({r}, {g}, {b})\n"
|
||||||
|
return result.rstrip()
|
||||||
|
|
||||||
|
def _op_mix(self, args: List[str]) -> str:
|
||||||
|
if len(args) < 2:
|
||||||
|
return "错误:请提供两种颜色"
|
||||||
|
r1, g1, b1 = self._parse_color(args[0])
|
||||||
|
r2, g2, b2 = self._parse_color(args[1])
|
||||||
|
opts = self._parse_opts(args[2:])
|
||||||
|
w = float(opts.get("w", 0.5))
|
||||||
|
w = max(0, min(1, w))
|
||||||
|
|
||||||
|
mr = int(r1 * (1 - w) + r2 * w)
|
||||||
|
mg = int(g1 * (1 - w) + g2 * w)
|
||||||
|
mb = int(b1 * (1 - w) + b2 * w)
|
||||||
|
|
||||||
|
result = f" 颜色混合 (权重 {w}):\n"
|
||||||
|
result += f" 颜色1: {self._rgb_to_hex(r1, g1, b1)}\n"
|
||||||
|
result += f" 颜色2: {self._rgb_to_hex(r2, g2, b2)}\n"
|
||||||
|
result += f" 混合: {self._rgb_to_hex(mr, mg, mb)}\n"
|
||||||
|
return result
|
||||||
|
|
||||||
|
def _op_blind(self, args: List[str]) -> str:
|
||||||
|
if len(args) < 2:
|
||||||
|
return "错误:请提供颜色和色盲类型\n类型: protanopia, deuteranopia, tritanopia"
|
||||||
|
r, g, b = self._parse_color(args[0])
|
||||||
|
blind_type = args[1].lower()
|
||||||
|
|
||||||
|
# 简化的色盲模拟矩阵
|
||||||
|
matrices = {
|
||||||
|
"protanopia": [[0.567, 0.433, 0.0], [0.558, 0.442, 0.0], [0.0, 0.242, 0.758]],
|
||||||
|
"deuteranopia": [[0.625, 0.375, 0.0], [0.7, 0.3, 0.0], [0.0, 0.3, 0.7]],
|
||||||
|
"tritanopia": [[0.95, 0.05, 0.0], [0.0, 0.433, 0.567], [0.0, 0.475, 0.525]],
|
||||||
|
}
|
||||||
|
|
||||||
|
matrix = matrices.get(blind_type)
|
||||||
|
if not matrix:
|
||||||
|
return f"错误:未知类型 '{blind_type}'\n支持: protanopia, deuteranopia, tritanopia"
|
||||||
|
|
||||||
|
nr = int(matrix[0][0] * r + matrix[0][1] * g + matrix[0][2] * b)
|
||||||
|
ng = int(matrix[1][0] * r + matrix[1][1] * g + matrix[1][2] * b)
|
||||||
|
nb = int(matrix[2][0] * r + matrix[2][1] * g + matrix[2][2] * b)
|
||||||
|
nr, ng, nb = max(0, min(255, nr)), max(0, min(255, ng)), max(0, min(255, nb))
|
||||||
|
|
||||||
|
result = f" 色盲模拟 ({blind_type}):\n"
|
||||||
|
result += f" 原色: {self._rgb_to_hex(r, g, b)}\n"
|
||||||
|
result += f" 模拟: {self._rgb_to_hex(nr, ng, nb)}\n"
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def test_plugin():
|
||||||
|
plugin = Liugin()
|
||||||
|
print("颜色工具测试:")
|
||||||
|
print(plugin.handle('convert "#3498db"'))
|
||||||
|
print(plugin.handle('contrast "#FFFFFF" "#000000"'))
|
||||||
|
print(plugin.handle('palette "#e74c3c" -n 7'))
|
||||||
|
print(plugin.handle('complementary "#3498db"'))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
test_plugin()
|
||||||
@@ -10,7 +10,7 @@ from pathlib import Path
|
|||||||
from typing import List
|
from typing import List
|
||||||
|
|
||||||
|
|
||||||
class Plugin:
|
class Liugin:
|
||||||
"""文件管理器 - 文件和目录的增删改查"""
|
"""文件管理器 - 文件和目录的增删改查"""
|
||||||
|
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
|
|||||||
@@ -443,7 +443,7 @@ JSON格式示例:
|
|||||||
# 测试函数
|
# 测试函数
|
||||||
def test_plugin():
|
def test_plugin():
|
||||||
"""测试插件功能"""
|
"""测试插件功能"""
|
||||||
plugin = Plugin()
|
plugin = Liugin()
|
||||||
print("前端测试验证插件测试:")
|
print("前端测试验证插件测试:")
|
||||||
|
|
||||||
print("\n1. 创建测试HTML文件:")
|
print("\n1. 创建测试HTML文件:")
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import subprocess
|
|||||||
from typing import Tuple, Optional
|
from typing import Tuple, Optional
|
||||||
|
|
||||||
|
|
||||||
class Plugin:
|
class Liugin:
|
||||||
"""Git 版本控制 - 基础操作 + 工作流自动化"""
|
"""Git 版本控制 - 基础操作 + 工作流自动化"""
|
||||||
|
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
|
|||||||
+1036
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,383 @@
|
|||||||
|
"""
|
||||||
|
UUID / ID 生成器插件 - 生成各种格式的唯一标识符
|
||||||
|
支持 UUID v1/v4/v5、NanoID、短ID、雪花ID、自定义格式
|
||||||
|
"""
|
||||||
|
|
||||||
|
import uuid
|
||||||
|
import hashlib
|
||||||
|
import time
|
||||||
|
import random
|
||||||
|
import string
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import struct
|
||||||
|
from datetime import datetime
|
||||||
|
from typing import List
|
||||||
|
|
||||||
|
|
||||||
|
class Liugin:
|
||||||
|
"""UUID / ID 生成器 - 多格式唯一标识符生成"""
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
self.usage = """UUID / ID 生成器
|
||||||
|
|
||||||
|
操作:
|
||||||
|
uuid [-v 版本] [-n 数量] - 生成 UUID(默认 v4)
|
||||||
|
v1=时间戳 v4=随机 v5=命名
|
||||||
|
nanoid [-s 长度] [-n 数量] - 生成 NanoID(默认21位)
|
||||||
|
short [-s 长度] [-n 数量] - 生成短ID(默认8位)
|
||||||
|
snowflake [-n 数量] - 生成雪花ID(时间排序)
|
||||||
|
custom <模板> [-n 数量] - 自定义格式生成
|
||||||
|
模板: {U}=大写字母 {L}=小写 {D}=数字 {X}=十六进制
|
||||||
|
ulid [-n 数量] - 生成 ULID(时间排序+随机)
|
||||||
|
timestamp - 当前时间戳(秒/毫秒/微秒)
|
||||||
|
from_name <命名空间> <名称> - 基于名称生成确定性 UUID (v5)
|
||||||
|
batch <类型> [-n 数量] [-o 文件] - 批量生成并保存到文件
|
||||||
|
|
||||||
|
示例:
|
||||||
|
id_generator uuid
|
||||||
|
id_generator uuid -v 1 -n 5
|
||||||
|
id_generator nanoid -s 16
|
||||||
|
id_generator short -s 6 -n 10
|
||||||
|
id_generator custom "USER-{D}{D}{D}{D}{U}{U}" -n 5
|
||||||
|
id_generator snowflake -n 3
|
||||||
|
id_generator batch uuid -n 100 -o ids.txt
|
||||||
|
"""
|
||||||
|
self.cli = None
|
||||||
|
self._machine_id = random.randint(0, 1023)
|
||||||
|
self._sequence = 0
|
||||||
|
self._last_ts = 0
|
||||||
|
|
||||||
|
def set_cli(self, cli):
|
||||||
|
self.cli = cli
|
||||||
|
|
||||||
|
def get_tool_info(self):
|
||||||
|
return {
|
||||||
|
"name": "id_generator",
|
||||||
|
"description": "UUID/ID 生成器 - 支持 UUID、NanoID、短ID、雪花ID、ULID、自定义格式",
|
||||||
|
"keywords": ["uuid", "id", "生成", "唯一", "标识", "nanoid", "snowflake", "ulid", "短id"],
|
||||||
|
"usage": self.usage
|
||||||
|
}
|
||||||
|
|
||||||
|
def get_mcp_definition(self):
|
||||||
|
return {
|
||||||
|
"name": "id_generator",
|
||||||
|
"description": "UUID/ID 生成器,支持多种格式",
|
||||||
|
"inputSchema": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"operation": {
|
||||||
|
"type": "string",
|
||||||
|
"enum": ["uuid", "nanoid", "short", "snowflake", "custom",
|
||||||
|
"ulid", "timestamp", "from_name", "batch"],
|
||||||
|
"description": "操作类型"
|
||||||
|
},
|
||||||
|
"version": {"type": "integer", "description": "UUID 版本 (1/4/5)"},
|
||||||
|
"length": {"type": "integer", "description": "ID 长度"},
|
||||||
|
"count": {"type": "integer", "description": "生成数量"},
|
||||||
|
"template": {"type": "string", "description": "自定义模板"},
|
||||||
|
"namespace": {"type": "string", "description": "命名空间"},
|
||||||
|
"name": {"type": "string", "description": "名称"},
|
||||||
|
"output": {"type": "string", "description": "输出文件"}
|
||||||
|
},
|
||||||
|
"required": ["operation"]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
def convert_mcp_args(self, arguments):
|
||||||
|
op = arguments.get("operation", "")
|
||||||
|
count = arguments.get("count", "")
|
||||||
|
parts = [op]
|
||||||
|
if count:
|
||||||
|
parts.extend(["-n", str(count)])
|
||||||
|
return " ".join(parts)
|
||||||
|
|
||||||
|
def handle(self, args: str) -> str:
|
||||||
|
try:
|
||||||
|
parts = self._parse_args(args)
|
||||||
|
if not parts:
|
||||||
|
return self._op_uuid([])
|
||||||
|
|
||||||
|
operation = parts[0].lower()
|
||||||
|
handlers = {
|
||||||
|
"uuid": self._op_uuid,
|
||||||
|
"nanoid": self._op_nanoid,
|
||||||
|
"short": self._op_short,
|
||||||
|
"snowflake": self._op_snowflake,
|
||||||
|
"custom": self._op_custom,
|
||||||
|
"ulid": self._op_ulid,
|
||||||
|
"timestamp": self._op_timestamp,
|
||||||
|
"from_name": self._op_from_name,
|
||||||
|
"batch": self._op_batch,
|
||||||
|
}
|
||||||
|
|
||||||
|
handler = handlers.get(operation)
|
||||||
|
if not handler:
|
||||||
|
return f"错误:不支持的操作 '{operation}'"
|
||||||
|
return handler(parts[1:])
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
return f"ID 生成错误: {str(e)}"
|
||||||
|
|
||||||
|
def _parse_args(self, args: str) -> List[str]:
|
||||||
|
parts, current, in_quotes, qc = [], "", False, None
|
||||||
|
for ch in args:
|
||||||
|
if ch in ('"', "'") and not in_quotes:
|
||||||
|
in_quotes, qc = True, ch
|
||||||
|
elif ch == qc and in_quotes:
|
||||||
|
in_quotes, qc = False, None
|
||||||
|
elif ch == ' ' and not in_quotes:
|
||||||
|
if current:
|
||||||
|
parts.append(current)
|
||||||
|
current = ""
|
||||||
|
else:
|
||||||
|
current += ch
|
||||||
|
if current:
|
||||||
|
parts.append(current)
|
||||||
|
return parts
|
||||||
|
|
||||||
|
def _parse_opts(self, args: List[str]) -> dict:
|
||||||
|
opts = {}
|
||||||
|
i = 0
|
||||||
|
while i < len(args):
|
||||||
|
if args[i].startswith("-") and i + 1 < len(args):
|
||||||
|
key = args[i].lstrip("-")
|
||||||
|
opts[key] = args[i + 1]
|
||||||
|
i += 1
|
||||||
|
i += 1
|
||||||
|
return opts
|
||||||
|
|
||||||
|
def _op_uuid(self, args: List[str]) -> str:
|
||||||
|
opts = self._parse_opts(args)
|
||||||
|
version = int(opts.get("v", 4))
|
||||||
|
count = int(opts.get("n", 1))
|
||||||
|
count = min(count, 1000)
|
||||||
|
|
||||||
|
ids = []
|
||||||
|
for _ in range(count):
|
||||||
|
if version == 1:
|
||||||
|
ids.append(str(uuid.uuid1()))
|
||||||
|
elif version == 4:
|
||||||
|
ids.append(str(uuid.uuid4()))
|
||||||
|
elif version == 5:
|
||||||
|
ids.append(str(uuid.uuid5(uuid.NAMESPACE_DNS, "example.com")))
|
||||||
|
else:
|
||||||
|
return f"错误:不支持的 UUID 版本: {version}"
|
||||||
|
|
||||||
|
header = f" UUID v{version} ({count} 个):\n"
|
||||||
|
if count <= 20:
|
||||||
|
return header + "\n".join(f" {u}" for u in ids)
|
||||||
|
else:
|
||||||
|
return header + "\n".join(f" {u}" for u in ids[:10]) + f"\n ... (共 {count} 个)"
|
||||||
|
|
||||||
|
def _op_nanoid(self, args: List[str]) -> str:
|
||||||
|
opts = self._parse_opts(args)
|
||||||
|
size = int(opts.get("s", 21))
|
||||||
|
count = int(opts.get("n", 1))
|
||||||
|
count = min(count, 1000)
|
||||||
|
|
||||||
|
alphabet = string.ascii_letters + string.digits + "_-"
|
||||||
|
ids = []
|
||||||
|
for _ in range(count):
|
||||||
|
ids.append(''.join(random.choices(alphabet, k=size)))
|
||||||
|
|
||||||
|
header = f" NanoID (长度 {size}, {count} 个):\n"
|
||||||
|
if count <= 20:
|
||||||
|
return header + "\n".join(f" {i}" for i in ids)
|
||||||
|
else:
|
||||||
|
return header + "\n".join(f" {i}" for i in ids[:10]) + f"\n ... (共 {count} 个)"
|
||||||
|
|
||||||
|
def _op_short(self, args: List[str]) -> str:
|
||||||
|
opts = self._parse_opts(args)
|
||||||
|
size = int(opts.get("s", 8))
|
||||||
|
count = int(opts.get("n", 1))
|
||||||
|
count = min(count, 1000)
|
||||||
|
|
||||||
|
chars = string.ascii_letters + string.digits
|
||||||
|
ids = []
|
||||||
|
for _ in range(count):
|
||||||
|
ids.append(''.join(random.choices(chars, k=size)))
|
||||||
|
|
||||||
|
header = f" 短ID (长度 {size}, {count} 个):\n"
|
||||||
|
if count <= 20:
|
||||||
|
return header + "\n".join(f" {i}" for i in ids)
|
||||||
|
else:
|
||||||
|
return header + "\n".join(f" {i}" for i in ids[:10]) + f"\n ... (共 {count} 个)"
|
||||||
|
|
||||||
|
def _op_snowflake(self, args: List[str]) -> str:
|
||||||
|
opts = self._parse_opts(args)
|
||||||
|
count = int(opts.get("n", 1))
|
||||||
|
count = min(count, 1000)
|
||||||
|
|
||||||
|
# Twitter Snowflake: 41位时间戳 + 10位机器ID + 12位序列号
|
||||||
|
epoch = 1288834974657 # Twitter epoch (2010-11-04)
|
||||||
|
|
||||||
|
ids = []
|
||||||
|
for _ in range(count):
|
||||||
|
ts = int(time.time() * 1000) - epoch
|
||||||
|
if ts == self._last_ts:
|
||||||
|
self._sequence = (self._sequence + 1) & 0xFFF
|
||||||
|
if self._sequence == 0:
|
||||||
|
while ts <= self._last_ts:
|
||||||
|
ts = int(time.time() * 1000) - epoch
|
||||||
|
else:
|
||||||
|
self._sequence = 0
|
||||||
|
self._last_ts = ts
|
||||||
|
|
||||||
|
snowflake_id = (ts << 22) | (self._machine_id << 12) | self._sequence
|
||||||
|
ids.append(str(snowflake_id))
|
||||||
|
|
||||||
|
header = f"❄️ 雪花ID ({count} 个):\n"
|
||||||
|
if count <= 20:
|
||||||
|
return header + "\n".join(f" {i}" for i in ids)
|
||||||
|
else:
|
||||||
|
return header + "\n".join(f" {i}" for i in ids[:10]) + f"\n ... (共 {count} 个)"
|
||||||
|
|
||||||
|
def _op_custom(self, args: List[str]) -> str:
|
||||||
|
if not args:
|
||||||
|
return "错误:请提供模板\n示例: custom \"ORDER-{D}{D}{D}{D}-{U}{U}{U}\""
|
||||||
|
template = args[0]
|
||||||
|
opts = self._parse_opts(args[1:])
|
||||||
|
count = int(opts.get("n", 1))
|
||||||
|
count = min(count, 1000)
|
||||||
|
|
||||||
|
ids = []
|
||||||
|
for _ in range(count):
|
||||||
|
result = []
|
||||||
|
for ch in template:
|
||||||
|
if ch == '{':
|
||||||
|
continue # handled below
|
||||||
|
result.append(ch)
|
||||||
|
# Actually use proper template parsing
|
||||||
|
ids.append(self._expand_template(template))
|
||||||
|
|
||||||
|
header = f" ️ 自定义ID (模板: {template}, {count} 个):\n"
|
||||||
|
if count <= 20:
|
||||||
|
return header + "\n".join(f" {i}" for i in ids)
|
||||||
|
else:
|
||||||
|
return header + "\n".join(f" {i}" for i in ids[:10]) + f"\n ... (共 {count} 个)"
|
||||||
|
|
||||||
|
def _expand_template(self, template: str) -> str:
|
||||||
|
result = []
|
||||||
|
i = 0
|
||||||
|
while i < len(template):
|
||||||
|
if template[i] == '{' and i + 2 < len(template) and template[i + 2] == '}':
|
||||||
|
token = template[i + 1]
|
||||||
|
if token == 'U':
|
||||||
|
result.append(random.choice(string.ascii_uppercase))
|
||||||
|
elif token == 'L':
|
||||||
|
result.append(random.choice(string.ascii_lowercase))
|
||||||
|
elif token == 'D':
|
||||||
|
result.append(random.choice(string.digits))
|
||||||
|
elif token == 'X':
|
||||||
|
result.append(random.choice('0123456789ABCDEF'))
|
||||||
|
elif token == 'x':
|
||||||
|
result.append(random.choice('0123456789abcdef'))
|
||||||
|
elif token == 'A':
|
||||||
|
result.append(random.choice(string.ascii_letters))
|
||||||
|
else:
|
||||||
|
result.append(template[i:i + 3])
|
||||||
|
i += 3
|
||||||
|
else:
|
||||||
|
result.append(template[i])
|
||||||
|
i += 1
|
||||||
|
return ''.join(result)
|
||||||
|
|
||||||
|
def _op_ulid(self, args: List[str]) -> str:
|
||||||
|
opts = self._parse_opts(args)
|
||||||
|
count = int(opts.get("n", 1))
|
||||||
|
count = min(count, 1000)
|
||||||
|
|
||||||
|
# ULID: 48位时间戳 + 80位随机数, Crockford Base32
|
||||||
|
alphabet = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"
|
||||||
|
|
||||||
|
ids = []
|
||||||
|
for _ in range(count):
|
||||||
|
ts = int(time.time() * 1000)
|
||||||
|
# 时间部分 (10 chars)
|
||||||
|
t_chars = []
|
||||||
|
t = ts
|
||||||
|
for _ in range(10):
|
||||||
|
t_chars.append(alphabet[t & 0x1F])
|
||||||
|
t >>= 5
|
||||||
|
t_chars.reverse()
|
||||||
|
# 随机部分 (16 chars)
|
||||||
|
r_chars = [random.choice(alphabet) for _ in range(16)]
|
||||||
|
ids.append(''.join(t_chars) + ''.join(r_chars))
|
||||||
|
|
||||||
|
header = f" ULID ({count} 个):\n"
|
||||||
|
if count <= 20:
|
||||||
|
return header + "\n".join(f" {i}" for i in ids)
|
||||||
|
else:
|
||||||
|
return header + "\n".join(f" {i}" for i in ids[:10]) + f"\n ... (共 {count} 个)"
|
||||||
|
|
||||||
|
def _op_timestamp(self, args: List[str]) -> str:
|
||||||
|
now = time.time()
|
||||||
|
return (f"⏱ 当前时间戳:\n"
|
||||||
|
f" 秒: {int(now)}\n"
|
||||||
|
f" 毫秒: {int(now * 1000)}\n"
|
||||||
|
f" 微秒: {int(now * 1000000)}\n"
|
||||||
|
f" ISO: {datetime.now().isoformat()}")
|
||||||
|
|
||||||
|
def _op_from_name(self, args: List[str]) -> str:
|
||||||
|
if len(args) < 2:
|
||||||
|
return "错误:格式: from_name <命名空间> <名称>\n命名空间: dns, url, oid, x500"
|
||||||
|
ns_map = {"dns": uuid.NAMESPACE_DNS, "url": uuid.NAMESPACE_URL,
|
||||||
|
"oid": uuid.NAMESPACE_OID, "x500": uuid.NAMESPACE_X500}
|
||||||
|
ns = ns_map.get(args[0].lower(), uuid.NAMESPACE_DNS)
|
||||||
|
name = args[1]
|
||||||
|
result = uuid.uuid5(ns, name)
|
||||||
|
return f" 确定性 UUID v5:\n 命名空间: {args[0]}\n 名称: {name}\n UUID: {result}"
|
||||||
|
|
||||||
|
def _op_batch(self, args: List[str]) -> str:
|
||||||
|
if not args:
|
||||||
|
return "错误:请提供类型 (uuid/nanoid/short/snowflake/ulid)"
|
||||||
|
id_type = args[0]
|
||||||
|
opts = self._parse_opts(args[1:])
|
||||||
|
count = int(opts.get("n", 10))
|
||||||
|
output = opts.get("o", "")
|
||||||
|
|
||||||
|
# 生成对应类型的ID
|
||||||
|
gen_args = [f"-n", str(count)]
|
||||||
|
handlers = {
|
||||||
|
"uuid": self._op_uuid,
|
||||||
|
"nanoid": self._op_nanoid,
|
||||||
|
"short": self._op_short,
|
||||||
|
"snowflake": self._op_snowflake,
|
||||||
|
"ulid": self._op_ulid,
|
||||||
|
}
|
||||||
|
handler = handlers.get(id_type)
|
||||||
|
if not handler:
|
||||||
|
return f"错误:不支持的类型 '{id_type}'"
|
||||||
|
|
||||||
|
result = handler(gen_args)
|
||||||
|
|
||||||
|
if output:
|
||||||
|
# 提取纯ID保存到文件
|
||||||
|
ids = [line.strip().lstrip(' ') for line in result.split('\n')
|
||||||
|
if line.strip() and not any(c in line for c in [' ', '️', '', '❄️', ''])]
|
||||||
|
try:
|
||||||
|
with open(output, 'w', encoding='utf-8') as f:
|
||||||
|
f.write('\n'.join(ids))
|
||||||
|
return f"{result}\n\n 已保存到: {output}"
|
||||||
|
except Exception as e:
|
||||||
|
return f"{result}\n\n 保存失败: {e}"
|
||||||
|
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def test_plugin():
|
||||||
|
plugin = Liugin()
|
||||||
|
print("ID 生成器测试:")
|
||||||
|
print(plugin.handle('uuid'))
|
||||||
|
print(plugin.handle('uuid -v 1 -n 3'))
|
||||||
|
print(plugin.handle('nanoid -s 16'))
|
||||||
|
print(plugin.handle('short -s 6 -n 5'))
|
||||||
|
print(plugin.handle('snowflake -n 3'))
|
||||||
|
print(plugin.handle('ulid'))
|
||||||
|
print(plugin.handle('timestamp'))
|
||||||
|
print(plugin.handle('custom "ORD-{D}{D}{D}{D}-{U}{U}{U}" -n 5'))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
test_plugin()
|
||||||
@@ -0,0 +1,370 @@
|
|||||||
|
"""
|
||||||
|
图像生成插件 - 基于 ai.2x.nz 的 ComfyUI 在线服务
|
||||||
|
支持自然语言描述和英文 Tag 两种模式
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
import json
|
||||||
|
import asyncio
|
||||||
|
import urllib.request
|
||||||
|
import time
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
|
||||||
|
class Liugin:
|
||||||
|
"""图像生成工具 — 自然语言/Tag 生图,基于 ComfyUI 在线服务"""
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
self.usage = """图像生成工具 — 基于 ai.2x.nz 的 ComfyUI 在线服务
|
||||||
|
|
||||||
|
操作:
|
||||||
|
generate <描述> - 自然语言描述生成图片(中文/英文均可)
|
||||||
|
tag <英文tags> - 直接 Tag 模式(逗号分隔的英文标签)
|
||||||
|
list - 列出可用的工作流/角色
|
||||||
|
status - 查看 GPU 状态
|
||||||
|
|
||||||
|
示例:
|
||||||
|
image_generator generate 一个白发蓝眼的猫耳少女在写代码
|
||||||
|
image_generator tag masterpiece, 1girl, white hair, blue eyes, cat ears, coding
|
||||||
|
image_generator generate 画一个赛博朋克风格的城市夜景 --width 1024 --height 768
|
||||||
|
|
||||||
|
说明:
|
||||||
|
- 自然语言模式会经过 LLM 翻译为 Tag,效果更好
|
||||||
|
- 直接 Tag 模式适合熟悉 Danbooru 标签的用户
|
||||||
|
- 默认分辨率 1024x1344(WAI 推荐)
|
||||||
|
- 最大分辨率 1344x1344
|
||||||
|
- 生成的图片保存在 screenshots/ 目录
|
||||||
|
"""
|
||||||
|
self.cli = None
|
||||||
|
self.api_base = "https://ai.2x.nz"
|
||||||
|
self.ws_url = "wss://ai.2x.nz/ws/run"
|
||||||
|
self.default_workflow = "WAI - 无Lora.json"
|
||||||
|
self.output_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "screenshots")
|
||||||
|
|
||||||
|
def set_cli(self, cli):
|
||||||
|
self.cli = cli
|
||||||
|
|
||||||
|
def get_tool_info(self):
|
||||||
|
return {
|
||||||
|
"name": "image_generator",
|
||||||
|
"description": "图像生成 — 自然语言/Tag 生图,基于 ComfyUI 在线服务(ai.2x.nz),支持中文描述",
|
||||||
|
"keywords": ["图像", "生成", "画图", "绘图", "AI画", "生图", "image", "generate", "draw", "paint",
|
||||||
|
"diffusion", "comfyui", "stable", "sd", "文生图", "text2img"],
|
||||||
|
"usage": self.usage
|
||||||
|
}
|
||||||
|
|
||||||
|
def handle(self, args: str) -> str:
|
||||||
|
try:
|
||||||
|
parts = args.strip().split(maxsplit=1)
|
||||||
|
if not parts:
|
||||||
|
return "错误:请提供操作类型\n\n" + self.usage
|
||||||
|
|
||||||
|
op = parts[0].lower()
|
||||||
|
rest = parts[1] if len(parts) > 1 else ""
|
||||||
|
|
||||||
|
handlers = {
|
||||||
|
"generate": self._generate,
|
||||||
|
"tag": self._generate_tag,
|
||||||
|
"gen": self._generate,
|
||||||
|
"g": self._generate,
|
||||||
|
"list": self._list_workflows,
|
||||||
|
"ls": self._list_workflows,
|
||||||
|
"status": self._gpu_status,
|
||||||
|
}
|
||||||
|
|
||||||
|
handler = handlers.get(op)
|
||||||
|
if not handler:
|
||||||
|
# 如果没有指定操作,把整个 args 当作自然语言描述
|
||||||
|
return self._generate(args)
|
||||||
|
|
||||||
|
return handler(rest)
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
return f"图像生成错误: {e}"
|
||||||
|
|
||||||
|
def _generate(self, args: str) -> str:
|
||||||
|
"""自然语言模式生成图片"""
|
||||||
|
# 解析 --width 和 --height 参数
|
||||||
|
width, height = 1024, 1344
|
||||||
|
prompt = args.strip()
|
||||||
|
|
||||||
|
if "--width" in prompt or "--height" in prompt or "--w" in prompt or "--h" in prompt:
|
||||||
|
import re
|
||||||
|
w_match = re.search(r'--w(?:idth)?\s+(\d+)', prompt)
|
||||||
|
h_match = re.search(r'--h(?:eight)?\s+(\d+)', prompt)
|
||||||
|
if w_match:
|
||||||
|
width = int(w_match.group(1))
|
||||||
|
prompt = prompt[:w_match.start()] + prompt[w_match.end():]
|
||||||
|
if h_match:
|
||||||
|
height = int(h_match.group(1))
|
||||||
|
prompt = prompt[:h_match.start()] + prompt[h_match.end():]
|
||||||
|
prompt = prompt.strip()
|
||||||
|
|
||||||
|
if not prompt:
|
||||||
|
return "错误:请提供图片描述\n示例: image_generator generate 一个白发猫耳少女"
|
||||||
|
|
||||||
|
# 限制分辨率
|
||||||
|
width = min(width, 1344)
|
||||||
|
height = min(height, 1344)
|
||||||
|
|
||||||
|
return self._run_generation(prompt, "", width, height, rewrite=True, override=False)
|
||||||
|
|
||||||
|
def _generate_tag(self, args: str) -> str:
|
||||||
|
"""直接 Tag 模式"""
|
||||||
|
width, height = 1024, 1344
|
||||||
|
prompt = args.strip()
|
||||||
|
|
||||||
|
if "--width" in prompt or "--height" in prompt or "--w" in prompt or "--h" in prompt:
|
||||||
|
import re
|
||||||
|
w_match = re.search(r'--w(?:idth)?\s+(\d+)', prompt)
|
||||||
|
h_match = re.search(r'--h(?:eight)?\s+(\d+)', prompt)
|
||||||
|
if w_match:
|
||||||
|
width = int(w_match.group(1))
|
||||||
|
prompt = prompt[:w_match.start()] + prompt[w_match.end():]
|
||||||
|
if h_match:
|
||||||
|
height = int(h_match.group(1))
|
||||||
|
prompt = prompt[:h_match.start()] + prompt[h_match.end():]
|
||||||
|
prompt = prompt.strip()
|
||||||
|
|
||||||
|
if not prompt:
|
||||||
|
return "错误:请提供 Tag\n示例: image_generator tag masterpiece, 1girl, white hair, blue eyes"
|
||||||
|
|
||||||
|
width = min(width, 1344)
|
||||||
|
height = min(height, 1344)
|
||||||
|
|
||||||
|
return self._run_generation("", prompt, width, height, rewrite=False, override=False)
|
||||||
|
|
||||||
|
def _run_generation(self, nl_prompt: str, direct_prompt: str, width: int, height: int,
|
||||||
|
rewrite: bool = False, override: bool = False) -> str:
|
||||||
|
"""执行图像生成(同步包装)"""
|
||||||
|
try:
|
||||||
|
import websocket as ws_lib
|
||||||
|
except ImportError:
|
||||||
|
# 回退:用 urllib 的方式不行,WebSocket 必须用专用库
|
||||||
|
# 尝试用 subprocess 调用 python 脚本
|
||||||
|
return self._run_generation_subprocess(nl_prompt, direct_prompt, width, height, rewrite, override)
|
||||||
|
|
||||||
|
try:
|
||||||
|
start_time = time.time()
|
||||||
|
ws = ws_lib.create_connection(self.ws_url, timeout=180)
|
||||||
|
|
||||||
|
payload = {
|
||||||
|
"workflow_path": self.default_workflow,
|
||||||
|
"inline_workflow": None,
|
||||||
|
"direct_prompt": direct_prompt,
|
||||||
|
"nl_prompt": nl_prompt,
|
||||||
|
"rewrite": rewrite,
|
||||||
|
"override": override,
|
||||||
|
"width": width,
|
||||||
|
"height": height,
|
||||||
|
}
|
||||||
|
ws.send(json.dumps(payload))
|
||||||
|
|
||||||
|
image_path = None
|
||||||
|
final_prompt = ""
|
||||||
|
error_msg = ""
|
||||||
|
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
raw = ws.recv()
|
||||||
|
data = json.loads(raw)
|
||||||
|
msg_type = data.get("type", "")
|
||||||
|
|
||||||
|
if msg_type == "image":
|
||||||
|
url = data.get("url", "")
|
||||||
|
filename = data.get("filename", "")
|
||||||
|
if url:
|
||||||
|
image_path = self._download_image(url, filename)
|
||||||
|
elif msg_type == "final_prompt":
|
||||||
|
final_prompt = data.get("final_prompt", "") if isinstance(data.get("final_prompt"), str) else data.get("prompt", "")
|
||||||
|
elif msg_type == "done":
|
||||||
|
break
|
||||||
|
elif msg_type == "error":
|
||||||
|
error_msg = data.get("message", "未知错误")
|
||||||
|
break
|
||||||
|
except Exception as e:
|
||||||
|
error_msg = str(e)
|
||||||
|
break
|
||||||
|
|
||||||
|
ws.close()
|
||||||
|
elapsed = time.time() - start_time
|
||||||
|
|
||||||
|
if error_msg:
|
||||||
|
return f" 生成失败: {error_msg}"
|
||||||
|
|
||||||
|
if image_path:
|
||||||
|
size = os.path.getsize(image_path)
|
||||||
|
size_str = f"{size/1024:.0f}KB" if size < 1024*1024 else f"{size/1024/1024:.1f}MB"
|
||||||
|
result = f" 图片生成成功!\n"
|
||||||
|
result += f" 路径: {image_path}\n"
|
||||||
|
result += f" 大小: {size_str}\n"
|
||||||
|
result += f" 分辨率: {width}x{height}\n"
|
||||||
|
result += f"⏱ 耗时: {elapsed:.1f}s\n"
|
||||||
|
if final_prompt:
|
||||||
|
result += f" Prompt: {final_prompt[:120]}...\n"
|
||||||
|
result += f"\n💡 提示: 用 'send_image {image_path}' 可以推送到手机"
|
||||||
|
return result
|
||||||
|
else:
|
||||||
|
return " 生成完成但未收到图片数据"
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
return f" 连接失败: {e}\n💡 请检查网络连接或稍后重试"
|
||||||
|
|
||||||
|
def _run_generation_subprocess(self, nl_prompt: str, direct_prompt: str, width: int, height: int,
|
||||||
|
rewrite: bool, override: bool) -> str:
|
||||||
|
"""用子进程执行 WebSocket 生成(无需 websocket 库)"""
|
||||||
|
import subprocess
|
||||||
|
import tempfile
|
||||||
|
|
||||||
|
script = f'''
|
||||||
|
import json, asyncio, urllib.request, os, sys
|
||||||
|
|
||||||
|
async def main():
|
||||||
|
try:
|
||||||
|
import websockets
|
||||||
|
except ImportError:
|
||||||
|
print("ERROR:需要安装 websockets: pip install websockets")
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
uri = "wss://ai.2x.nz/ws/run"
|
||||||
|
async with websockets.connect(uri) as ws:
|
||||||
|
payload = {{
|
||||||
|
"workflow_path": "{self.default_workflow}",
|
||||||
|
"inline_workflow": None,
|
||||||
|
"direct_prompt": {json.dumps(direct_prompt)},
|
||||||
|
"nl_prompt": {json.dumps(nl_prompt)},
|
||||||
|
"rewrite": {"true" if rewrite else "false"},
|
||||||
|
"override": {"true" if override else "false"},
|
||||||
|
"width": {width},
|
||||||
|
"height": {height},
|
||||||
|
}}
|
||||||
|
await ws.send(json.dumps(payload))
|
||||||
|
|
||||||
|
image_url = None
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
msg = await asyncio.wait_for(ws.recv(), timeout=180)
|
||||||
|
data = json.loads(msg)
|
||||||
|
t = data.get("type", "")
|
||||||
|
if t == "image":
|
||||||
|
image_url = data.get("url", "")
|
||||||
|
elif t == "done":
|
||||||
|
break
|
||||||
|
elif t == "error":
|
||||||
|
print(f"ERROR:{{data.get('message','')}}")
|
||||||
|
break
|
||||||
|
except asyncio.TimeoutError:
|
||||||
|
print("ERROR:超时")
|
||||||
|
break
|
||||||
|
|
||||||
|
if image_url:
|
||||||
|
full_url = f"https://ai.2x.nz{{image_url}}"
|
||||||
|
out_path = os.path.join("{self.output_dir}", f"generated_{{os.path.basename(image_url)}}")
|
||||||
|
os.makedirs(os.path.dirname(out_path), exist_ok=True)
|
||||||
|
urllib.request.urlretrieve(full_url, out_path)
|
||||||
|
print(f"OK:{{out_path}}")
|
||||||
|
|
||||||
|
asyncio.run(main())
|
||||||
|
'''
|
||||||
|
|
||||||
|
script_path = os.path.join(self.output_dir, "_gen_temp.py")
|
||||||
|
os.makedirs(self.output_dir, exist_ok=True)
|
||||||
|
with open(script_path, 'w') as f:
|
||||||
|
f.write(script)
|
||||||
|
|
||||||
|
try:
|
||||||
|
result = subprocess.run(
|
||||||
|
["python3", script_path],
|
||||||
|
capture_output=True, text=True, timeout=200
|
||||||
|
)
|
||||||
|
output = result.stdout.strip()
|
||||||
|
|
||||||
|
if output.startswith("OK:"):
|
||||||
|
image_path = output[3:]
|
||||||
|
size = os.path.getsize(image_path)
|
||||||
|
size_str = f"{size/1024:.0f}KB" if size < 1024*1024 else f"{size/1024/1024:.1f}MB"
|
||||||
|
res = f" 图片生成成功!\n"
|
||||||
|
res += f" 路径: {image_path}\n"
|
||||||
|
res += f" 大小: {size_str}\n"
|
||||||
|
res += f" 分辨率: {width}x{height}\n"
|
||||||
|
res += f"\n💡 提示: 用 'send_image {image_path}' 可以推送到手机"
|
||||||
|
return res
|
||||||
|
elif output.startswith("ERROR:"):
|
||||||
|
return f" {output[6:]}"
|
||||||
|
else:
|
||||||
|
return f" 生成异常:\n{result.stdout}\n{result.stderr}"
|
||||||
|
except subprocess.TimeoutExpired:
|
||||||
|
return " 生成超时(>200s),请稍后重试"
|
||||||
|
finally:
|
||||||
|
try:
|
||||||
|
os.remove(script_path)
|
||||||
|
except:
|
||||||
|
pass
|
||||||
|
|
||||||
|
def _download_image(self, url: str, filename: str) -> str:
|
||||||
|
"""下载生成的图片"""
|
||||||
|
full_url = f"{self.api_base}{url}"
|
||||||
|
os.makedirs(self.output_dir, exist_ok=True)
|
||||||
|
out_path = os.path.join(self.output_dir, f"gen_{filename}")
|
||||||
|
urllib.request.urlretrieve(full_url, out_path)
|
||||||
|
return out_path
|
||||||
|
|
||||||
|
def _list_workflows(self, args: str) -> str:
|
||||||
|
"""列出可用的工作流"""
|
||||||
|
try:
|
||||||
|
import urllib.request
|
||||||
|
req = urllib.request.Request(f"{self.api_base}/api/workflows")
|
||||||
|
with urllib.request.urlopen(req, timeout=10) as resp:
|
||||||
|
data = json.loads(resp.read())
|
||||||
|
|
||||||
|
workflows = data.get("workflows", [])
|
||||||
|
result = f" 可用工作流 ({len(workflows)} 个):\n\n"
|
||||||
|
|
||||||
|
lora_workflows = []
|
||||||
|
no_lora = []
|
||||||
|
for w in workflows:
|
||||||
|
name = w.get("path", "")
|
||||||
|
if "无Lora" in name or "no" in name.lower():
|
||||||
|
no_lora.append(name)
|
||||||
|
else:
|
||||||
|
lora_workflows.append(name)
|
||||||
|
|
||||||
|
if no_lora:
|
||||||
|
result += " 通用(无角色绑定):\n"
|
||||||
|
for w in no_lora:
|
||||||
|
result += f" • {w}\n"
|
||||||
|
|
||||||
|
if lora_workflows:
|
||||||
|
result += "\n 角色工作流:\n"
|
||||||
|
for w in lora_workflows:
|
||||||
|
result += f" • {w}\n"
|
||||||
|
|
||||||
|
result += "\n💡 使用 'image_generator generate <描述>' 自然语言生图"
|
||||||
|
result += "\n💡 使用 'image_generator tag <tags>' 直接 Tag 生图"
|
||||||
|
return result
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
return f" 获取工作流列表失败: {e}"
|
||||||
|
|
||||||
|
def _gpu_status(self, args: str) -> str:
|
||||||
|
"""查看 GPU 状态"""
|
||||||
|
try:
|
||||||
|
import urllib.request
|
||||||
|
req = urllib.request.Request(f"{self.api_base}/api/gpu")
|
||||||
|
with urllib.request.urlopen(req, timeout=10) as resp:
|
||||||
|
data = json.loads(resp.read())
|
||||||
|
|
||||||
|
result = " 服务器 GPU 状态:\n"
|
||||||
|
for gpu in data.get("gpus", []):
|
||||||
|
name = gpu.get("name", "未知")
|
||||||
|
util = gpu.get("utilization", 0)
|
||||||
|
mem_used = gpu.get("memory_used", 0)
|
||||||
|
mem_total = gpu.get("memory_total", 0)
|
||||||
|
temp = gpu.get("temperature", 0)
|
||||||
|
result += f" {name}\n"
|
||||||
|
result += f" GPU 负载: {util}%\n"
|
||||||
|
result += f" 显存: {mem_used}/{mem_total} MiB\n"
|
||||||
|
result += f" 温度: {temp}°C\n"
|
||||||
|
return result
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
return f" 获取 GPU 状态失败: {e}"
|
||||||
@@ -0,0 +1,386 @@
|
|||||||
|
"""
|
||||||
|
JSON 工具箱插件 - JSON 格式化、校验、查询、转换
|
||||||
|
提供 JSON 美化、压缩、验证、路径查询、类型转换等功能
|
||||||
|
"""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
from typing import List
|
||||||
|
|
||||||
|
|
||||||
|
class Liugin:
|
||||||
|
"""JSON 工具箱 - 格式化/校验/查询/转换"""
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
self.usage = """JSON 工具箱
|
||||||
|
|
||||||
|
操作:
|
||||||
|
format <文件或JSON> - 美化 JSON(自动缩进)
|
||||||
|
minify <文件或JSON> - 压缩 JSON(去除空白)
|
||||||
|
validate <文件或JSON> - 校验 JSON 是否合法
|
||||||
|
query <文件或JSON> <路径> - 按路径查询值(如 users[0].name)
|
||||||
|
keys <文件或JSON> - 列出所有键(扁平化)
|
||||||
|
diff <文件1> <文件2> - 比较两个 JSON 的差异
|
||||||
|
to_csv <文件或JSON> - 将 JSON 数组转为 CSV
|
||||||
|
merge <文件1> <文件2> - 合并两个 JSON 对象
|
||||||
|
sample <文件或JSON> [-n 数量] - 从数组中随机采样
|
||||||
|
schema <文件或JSON> - 推断 JSON Schema
|
||||||
|
|
||||||
|
示例:
|
||||||
|
json_toolkit format data.json
|
||||||
|
json_toolkit validate '{"name": "test"}'
|
||||||
|
json_toolkit query config.json "database.host"
|
||||||
|
json_toolkit keys data.json
|
||||||
|
json_toolkit diff a.json b.json
|
||||||
|
"""
|
||||||
|
self.cli = None
|
||||||
|
|
||||||
|
def set_cli(self, cli):
|
||||||
|
self.cli = cli
|
||||||
|
|
||||||
|
def get_tool_info(self):
|
||||||
|
return {
|
||||||
|
"name": "json_toolkit",
|
||||||
|
"description": "JSON 工具箱 - 格式化、压缩、校验、路径查询、键提取、差异比较、转换",
|
||||||
|
"keywords": ["json", "格式化", "校验", "查询", "格式", "转换", "美化", "压缩", "validate", "format"],
|
||||||
|
"usage": self.usage
|
||||||
|
}
|
||||||
|
|
||||||
|
def get_mcp_definition(self):
|
||||||
|
return {
|
||||||
|
"name": "json_toolkit",
|
||||||
|
"description": "JSON 工具箱,支持格式化、压缩、校验、路径查询、键提取、差异比较",
|
||||||
|
"inputSchema": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"operation": {
|
||||||
|
"type": "string",
|
||||||
|
"enum": ["format", "minify", "validate", "query", "keys",
|
||||||
|
"diff", "to_csv", "merge", "sample", "schema"],
|
||||||
|
"description": "操作类型"
|
||||||
|
},
|
||||||
|
"input": {"type": "string", "description": "JSON 字符串或文件路径"},
|
||||||
|
"path": {"type": "string", "description": "查询路径(query 操作用)"},
|
||||||
|
"input2": {"type": "string", "description": "第二个 JSON 输入(diff/merge 用)"},
|
||||||
|
"count": {"type": "integer", "description": "采样数量(sample 操作用)"}
|
||||||
|
},
|
||||||
|
"required": ["operation", "input"]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
def convert_mcp_args(self, arguments):
|
||||||
|
op = arguments.get("operation", "")
|
||||||
|
inp = arguments.get("input", "")
|
||||||
|
path = arguments.get("path", "")
|
||||||
|
parts = [op, inp]
|
||||||
|
if path:
|
||||||
|
parts.append(path)
|
||||||
|
return " ".join(parts)
|
||||||
|
|
||||||
|
def handle(self, args: str) -> str:
|
||||||
|
try:
|
||||||
|
parts = self._parse_args(args)
|
||||||
|
if not parts:
|
||||||
|
return "错误:请提供操作类型"
|
||||||
|
|
||||||
|
operation = parts[0].lower()
|
||||||
|
handlers = {
|
||||||
|
"format": self._op_format,
|
||||||
|
"minify": self._op_minify,
|
||||||
|
"validate": self._op_validate,
|
||||||
|
"query": self._op_query,
|
||||||
|
"keys": self._op_keys,
|
||||||
|
"diff": self._op_diff,
|
||||||
|
"to_csv": self._op_to_csv,
|
||||||
|
"merge": self._op_merge,
|
||||||
|
"sample": self._op_sample,
|
||||||
|
"schema": self._op_schema,
|
||||||
|
}
|
||||||
|
|
||||||
|
handler = handlers.get(operation)
|
||||||
|
if not handler:
|
||||||
|
return f"错误:不支持的操作 '{operation}'\n支持: {', '.join(handlers.keys())}"
|
||||||
|
return handler(parts[1:])
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
return f"JSON 工具错误: {str(e)}"
|
||||||
|
|
||||||
|
def _parse_args(self, args: str) -> List[str]:
|
||||||
|
parts, current, in_quotes, qc = [], "", False, None
|
||||||
|
for ch in args:
|
||||||
|
if ch in ('"', "'") and not in_quotes:
|
||||||
|
in_quotes, qc = True, ch
|
||||||
|
elif ch == qc and in_quotes:
|
||||||
|
in_quotes, qc = False, None
|
||||||
|
elif ch == ' ' and not in_quotes:
|
||||||
|
if current:
|
||||||
|
parts.append(current)
|
||||||
|
current = ""
|
||||||
|
else:
|
||||||
|
current += ch
|
||||||
|
if current:
|
||||||
|
parts.append(current)
|
||||||
|
return parts
|
||||||
|
|
||||||
|
def _load_json(self, text: str):
|
||||||
|
"""加载 JSON(支持文件路径或 JSON 字符串)"""
|
||||||
|
if os.path.isfile(text):
|
||||||
|
with open(text, 'r', encoding='utf-8') as f:
|
||||||
|
return json.load(f), f"文件: {text}"
|
||||||
|
try:
|
||||||
|
return json.loads(text), "JSON 字符串"
|
||||||
|
except json.JSONDecodeError as e:
|
||||||
|
raise ValueError(f"无效的 JSON: {e}")
|
||||||
|
|
||||||
|
def _op_format(self, args: List[str]) -> str:
|
||||||
|
if not args:
|
||||||
|
return "错误:请提供 JSON 文件或字符串"
|
||||||
|
data, source = self._load_json(args[0])
|
||||||
|
formatted = json.dumps(data, indent=2, ensure_ascii=False)
|
||||||
|
return f"✅ 格式化结果 ({source}):\n{formatted}"
|
||||||
|
|
||||||
|
def _op_minify(self, args: List[str]) -> str:
|
||||||
|
if not args:
|
||||||
|
return "错误:请提供 JSON 文件或字符串"
|
||||||
|
data, source = self._load_json(args[0])
|
||||||
|
minified = json.dumps(data, separators=(',', ':'), ensure_ascii=False)
|
||||||
|
original_len = len(json.dumps(data, indent=2, ensure_ascii=False))
|
||||||
|
saved = original_len - len(minified)
|
||||||
|
return f"✅ 压缩结果 ({source}):\n{minified}\n\n📊 大小: {len(minified)} 字符 (节省 {saved} 字符, {saved/original_len*100:.1f}%)"
|
||||||
|
|
||||||
|
def _op_validate(self, args: List[str]) -> str:
|
||||||
|
if not args:
|
||||||
|
return "错误:请提供 JSON 文件或字符串"
|
||||||
|
text = args[0]
|
||||||
|
try:
|
||||||
|
if os.path.isfile(text):
|
||||||
|
with open(text, 'r', encoding='utf-8') as f:
|
||||||
|
data = json.load(f)
|
||||||
|
source = f"文件: {text}"
|
||||||
|
else:
|
||||||
|
data = json.loads(text)
|
||||||
|
source = "JSON 字符串"
|
||||||
|
|
||||||
|
depth = self._get_depth(data)
|
||||||
|
keys_count = self._count_keys(data)
|
||||||
|
|
||||||
|
result = f"✅ JSON 合法 ({source})\n"
|
||||||
|
result += f" 类型: {type(data).__name__}\n"
|
||||||
|
result += f" 嵌套深度: {depth}\n"
|
||||||
|
result += f" 键总数: {keys_count}"
|
||||||
|
return result
|
||||||
|
except json.JSONDecodeError as e:
|
||||||
|
return f"❌ JSON 无效:\n 行 {e.lineno}, 列 {e.colno}: {e.msg}"
|
||||||
|
except Exception as e:
|
||||||
|
return f"❌ 验证失败: {e}"
|
||||||
|
|
||||||
|
def _op_query(self, args: List[str]) -> str:
|
||||||
|
if len(args) < 2:
|
||||||
|
return "错误:格式: query <JSON或文件> <路径>\n示例: query data.json users[0].name"
|
||||||
|
data, _ = self._load_json(args[0])
|
||||||
|
path = args[1]
|
||||||
|
|
||||||
|
result = data
|
||||||
|
parts = re.findall(r'\w+|\[\d+\]', path)
|
||||||
|
current_path = ""
|
||||||
|
|
||||||
|
for part in parts:
|
||||||
|
if part.startswith('['):
|
||||||
|
idx = int(part[1:-1])
|
||||||
|
current_path += part
|
||||||
|
if isinstance(result, list) and 0 <= idx < len(result):
|
||||||
|
result = result[idx]
|
||||||
|
else:
|
||||||
|
return f"❌ 路径 '{current_path}' 无效: 索引越界或非数组"
|
||||||
|
else:
|
||||||
|
current_path += f".{part}" if current_path else part
|
||||||
|
if isinstance(result, dict) and part in result:
|
||||||
|
result = result[part]
|
||||||
|
else:
|
||||||
|
return f"❌ 路径 '{current_path}' 无效: 键不存在"
|
||||||
|
|
||||||
|
output = json.dumps(result, indent=2, ensure_ascii=False) if isinstance(result, (dict, list)) else str(result)
|
||||||
|
return f"🔍 查询结果 ({path}):\n{output}"
|
||||||
|
|
||||||
|
def _op_keys(self, args: List[str]) -> str:
|
||||||
|
if not args:
|
||||||
|
return "错误:请提供 JSON 文件或字符串"
|
||||||
|
data, _ = self._load_json(args[0])
|
||||||
|
|
||||||
|
keys = []
|
||||||
|
self._flatten_keys(data, "", keys)
|
||||||
|
|
||||||
|
result = f"🔑 键列表 (共 {len(keys)} 个):\n"
|
||||||
|
for k in keys:
|
||||||
|
result += f" {k}\n"
|
||||||
|
return result.rstrip()
|
||||||
|
|
||||||
|
def _flatten_keys(self, obj, prefix, keys):
|
||||||
|
if isinstance(obj, dict):
|
||||||
|
for k, v in obj.items():
|
||||||
|
full_key = f"{prefix}.{k}" if prefix else k
|
||||||
|
keys.append(full_key)
|
||||||
|
self._flatten_keys(v, full_key, keys)
|
||||||
|
elif isinstance(obj, list) and obj:
|
||||||
|
self._flatten_keys(obj[0], f"{prefix}[0]", keys)
|
||||||
|
|
||||||
|
def _op_diff(self, args: List[str]) -> str:
|
||||||
|
if len(args) < 2:
|
||||||
|
return "错误:请提供两个 JSON 文件或字符串"
|
||||||
|
data1, src1 = self._load_json(args[0])
|
||||||
|
data2, src2 = self._load_json(args[1])
|
||||||
|
|
||||||
|
diffs = []
|
||||||
|
self._compare(data1, data2, "", diffs)
|
||||||
|
|
||||||
|
if not diffs:
|
||||||
|
return "✅ 两个 JSON 完全相同"
|
||||||
|
|
||||||
|
result = f"🔀 差异比较 ({len(diffs)} 处不同):\n"
|
||||||
|
for d in diffs[:50]:
|
||||||
|
result += f" {d}\n"
|
||||||
|
if len(diffs) > 50:
|
||||||
|
result += f" ... 还有 {len(diffs) - 50} 处差异"
|
||||||
|
return result.rstrip()
|
||||||
|
|
||||||
|
def _compare(self, a, b, path, diffs):
|
||||||
|
if type(a) != type(b):
|
||||||
|
diffs.append(f" 类型不同 @ {path or '根'}: {type(a).__name__} vs {type(b).__name__}")
|
||||||
|
return
|
||||||
|
if isinstance(a, dict):
|
||||||
|
all_keys = set(a.keys()) | set(b.keys())
|
||||||
|
for k in sorted(all_keys):
|
||||||
|
p = f"{path}.{k}" if path else k
|
||||||
|
if k not in a:
|
||||||
|
diffs.append(f"➕ 新增 @ {p}: {b[k]}")
|
||||||
|
elif k not in b:
|
||||||
|
diffs.append(f"➖ 删除 @ {p}: {a[k]}")
|
||||||
|
else:
|
||||||
|
self._compare(a[k], b[k], p, diffs)
|
||||||
|
elif isinstance(a, list):
|
||||||
|
if len(a) != len(b):
|
||||||
|
diffs.append(f" 数组长度不同 @ {path}: {len(a)} vs {len(b)}")
|
||||||
|
for i in range(min(len(a), len(b))):
|
||||||
|
self._compare(a[i], b[i], f"{path}[{i}]", diffs)
|
||||||
|
else:
|
||||||
|
if a != b:
|
||||||
|
diffs.append(f" 值不同 @ {path}: {a!r} → {b!r}")
|
||||||
|
|
||||||
|
def _op_to_csv(self, args: List[str]) -> str:
|
||||||
|
if not args:
|
||||||
|
return "错误:请提供 JSON 文件或字符串"
|
||||||
|
data, _ = self._load_json(args[0])
|
||||||
|
|
||||||
|
if not isinstance(data, list) or not data:
|
||||||
|
return "错误:需要非空 JSON 数组"
|
||||||
|
if not isinstance(data[0], dict):
|
||||||
|
return "错误:数组元素必须是对象"
|
||||||
|
|
||||||
|
headers = list(data[0].keys())
|
||||||
|
lines = [",".join(headers)]
|
||||||
|
for item in data:
|
||||||
|
row = []
|
||||||
|
for h in headers:
|
||||||
|
val = str(item.get(h, ""))
|
||||||
|
if "," in val or '"' in val or "\n" in val:
|
||||||
|
val = '"' + val.replace('"', '""') + '"'
|
||||||
|
row.append(val)
|
||||||
|
lines.append(",".join(row))
|
||||||
|
|
||||||
|
csv_content = "\n".join(lines)
|
||||||
|
return f"📊 CSV 转换结果 ({len(data)} 行):\n{csv_content}"
|
||||||
|
|
||||||
|
def _op_merge(self, args: List[str]) -> str:
|
||||||
|
if len(args) < 2:
|
||||||
|
return "错误:请提供两个 JSON 文件或字符串"
|
||||||
|
data1, _ = self._load_json(args[0])
|
||||||
|
data2, _ = self._load_json(args[1])
|
||||||
|
|
||||||
|
if not isinstance(data1, dict) or not isinstance(data2, dict):
|
||||||
|
return "错误:合并仅支持 JSON 对象"
|
||||||
|
|
||||||
|
merged = self._deep_merge(data1, data2)
|
||||||
|
return f"✅ 合并结果:\n{json.dumps(merged, indent=2, ensure_ascii=False)}"
|
||||||
|
|
||||||
|
def _deep_merge(self, a, b):
|
||||||
|
result = a.copy()
|
||||||
|
for k, v in b.items():
|
||||||
|
if k in result and isinstance(result[k], dict) and isinstance(v, dict):
|
||||||
|
result[k] = self._deep_merge(result[k], v)
|
||||||
|
else:
|
||||||
|
result[k] = v
|
||||||
|
return result
|
||||||
|
|
||||||
|
def _op_sample(self, args: List[str]) -> str:
|
||||||
|
if not args:
|
||||||
|
return "错误:请提供 JSON 文件或字符串"
|
||||||
|
data, _ = self._load_json(args[0])
|
||||||
|
count = 3
|
||||||
|
for i, a in enumerate(args):
|
||||||
|
if a == "-n" and i + 1 < len(args):
|
||||||
|
count = int(args[i + 1])
|
||||||
|
|
||||||
|
if not isinstance(data, list):
|
||||||
|
return "错误:需要 JSON 数组"
|
||||||
|
|
||||||
|
import random
|
||||||
|
sampled = random.sample(data, min(count, len(data)))
|
||||||
|
return f"🎲 随机采样 ({len(sampled)}/{len(data)}):\n{json.dumps(sampled, indent=2, ensure_ascii=False)}"
|
||||||
|
|
||||||
|
def _op_schema(self, args: List[str]) -> str:
|
||||||
|
if not args:
|
||||||
|
return "错误:请提供 JSON 文件或字符串"
|
||||||
|
data, _ = self._load_json(args[0])
|
||||||
|
schema = self._infer_schema(data)
|
||||||
|
return f"📋 推断 Schema:\n{json.dumps(schema, indent=2, ensure_ascii=False)}"
|
||||||
|
|
||||||
|
def _infer_schema(self, obj, depth=0):
|
||||||
|
if depth > 10:
|
||||||
|
return {"type": "any"}
|
||||||
|
if isinstance(obj, dict):
|
||||||
|
props = {}
|
||||||
|
for k, v in obj.items():
|
||||||
|
props[k] = self._infer_schema(v, depth + 1)
|
||||||
|
return {"type": "object", "properties": props}
|
||||||
|
elif isinstance(obj, list):
|
||||||
|
if obj:
|
||||||
|
return {"type": "array", "items": self._infer_schema(obj[0], depth + 1)}
|
||||||
|
return {"type": "array", "items": {}}
|
||||||
|
elif isinstance(obj, bool):
|
||||||
|
return {"type": "boolean"}
|
||||||
|
elif isinstance(obj, int):
|
||||||
|
return {"type": "integer"}
|
||||||
|
elif isinstance(obj, float):
|
||||||
|
return {"type": "number"}
|
||||||
|
else:
|
||||||
|
return {"type": "string"}
|
||||||
|
|
||||||
|
def _get_depth(self, obj, depth=0):
|
||||||
|
if depth > 50:
|
||||||
|
return depth
|
||||||
|
if isinstance(obj, dict):
|
||||||
|
return max((self._get_depth(v, depth + 1) for v in obj.values()), default=depth)
|
||||||
|
elif isinstance(obj, list):
|
||||||
|
return max((self._get_depth(v, depth + 1) for v in obj), default=depth)
|
||||||
|
return depth
|
||||||
|
|
||||||
|
def _count_keys(self, obj):
|
||||||
|
if isinstance(obj, dict):
|
||||||
|
return len(obj) + sum(self._count_keys(v) for v in obj.values())
|
||||||
|
elif isinstance(obj, list):
|
||||||
|
return sum(self._count_keys(v) for v in obj)
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_plugin():
|
||||||
|
plugin = Liugin()
|
||||||
|
print("JSON 工具箱测试:")
|
||||||
|
print(plugin.handle('validate \'{"name": "test", "age": 25}\''))
|
||||||
|
print(plugin.handle('format \'{"name":"test","items":[1,2,3]}\''))
|
||||||
|
print(plugin.handle('keys \'{"database": {"host": "localhost", "port": 3306}}\''))
|
||||||
|
print(plugin.handle('query \'{"users": [{"name": "Alice"}]}\' users[0].name'))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
test_plugin()
|
||||||
@@ -0,0 +1,540 @@
|
|||||||
|
"""
|
||||||
|
Markdown 工具插件 - Markdown 渲染、目录生成、格式转换
|
||||||
|
支持 TOC 生成、标题提取、表格生成、格式化、统计
|
||||||
|
"""
|
||||||
|
|
||||||
|
import re
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from typing import List, Tuple
|
||||||
|
|
||||||
|
|
||||||
|
class Liugin:
|
||||||
|
"""Markdown 工具 - TOC/渲染/格式转换/统计"""
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
self.usage = """Markdown 工具
|
||||||
|
|
||||||
|
操作:
|
||||||
|
toc <文件或Markdown> - 生成目录 (Table of Contents)
|
||||||
|
headings <文件或Markdown> - 提取所有标题
|
||||||
|
stats <文件或Markdown> - 统计信息(字数/行数/段落数等)
|
||||||
|
table <数据> - 从 JSON 数组生成 Markdown 表格
|
||||||
|
checklist <文件> - 提取所有待办事项
|
||||||
|
links <文件或Markdown> - 提取所有链接
|
||||||
|
images <文件或Markdown> - 提取所有图片
|
||||||
|
frontmatter <文件> - 提取 YAML frontmatter
|
||||||
|
format <文件或Markdown> - 格式化(标题层级、列表缩进等)
|
||||||
|
wordcount <文件或Markdown> - 详细字数统计
|
||||||
|
outline <文件或Markdown> - 生成大纲视图
|
||||||
|
lint <文件> - Markdown 语法检查
|
||||||
|
|
||||||
|
示例:
|
||||||
|
markdown_tool toc README.md
|
||||||
|
markdown_tool stats article.md
|
||||||
|
markdown_tool table '[{"name":"Alice","age":25},{"name":"Bob","age":30}]'
|
||||||
|
markdown_tool checklist TODO.md
|
||||||
|
markdown_tool links README.md
|
||||||
|
markdown_tool lint README.md
|
||||||
|
"""
|
||||||
|
self.cli = None
|
||||||
|
|
||||||
|
def set_cli(self, cli):
|
||||||
|
self.cli = cli
|
||||||
|
|
||||||
|
def get_tool_info(self):
|
||||||
|
return {
|
||||||
|
"name": "markdown_tool",
|
||||||
|
"description": "Markdown 工具 - TOC 生成、标题提取、统计、表格生成、语法检查",
|
||||||
|
"keywords": ["markdown", "md", "目录", "toc", "标题", "表格", "统计", "链接", "检查"],
|
||||||
|
"usage": self.usage
|
||||||
|
}
|
||||||
|
|
||||||
|
def get_mcp_definition(self):
|
||||||
|
return {
|
||||||
|
"name": "markdown_tool",
|
||||||
|
"description": "Markdown 工具,支持 TOC、统计、表格生成、链接提取、语法检查",
|
||||||
|
"inputSchema": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"operation": {
|
||||||
|
"type": "string",
|
||||||
|
"enum": ["toc", "headings", "stats", "table", "checklist",
|
||||||
|
"links", "images", "frontmatter", "format",
|
||||||
|
"wordcount", "outline", "lint"],
|
||||||
|
"description": "操作类型"
|
||||||
|
},
|
||||||
|
"input": {"type": "string", "description": "Markdown 文件路径或内容"},
|
||||||
|
"data": {"type": "string", "description": "JSON 数据(table 操作用)"}
|
||||||
|
},
|
||||||
|
"required": ["operation", "input"]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
def convert_mcp_args(self, arguments):
|
||||||
|
op = arguments.get("operation", "")
|
||||||
|
inp = arguments.get("input", "")
|
||||||
|
return f"{op} {inp}".strip()
|
||||||
|
|
||||||
|
def _load_content(self, text: str) -> Tuple[str, str]:
|
||||||
|
"""加载内容(文件路径或文本)"""
|
||||||
|
if os.path.isfile(text):
|
||||||
|
with open(text, 'r', encoding='utf-8') as f:
|
||||||
|
return f.read(), f"文件: {text}"
|
||||||
|
return text, "文本输入"
|
||||||
|
|
||||||
|
def handle(self, args: str) -> str:
|
||||||
|
try:
|
||||||
|
parts = self._parse_args(args)
|
||||||
|
if not parts:
|
||||||
|
return "错误:请提供操作类型"
|
||||||
|
|
||||||
|
operation = parts[0].lower()
|
||||||
|
handlers = {
|
||||||
|
"toc": self._op_toc,
|
||||||
|
"headings": self._op_headings,
|
||||||
|
"stats": self._op_stats,
|
||||||
|
"table": self._op_table,
|
||||||
|
"checklist": self._op_checklist,
|
||||||
|
"links": self._op_links,
|
||||||
|
"images": self._op_images,
|
||||||
|
"frontmatter": self._op_frontmatter,
|
||||||
|
"format": self._op_format,
|
||||||
|
"wordcount": self._op_wordcount,
|
||||||
|
"outline": self._op_outline,
|
||||||
|
"lint": self._op_lint,
|
||||||
|
}
|
||||||
|
|
||||||
|
handler = handlers.get(operation)
|
||||||
|
if not handler:
|
||||||
|
return f"错误:不支持的操作 '{operation}'"
|
||||||
|
return handler(parts[1:])
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
return f"Markdown 工具错误: {str(e)}"
|
||||||
|
|
||||||
|
def _parse_args(self, args: str) -> List[str]:
|
||||||
|
parts, current, in_quotes, qc = [], "", False, None
|
||||||
|
for ch in args:
|
||||||
|
if ch in ('"', "'") and not in_quotes:
|
||||||
|
in_quotes, qc = True, ch
|
||||||
|
elif ch == qc and in_quotes:
|
||||||
|
in_quotes, qc = False, None
|
||||||
|
elif ch == ' ' and not in_quotes:
|
||||||
|
if current:
|
||||||
|
parts.append(current)
|
||||||
|
current = ""
|
||||||
|
else:
|
||||||
|
current += ch
|
||||||
|
if current:
|
||||||
|
parts.append(current)
|
||||||
|
return parts
|
||||||
|
|
||||||
|
def _extract_headings(self, content: str) -> List[Tuple[int, str, str]]:
|
||||||
|
"""提取标题: [(level, text, slug)]"""
|
||||||
|
headings = []
|
||||||
|
in_code = False
|
||||||
|
for line in content.split('\n'):
|
||||||
|
if line.strip().startswith('```'):
|
||||||
|
in_code = not in_code
|
||||||
|
continue
|
||||||
|
if in_code:
|
||||||
|
continue
|
||||||
|
match = re.match(r'^(#{1,6})\s+(.+)', line)
|
||||||
|
if match:
|
||||||
|
level = len(match.group(1))
|
||||||
|
text = match.group(2).strip()
|
||||||
|
# 生成 slug
|
||||||
|
slug = re.sub(r'[^\w\s-]', '', text.lower())
|
||||||
|
slug = re.sub(r'\s+', '-', slug.strip())
|
||||||
|
headings.append((level, text, slug))
|
||||||
|
return headings
|
||||||
|
|
||||||
|
def _op_toc(self, args: List[str]) -> str:
|
||||||
|
if not args:
|
||||||
|
return "错误:请提供 Markdown 文件或内容"
|
||||||
|
content, source = self._load_content(args[0])
|
||||||
|
headings = self._extract_headings(content)
|
||||||
|
|
||||||
|
if not headings:
|
||||||
|
return "📭 未找到标题"
|
||||||
|
|
||||||
|
result = f" 目录 ({source}):\n"
|
||||||
|
result += "─" * 40 + "\n"
|
||||||
|
for level, text, slug in headings:
|
||||||
|
indent = " " * (level - 1)
|
||||||
|
result += f"{indent}- [{text}](#{slug})\n"
|
||||||
|
return result.rstrip()
|
||||||
|
|
||||||
|
def _op_headings(self, args: List[str]) -> str:
|
||||||
|
if not args:
|
||||||
|
return "错误:请提供 Markdown 文件或内容"
|
||||||
|
content, source = self._load_content(args[0])
|
||||||
|
headings = self._extract_headings(content)
|
||||||
|
|
||||||
|
if not headings:
|
||||||
|
return "📭 未找到标题"
|
||||||
|
|
||||||
|
result = f" 标题列表 ({len(headings)} 个):\n"
|
||||||
|
for level, text, _ in headings:
|
||||||
|
prefix = "#" * level
|
||||||
|
result += f" {prefix:8s} {text}\n"
|
||||||
|
return result.rstrip()
|
||||||
|
|
||||||
|
def _op_stats(self, args: List[str]) -> str:
|
||||||
|
if not args:
|
||||||
|
return "错误:请提供 Markdown 文件或内容"
|
||||||
|
content, source = self._load_content(args[0])
|
||||||
|
|
||||||
|
lines = content.split('\n')
|
||||||
|
total_lines = len(lines)
|
||||||
|
blank_lines = sum(1 for l in lines if not l.strip())
|
||||||
|
code_blocks = content.count('```') // 2
|
||||||
|
headings = len(self._extract_headings(content))
|
||||||
|
links = len(re.findall(r'\[([^\]]+)\]\([^)]+\)', content))
|
||||||
|
images = len(re.findall(r'!\[([^\]]*)\]\([^)]+\)', content))
|
||||||
|
# 中文字符
|
||||||
|
chinese = len(re.findall(r'[\u4e00-\u9fff]', content))
|
||||||
|
# 英文单词
|
||||||
|
english = len(re.findall(r'[a-zA-Z]+', content))
|
||||||
|
|
||||||
|
# 段落数(连续非空行)
|
||||||
|
paragraphs = 0
|
||||||
|
in_para = False
|
||||||
|
for l in lines:
|
||||||
|
if l.strip():
|
||||||
|
if not in_para:
|
||||||
|
paragraphs += 1
|
||||||
|
in_para = True
|
||||||
|
else:
|
||||||
|
in_para = False
|
||||||
|
|
||||||
|
result = f"📊 Markdown 统计 ({source})\n"
|
||||||
|
result += "─" * 35 + "\n"
|
||||||
|
result += f" 总行数: {total_lines}\n"
|
||||||
|
result += f" 空行: {blank_lines}\n"
|
||||||
|
result += f" 段落: {paragraphs}\n"
|
||||||
|
result += f" 代码块: {code_blocks}\n"
|
||||||
|
result += f" 标题: {headings}\n"
|
||||||
|
result += f" 链接: {links}\n"
|
||||||
|
result += f" 图片: {images}\n"
|
||||||
|
result += f" 中文字: {chinese}\n"
|
||||||
|
result += f" 英文词: {english}\n"
|
||||||
|
result += f" 字符数: {len(content)}\n"
|
||||||
|
return result.rstrip()
|
||||||
|
|
||||||
|
def _op_table(self, args: List[str]) -> str:
|
||||||
|
if not args:
|
||||||
|
return "错误:请提供 JSON 数组"
|
||||||
|
data_str = args[0]
|
||||||
|
try:
|
||||||
|
data = json.loads(data_str)
|
||||||
|
except json.JSONDecodeError as e:
|
||||||
|
return f"❌ JSON 解析错误: {e}"
|
||||||
|
|
||||||
|
if not isinstance(data, list) or not data:
|
||||||
|
return "❌ 需要非空 JSON 数组"
|
||||||
|
if not isinstance(data[0], dict):
|
||||||
|
return "❌ 数组元素必须是对象"
|
||||||
|
|
||||||
|
headers = list(data[0].keys())
|
||||||
|
# 计算列宽
|
||||||
|
widths = {h: len(h) for h in headers}
|
||||||
|
for row in data:
|
||||||
|
for h in headers:
|
||||||
|
widths[h] = max(widths[h], len(str(row.get(h, ""))))
|
||||||
|
|
||||||
|
# 生成表格
|
||||||
|
header_line = "| " + " | ".join(h.ljust(widths[h]) for h in headers) + " |"
|
||||||
|
sep_line = "| " + " | ".join("-" * widths[h] for h in headers) + " |"
|
||||||
|
rows = []
|
||||||
|
for row in data:
|
||||||
|
rows.append("| " + " | ".join(str(row.get(h, "")).ljust(widths[h]) for h in headers) + " |")
|
||||||
|
|
||||||
|
result = f" Markdown 表格 ({len(data)} 行):\n\n"
|
||||||
|
result += header_line + "\n" + sep_line + "\n" + "\n".join(rows)
|
||||||
|
return result
|
||||||
|
|
||||||
|
def _op_checklist(self, args: List[str]) -> str:
|
||||||
|
if not args:
|
||||||
|
return "错误:请提供 Markdown 文件"
|
||||||
|
content, source = self._load_content(args[0])
|
||||||
|
|
||||||
|
todos = []
|
||||||
|
done = []
|
||||||
|
for i, line in enumerate(content.split('\n'), 1):
|
||||||
|
match = re.match(r'^(\s*)[-*]\s*\[([ xX])\]\s*(.+)', line)
|
||||||
|
if match:
|
||||||
|
indent = match.group(1)
|
||||||
|
checked = match.group(2).lower() == 'x'
|
||||||
|
text = match.group(3).strip()
|
||||||
|
if checked:
|
||||||
|
done.append((i, text))
|
||||||
|
else:
|
||||||
|
todos.append((i, text))
|
||||||
|
|
||||||
|
result = f" 待办事项 ({source}):\n"
|
||||||
|
result += "─" * 45 + "\n"
|
||||||
|
result += f" ☑ 已完成: {len(done)} 个\n"
|
||||||
|
result += f" 未完成: {len(todos)} 个\n"
|
||||||
|
result += "─" * 45 + "\n"
|
||||||
|
|
||||||
|
if todos:
|
||||||
|
result += "\n 未完成:\n"
|
||||||
|
for line_no, text in todos[:30]:
|
||||||
|
result += f" L{line_no:4d} {text}\n"
|
||||||
|
if done:
|
||||||
|
result += "\n 已完成:\n"
|
||||||
|
for line_no, text in done[:20]:
|
||||||
|
result += f" L{line_no:4d} {text}\n"
|
||||||
|
return result.rstrip()
|
||||||
|
|
||||||
|
def _op_links(self, args: List[str]) -> str:
|
||||||
|
if not args:
|
||||||
|
return "错误:请提供 Markdown 文件或内容"
|
||||||
|
content, source = self._load_content(args[0])
|
||||||
|
|
||||||
|
links = re.findall(r'\[([^\]]+)\]\(([^)]+)\)', content)
|
||||||
|
if not links:
|
||||||
|
return f"📭 未找到链接 ({source})"
|
||||||
|
|
||||||
|
result = f" 链接列表 ({len(links)} 个, {source}):\n"
|
||||||
|
result += "─" * 50 + "\n"
|
||||||
|
seen = set()
|
||||||
|
for text, url in links:
|
||||||
|
if url not in seen:
|
||||||
|
seen.add(url)
|
||||||
|
result += f" {text[:30]:30s} → {url}\n"
|
||||||
|
return result.rstrip()
|
||||||
|
|
||||||
|
def _op_images(self, args: List[str]) -> str:
|
||||||
|
if not args:
|
||||||
|
return "错误:请提供 Markdown 文件或内容"
|
||||||
|
content, source = self._load_content(args[0])
|
||||||
|
|
||||||
|
images = re.findall(r'!\[([^\]]*)\]\(([^)]+)\)', content)
|
||||||
|
if not images:
|
||||||
|
return f"📭 未找到图片 ({source})"
|
||||||
|
|
||||||
|
result = f" ️ 图片列表 ({len(images)} 个, {source}):\n"
|
||||||
|
result += "─" * 50 + "\n"
|
||||||
|
seen = set()
|
||||||
|
for alt, url in images:
|
||||||
|
if url not in seen:
|
||||||
|
seen.add(url)
|
||||||
|
result += f" {alt[:25]:25s} → {url}\n"
|
||||||
|
return result.rstrip()
|
||||||
|
|
||||||
|
def _op_frontmatter(self, args: List[str]) -> str:
|
||||||
|
if not args:
|
||||||
|
return "错误:请提供 Markdown 文件"
|
||||||
|
content, source = self._load_content(args[0])
|
||||||
|
|
||||||
|
match = re.match(r'^---\n(.*?)\n---', content, re.DOTALL)
|
||||||
|
if not match:
|
||||||
|
return f"📭 未找到 frontmatter ({source})"
|
||||||
|
|
||||||
|
fm = match.group(1)
|
||||||
|
result = f" Frontmatter ({source}):\n"
|
||||||
|
result += "─" * 35 + "\n"
|
||||||
|
result += fm
|
||||||
|
return result
|
||||||
|
|
||||||
|
def _op_format(self, args: List[str]) -> str:
|
||||||
|
if not args:
|
||||||
|
return "错误:请提供 Markdown 文件或内容"
|
||||||
|
content, source = self._load_content(args[0])
|
||||||
|
lines = content.split('\n')
|
||||||
|
formatted = []
|
||||||
|
prev_blank = False
|
||||||
|
|
||||||
|
for line in lines:
|
||||||
|
stripped = line.strip()
|
||||||
|
# 确保标题前后有空行
|
||||||
|
if re.match(r'^#{1,6}\s', stripped):
|
||||||
|
if formatted and not prev_blank:
|
||||||
|
formatted.append('')
|
||||||
|
formatted.append(stripped)
|
||||||
|
prev_blank = False
|
||||||
|
continue
|
||||||
|
# 确保列表项格式一致
|
||||||
|
if re.match(r'^[-*]\s', stripped):
|
||||||
|
formatted.append(re.sub(r'^[-*]\s', '- ', stripped))
|
||||||
|
prev_blank = False
|
||||||
|
continue
|
||||||
|
# 去除多余空行
|
||||||
|
if not stripped:
|
||||||
|
if not prev_blank:
|
||||||
|
formatted.append('')
|
||||||
|
prev_blank = True
|
||||||
|
continue
|
||||||
|
|
||||||
|
prev_blank = False
|
||||||
|
formatted.append(line.rstrip())
|
||||||
|
|
||||||
|
# 确保文件末尾有换行
|
||||||
|
while formatted and not formatted[-1]:
|
||||||
|
formatted.pop()
|
||||||
|
formatted.append('')
|
||||||
|
|
||||||
|
return f"✅ 格式化完成 ({source}):\n" + '\n'.join(formatted)
|
||||||
|
|
||||||
|
def _op_wordcount(self, args: List[str]) -> str:
|
||||||
|
if not args:
|
||||||
|
return "错误:请提供 Markdown 文件或内容"
|
||||||
|
content, source = self._load_content(args[0])
|
||||||
|
|
||||||
|
# 移除代码块
|
||||||
|
no_code = re.sub(r'```[\s\S]*?```', '', content)
|
||||||
|
# 移除行内代码
|
||||||
|
no_code = re.sub(r'`[^`]+`', '', no_code)
|
||||||
|
# 移除链接标记
|
||||||
|
no_code = re.sub(r'\[([^\]]+)\]\([^)]+\)', r'\1', no_code)
|
||||||
|
# 移除图片标记
|
||||||
|
no_code = re.sub(r'!\[([^\]]*)\]\([^)]+\)', '', no_code)
|
||||||
|
# 移除标题标记
|
||||||
|
no_code = re.sub(r'^#{1,6}\s+', '', no_code, flags=re.MULTILINE)
|
||||||
|
# 移除加粗/斜体标记
|
||||||
|
no_code = re.sub(r'\*{1,2}([^*]+)\*{1,2}', r'\1', no_code)
|
||||||
|
|
||||||
|
chinese = len(re.findall(r'[\u4e00-\u9fff]', no_code))
|
||||||
|
english_words = re.findall(r'[a-zA-Z]+', no_code)
|
||||||
|
english = len(english_words)
|
||||||
|
total_chars = len(no_code.strip())
|
||||||
|
|
||||||
|
# 阅读时间估算(中文 300字/分钟, 英文 200词/分钟)
|
||||||
|
read_time_cn = chinese / 300
|
||||||
|
read_time_en = english / 200
|
||||||
|
read_time = read_time_cn + read_time_en
|
||||||
|
|
||||||
|
result = f" 详细字数统计 ({source}):\n"
|
||||||
|
result += "─" * 35 + "\n"
|
||||||
|
result += f" 中文字数: {chinese}\n"
|
||||||
|
result += f" 英文单词: {english}\n"
|
||||||
|
result += f" 总字符数: {total_chars}\n"
|
||||||
|
result += f" 预计阅读: {read_time:.1f} 分钟\n"
|
||||||
|
return result.rstrip()
|
||||||
|
|
||||||
|
def _op_outline(self, args: List[str]) -> str:
|
||||||
|
if not args:
|
||||||
|
return "错误:请提供 Markdown 文件或内容"
|
||||||
|
content, source = self._load_content(args[0])
|
||||||
|
headings = self._extract_headings(content)
|
||||||
|
|
||||||
|
if not headings:
|
||||||
|
return "📭 未找到标题"
|
||||||
|
|
||||||
|
result = f" 大纲视图 ({source}):\n"
|
||||||
|
result += "═" * 40 + "\n"
|
||||||
|
for level, text, _ in headings:
|
||||||
|
if level == 1:
|
||||||
|
result += f"\n {text}\n"
|
||||||
|
result += "─" * 30 + "\n"
|
||||||
|
elif level == 2:
|
||||||
|
result += f" {text}\n"
|
||||||
|
elif level == 3:
|
||||||
|
result += f" {text}\n"
|
||||||
|
else:
|
||||||
|
result += f" {'·' * (level - 3)} {text}\n"
|
||||||
|
return result.rstrip()
|
||||||
|
|
||||||
|
def _op_lint(self, args: List[str]) -> str:
|
||||||
|
if not args:
|
||||||
|
return "错误:请提供 Markdown 文件"
|
||||||
|
file_path = args[0]
|
||||||
|
if not os.path.isfile(file_path):
|
||||||
|
return f"❌ 文件不存在: {file_path}"
|
||||||
|
|
||||||
|
with open(file_path, 'r', encoding='utf-8') as f:
|
||||||
|
content = f.read()
|
||||||
|
lines = content.split('\n')
|
||||||
|
|
||||||
|
issues = []
|
||||||
|
in_code = False
|
||||||
|
prev_blank = False
|
||||||
|
heading_levels = []
|
||||||
|
|
||||||
|
for i, line in enumerate(lines, 1):
|
||||||
|
stripped = line.strip()
|
||||||
|
|
||||||
|
# 代码块跟踪
|
||||||
|
if stripped.startswith('```'):
|
||||||
|
in_code = not in_code
|
||||||
|
continue
|
||||||
|
if in_code:
|
||||||
|
continue
|
||||||
|
|
||||||
|
# 检查标题格式
|
||||||
|
heading_match = re.match(r'^(#{1,6})\s+(.+)', line)
|
||||||
|
if heading_match:
|
||||||
|
level = len(heading_match.group(1))
|
||||||
|
text = heading_match.group(2)
|
||||||
|
# 检查标题前后空行
|
||||||
|
if i > 1 and lines[i - 2].strip() and not lines[i - 2].startswith('#'):
|
||||||
|
issues.append(f" L{i:4d} 标题前缺少空行")
|
||||||
|
# 检查标题层级跳跃
|
||||||
|
if heading_levels and level > heading_levels[-1] + 1:
|
||||||
|
issues.append(f" L{i:4d} 标题层级跳跃 ({heading_levels[-1]} → {level})")
|
||||||
|
heading_levels.append(level)
|
||||||
|
# 检查标题末尾空格
|
||||||
|
if text != text.rstrip():
|
||||||
|
issues.append(f" L{i:4d} 标题末尾有多余空格")
|
||||||
|
else:
|
||||||
|
# 检查行尾空格
|
||||||
|
if line != line.rstrip() and stripped:
|
||||||
|
trailing = len(line) - len(line.rstrip())
|
||||||
|
if trailing >= 2: # 2个以上空格是换行符
|
||||||
|
pass # 这是合法的 Markdown 换行
|
||||||
|
elif trailing > 0:
|
||||||
|
issues.append(f" L{i:4d} 行尾有多余空格")
|
||||||
|
|
||||||
|
# 检查连续空行
|
||||||
|
if not stripped:
|
||||||
|
if prev_blank:
|
||||||
|
issues.append(f" L{i:4d} 连续空行")
|
||||||
|
prev_blank = True
|
||||||
|
else:
|
||||||
|
prev_blank = False
|
||||||
|
|
||||||
|
# 检查列表格式
|
||||||
|
list_match = re.match(r'^(\s*)[-*+]\s', line)
|
||||||
|
if list_match:
|
||||||
|
indent = len(list_match.group(1))
|
||||||
|
if indent % 2 != 0 and indent > 0:
|
||||||
|
issues.append(f" L{i:4d} 列表缩进不是2的倍数")
|
||||||
|
|
||||||
|
# 检查链接格式
|
||||||
|
if re.search(r'\[[^\]]*\]\(\s*\)', line):
|
||||||
|
issues.append(f" L{i:4d} 链接URL为空")
|
||||||
|
|
||||||
|
# 检查重复词
|
||||||
|
words = stripped.lower().split()
|
||||||
|
for j in range(len(words) - 1):
|
||||||
|
if len(words[j]) > 2 and words[j] == words[j + 1]:
|
||||||
|
issues.append(f" L{i:4d} 重复词: '{words[j]}'")
|
||||||
|
|
||||||
|
result = f" ️ Markdown 语法检查 ({file_path}):\n"
|
||||||
|
result += "─" * 45 + "\n"
|
||||||
|
|
||||||
|
if not issues:
|
||||||
|
result += " 未发现问题!\n"
|
||||||
|
else:
|
||||||
|
result += f" 发现 {len(issues)} 个问题:\n\n"
|
||||||
|
for issue in issues[:50]:
|
||||||
|
result += f" {issue}\n"
|
||||||
|
if len(issues) > 50:
|
||||||
|
result += f"\n ... 还有 {len(issues) - 50} 个问题\n"
|
||||||
|
|
||||||
|
return result.rstrip()
|
||||||
|
|
||||||
|
|
||||||
|
def test_plugin():
|
||||||
|
plugin = Liugin()
|
||||||
|
print("Markdown 工具测试:")
|
||||||
|
print(plugin.handle('headings "# Hello\\n## World\\n### Sub"'))
|
||||||
|
print(plugin.handle('stats "# Hello\\n\\nThis is a test."'))
|
||||||
|
print(plugin.handle('table \'[{"name":"Alice","age":25},{"name":"Bob","age":30}]\''))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
test_plugin()
|
||||||
@@ -0,0 +1,185 @@
|
|||||||
|
"""
|
||||||
|
记忆系统插件 — 包装 xcli_core/memory.py 中的 MemoryManager
|
||||||
|
使 AI 可以通过工具接口读写日记、搜索记忆、管理聊天记录
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
|
||||||
|
# 添加项目根目录到 path
|
||||||
|
current_dir = os.path.dirname(os.path.abspath(__file__))
|
||||||
|
project_root = os.path.dirname(current_dir)
|
||||||
|
sys.path.insert(0, project_root)
|
||||||
|
|
||||||
|
from xcli_core.memory import MemoryManager
|
||||||
|
|
||||||
|
|
||||||
|
class Liugin:
|
||||||
|
"""持久化记忆系统 — AI 可写日记、搜索记忆、管理聊天记录"""
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
self.cli = None
|
||||||
|
self.memory = None
|
||||||
|
self.usage = """持久化记忆系统工具
|
||||||
|
|
||||||
|
操作:
|
||||||
|
diary <内容> - 写当日日记
|
||||||
|
diary_ai <内容> - AI 写观察日记(标记为 AI 观察)
|
||||||
|
remember <内容> - 记录到长期记忆 (MEMORY.md)
|
||||||
|
search <关键词> - 全局搜索(日记+记忆+聊天记录)
|
||||||
|
context - 查看当前注入的记忆上下文
|
||||||
|
diary_list - 列出所有日记文件
|
||||||
|
diary_read <日期> - 读取指定日期的日记(如 2026-04-27)
|
||||||
|
chat_list - 列出最近的聊天记录
|
||||||
|
chat_search <关键词> - 在聊天记录中搜索
|
||||||
|
memory_read - 读取 MEMORY.md 长期记忆
|
||||||
|
memory_write <内容> - 写入 MEMORY.md(追加)
|
||||||
|
|
||||||
|
JSON 格式示例:
|
||||||
|
{"action": "use_tool", "tool": "memory_plugin", "args": "diary 今天完成了API对接"}
|
||||||
|
{"action": "use_tool", "tool": "memory_plugin", "args": "search 定时任务"}
|
||||||
|
{"action": "use_tool", "tool": "memory_plugin", "args": "remember 用户偏好深色主题"}
|
||||||
|
"""
|
||||||
|
|
||||||
|
def set_cli(self, cli):
|
||||||
|
self.cli = cli
|
||||||
|
# 初始化 MemoryManager
|
||||||
|
project_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||||
|
self.memory = MemoryManager(project_dir)
|
||||||
|
# 挂载到 cli 实例上,让 cli_core.py 能访问
|
||||||
|
cli.memory_manager = self.memory
|
||||||
|
|
||||||
|
def get_tool_info(self):
|
||||||
|
return {
|
||||||
|
"name": "memory_plugin",
|
||||||
|
"description": "持久化记忆系统 — AI 可写日记、记录长期记忆、搜索历史对话和日记。支持自动压缩上下文。",
|
||||||
|
"keywords": ["记忆", "memory", "日记", "diary", "搜索", "search", "历史", "history",
|
||||||
|
"remember", "聊天记录", "chat", "上下文", "context", "压缩", "compress"],
|
||||||
|
"usage": self.usage
|
||||||
|
}
|
||||||
|
|
||||||
|
def handle(self, args: str) -> str:
|
||||||
|
if not self.memory:
|
||||||
|
return "错误:记忆系统未初始化"
|
||||||
|
|
||||||
|
if not args or not args.strip():
|
||||||
|
return self._help()
|
||||||
|
|
||||||
|
parts = args.strip().split(None, 1)
|
||||||
|
action = parts[0].lower()
|
||||||
|
rest = parts[1].strip() if len(parts) > 1 else ""
|
||||||
|
|
||||||
|
handlers = {
|
||||||
|
"diary": self._diary,
|
||||||
|
"diary_ai": self._diary_ai,
|
||||||
|
"remember": self._remember,
|
||||||
|
"search": self._search,
|
||||||
|
"context": self._context,
|
||||||
|
"diary_list": self._diary_list,
|
||||||
|
"diary_read": self._diary_read,
|
||||||
|
"chat_list": self._chat_list,
|
||||||
|
"chat_search": self._chat_search,
|
||||||
|
"memory_read": self._memory_read,
|
||||||
|
"memory_write": self._memory_write,
|
||||||
|
"help": lambda _: self._help(),
|
||||||
|
}
|
||||||
|
|
||||||
|
handler = handlers.get(action)
|
||||||
|
if not handler:
|
||||||
|
return f"未知操作: {action}\n" + self._help()
|
||||||
|
|
||||||
|
return handler(rest)
|
||||||
|
|
||||||
|
def _diary(self, content: str) -> str:
|
||||||
|
if not content:
|
||||||
|
return "错误:请提供日记内容\n用法: diary <内容>"
|
||||||
|
self.memory.write_diary(content)
|
||||||
|
return f" 日记已写入 {self.memory._today_file()}"
|
||||||
|
|
||||||
|
def _diary_ai(self, content: str) -> str:
|
||||||
|
if not content:
|
||||||
|
return "错误:请提供 AI 观察内容\n用法: diary_ai <内容>"
|
||||||
|
self.memory.write_ai_diary(content)
|
||||||
|
return f" AI 观察日记已写入"
|
||||||
|
|
||||||
|
def _remember(self, content: str) -> str:
|
||||||
|
if not content:
|
||||||
|
return "错误:请提供要记住的内容\n用法: remember <内容>"
|
||||||
|
self.memory.append_memory("备忘", f"- {content}")
|
||||||
|
return f" 已记录到 MEMORY.md 长期记忆"
|
||||||
|
|
||||||
|
def _search(self, keyword: str) -> str:
|
||||||
|
if not keyword:
|
||||||
|
return "错误:请提供搜索关键词\n用法: search <关键词>"
|
||||||
|
results = self.memory.search_memory(keyword)
|
||||||
|
if not results:
|
||||||
|
return f" 未找到与 '{keyword}' 相关的记忆"
|
||||||
|
lines = [f" 搜索 '{keyword}' 的结果 ({len(results)} 条):"]
|
||||||
|
for r in results:
|
||||||
|
source = r.get("source", "")
|
||||||
|
snippet = r.get("snippet", "")
|
||||||
|
role = r.get("role", "")
|
||||||
|
line_num = r.get("line", "")
|
||||||
|
prefix = f"[{role}] " if role else ""
|
||||||
|
line_info = f" (L{line_num})" if line_num else ""
|
||||||
|
lines.append(f" {source}{line_info}: {prefix}{snippet}")
|
||||||
|
return "\n".join(lines)
|
||||||
|
|
||||||
|
def _context(self, _: str) -> str:
|
||||||
|
ctx = self.memory.build_memory_context()
|
||||||
|
return ctx if ctx else " 当前没有记忆上下文"
|
||||||
|
|
||||||
|
def _diary_list(self, _: str) -> str:
|
||||||
|
files = self.memory.list_diary_files()
|
||||||
|
if not files:
|
||||||
|
return " 还没有日记文件"
|
||||||
|
return " 日记文件:\n" + "\n".join(f" {f}" for f in files[:20])
|
||||||
|
|
||||||
|
def _diary_read(self, date_str: str) -> str:
|
||||||
|
if not date_str:
|
||||||
|
return "错误:请提供日期\n用法: diary_read <日期,如 2026-04-27>"
|
||||||
|
content = self.memory.load_diary(date_str)
|
||||||
|
return content if content else f" 没有找到 {date_str} 的日记"
|
||||||
|
|
||||||
|
def _chat_list(self, _: str) -> str:
|
||||||
|
chats = self.memory.list_chats()
|
||||||
|
if not chats:
|
||||||
|
return " 没有保存的聊天记录"
|
||||||
|
lines = [" 最近的聊天记录:"]
|
||||||
|
for c in chats:
|
||||||
|
lines.append(f" {c['name']} ({c['time']}, {c['size_kb']}KB)")
|
||||||
|
return "\n".join(lines)
|
||||||
|
|
||||||
|
def _chat_search(self, keyword: str) -> str:
|
||||||
|
if not keyword:
|
||||||
|
return "错误:请提供关键词\n用法: chat_search <关键词>"
|
||||||
|
results = self.memory.search_chats(keyword)
|
||||||
|
if not results:
|
||||||
|
return f" 未在聊天记录中找到 '{keyword}'"
|
||||||
|
lines = [f" 聊天记录搜索 '{keyword}':"]
|
||||||
|
for r in results:
|
||||||
|
lines.append(f" {r['file']} [{r['role']}]: {r['snippet']}")
|
||||||
|
return "\n".join(lines)
|
||||||
|
|
||||||
|
def _memory_read(self, _: str) -> str:
|
||||||
|
content = self.memory.load_memory()
|
||||||
|
return content if content else " MEMORY.md 为空"
|
||||||
|
|
||||||
|
def _memory_write(self, content: str) -> str:
|
||||||
|
if not content:
|
||||||
|
return "错误:请提供内容\n用法: memory_write <内容>"
|
||||||
|
self.memory.append_memory("备忘", f"- {content}")
|
||||||
|
return f" 已写入 MEMORY.md"
|
||||||
|
|
||||||
|
def _help(self) -> str:
|
||||||
|
return """ 记忆系统用法:
|
||||||
|
diary <内容> - 写当日日记
|
||||||
|
diary_ai <内容> - AI 写观察日记
|
||||||
|
remember <内容> - 记到长期记忆 (MEMORY.md)
|
||||||
|
search <关键词> - 全局搜索记忆
|
||||||
|
context - 查看记忆上下文
|
||||||
|
diary_list - 列出日记
|
||||||
|
diary_read <日期> - 读取日记
|
||||||
|
chat_list - 列出聊天记录
|
||||||
|
chat_search <关键词> - 搜索聊天记录
|
||||||
|
memory_read - 读取 MEMORY.md
|
||||||
|
memory_write <内容> - 写入 MEMORY.md"""
|
||||||
@@ -0,0 +1,442 @@
|
|||||||
|
"""
|
||||||
|
正则表达式测试器插件 - 测试、调试、管理正则表达式
|
||||||
|
支持匹配测试、提取、替换、常用模式库
|
||||||
|
"""
|
||||||
|
|
||||||
|
import re
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from typing import List
|
||||||
|
|
||||||
|
|
||||||
|
class Liugin:
|
||||||
|
"""正则表达式测试器 - 测试、调试、管理正则"""
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
self.usage = """正则表达式测试器
|
||||||
|
|
||||||
|
操作:
|
||||||
|
test <正则> <文本> [-f flags] - 测试正则是否匹配
|
||||||
|
match <正则> <文本> [-f flags] - 提取所有匹配项
|
||||||
|
replace <正则> <文本> <替换> - 测试替换
|
||||||
|
groups <正则> <文本> - 显示分组信息
|
||||||
|
explain <正则> - 解释正则含义
|
||||||
|
flags <正则> <文本> - 测试不同标志组合
|
||||||
|
pattern [名称] - 列出/查看常用模式
|
||||||
|
save <名称> <正则> [-d 描述] - 保存自定义模式
|
||||||
|
delete_pattern <名称> - 删除自定义模式
|
||||||
|
bench <正则> <文本> [-n 次数] - 性能测试
|
||||||
|
|
||||||
|
标志 (flags):
|
||||||
|
i - 忽略大小写 m - 多行模式 s - 点匹配换行
|
||||||
|
x - 详细模式 a - ASCII模式
|
||||||
|
|
||||||
|
示例:
|
||||||
|
regex_tester test "\\d+" "abc123def456"
|
||||||
|
regex_tester match "[a-z]+@[a-z]+\\.[a-z]+" "test@example.com foo@bar.org"
|
||||||
|
regex_tester groups "(\\w+)@(\\w+)\\.(\\w+)" "user@domain.com"
|
||||||
|
regex_tester explain "[a-z]+@\\w+\\.\\w+"
|
||||||
|
regex_tester pattern email
|
||||||
|
"""
|
||||||
|
self.cli = None
|
||||||
|
self.patterns_file = "regex_patterns.json"
|
||||||
|
self.custom_patterns = self._load_patterns()
|
||||||
|
|
||||||
|
def set_cli(self, cli):
|
||||||
|
self.cli = cli
|
||||||
|
|
||||||
|
def get_tool_info(self):
|
||||||
|
return {
|
||||||
|
"name": "regex_tester",
|
||||||
|
"description": "正则表达式测试器 - 测试匹配、提取、替换、解释、常用模式库",
|
||||||
|
"keywords": ["正则", "regex", "匹配", "表达式", "测试", "替换", "提取", "模式"],
|
||||||
|
"usage": self.usage
|
||||||
|
}
|
||||||
|
|
||||||
|
def get_mcp_definition(self):
|
||||||
|
return {
|
||||||
|
"name": "regex_tester",
|
||||||
|
"description": "正则表达式测试器,支持匹配测试、提取、替换、解释、性能测试",
|
||||||
|
"inputSchema": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"operation": {
|
||||||
|
"type": "string",
|
||||||
|
"enum": ["test", "match", "replace", "groups", "explain",
|
||||||
|
"flags", "pattern", "save", "bench"],
|
||||||
|
"description": "操作类型"
|
||||||
|
},
|
||||||
|
"pattern": {"type": "string", "description": "正则表达式"},
|
||||||
|
"text": {"type": "string", "description": "测试文本"},
|
||||||
|
"replacement": {"type": "string", "description": "替换文本"},
|
||||||
|
"flags": {"type": "string", "description": "标志 (i/m/s/x)"},
|
||||||
|
"name": {"type": "string", "description": "模式名称"},
|
||||||
|
"description": {"type": "string", "description": "模式描述"},
|
||||||
|
"count": {"type": "integer", "description": "测试次数"}
|
||||||
|
},
|
||||||
|
"required": ["operation"]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
def convert_mcp_args(self, arguments):
|
||||||
|
op = arguments.get("operation", "")
|
||||||
|
pattern = arguments.get("pattern", "")
|
||||||
|
text = arguments.get("text", "")
|
||||||
|
return f"{op} {pattern} {text}".strip()
|
||||||
|
|
||||||
|
def _load_patterns(self):
|
||||||
|
try:
|
||||||
|
if os.path.exists(self.patterns_file):
|
||||||
|
with open(self.patterns_file, 'r', encoding='utf-8') as f:
|
||||||
|
return json.load(f)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
return self._default_patterns()
|
||||||
|
|
||||||
|
def _save_patterns(self):
|
||||||
|
try:
|
||||||
|
with open(self.patterns_file, 'w', encoding='utf-8') as f:
|
||||||
|
json.dump(self.custom_patterns, f, ensure_ascii=False, indent=2)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
def _default_patterns(self):
|
||||||
|
return {
|
||||||
|
"email": {"pattern": r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}", "desc": "邮箱地址"},
|
||||||
|
"phone_cn": {"pattern": r"1[3-9]\d{9}", "desc": "中国手机号"},
|
||||||
|
"url": {"pattern": r"https?://[^\s<>\"']+|www\.[^\s<>\"']+", "desc": "URL链接"},
|
||||||
|
"ipv4": {"pattern": r"\b(?:\d{1,3}\.){3}\d{1,3}\b", "desc": "IPv4地址"},
|
||||||
|
"date": {"pattern": r"\d{4}[-/]\d{1,2}[-/]\d{1,2}", "desc": "日期格式"},
|
||||||
|
"time": {"pattern": r"\d{2}:\d{2}(:\d{2})?", "desc": "时间格式"},
|
||||||
|
"chinese": {"pattern": r"[\u4e00-\u9fff]+", "desc": "中文字符"},
|
||||||
|
"id_card": {"pattern": r"\d{17}[\dXx]", "desc": "身份证号"},
|
||||||
|
"html_tag": {"pattern": r"<[^>]+>", "desc": "HTML标签"},
|
||||||
|
"ip_port": {"pattern": r"\b(?:\d{1,3}\.){3}\d{1,3}:\d{1,5}\b", "desc": "IP:端口"},
|
||||||
|
"mac_addr": {"pattern": r"([0-9A-Fa-f]{2}[:-]){5}[0-9A-Fa-f]{2}", "desc": "MAC地址"},
|
||||||
|
"hex_color": {"pattern": r"#[0-9A-Fa-f]{3,8}", "desc": "十六进制颜色"},
|
||||||
|
"number": {"pattern": r"-?\d+\.?\d*", "desc": "数字(整数/浮点)"},
|
||||||
|
"word": {"pattern": r"\b\w+\b", "desc": "单词"},
|
||||||
|
}
|
||||||
|
|
||||||
|
def handle(self, args: str) -> str:
|
||||||
|
try:
|
||||||
|
parts = self._parse_args(args)
|
||||||
|
if not parts:
|
||||||
|
return "错误:请提供操作类型"
|
||||||
|
|
||||||
|
operation = parts[0].lower()
|
||||||
|
handlers = {
|
||||||
|
"test": self._op_test,
|
||||||
|
"match": self._op_match,
|
||||||
|
"replace": self._op_replace,
|
||||||
|
"groups": self._op_groups,
|
||||||
|
"explain": self._op_explain,
|
||||||
|
"flags": self._op_flags,
|
||||||
|
"pattern": self._op_pattern,
|
||||||
|
"save": self._op_save,
|
||||||
|
"delete_pattern": self._op_delete_pattern,
|
||||||
|
"bench": self._op_bench,
|
||||||
|
}
|
||||||
|
|
||||||
|
handler = handlers.get(operation)
|
||||||
|
if not handler:
|
||||||
|
return f"错误:不支持的操作 '{operation}'"
|
||||||
|
return handler(parts[1:])
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
return f"正则测试错误: {str(e)}"
|
||||||
|
|
||||||
|
def _parse_args(self, args: str) -> List[str]:
|
||||||
|
parts, current, in_quotes, qc = [], "", False, None
|
||||||
|
for ch in args:
|
||||||
|
if ch in ('"', "'") and not in_quotes:
|
||||||
|
in_quotes, qc = True, ch
|
||||||
|
elif ch == qc and in_quotes:
|
||||||
|
in_quotes, qc = False, None
|
||||||
|
elif ch == ' ' and not in_quotes:
|
||||||
|
if current:
|
||||||
|
parts.append(current)
|
||||||
|
current = ""
|
||||||
|
else:
|
||||||
|
current += ch
|
||||||
|
if current:
|
||||||
|
parts.append(current)
|
||||||
|
return parts
|
||||||
|
|
||||||
|
def _parse_flags(self, flags_str: str) -> int:
|
||||||
|
flags = 0
|
||||||
|
for c in flags_str.lower():
|
||||||
|
if c == 'i': flags |= re.IGNORECASE
|
||||||
|
elif c == 'm': flags |= re.MULTILINE
|
||||||
|
elif c == 's': flags |= re.DOTALL
|
||||||
|
elif c == 'x': flags |= re.VERBOSE
|
||||||
|
return flags
|
||||||
|
|
||||||
|
def _op_test(self, args: List[str]) -> str:
|
||||||
|
if len(args) < 2:
|
||||||
|
return "错误:格式: test <正则> <文本> [-f 标志]"
|
||||||
|
pattern_str, text = args[0], args[1]
|
||||||
|
flags = 0
|
||||||
|
for i, a in enumerate(args):
|
||||||
|
if a == "-f" and i + 1 < len(args):
|
||||||
|
flags = self._parse_flags(args[i + 1])
|
||||||
|
|
||||||
|
try:
|
||||||
|
pattern = re.compile(pattern_str, flags)
|
||||||
|
match = pattern.search(text)
|
||||||
|
if match:
|
||||||
|
return (f"✅ 匹配成功!\n"
|
||||||
|
f" 正则: {pattern_str}\n"
|
||||||
|
f" 位置: {match.start()}-{match.end()}\n"
|
||||||
|
f" 匹配: '{match.group()}'\n"
|
||||||
|
f" 全文: {pattern.findall(text)}")
|
||||||
|
else:
|
||||||
|
return f"❌ 无匹配\n 正则: {pattern_str}\n 文本: {text[:100]}"
|
||||||
|
except re.error as e:
|
||||||
|
return f"❌ 正则语法错误: {e}"
|
||||||
|
|
||||||
|
def _op_match(self, args: List[str]) -> str:
|
||||||
|
if len(args) < 2:
|
||||||
|
return "错误:格式: match <正则> <文本>"
|
||||||
|
pattern_str, text = args[0], args[1]
|
||||||
|
flags = 0
|
||||||
|
for i, a in enumerate(args):
|
||||||
|
if a == "-f" and i + 1 < len(args):
|
||||||
|
flags = self._parse_flags(args[i + 1])
|
||||||
|
|
||||||
|
try:
|
||||||
|
pattern = re.compile(pattern_str, flags)
|
||||||
|
matches = pattern.finditer(text)
|
||||||
|
|
||||||
|
results = []
|
||||||
|
for m in matches:
|
||||||
|
results.append(f" [{m.start():3d}-{m.end():3d}] '{m.group()}'")
|
||||||
|
|
||||||
|
if results:
|
||||||
|
return f" 找到 {len(results)} 个匹配:\n" + "\n".join(results)
|
||||||
|
else:
|
||||||
|
return "❌ 未找到匹配"
|
||||||
|
except re.error as e:
|
||||||
|
return f"❌ 正则语法错误: {e}"
|
||||||
|
|
||||||
|
def _op_replace(self, args: List[str]) -> str:
|
||||||
|
if len(args) < 3:
|
||||||
|
return "错误:格式: replace <正则> <文本> <替换>"
|
||||||
|
pattern_str, text, replacement = args[0], args[1], args[2]
|
||||||
|
|
||||||
|
try:
|
||||||
|
result = re.sub(pattern_str, replacement, text)
|
||||||
|
count = len(re.findall(pattern_str, text))
|
||||||
|
return (f" 替换结果 ({count} 处):\n"
|
||||||
|
f" 原文: {text}\n"
|
||||||
|
f" 结果: {result}")
|
||||||
|
except re.error as e:
|
||||||
|
return f"❌ 正则语法错误: {e}"
|
||||||
|
|
||||||
|
def _op_groups(self, args: List[str]) -> str:
|
||||||
|
if len(args) < 2:
|
||||||
|
return "错误:格式: groups <正则> <文本>"
|
||||||
|
pattern_str, text = args[0], args[1]
|
||||||
|
|
||||||
|
try:
|
||||||
|
pattern = re.compile(pattern_str)
|
||||||
|
match = pattern.search(text)
|
||||||
|
if not match:
|
||||||
|
return "❌ 无匹配"
|
||||||
|
|
||||||
|
result = f" 分组信息:\n"
|
||||||
|
result += f" 完整匹配: '{match.group()}' (span: {match.span()})\n"
|
||||||
|
for i, group in enumerate(match.groups(), 1):
|
||||||
|
result += f" 分组 {i}: '{group}' (span: {match.span(i) if group else 'N/A'})\n"
|
||||||
|
if match.groupdict():
|
||||||
|
result += f" 命名分组:\n"
|
||||||
|
for name, value in match.groupdict().items():
|
||||||
|
result += f" {name}: '{value}'\n"
|
||||||
|
return result.rstrip()
|
||||||
|
except re.error as e:
|
||||||
|
return f"❌ 正则语法错误: {e}"
|
||||||
|
|
||||||
|
def _op_explain(self, args: List[str]) -> str:
|
||||||
|
if not args:
|
||||||
|
return "错误:请提供正则表达式"
|
||||||
|
pattern_str = args[0]
|
||||||
|
|
||||||
|
explanations = []
|
||||||
|
i = 0
|
||||||
|
while i < len(pattern_str):
|
||||||
|
ch = pattern_str[i]
|
||||||
|
|
||||||
|
if ch == '\\':
|
||||||
|
if i + 1 < len(pattern_str):
|
||||||
|
next_ch = pattern_str[i + 1]
|
||||||
|
escape_map = {
|
||||||
|
'd': '数字 [0-9]', 'D': '非数字', 'w': '字母/数字/下划线',
|
||||||
|
'W': '非字母数字下划线', 's': '空白字符', 'S': '非空白字符',
|
||||||
|
'b': '单词边界', 'B': '非单词边界', 'n': '换行', 't': '制表符',
|
||||||
|
}
|
||||||
|
if next_ch in escape_map:
|
||||||
|
explanations.append(('\\' + next_ch, escape_map[next_ch]))
|
||||||
|
else:
|
||||||
|
explanations.append(('\\' + next_ch, f'转义字符 {next_ch}'))
|
||||||
|
i += 2
|
||||||
|
continue
|
||||||
|
|
||||||
|
if ch == '.':
|
||||||
|
explanations.append(('.', '任意字符(除换行)'))
|
||||||
|
elif ch == '^':
|
||||||
|
explanations.append(('^', '行/字符串开头'))
|
||||||
|
elif ch == '$':
|
||||||
|
explanations.append(('$', '行/字符串结尾'))
|
||||||
|
elif ch == '*':
|
||||||
|
explanations.append(('*', '0次或多次'))
|
||||||
|
elif ch == '+':
|
||||||
|
explanations.append(('+', '1次或多次'))
|
||||||
|
elif ch == '?':
|
||||||
|
explanations.append(('?', '0次或1次'))
|
||||||
|
elif ch == '{':
|
||||||
|
end = pattern_str.find('}', i)
|
||||||
|
if end != -1:
|
||||||
|
quantifier = pattern_str[i:end + 1]
|
||||||
|
explanations.append((quantifier, f'量词: {quantifier}'))
|
||||||
|
i = end + 1
|
||||||
|
continue
|
||||||
|
elif ch == '[':
|
||||||
|
end = pattern_str.find(']', i)
|
||||||
|
if end != -1:
|
||||||
|
char_class = pattern_str[i:end + 1]
|
||||||
|
explanations.append((char_class, f'字符类: {char_class}'))
|
||||||
|
i = end + 1
|
||||||
|
continue
|
||||||
|
elif ch == '(':
|
||||||
|
if i + 1 < len(pattern_str) and pattern_str[i + 1] == '?':
|
||||||
|
if i + 2 < len(pattern_str):
|
||||||
|
special = pattern_str[i + 2]
|
||||||
|
if special == ':':
|
||||||
|
explanations.append(('(?:', '非捕获组'))
|
||||||
|
elif special == '=':
|
||||||
|
explanations.append(('(?=', '正向前瞻'))
|
||||||
|
elif special == '!':
|
||||||
|
explanations.append(('(?!', '负向前瞻'))
|
||||||
|
i += 3
|
||||||
|
continue
|
||||||
|
explanations.append(('(', '捕获组开始'))
|
||||||
|
elif ch == ')':
|
||||||
|
explanations.append((')', '组结束'))
|
||||||
|
elif ch == '|':
|
||||||
|
explanations.append(('|', '或 (交替)'))
|
||||||
|
|
||||||
|
i += 1
|
||||||
|
|
||||||
|
result = f" 正则解释: {pattern_str}\n"
|
||||||
|
result += "─" * 45 + "\n"
|
||||||
|
for token, meaning in explanations:
|
||||||
|
result += f" {token:12s} → {meaning}\n"
|
||||||
|
return result.rstrip()
|
||||||
|
|
||||||
|
def _op_flags(self, args: List[str]) -> str:
|
||||||
|
if len(args) < 2:
|
||||||
|
return "错误:格式: flags <正则> <文本>"
|
||||||
|
pattern_str, text = args[0], args[1]
|
||||||
|
|
||||||
|
flag_combos = [
|
||||||
|
("", 0, "默认"),
|
||||||
|
("i", re.IGNORECASE, "忽略大小写"),
|
||||||
|
("m", re.MULTILINE, "多行模式"),
|
||||||
|
("s", re.DOTALL, "点匹配换行"),
|
||||||
|
("im", re.IGNORECASE | re.MULTILINE, "忽略大小写+多行"),
|
||||||
|
]
|
||||||
|
|
||||||
|
result = f" ️ 标志测试: {pattern_str}\n"
|
||||||
|
result += "─" * 45 + "\n"
|
||||||
|
for flag_str, flag_val, desc in flag_combos:
|
||||||
|
try:
|
||||||
|
matches = re.findall(pattern_str, text, flag_val)
|
||||||
|
count = len(matches) if isinstance(matches, list) else 1
|
||||||
|
result += f" [{flag_str or '-':3s}] {desc:12s} → {count} 个匹配: {matches[:3]}\n"
|
||||||
|
except re.error as e:
|
||||||
|
result += f" [{flag_str or '-':3s}] {desc:12s} → 错误: {e}\n"
|
||||||
|
return result.rstrip()
|
||||||
|
|
||||||
|
def _op_pattern(self, args: List[str]) -> str:
|
||||||
|
if args:
|
||||||
|
name = args[0]
|
||||||
|
if name in self.custom_patterns:
|
||||||
|
p = self.custom_patterns[name]
|
||||||
|
return f" 模式 '{name}':\n 正则: {p['pattern']}\n 描述: {p.get('desc', '')}"
|
||||||
|
return f"❌ 未找到模式: {name}"
|
||||||
|
|
||||||
|
result = " 常用正则模式:\n"
|
||||||
|
result += "─" * 50 + "\n"
|
||||||
|
for name, p in self.custom_patterns.items():
|
||||||
|
result += f" {name:15s} {p['pattern'][:35]:35s} {p.get('desc', '')}\n"
|
||||||
|
return result.rstrip()
|
||||||
|
|
||||||
|
def _op_save(self, args: List[str]) -> str:
|
||||||
|
if len(args) < 2:
|
||||||
|
return "错误:格式: save <名称> <正则> [-d 描述]"
|
||||||
|
name, pattern_str = args[0], args[1]
|
||||||
|
desc = ""
|
||||||
|
for i, a in enumerate(args):
|
||||||
|
if a == "-d" and i + 1 < len(args):
|
||||||
|
desc = args[i + 1]
|
||||||
|
|
||||||
|
# 验证正则
|
||||||
|
try:
|
||||||
|
re.compile(pattern_str)
|
||||||
|
except re.error as e:
|
||||||
|
return f"❌ 正则语法错误: {e}"
|
||||||
|
|
||||||
|
self.custom_patterns[name] = {"pattern": pattern_str, "desc": desc}
|
||||||
|
self._save_patterns()
|
||||||
|
return f"✅ 已保存模式 '{name}': {pattern_str}"
|
||||||
|
|
||||||
|
def _op_delete_pattern(self, args: List[str]) -> str:
|
||||||
|
if not args:
|
||||||
|
return "错误:请提供模式名称"
|
||||||
|
name = args[0]
|
||||||
|
if name in self.custom_patterns:
|
||||||
|
del self.custom_patterns[name]
|
||||||
|
self._save_patterns()
|
||||||
|
return f" ️ 已删除模式: {name}"
|
||||||
|
return f"❌ 未找到模式: {name}"
|
||||||
|
|
||||||
|
def _op_bench(self, args: List[str]) -> str:
|
||||||
|
if len(args) < 2:
|
||||||
|
return "错误:格式: bench <正则> <文本> [-n 次数]"
|
||||||
|
pattern_str, text = args[0], args[1]
|
||||||
|
count = 10000
|
||||||
|
for i, a in enumerate(args):
|
||||||
|
if a == "-n" and i + 1 < len(args):
|
||||||
|
count = int(args[i + 1])
|
||||||
|
|
||||||
|
try:
|
||||||
|
import time
|
||||||
|
pattern = re.compile(pattern_str)
|
||||||
|
|
||||||
|
start = time.perf_counter()
|
||||||
|
for _ in range(count):
|
||||||
|
pattern.findall(text)
|
||||||
|
elapsed = time.perf_counter() - start
|
||||||
|
|
||||||
|
per_op = elapsed / count * 1_000_000 # 微秒
|
||||||
|
return (f"⏱ 性能测试:\n"
|
||||||
|
f" 正则: {pattern_str}\n"
|
||||||
|
f" 次数: {count}\n"
|
||||||
|
f" 总耗时: {elapsed:.3f}s\n"
|
||||||
|
f" 每次: {per_op:.2f}μs\n"
|
||||||
|
f" 吞吐: {count / elapsed:.0f} ops/s")
|
||||||
|
except re.error as e:
|
||||||
|
return f"❌ 正则语法错误: {e}"
|
||||||
|
|
||||||
|
|
||||||
|
def test_plugin():
|
||||||
|
plugin = Liugin()
|
||||||
|
print("正则表达式测试器测试:")
|
||||||
|
print(plugin.handle('test "\\d+" "abc123def456"'))
|
||||||
|
print(plugin.handle('match "[a-z]+" "hello world foo bar"'))
|
||||||
|
print(plugin.handle('groups "(\\w+)@(\\w+)\\.(\\w+)" "user@domain.com"'))
|
||||||
|
print(plugin.handle('explain "\\d{4}-\\d{2}-\\d{2}"'))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
test_plugin()
|
||||||
@@ -0,0 +1,428 @@
|
|||||||
|
"""
|
||||||
|
代码片段管理器插件 - 保存、搜索、复用常用代码片段
|
||||||
|
支持分类、标签、搜索、导出,JSON 持久化存储
|
||||||
|
"""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import time
|
||||||
|
import hashlib
|
||||||
|
from datetime import datetime
|
||||||
|
from typing import List, Optional
|
||||||
|
|
||||||
|
|
||||||
|
class Liugin:
|
||||||
|
"""代码片段管理器 - 保存和复用代码片段"""
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
self.usage = """代码片段管理器
|
||||||
|
|
||||||
|
操作:
|
||||||
|
add <名称> -l <语言> -c "代码" [-t 标签1,标签2] [-d 描述]
|
||||||
|
- 添加代码片段
|
||||||
|
list [-l 语言] [-t 标签] - 列出片段(可按语言/标签过滤)
|
||||||
|
get <名称或ID> - 获取片段详情
|
||||||
|
search <关键词> - 搜索片段(名称/描述/代码/标签)
|
||||||
|
delete <名称或ID> - 删除片段
|
||||||
|
edit <名称或ID> -c "新代码" - 更新片段代码
|
||||||
|
export [文件] - 导出所有片段
|
||||||
|
import <文件> - 导入片段
|
||||||
|
tags - 列出所有标签
|
||||||
|
stats - 统计信息
|
||||||
|
copy <名称或ID> - 复制到剪贴板(如可用)
|
||||||
|
recent [-n 数量] - 最近添加的片段
|
||||||
|
|
||||||
|
示例:
|
||||||
|
snippet_manager add quick_sort -l python -c "def qsort(arr): ..." -t 排序,算法
|
||||||
|
snippet_manager list -l python
|
||||||
|
snippet_manager search 排序
|
||||||
|
snippet_manager get quick_sort
|
||||||
|
"""
|
||||||
|
self.cli = None
|
||||||
|
self.snippets_file = "snippets.json"
|
||||||
|
self.snippets = []
|
||||||
|
self._load_snippets()
|
||||||
|
|
||||||
|
def set_cli(self, cli):
|
||||||
|
self.cli = cli
|
||||||
|
|
||||||
|
def get_tool_info(self):
|
||||||
|
return {
|
||||||
|
"name": "snippet_manager",
|
||||||
|
"description": "代码片段管理器 - 保存、搜索、复用常用代码片段,支持分类和标签",
|
||||||
|
"keywords": ["代码", "片段", "snippet", "模板", "复用", "保存", "搜索", "代码片段"],
|
||||||
|
"usage": self.usage
|
||||||
|
}
|
||||||
|
|
||||||
|
def get_mcp_definition(self):
|
||||||
|
return {
|
||||||
|
"name": "snippet_manager",
|
||||||
|
"description": "代码片段管理器,支持添加、搜索、获取、删除代码片段",
|
||||||
|
"inputSchema": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"operation": {
|
||||||
|
"type": "string",
|
||||||
|
"enum": ["add", "list", "get", "search", "delete",
|
||||||
|
"edit", "export", "import", "tags", "stats", "recent"],
|
||||||
|
"description": "操作类型"
|
||||||
|
},
|
||||||
|
"name": {"type": "string", "description": "片段名称或ID"},
|
||||||
|
"language": {"type": "string", "description": "编程语言"},
|
||||||
|
"code": {"type": "string", "description": "代码内容"},
|
||||||
|
"tags": {"type": "string", "description": "标签(逗号分隔)"},
|
||||||
|
"description": {"type": "string", "description": "描述"},
|
||||||
|
"keyword": {"type": "string", "description": "搜索关键词"},
|
||||||
|
"file": {"type": "string", "description": "文件路径"},
|
||||||
|
"count": {"type": "integer", "description": "数量"}
|
||||||
|
},
|
||||||
|
"required": ["operation"]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
def convert_mcp_args(self, arguments):
|
||||||
|
op = arguments.get("operation", "")
|
||||||
|
name = arguments.get("name", "")
|
||||||
|
return f"{op} {name}".strip()
|
||||||
|
|
||||||
|
def _load_snippets(self):
|
||||||
|
try:
|
||||||
|
if os.path.exists(self.snippets_file):
|
||||||
|
with open(self.snippets_file, 'r', encoding='utf-8') as f:
|
||||||
|
self.snippets = json.load(f)
|
||||||
|
except Exception:
|
||||||
|
self.snippets = []
|
||||||
|
|
||||||
|
def _save_snippets(self):
|
||||||
|
try:
|
||||||
|
with open(self.snippets_file, 'w', encoding='utf-8') as f:
|
||||||
|
json.dump(self.snippets, f, ensure_ascii=False, indent=2)
|
||||||
|
return None
|
||||||
|
except Exception as e:
|
||||||
|
return f"保存失败: {e}"
|
||||||
|
|
||||||
|
def _gen_id(self, name: str) -> str:
|
||||||
|
return hashlib.md5(f"{name}{time.time()}".encode()).hexdigest()[:8]
|
||||||
|
|
||||||
|
def handle(self, args: str) -> str:
|
||||||
|
try:
|
||||||
|
parts = self._parse_args(args)
|
||||||
|
if not parts:
|
||||||
|
return self._op_list([])
|
||||||
|
|
||||||
|
operation = parts[0].lower()
|
||||||
|
handlers = {
|
||||||
|
"add": self._op_add,
|
||||||
|
"list": self._op_list,
|
||||||
|
"get": self._op_get,
|
||||||
|
"search": self._op_search,
|
||||||
|
"delete": self._op_delete,
|
||||||
|
"edit": self._op_edit,
|
||||||
|
"export": self._op_export,
|
||||||
|
"import": self._op_import,
|
||||||
|
"tags": self._op_tags,
|
||||||
|
"stats": self._op_stats,
|
||||||
|
"recent": self._op_recent,
|
||||||
|
"copy": self._op_copy,
|
||||||
|
}
|
||||||
|
|
||||||
|
handler = handlers.get(operation)
|
||||||
|
if not handler:
|
||||||
|
return f"错误:不支持的操作 '{operation}'"
|
||||||
|
return handler(parts[1:])
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
return f"片段管理错误: {str(e)}"
|
||||||
|
|
||||||
|
def _parse_args(self, args: str) -> List[str]:
|
||||||
|
parts, current, in_quotes, qc = [], "", False, None
|
||||||
|
for ch in args:
|
||||||
|
if ch in ('"', "'") and not in_quotes:
|
||||||
|
in_quotes, qc = True, ch
|
||||||
|
elif ch == qc and in_quotes:
|
||||||
|
in_quotes, qc = False, None
|
||||||
|
elif ch == ' ' and not in_quotes:
|
||||||
|
if current:
|
||||||
|
parts.append(current)
|
||||||
|
current = ""
|
||||||
|
else:
|
||||||
|
current += ch
|
||||||
|
if current:
|
||||||
|
parts.append(current)
|
||||||
|
return parts
|
||||||
|
|
||||||
|
def _op_add(self, args: List[str]) -> str:
|
||||||
|
if not args:
|
||||||
|
return "错误:请提供片段名称"
|
||||||
|
name = args[0]
|
||||||
|
language, code, tags, desc = "", "", [], ""
|
||||||
|
|
||||||
|
i = 1
|
||||||
|
while i < len(args):
|
||||||
|
if args[i] == "-l" and i + 1 < len(args):
|
||||||
|
language = args[i + 1]; i += 1
|
||||||
|
elif args[i] == "-c" and i + 1 < len(args):
|
||||||
|
code = args[i + 1]; i += 1
|
||||||
|
elif args[i] == "-t" and i + 1 < len(args):
|
||||||
|
tags = [t.strip() for t in args[i + 1].split(",") if t.strip()]; i += 1
|
||||||
|
elif args[i] == "-d" and i + 1 < len(args):
|
||||||
|
desc = args[i + 1]; i += 1
|
||||||
|
i += 1
|
||||||
|
|
||||||
|
if not code:
|
||||||
|
return "错误:请用 -c 提供代码内容"
|
||||||
|
|
||||||
|
# 检查重名
|
||||||
|
for s in self.snippets:
|
||||||
|
if s["name"] == name:
|
||||||
|
return f"错误:片段 '{name}' 已存在,用 edit 更新"
|
||||||
|
|
||||||
|
snippet = {
|
||||||
|
"id": self._gen_id(name),
|
||||||
|
"name": name,
|
||||||
|
"language": language,
|
||||||
|
"code": code,
|
||||||
|
"tags": tags,
|
||||||
|
"description": desc,
|
||||||
|
"created_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
|
||||||
|
"usage_count": 0
|
||||||
|
}
|
||||||
|
self.snippets.append(snippet)
|
||||||
|
err = self._save_snippets()
|
||||||
|
if err:
|
||||||
|
return err
|
||||||
|
return f"✅ 已添加片段 '{name}' (ID: {snippet['id']}, 语言: {language or '未指定'})"
|
||||||
|
|
||||||
|
def _op_list(self, args: List[str]) -> str:
|
||||||
|
lang_filter, tag_filter = None, None
|
||||||
|
i = 0
|
||||||
|
while i < len(args):
|
||||||
|
if args[i] == "-l" and i + 1 < len(args):
|
||||||
|
lang_filter = args[i + 1].lower(); i += 1
|
||||||
|
elif args[i] == "-t" and i + 1 < len(args):
|
||||||
|
tag_filter = args[i + 1].lower(); i += 1
|
||||||
|
i += 1
|
||||||
|
|
||||||
|
filtered = self.snippets
|
||||||
|
if lang_filter:
|
||||||
|
filtered = [s for s in filtered if s.get("language", "").lower() == lang_filter]
|
||||||
|
if tag_filter:
|
||||||
|
filtered = [s for s in filtered if any(tag_filter in t.lower() for t in s.get("tags", []))]
|
||||||
|
|
||||||
|
if not filtered:
|
||||||
|
return "📭 没有找到代码片段"
|
||||||
|
|
||||||
|
result = f"\n📝 代码片段列表 (共 {len(filtered)} 个)\n"
|
||||||
|
result += "─" * 55 + "\n"
|
||||||
|
for s in filtered:
|
||||||
|
lang = s.get("language", "未知")
|
||||||
|
tags = ", ".join(s.get("tags", [])) if s.get("tags") else ""
|
||||||
|
code_preview = s.get("code", "")[:60].replace("\n", "↵")
|
||||||
|
result += f" [{s['id']}] {s['name']} ({lang})\n"
|
||||||
|
if tags:
|
||||||
|
result += f" ️ {tags}\n"
|
||||||
|
result += f" {code_preview}...\n"
|
||||||
|
result += f" ⏱ {s.get('created_at', '未知')}\n\n"
|
||||||
|
|
||||||
|
result += "─" * 55
|
||||||
|
return result
|
||||||
|
|
||||||
|
def _op_get(self, args: List[str]) -> str:
|
||||||
|
if not args:
|
||||||
|
return "错误:请提供片段名称或ID"
|
||||||
|
key = args[0]
|
||||||
|
snippet = self._find_snippet(key)
|
||||||
|
if not snippet:
|
||||||
|
return f"❌ 未找到片段: {key}"
|
||||||
|
|
||||||
|
snippet["usage_count"] = snippet.get("usage_count", 0) + 1
|
||||||
|
self._save_snippets()
|
||||||
|
|
||||||
|
result = f"\n 片段: {snippet['name']}\n"
|
||||||
|
result += "─" * 50 + "\n"
|
||||||
|
result += f" ID: {snippet['id']}\n"
|
||||||
|
result += f" 语言: {snippet.get('language', '未指定')}\n"
|
||||||
|
if snippet.get("tags"):
|
||||||
|
result += f" ️ 标签: {', '.join(snippet['tags'])}\n"
|
||||||
|
if snippet.get("description"):
|
||||||
|
result += f" 描述: {snippet['description']}\n"
|
||||||
|
result += f" 创建: {snippet.get('created_at', '未知')}\n"
|
||||||
|
result += f" 使用: {snippet.get('usage_count', 0)} 次\n"
|
||||||
|
result += "─" * 50 + "\n"
|
||||||
|
result += f" 代码:\n{snippet['code']}\n"
|
||||||
|
result += "─" * 50
|
||||||
|
return result
|
||||||
|
|
||||||
|
def _op_search(self, args: List[str]) -> str:
|
||||||
|
if not args:
|
||||||
|
return "错误:请提供搜索关键词"
|
||||||
|
keyword = " ".join(args).lower()
|
||||||
|
|
||||||
|
results = []
|
||||||
|
for s in self.snippets:
|
||||||
|
searchable = f"{s['name']} {s.get('description', '')} {s.get('code', '')} {' '.join(s.get('tags', []))} {s.get('language', '')}".lower()
|
||||||
|
if keyword in searchable:
|
||||||
|
results.append(s)
|
||||||
|
|
||||||
|
if not results:
|
||||||
|
return f" 未找到匹配 '{keyword}' 的片段"
|
||||||
|
|
||||||
|
output = f" 搜索结果 ({len(results)} 个):\n"
|
||||||
|
output += "─" * 50 + "\n"
|
||||||
|
for s in results:
|
||||||
|
lang = s.get("language", "")
|
||||||
|
output += f" [{s['id']}] {s['name']} ({lang}) - {s.get('description', '')[:40]}\n"
|
||||||
|
return output.rstrip()
|
||||||
|
|
||||||
|
def _op_delete(self, args: List[str]) -> str:
|
||||||
|
if not args:
|
||||||
|
return "错误:请提供片段名称或ID"
|
||||||
|
key = args[0]
|
||||||
|
for i, s in enumerate(self.snippets):
|
||||||
|
if s["name"] == key or s["id"] == key:
|
||||||
|
removed = self.snippets.pop(i)
|
||||||
|
self._save_snippets()
|
||||||
|
return f" ️ 已删除片段: {removed['name']}"
|
||||||
|
return f"❌ 未找到片段: {key}"
|
||||||
|
|
||||||
|
def _op_edit(self, args: List[str]) -> str:
|
||||||
|
if not args:
|
||||||
|
return "错误:请提供片段名称或ID"
|
||||||
|
key = args[0]
|
||||||
|
snippet = self._find_snippet(key)
|
||||||
|
if not snippet:
|
||||||
|
return f"❌ 未找到片段: {key}"
|
||||||
|
|
||||||
|
new_code = None
|
||||||
|
new_desc = None
|
||||||
|
i = 1
|
||||||
|
while i < len(args):
|
||||||
|
if args[i] == "-c" and i + 1 < len(args):
|
||||||
|
new_code = args[i + 1]; i += 1
|
||||||
|
elif args[i] == "-d" and i + 1 < len(args):
|
||||||
|
new_desc = args[i + 1]; i += 1
|
||||||
|
i += 1
|
||||||
|
|
||||||
|
if new_code:
|
||||||
|
snippet["code"] = new_code
|
||||||
|
if new_desc:
|
||||||
|
snippet["description"] = new_desc
|
||||||
|
snippet["updated_at"] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||||||
|
|
||||||
|
self._save_snippets()
|
||||||
|
return f"✅ 已更新片段: {snippet['name']}"
|
||||||
|
|
||||||
|
def _op_export(self, args: List[str]) -> str:
|
||||||
|
output_file = args[0] if args else "snippets_export.json"
|
||||||
|
try:
|
||||||
|
with open(output_file, 'w', encoding='utf-8') as f:
|
||||||
|
json.dump(self.snippets, f, ensure_ascii=False, indent=2)
|
||||||
|
return f"✅ 已导出 {len(self.snippets)} 个片段到: {output_file}"
|
||||||
|
except Exception as e:
|
||||||
|
return f"❌ 导出失败: {e}"
|
||||||
|
|
||||||
|
def _op_import(self, args: List[str]) -> str:
|
||||||
|
if not args:
|
||||||
|
return "错误:请提供导入文件路径"
|
||||||
|
file_path = args[0]
|
||||||
|
if not os.path.isfile(file_path):
|
||||||
|
return f"❌ 文件不存在: {file_path}"
|
||||||
|
try:
|
||||||
|
with open(file_path, 'r', encoding='utf-8') as f:
|
||||||
|
imported = json.load(f)
|
||||||
|
if not isinstance(imported, list):
|
||||||
|
return "❌ 文件格式错误:需要 JSON 数组"
|
||||||
|
|
||||||
|
existing_names = {s["name"] for s in self.snippets}
|
||||||
|
added = 0
|
||||||
|
for s in imported:
|
||||||
|
if isinstance(s, dict) and s.get("name") and s["name"] not in existing_names:
|
||||||
|
s["id"] = self._gen_id(s["name"])
|
||||||
|
self.snippets.append(s)
|
||||||
|
existing_names.add(s["name"])
|
||||||
|
added += 1
|
||||||
|
|
||||||
|
self._save_snippets()
|
||||||
|
return f"✅ 已导入 {added} 个片段 (跳过 {len(imported) - added} 个重复)"
|
||||||
|
except Exception as e:
|
||||||
|
return f"❌ 导入失败: {e}"
|
||||||
|
|
||||||
|
def _op_tags(self, args: List[str]) -> str:
|
||||||
|
tag_count = {}
|
||||||
|
for s in self.snippets:
|
||||||
|
for t in s.get("tags", []):
|
||||||
|
tag_count[t] = tag_count.get(t, 0) + 1
|
||||||
|
|
||||||
|
if not tag_count:
|
||||||
|
return " ️ 暂无标签"
|
||||||
|
|
||||||
|
result = " ️ 标签列表:\n"
|
||||||
|
for tag, count in sorted(tag_count.items(), key=lambda x: -x[1]):
|
||||||
|
result += f" {tag} ({count})\n"
|
||||||
|
return result.rstrip()
|
||||||
|
|
||||||
|
def _op_stats(self, args: List[str]) -> str:
|
||||||
|
total = len(self.snippets)
|
||||||
|
if not total:
|
||||||
|
return "📊 暂无片段"
|
||||||
|
|
||||||
|
lang_count = {}
|
||||||
|
total_usage = 0
|
||||||
|
for s in self.snippets:
|
||||||
|
lang = s.get("language", "未知")
|
||||||
|
lang_count[lang] = lang_count.get(lang, 0) + 1
|
||||||
|
total_usage += s.get("usage_count", 0)
|
||||||
|
|
||||||
|
result = f"📊 片段统计\n"
|
||||||
|
result += "─" * 30 + "\n"
|
||||||
|
result += f" 总数: {total}\n"
|
||||||
|
result += f" 总使用: {total_usage} 次\n"
|
||||||
|
result += f" 语言分布:\n"
|
||||||
|
for lang, count in sorted(lang_count.items(), key=lambda x: -x[1]):
|
||||||
|
result += f" {lang}: {count}\n"
|
||||||
|
return result.rstrip()
|
||||||
|
|
||||||
|
def _op_recent(self, args: List[str]) -> str:
|
||||||
|
count = 5
|
||||||
|
for i, a in enumerate(args):
|
||||||
|
if a == "-n" and i + 1 < len(args):
|
||||||
|
count = int(args[i + 1])
|
||||||
|
|
||||||
|
recent = sorted(self.snippets, key=lambda s: s.get("created_at", ""), reverse=True)[:count]
|
||||||
|
if not recent:
|
||||||
|
return "📭 暂无片段"
|
||||||
|
|
||||||
|
result = f"⏰ 最近 {len(recent)} 个片段:\n"
|
||||||
|
for s in recent:
|
||||||
|
result += f" [{s['id']}] {s['name']} - {s.get('created_at', '')}\n"
|
||||||
|
return result.rstrip()
|
||||||
|
|
||||||
|
def _op_copy(self, args: List[str]) -> str:
|
||||||
|
if not args:
|
||||||
|
return "错误:请提供片段名称或ID"
|
||||||
|
snippet = self._find_snippet(args[0])
|
||||||
|
if not snippet:
|
||||||
|
return f"❌ 未找到片段: {args[0]}"
|
||||||
|
|
||||||
|
snippet["usage_count"] = snippet.get("usage_count", 0) + 1
|
||||||
|
self._save_snippets()
|
||||||
|
return f" 代码内容 ({snippet['name']}):\n{snippet['code']}"
|
||||||
|
|
||||||
|
def _find_snippet(self, key: str) -> Optional[dict]:
|
||||||
|
for s in self.snippets:
|
||||||
|
if s["name"] == key or s["id"] == key:
|
||||||
|
return s
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def test_plugin():
|
||||||
|
plugin = Liugin()
|
||||||
|
print("代码片段管理器测试:")
|
||||||
|
print(plugin.handle('add hello -l python -c "print(\'Hello, World!\')" -t 示例,入门 -d 最简单的Python程序'))
|
||||||
|
print(plugin.handle('add fib -l python -c "def fib(n): return n if n < 2 else fib(n-1)+fib(n-2)" -t 算法,递归'))
|
||||||
|
print(plugin.handle('list'))
|
||||||
|
print(plugin.handle('search python'))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
test_plugin()
|
||||||
@@ -543,7 +543,7 @@ if __name__ == "__main__":
|
|||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
plugin = Plugin()
|
plugin = Liugin()
|
||||||
print("语音识别插件")
|
print("语音识别插件")
|
||||||
print(f"临时目录: {plugin.temp_dir}")
|
print(f"临时目录: {plugin.temp_dir}")
|
||||||
print("\n" + plugin.usage)
|
print("\n" + plugin.usage)
|
||||||
@@ -42,7 +42,7 @@ class SubAgent:
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
class Plugin:
|
class Liugin:
|
||||||
"""子 Agent 系统 - 创建、管理、协作"""
|
"""子 Agent 系统 - 创建、管理、协作"""
|
||||||
|
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
|
|||||||
@@ -258,7 +258,7 @@ JSON格式示例:
|
|||||||
# 测试函数
|
# 测试函数
|
||||||
def test_plugin():
|
def test_plugin():
|
||||||
"""测试插件功能"""
|
"""测试插件功能"""
|
||||||
plugin = Plugin()
|
plugin = Liugin()
|
||||||
print("任务管理插件测试:")
|
print("任务管理插件测试:")
|
||||||
|
|
||||||
print("\n1. 添加任务:")
|
print("\n1. 添加任务:")
|
||||||
|
|||||||
@@ -0,0 +1,804 @@
|
|||||||
|
"""
|
||||||
|
工作流插件 - YAML 定义的多步骤自动化流程
|
||||||
|
|
||||||
|
支持:
|
||||||
|
- 顺序执行多步骤
|
||||||
|
- 步骤间变量传递 ({{prev.output}})
|
||||||
|
- 条件分支 (on_fail / on_success)
|
||||||
|
- 错误处理 (continue_on_error)
|
||||||
|
- 状态持久化 (断点续跑)
|
||||||
|
- 调用其他插件作为步骤
|
||||||
|
|
||||||
|
用法:
|
||||||
|
/workflow run <file.yaml>
|
||||||
|
/workflow list
|
||||||
|
/workflow status <workflow_id>
|
||||||
|
/workflow resume <workflow_id>
|
||||||
|
/workflow abort <workflow_id>
|
||||||
|
"""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import time
|
||||||
|
import uuid
|
||||||
|
from datetime import datetime
|
||||||
|
from colorama import Fore, Style
|
||||||
|
|
||||||
|
|
||||||
|
# ── YAML 解析(内置轻量实现,不依赖 PyYAML) ──
|
||||||
|
|
||||||
|
def _parse_yaml(text: str) -> dict:
|
||||||
|
"""轻量 YAML 解析器,支持工作流所需的子集"""
|
||||||
|
import yaml # 延迟导入,失败时回退
|
||||||
|
return yaml.safe_load(text)
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_yaml_fallback(text: str) -> dict:
|
||||||
|
"""内置回退解析器,仅支持简单结构"""
|
||||||
|
result = {}
|
||||||
|
current_key = None
|
||||||
|
current_list = None
|
||||||
|
current_dict = None
|
||||||
|
|
||||||
|
for line in text.split('\n'):
|
||||||
|
stripped = line.strip()
|
||||||
|
if not stripped or stripped.startswith('#'):
|
||||||
|
continue
|
||||||
|
|
||||||
|
indent = len(line) - len(line.lstrip())
|
||||||
|
|
||||||
|
if indent == 0 and ':' in stripped:
|
||||||
|
key, _, val = stripped.partition(':')
|
||||||
|
key = key.strip()
|
||||||
|
val = val.strip()
|
||||||
|
if val:
|
||||||
|
result[key] = _yaml_value(val)
|
||||||
|
else:
|
||||||
|
result[key] = None
|
||||||
|
current_key = key
|
||||||
|
current_list = None
|
||||||
|
current_dict = None
|
||||||
|
elif indent > 0 and stripped.startswith('- '):
|
||||||
|
if current_key:
|
||||||
|
if not isinstance(result.get(current_key), list):
|
||||||
|
result[current_key] = []
|
||||||
|
item_text = stripped[2:].strip()
|
||||||
|
if ':' in item_text:
|
||||||
|
item = {}
|
||||||
|
k, _, v = item_text.partition(':')
|
||||||
|
item[k.strip()] = _yaml_value(v.strip())
|
||||||
|
current_dict = item
|
||||||
|
result[current_key].append(item)
|
||||||
|
else:
|
||||||
|
result[current_key].append(_yaml_value(item_text))
|
||||||
|
elif indent > 0 and ':' in stripped and current_dict is not None:
|
||||||
|
key, _, val = stripped.partition(':')
|
||||||
|
current_dict[key.strip()] = _yaml_value(val.strip())
|
||||||
|
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def _yaml_value(s: str):
|
||||||
|
"""转换单个 YAML 值"""
|
||||||
|
if not s:
|
||||||
|
return None
|
||||||
|
# 去除引号
|
||||||
|
if (s.startswith('"') and s.endswith('"')) or (s.startswith("'") and s.endswith("'")):
|
||||||
|
return s[1:-1]
|
||||||
|
if s.lower() in ('true', 'yes', 'on'):
|
||||||
|
return True
|
||||||
|
if s.lower() in ('false', 'no', 'off'):
|
||||||
|
return False
|
||||||
|
if s.lower() in ('null', 'none', '~'):
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
return int(s)
|
||||||
|
except ValueError:
|
||||||
|
pass
|
||||||
|
try:
|
||||||
|
return float(s)
|
||||||
|
except ValueError:
|
||||||
|
pass
|
||||||
|
return s
|
||||||
|
|
||||||
|
|
||||||
|
def _load_yaml_file(path: str) -> dict:
|
||||||
|
"""加载 YAML 文件"""
|
||||||
|
with open(path, 'r', encoding='utf-8') as f:
|
||||||
|
text = f.read()
|
||||||
|
try:
|
||||||
|
return _parse_yaml(text)
|
||||||
|
except ImportError:
|
||||||
|
return _parse_yaml_fallback(text)
|
||||||
|
|
||||||
|
|
||||||
|
# ── 变量替换引擎 ──
|
||||||
|
|
||||||
|
def _resolve_vars(text: str, context: dict) -> str:
|
||||||
|
"""
|
||||||
|
替换 {{key}} 和 {{key.nested}} 形式的变量
|
||||||
|
|
||||||
|
支持:
|
||||||
|
{{var}} → context['var']
|
||||||
|
{{step.output}} → context['steps']['step']['output']
|
||||||
|
{{step.exit_code}} → context['steps']['step']['exit_code']
|
||||||
|
{{env.HOME}} → os.environ['HOME']
|
||||||
|
{{args.name}} → context['args']['name']
|
||||||
|
"""
|
||||||
|
def replacer(match):
|
||||||
|
path = match.group(1).strip()
|
||||||
|
parts = path.split('.')
|
||||||
|
|
||||||
|
if parts[0] == 'env':
|
||||||
|
return os.environ.get('.'.join(parts[1:]), '')
|
||||||
|
|
||||||
|
if parts[0] == 'args' and len(parts) > 1:
|
||||||
|
val = context.get('args', {})
|
||||||
|
for p in parts[1:]:
|
||||||
|
if isinstance(val, dict):
|
||||||
|
val = val.get(p, '')
|
||||||
|
else:
|
||||||
|
return ''
|
||||||
|
return str(val)
|
||||||
|
|
||||||
|
if parts[0] == 'steps' and len(parts) >= 3:
|
||||||
|
step_name = parts[1]
|
||||||
|
attr = parts[2]
|
||||||
|
step_data = context.get('steps', {}).get(step_name, {})
|
||||||
|
val = step_data.get(attr, '')
|
||||||
|
# 支持 deeper nesting: {{steps.foo.output.field}}
|
||||||
|
for p in parts[3:]:
|
||||||
|
if isinstance(val, dict):
|
||||||
|
val = val.get(p, '')
|
||||||
|
else:
|
||||||
|
return ''
|
||||||
|
return str(val)
|
||||||
|
|
||||||
|
# 顶层变量
|
||||||
|
val = context
|
||||||
|
for p in parts:
|
||||||
|
if isinstance(val, dict):
|
||||||
|
val = val.get(p, '')
|
||||||
|
else:
|
||||||
|
return ''
|
||||||
|
return str(val)
|
||||||
|
|
||||||
|
return re.sub(r'\{\{(.+?)\}\}', replacer, text)
|
||||||
|
|
||||||
|
|
||||||
|
def _resolve_value(val, context):
|
||||||
|
"""递归解析值中的变量(支持 dict/list/str)"""
|
||||||
|
if isinstance(val, str):
|
||||||
|
return _resolve_vars(val, context)
|
||||||
|
elif isinstance(val, dict):
|
||||||
|
return {k: _resolve_value(v, context) for k, v in val.items()}
|
||||||
|
elif isinstance(val, list):
|
||||||
|
return [_resolve_value(item, context) for item in val]
|
||||||
|
return val
|
||||||
|
|
||||||
|
|
||||||
|
# ── 工作流引擎 ──
|
||||||
|
|
||||||
|
class WorkflowEngine:
|
||||||
|
"""工作流执行引擎"""
|
||||||
|
|
||||||
|
def __init__(self, cli_instance=None):
|
||||||
|
self.cli = cli_instance
|
||||||
|
self.workflows_dir = "workflows"
|
||||||
|
self.state_dir = os.path.join(self.workflows_dir, ".state")
|
||||||
|
os.makedirs(self.state_dir, exist_ok=True)
|
||||||
|
|
||||||
|
def run(self, path: str, args: dict = None) -> str:
|
||||||
|
"""执行工作流"""
|
||||||
|
if not os.path.exists(path):
|
||||||
|
return f"❌ 工作流文件不存在: {path}"
|
||||||
|
|
||||||
|
try:
|
||||||
|
wf = _load_yaml_file(path)
|
||||||
|
except Exception as e:
|
||||||
|
return f"❌ 解析工作流文件失败: {e}"
|
||||||
|
|
||||||
|
wf_name = wf.get('name', os.path.basename(path).replace('.yaml', '').replace('.yml', ''))
|
||||||
|
steps = wf.get('steps', [])
|
||||||
|
if not steps:
|
||||||
|
return f"❌ 工作流 '{wf_name}' 没有步骤"
|
||||||
|
|
||||||
|
wf_id = f"{wf_name}-{uuid.uuid4().hex[:8]}"
|
||||||
|
context = {
|
||||||
|
'args': args or {},
|
||||||
|
'steps': {},
|
||||||
|
'workflow': {
|
||||||
|
'id': wf_id,
|
||||||
|
'name': wf_name,
|
||||||
|
'path': path,
|
||||||
|
'started_at': datetime.now().isoformat(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# 保存初始状态
|
||||||
|
self._save_state(wf_id, {
|
||||||
|
'workflow': wf_name,
|
||||||
|
'path': path,
|
||||||
|
'status': 'running',
|
||||||
|
'current_step': 0,
|
||||||
|
'context': context,
|
||||||
|
'started_at': context['workflow']['started_at'],
|
||||||
|
})
|
||||||
|
|
||||||
|
print(f"\n{Fore.CYAN}🔄 工作流 '{wf_name}' 开始 (ID: {wf_id}){Style.RESET_ALL}")
|
||||||
|
print(f" 共 {len(steps)} 个步骤\n")
|
||||||
|
|
||||||
|
failed = False
|
||||||
|
for i, step in enumerate(steps):
|
||||||
|
step_name = step.get('name', f'step_{i+1}')
|
||||||
|
step_type = step.get('type', 'tool')
|
||||||
|
condition = step.get('if', None)
|
||||||
|
continue_on_error = step.get('continue_on_error', False)
|
||||||
|
|
||||||
|
# 检查条件
|
||||||
|
if condition:
|
||||||
|
resolved_condition = _resolve_vars(condition, context)
|
||||||
|
if not self._eval_condition(resolved_condition):
|
||||||
|
print(f" {Fore.YELLOW}⏭ [{step_name}] 条件不满足,跳过{Style.RESET_ALL}")
|
||||||
|
context['steps'][step_name] = {
|
||||||
|
'output': '', 'exit_code': 0, 'skipped': True
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
|
||||||
|
# 解析步骤参数
|
||||||
|
resolved_step = _resolve_value(step, context)
|
||||||
|
|
||||||
|
print(f" {Fore.CYAN}▶ [{step_name}] {step_type}{Style.RESET_ALL}")
|
||||||
|
|
||||||
|
# 更新状态
|
||||||
|
self._save_state(wf_id, {
|
||||||
|
'workflow': wf_name,
|
||||||
|
'path': path,
|
||||||
|
'status': 'running',
|
||||||
|
'current_step': i,
|
||||||
|
'current_step_name': step_name,
|
||||||
|
'context': context,
|
||||||
|
'started_at': context['workflow']['started_at'],
|
||||||
|
})
|
||||||
|
|
||||||
|
try:
|
||||||
|
result = self._execute_step(resolved_step, context)
|
||||||
|
context['steps'][step_name] = result
|
||||||
|
|
||||||
|
if result.get('exit_code', 0) == 0:
|
||||||
|
output_preview = str(result.get('output', ''))[:100]
|
||||||
|
print(f" {Fore.GREEN}✓ [{step_name}] 完成{Style.RESET_ALL}"
|
||||||
|
f"{' → ' + output_preview if output_preview else ''}")
|
||||||
|
else:
|
||||||
|
failed = True
|
||||||
|
print(f" {Fore.RED}✗ [{step_name}] 失败 (exit={result.get('exit_code')}){Style.RESET_ALL}")
|
||||||
|
print(f" {result.get('error', result.get('output', ''))[:200]}")
|
||||||
|
|
||||||
|
if not continue_on_error:
|
||||||
|
# 检查 on_fail 分支
|
||||||
|
on_fail = resolved_step.get('on_fail')
|
||||||
|
if on_fail:
|
||||||
|
print(f" {Fore.YELLOW}→ 执行 on_fail 分支{Style.RESET_ALL}")
|
||||||
|
self._execute_on_fail(on_fail, context)
|
||||||
|
break
|
||||||
|
else:
|
||||||
|
print(f" {Fore.YELLOW}⚠ continue_on_error=true,继续{Style.RESET_ALL}")
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
failed = True
|
||||||
|
context['steps'][step_name] = {
|
||||||
|
'output': '', 'exit_code': 1, 'error': str(e)
|
||||||
|
}
|
||||||
|
print(f" {Fore.RED}✗ [{step_name}] 异常: {e}{Style.RESET_ALL}")
|
||||||
|
if not continue_on_error:
|
||||||
|
break
|
||||||
|
|
||||||
|
# 完成状态
|
||||||
|
status = 'failed' if failed else 'completed'
|
||||||
|
context['workflow']['finished_at'] = datetime.now().isoformat()
|
||||||
|
context['workflow']['status'] = status
|
||||||
|
|
||||||
|
self._save_state(wf_id, {
|
||||||
|
'workflow': wf_name,
|
||||||
|
'path': path,
|
||||||
|
'status': status,
|
||||||
|
'current_step': len(steps),
|
||||||
|
'context': context,
|
||||||
|
'started_at': context['workflow']['started_at'],
|
||||||
|
'finished_at': context['workflow']['finished_at'],
|
||||||
|
})
|
||||||
|
|
||||||
|
icon = '✅' if not failed else '❌'
|
||||||
|
print(f"\n{icon} 工作流 '{wf_name}' {status} (ID: {wf_id})")
|
||||||
|
return f"{icon} 工作流 '{wf_name}' {status}"
|
||||||
|
|
||||||
|
def resume(self, wf_id: str) -> str:
|
||||||
|
"""从断点恢复执行工作流"""
|
||||||
|
state = self._load_state(wf_id)
|
||||||
|
if not state:
|
||||||
|
return f"❌ 未找到工作流状态: {wf_id}"
|
||||||
|
|
||||||
|
if state.get('status') == 'completed':
|
||||||
|
return f"ℹ️ 工作流已完成: {wf_id}"
|
||||||
|
|
||||||
|
path = state.get('path', '')
|
||||||
|
if not os.path.exists(path):
|
||||||
|
return f"❌ 工作流文件不存在: {path}"
|
||||||
|
|
||||||
|
try:
|
||||||
|
wf = _load_yaml_file(path)
|
||||||
|
except Exception as e:
|
||||||
|
return f"❌ 解析工作流文件失败: {e}"
|
||||||
|
|
||||||
|
steps = wf.get('steps', [])
|
||||||
|
start_from = state.get('current_step', 0)
|
||||||
|
context = state.get('context', {})
|
||||||
|
|
||||||
|
print(f"\n{Fore.CYAN}🔄 恢复工作流 '{wf.get('name', wf_id)}' 从步骤 {start_from + 1}{Style.RESET_ALL}")
|
||||||
|
|
||||||
|
failed = False
|
||||||
|
for i in range(start_from, len(steps)):
|
||||||
|
step = steps[i]
|
||||||
|
step_name = step.get('name', f'step_{i+1}')
|
||||||
|
step_type = step.get('type', 'tool')
|
||||||
|
continue_on_error = step.get('continue_on_error', False)
|
||||||
|
|
||||||
|
resolved_step = _resolve_value(step, context)
|
||||||
|
print(f" {Fore.CYAN}▶ [{step_name}] {step_type}{Style.RESET_ALL}")
|
||||||
|
|
||||||
|
try:
|
||||||
|
result = self._execute_step(resolved_step, context)
|
||||||
|
context['steps'][step_name] = result
|
||||||
|
|
||||||
|
if result.get('exit_code', 0) == 0:
|
||||||
|
print(f" {Fore.GREEN}✓ [{step_name}] 完成{Style.RESET_ALL}")
|
||||||
|
else:
|
||||||
|
failed = True
|
||||||
|
print(f" {Fore.RED}✗ [{step_name}] 失败{Style.RESET_ALL}")
|
||||||
|
if not continue_on_error:
|
||||||
|
break
|
||||||
|
except Exception as e:
|
||||||
|
failed = True
|
||||||
|
context['steps'][step_name] = {'output': '', 'exit_code': 1, 'error': str(e)}
|
||||||
|
print(f" {Fore.RED}✗ [{step_name}] 异常: {e}{Style.RESET_ALL}")
|
||||||
|
if not continue_on_error:
|
||||||
|
break
|
||||||
|
|
||||||
|
status = 'failed' if failed else 'completed'
|
||||||
|
self._save_state(wf_id, {**state, 'status': status, 'current_step': len(steps)})
|
||||||
|
|
||||||
|
return f"{'✅' if not failed else '❌'} 工作流 {status}"
|
||||||
|
|
||||||
|
def list_workflows(self) -> str:
|
||||||
|
"""列出所有工作流文件"""
|
||||||
|
if not os.path.exists(self.workflows_dir):
|
||||||
|
return "📁 workflows/ 目录不存在"
|
||||||
|
|
||||||
|
files = [f for f in os.listdir(self.workflows_dir)
|
||||||
|
if f.endswith(('.yaml', '.yml')) and not f.startswith('.')]
|
||||||
|
|
||||||
|
if not files:
|
||||||
|
return "📁 workflows/ 目录中没有工作流文件"
|
||||||
|
|
||||||
|
result = f"📁 工作流列表 ({len(files)} 个):\n"
|
||||||
|
for f in sorted(files):
|
||||||
|
path = os.path.join(self.workflows_dir, f)
|
||||||
|
try:
|
||||||
|
wf = _load_yaml_file(path)
|
||||||
|
name = wf.get('name', f.replace('.yaml', '').replace('.yml', ''))
|
||||||
|
desc = wf.get('description', '')
|
||||||
|
steps_count = len(wf.get('steps', []))
|
||||||
|
result += f" 📄 {f}\n"
|
||||||
|
result += f" 名称: {name} 步骤: {steps_count}\n"
|
||||||
|
if desc:
|
||||||
|
result += f" 描述: {desc}\n"
|
||||||
|
except Exception:
|
||||||
|
result += f" 📄 {f} (解析失败)\n"
|
||||||
|
return result
|
||||||
|
|
||||||
|
def status(self, wf_id: str) -> str:
|
||||||
|
"""查看工作流状态"""
|
||||||
|
state = self._load_state(wf_id)
|
||||||
|
if not state:
|
||||||
|
return f"❌ 未找到工作流: {wf_id}"
|
||||||
|
|
||||||
|
ctx = state.get('context', {})
|
||||||
|
wf_info = ctx.get('workflow', {})
|
||||||
|
steps_done = ctx.get('steps', {})
|
||||||
|
|
||||||
|
lines = [
|
||||||
|
f"📋 工作流: {state.get('workflow', '?')}",
|
||||||
|
f" ID: {wf_id}",
|
||||||
|
f" 状态: {state.get('status', '?')}",
|
||||||
|
f" 进度: 步骤 {state.get('current_step', 0)}",
|
||||||
|
f" 开始: {state.get('started_at', '?')}",
|
||||||
|
]
|
||||||
|
if state.get('finished_at'):
|
||||||
|
lines.append(f" 结束: {state['finished_at']}")
|
||||||
|
|
||||||
|
if steps_done:
|
||||||
|
lines.append(f" 已完成步骤:")
|
||||||
|
for name, data in steps_done.items():
|
||||||
|
icon = '✓' if data.get('exit_code', 0) == 0 else ('⏭' if data.get('skipped') else '✗')
|
||||||
|
lines.append(f" {icon} {name}")
|
||||||
|
|
||||||
|
return '\n'.join(lines)
|
||||||
|
|
||||||
|
def list_states(self) -> str:
|
||||||
|
"""列出所有工作流运行状态"""
|
||||||
|
if not os.path.exists(self.state_dir):
|
||||||
|
return "没有工作流运行记录"
|
||||||
|
|
||||||
|
files = [f for f in os.listdir(self.state_dir) if f.endswith('.json')]
|
||||||
|
if not files:
|
||||||
|
return "没有工作流运行记录"
|
||||||
|
|
||||||
|
result = f"📋 工作流运行记录 ({len(files)} 个):\n"
|
||||||
|
for f in sorted(files, reverse=True)[:20]:
|
||||||
|
wf_id = f.replace('.json', '')
|
||||||
|
try:
|
||||||
|
with open(os.path.join(self.state_dir, f), 'r') as fh:
|
||||||
|
state = json.load(fh)
|
||||||
|
status_icon = {'running': '🔄', 'completed': '✅', 'failed': '❌'}.get(state.get('status'), '❓')
|
||||||
|
result += f" {status_icon} {wf_id} — {state.get('workflow', '?')} ({state.get('status', '?')})\n"
|
||||||
|
except Exception:
|
||||||
|
result += f" ❓ {wf_id}\n"
|
||||||
|
return result
|
||||||
|
|
||||||
|
def abort(self, wf_id: str) -> str:
|
||||||
|
"""中止工作流"""
|
||||||
|
state = self._load_state(wf_id)
|
||||||
|
if not state:
|
||||||
|
return f"❌ 未找到工作流: {wf_id}"
|
||||||
|
|
||||||
|
state['status'] = 'aborted'
|
||||||
|
self._save_state(wf_id, state)
|
||||||
|
return f"🛑 工作流已中止: {wf_id}"
|
||||||
|
|
||||||
|
# ── 步骤执行 ──
|
||||||
|
|
||||||
|
def _execute_step(self, step: dict, context: dict) -> dict:
|
||||||
|
"""执行单个步骤"""
|
||||||
|
step_type = step.get('type', 'tool')
|
||||||
|
|
||||||
|
if step_type == 'tool':
|
||||||
|
return self._exec_tool_step(step, context)
|
||||||
|
elif step_type == 'shell':
|
||||||
|
return self._exec_shell_step(step, context)
|
||||||
|
elif step_type == 'set':
|
||||||
|
return self._exec_set_step(step, context)
|
||||||
|
elif step_type == 'echo':
|
||||||
|
return self._exec_echo_step(step, context)
|
||||||
|
elif step_type == 'wait':
|
||||||
|
return self._exec_wait_step(step, context)
|
||||||
|
elif step_type == 'if':
|
||||||
|
return self._exec_if_step(step, context)
|
||||||
|
else:
|
||||||
|
return {'output': '', 'exit_code': 1, 'error': f'未知步骤类型: {step_type}'}
|
||||||
|
|
||||||
|
def _exec_tool_step(self, step: dict, context: dict) -> dict:
|
||||||
|
"""执行插件工具步骤"""
|
||||||
|
tool_name = step.get('tool', '')
|
||||||
|
tool_args = step.get('args', '')
|
||||||
|
|
||||||
|
if not tool_name:
|
||||||
|
return {'output': '', 'exit_code': 1, 'error': '未指定 tool 名称'}
|
||||||
|
|
||||||
|
if not self.cli:
|
||||||
|
return {'output': '', 'exit_code': 1, 'error': 'CLI 实例不可用'}
|
||||||
|
|
||||||
|
try:
|
||||||
|
# 获取工具管理器
|
||||||
|
tool_mgr = getattr(self.cli, 'tool_manager', None) or getattr(self.cli, 'liugin_manager', None)
|
||||||
|
if not tool_mgr:
|
||||||
|
return {'output': '', 'exit_code': 1, 'error': '工具管理器不可用'}
|
||||||
|
|
||||||
|
# 解析参数
|
||||||
|
args_str = str(tool_args) if tool_args else ''
|
||||||
|
|
||||||
|
# 调用工具
|
||||||
|
if hasattr(tool_mgr, 'execute'):
|
||||||
|
result = tool_mgr.execute(tool_name, args_str)
|
||||||
|
output = result.get('result', '') if isinstance(result, dict) else str(result)
|
||||||
|
elif hasattr(tool_mgr, 'tools'):
|
||||||
|
# LiuginManager 兼容
|
||||||
|
tool = tool_mgr.get_tool_by_name(tool_name)
|
||||||
|
if tool and 'handler' in tool:
|
||||||
|
output = tool['handler'](args_str)
|
||||||
|
else:
|
||||||
|
return {'output': '', 'exit_code': 1, 'error': f'未找到工具: {tool_name}'}
|
||||||
|
else:
|
||||||
|
return {'output': '', 'exit_code': 1, 'error': '无法调用工具'}
|
||||||
|
|
||||||
|
return {'output': str(output), 'exit_code': 0}
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
return {'output': '', 'exit_code': 1, 'error': str(e)}
|
||||||
|
|
||||||
|
def _exec_shell_step(self, step: dict, context: dict) -> dict:
|
||||||
|
"""执行 shell 命令步骤"""
|
||||||
|
import subprocess
|
||||||
|
|
||||||
|
cmd = step.get('command', step.get('cmd', ''))
|
||||||
|
if not cmd:
|
||||||
|
return {'output': '', 'exit_code': 1, 'error': '未指定 command'}
|
||||||
|
|
||||||
|
cwd = step.get('cwd', None)
|
||||||
|
timeout = step.get('timeout', 60)
|
||||||
|
|
||||||
|
try:
|
||||||
|
result = subprocess.run(
|
||||||
|
cmd, shell=True, capture_output=True, text=True,
|
||||||
|
timeout=timeout, cwd=cwd
|
||||||
|
)
|
||||||
|
return {
|
||||||
|
'output': result.stdout.strip(),
|
||||||
|
'error': result.stderr.strip(),
|
||||||
|
'exit_code': result.returncode,
|
||||||
|
}
|
||||||
|
except subprocess.TimeoutExpired:
|
||||||
|
return {'output': '', 'exit_code': 1, 'error': f'命令超时 ({timeout}s)'}
|
||||||
|
except Exception as e:
|
||||||
|
return {'output': '', 'exit_code': 1, 'error': str(e)}
|
||||||
|
|
||||||
|
def _exec_set_step(self, step: dict, context: dict) -> dict:
|
||||||
|
"""设置变量步骤"""
|
||||||
|
variables = step.get('variables', step.get('vars', {}))
|
||||||
|
for key, val in variables.items():
|
||||||
|
context[key] = _resolve_value(val, context)
|
||||||
|
return {'output': f'设置 {len(variables)} 个变量', 'exit_code': 0}
|
||||||
|
|
||||||
|
def _exec_echo_step(self, step: dict, context: dict) -> dict:
|
||||||
|
"""打印步骤"""
|
||||||
|
message = step.get('message', step.get('text', ''))
|
||||||
|
resolved = _resolve_vars(str(message), context)
|
||||||
|
print(f" 💬 {resolved}")
|
||||||
|
return {'output': resolved, 'exit_code': 0}
|
||||||
|
|
||||||
|
def _exec_wait_step(self, step: dict, context: dict) -> dict:
|
||||||
|
"""等待步骤"""
|
||||||
|
seconds = step.get('seconds', step.get('time', 1))
|
||||||
|
time.sleep(seconds)
|
||||||
|
return {'output': f'等待 {seconds} 秒', 'exit_code': 0}
|
||||||
|
|
||||||
|
def _exec_if_step(self, step: dict, context: dict) -> dict:
|
||||||
|
"""条件分支步骤"""
|
||||||
|
condition = step.get('condition', '')
|
||||||
|
resolved = _resolve_vars(str(condition), context)
|
||||||
|
|
||||||
|
if self._eval_condition(resolved):
|
||||||
|
then_steps = step.get('then', [])
|
||||||
|
return self._run_sub_steps(then_steps, context)
|
||||||
|
else:
|
||||||
|
else_steps = step.get('else', [])
|
||||||
|
if else_steps:
|
||||||
|
return self._run_sub_steps(else_steps, context)
|
||||||
|
return {'output': '条件不满足,无 else 分支', 'exit_code': 0}
|
||||||
|
|
||||||
|
def _run_sub_steps(self, steps: list, context: dict) -> dict:
|
||||||
|
"""执行子步骤列表"""
|
||||||
|
outputs = []
|
||||||
|
for sub_step in steps:
|
||||||
|
result = self._execute_step(sub_step, context)
|
||||||
|
outputs.append(result.get('output', ''))
|
||||||
|
if result.get('exit_code', 0) != 0:
|
||||||
|
return result
|
||||||
|
return {'output': '\n'.join(outputs), 'exit_code': 0}
|
||||||
|
|
||||||
|
def _eval_condition(self, condition: str) -> bool:
|
||||||
|
"""评估条件表达式"""
|
||||||
|
condition = condition.strip()
|
||||||
|
if not condition:
|
||||||
|
return True
|
||||||
|
|
||||||
|
# 简单比较: "value == expected"
|
||||||
|
for op in ['==', '!=', '>=', '<=', '>', '<']:
|
||||||
|
if op in condition:
|
||||||
|
left, _, right = condition.partition(op)
|
||||||
|
left = left.strip().strip('"').strip("'")
|
||||||
|
right = right.strip().strip('"').strip("'")
|
||||||
|
try:
|
||||||
|
left_n, right_n = float(left), float(right)
|
||||||
|
if op == '==': return left_n == right_n
|
||||||
|
if op == '!=': return left_n != right_n
|
||||||
|
if op == '>=': return left_n >= right_n
|
||||||
|
if op == '<=': return left_n <= right_n
|
||||||
|
if op == '>': return left_n > right_n
|
||||||
|
if op == '<': return left_n < right_n
|
||||||
|
except ValueError:
|
||||||
|
if op == '==': return left == right
|
||||||
|
if op == '!=': return left != right
|
||||||
|
|
||||||
|
# 布尔值
|
||||||
|
if condition.lower() in ('true', '1', 'yes'):
|
||||||
|
return True
|
||||||
|
if condition.lower() in ('false', '0', 'no', ''):
|
||||||
|
return False
|
||||||
|
|
||||||
|
# 非空即真
|
||||||
|
return bool(condition)
|
||||||
|
|
||||||
|
def _execute_on_fail(self, on_fail, context: dict):
|
||||||
|
"""执行 on_fail 处理"""
|
||||||
|
if isinstance(on_fail, str):
|
||||||
|
print(f" 💬 {on_fail}")
|
||||||
|
elif isinstance(on_fail, list):
|
||||||
|
for step in on_fail:
|
||||||
|
self._execute_step(step, context)
|
||||||
|
|
||||||
|
# ── 状态持久化 ──
|
||||||
|
|
||||||
|
def _save_state(self, wf_id: str, state: dict):
|
||||||
|
"""保存工作流状态"""
|
||||||
|
path = os.path.join(self.state_dir, f"{wf_id}.json")
|
||||||
|
try:
|
||||||
|
with open(path, 'w', encoding='utf-8') as f:
|
||||||
|
json.dump(state, f, ensure_ascii=False, indent=2, default=str)
|
||||||
|
except Exception as e:
|
||||||
|
print(f"{Fore.YELLOW}⚠ 保存状态失败: {e}{Style.RESET_ALL}")
|
||||||
|
|
||||||
|
def _load_state(self, wf_id: str) -> dict:
|
||||||
|
"""加载工作流状态"""
|
||||||
|
path = os.path.join(self.state_dir, f"{wf_id}.json")
|
||||||
|
if not os.path.exists(path):
|
||||||
|
return {}
|
||||||
|
try:
|
||||||
|
with open(path, 'r', encoding='utf-8') as f:
|
||||||
|
return json.load(f)
|
||||||
|
except Exception:
|
||||||
|
return {}
|
||||||
|
|
||||||
|
|
||||||
|
# ── Liugin 插件接口 ──
|
||||||
|
|
||||||
|
class Liugin:
|
||||||
|
"""工作流插件"""
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
self.engine = None
|
||||||
|
self.usage = """工作流工具使用方法:
|
||||||
|
|
||||||
|
JSON格式示例:
|
||||||
|
{"action": "use_tool", "tool": "workflow", "args": "run deploy.yaml"} - 执行工作流
|
||||||
|
{"action": "use_tool", "tool": "workflow", "args": "list"} - 列出工作流文件
|
||||||
|
{"action": "use_tool", "tool": "workflow", "args": "states"} - 查看运行记录
|
||||||
|
{"action": "use_tool", "tool": "workflow", "args": "status <id>"} - 查看状态
|
||||||
|
{"action": "use_tool", "tool": "workflow", "args": "resume <id>"} - 恢复执行
|
||||||
|
{"action": "use_tool", "tool": "workflow", "args": "abort <id>"} - 中止工作流
|
||||||
|
|
||||||
|
工作流 YAML 格式示例:
|
||||||
|
name: deploy
|
||||||
|
description: 部署流程
|
||||||
|
steps:
|
||||||
|
- name: lint
|
||||||
|
type: shell
|
||||||
|
command: "npm run lint"
|
||||||
|
- name: test
|
||||||
|
type: shell
|
||||||
|
command: "npm test"
|
||||||
|
continue_on_error: true
|
||||||
|
- name: build
|
||||||
|
type: shell
|
||||||
|
command: "npm run build"
|
||||||
|
if: "{{test.exit_code}} == 0"
|
||||||
|
- name: notify
|
||||||
|
type: echo
|
||||||
|
message: "构建完成: {{build.output}}"
|
||||||
|
|
||||||
|
支持的步骤类型:
|
||||||
|
- tool: 调用插件工具 (tool, args)
|
||||||
|
- shell: 执行系统命令 (command, cwd, timeout)
|
||||||
|
- echo: 打印消息 (message)
|
||||||
|
- wait: 等待 (seconds)
|
||||||
|
- set: 设置变量 (variables)
|
||||||
|
- if: 条件分支 (condition, then, else)
|
||||||
|
|
||||||
|
变量引用:
|
||||||
|
{{steps.step_name.output}} - 步骤输出
|
||||||
|
{{steps.step_name.exit_code}} - 步骤退出码
|
||||||
|
{{env.VAR_NAME}} - 环境变量
|
||||||
|
{{args.param}} - 工作流参数"""
|
||||||
|
|
||||||
|
def set_cli(self, cli):
|
||||||
|
self.cli = cli
|
||||||
|
self.engine = WorkflowEngine(cli)
|
||||||
|
cli.register_liugin_command('workflow', self.command_handler)
|
||||||
|
cli.register_liugin_command('wf', self.command_handler)
|
||||||
|
|
||||||
|
def command_handler(self, args):
|
||||||
|
return self.handle(args)
|
||||||
|
|
||||||
|
def get_tool_info(self):
|
||||||
|
return {
|
||||||
|
"name": "workflow",
|
||||||
|
"description": "工作流引擎 - YAML 定义的多步骤自动化流程,支持变量传递、条件分支、断点续跑",
|
||||||
|
"keywords": ["workflow", "工作流", "流程", "自动化", "pipeline", "deploy", "build", "run"],
|
||||||
|
"usage": self.usage
|
||||||
|
}
|
||||||
|
|
||||||
|
def get_mcp_definition(self):
|
||||||
|
return {
|
||||||
|
"name": "workflow",
|
||||||
|
"description": "工作流引擎 - 执行、管理 YAML 定义的自动化工作流",
|
||||||
|
"inputSchema": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"operation": {
|
||||||
|
"type": "string",
|
||||||
|
"enum": ["run", "list", "states", "status", "resume", "abort"],
|
||||||
|
"description": "操作类型"
|
||||||
|
},
|
||||||
|
"target": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "工作流文件路径(run) 或工作流ID(status/resume/abort)"
|
||||||
|
},
|
||||||
|
"args": {
|
||||||
|
"type": "object",
|
||||||
|
"description": "工作流参数 (run 时使用)"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": ["operation"]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
def convert_mcp_args(self, arguments):
|
||||||
|
op = arguments.get("operation", "")
|
||||||
|
target = arguments.get("target", "")
|
||||||
|
args = arguments.get("args", "")
|
||||||
|
if args and isinstance(args, dict):
|
||||||
|
args_str = ' '.join(f'{k}={v}' for k, v in args.items())
|
||||||
|
return f"{op} {target} {args_str}".strip()
|
||||||
|
return f"{op} {target}".strip()
|
||||||
|
|
||||||
|
def handle(self, args):
|
||||||
|
try:
|
||||||
|
args = args.strip()
|
||||||
|
if not args:
|
||||||
|
return self.usage
|
||||||
|
|
||||||
|
parts = args.split(None, 2)
|
||||||
|
action = parts[0].lower()
|
||||||
|
|
||||||
|
if action == 'run':
|
||||||
|
if len(parts) < 2:
|
||||||
|
return "❌ 请指定工作流文件: workflow run <file.yaml>"
|
||||||
|
path = parts[1]
|
||||||
|
# 解析内联参数
|
||||||
|
wf_args = {}
|
||||||
|
if len(parts) > 2:
|
||||||
|
for part in parts[2].split():
|
||||||
|
if '=' in part:
|
||||||
|
k, v = part.split('=', 1)
|
||||||
|
wf_args[k] = v
|
||||||
|
return self.engine.run(path, wf_args)
|
||||||
|
|
||||||
|
elif action == 'list':
|
||||||
|
return self.engine.list_workflows()
|
||||||
|
|
||||||
|
elif action == 'states':
|
||||||
|
return self.engine.list_states()
|
||||||
|
|
||||||
|
elif action == 'status':
|
||||||
|
if len(parts) < 2:
|
||||||
|
return "❌ 请指定工作流 ID: workflow status <id>"
|
||||||
|
return self.engine.status(parts[1])
|
||||||
|
|
||||||
|
elif action == 'resume':
|
||||||
|
if len(parts) < 2:
|
||||||
|
return "❌ 请指定工作流 ID: workflow resume <id>"
|
||||||
|
return self.engine.resume(parts[1])
|
||||||
|
|
||||||
|
elif action == 'abort':
|
||||||
|
if len(parts) < 2:
|
||||||
|
return "❌ 请指定工作流 ID: workflow abort <id>"
|
||||||
|
return self.engine.abort(parts[1])
|
||||||
|
|
||||||
|
else:
|
||||||
|
# 默认当作 run
|
||||||
|
if os.path.exists(action):
|
||||||
|
return self.engine.run(action)
|
||||||
|
return f"❌ 未知操作: {action}\n\n{self.usage}"
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
return f"❌ 工作流操作错误: {e}"
|
||||||
@@ -16,3 +16,5 @@ ENABLE_TOOL_SEARCH = True
|
|||||||
ENABLE_AUTO_ENGINEER = True
|
ENABLE_AUTO_ENGINEER = True
|
||||||
ENABLE_GIT_WORKFLOW = True
|
ENABLE_GIT_WORKFLOW = True
|
||||||
ENABLE_PROJECT_ANALYZER = True
|
ENABLE_PROJECT_ANALYZER = True
|
||||||
|
|
||||||
|
ENABLE_DGLAB_WS = False
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
Line 1
|
|
||||||
MODIFIED LINE
|
|
||||||
Line 3
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
Line 1
|
|
||||||
REPLACED LINE 2
|
|
||||||
Line 3
|
|
||||||
REPLACED LINE 4
|
|
||||||
Line 5
|
|
||||||
@@ -357,6 +357,147 @@ class TestBrowserAuto:
|
|||||||
# 引擎加载测试
|
# 引擎加载测试
|
||||||
# ══════════════════════════════════════
|
# ══════════════════════════════════════
|
||||||
|
|
||||||
|
class TestGuiAuto:
|
||||||
|
"""gui_auto 功能测试"""
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def gui(self):
|
||||||
|
mod = load_module("gui_auto", os.path.join(PLUGINS_DIR, "gui_auto.py"))
|
||||||
|
return mod.Plugin()
|
||||||
|
|
||||||
|
def test_tool_info(self, gui):
|
||||||
|
info = gui.get_tool_info()
|
||||||
|
assert info["name"] == "gui_auto"
|
||||||
|
assert "GUI" in info["description"]
|
||||||
|
assert len(info["keywords"]) >= 5
|
||||||
|
|
||||||
|
def test_mcp_definition(self, gui):
|
||||||
|
mcp = gui.get_mcp_definition()
|
||||||
|
assert mcp["name"] == "gui_auto"
|
||||||
|
assert "inputSchema" in mcp
|
||||||
|
assert "operation" in mcp["inputSchema"]["properties"]
|
||||||
|
|
||||||
|
def test_convert_mcp_args(self, gui):
|
||||||
|
args = {"operation": "click", "target": "确定"}
|
||||||
|
result = gui.convert_mcp_args(args)
|
||||||
|
assert "click" in result
|
||||||
|
assert "确定" in result
|
||||||
|
|
||||||
|
def test_convert_mcp_args_xy(self, gui):
|
||||||
|
args = {"operation": "click", "x": 100, "y": 200}
|
||||||
|
result = gui.convert_mcp_args(args)
|
||||||
|
assert "--xy" in result
|
||||||
|
assert "100" in result
|
||||||
|
|
||||||
|
def test_convert_mcp_args_snapshot(self, gui):
|
||||||
|
args = {"operation": "snapshot", "depth": 3}
|
||||||
|
result = gui.convert_mcp_args(args)
|
||||||
|
assert "snapshot" in result
|
||||||
|
assert "3" in result
|
||||||
|
|
||||||
|
def test_empty_args(self, gui):
|
||||||
|
result = gui.handle("")
|
||||||
|
assert "错误" in result
|
||||||
|
|
||||||
|
def test_invalid_operation(self, gui):
|
||||||
|
result = gui.handle("nonexistent_op")
|
||||||
|
assert "不支持" in result
|
||||||
|
|
||||||
|
def test_click_no_args(self, gui):
|
||||||
|
result = gui.handle("click")
|
||||||
|
assert "错误" in result
|
||||||
|
|
||||||
|
def test_type_no_args(self, gui):
|
||||||
|
result = gui.handle("type")
|
||||||
|
assert "错误" in result
|
||||||
|
|
||||||
|
def test_type_missing_text(self, gui):
|
||||||
|
result = gui.handle("type 按钮")
|
||||||
|
assert "错误" in result
|
||||||
|
|
||||||
|
def test_find_no_args(self, gui):
|
||||||
|
result = gui.handle("find")
|
||||||
|
assert "错误" in result
|
||||||
|
|
||||||
|
def test_findall_no_args(self, gui):
|
||||||
|
result = gui.handle("findall")
|
||||||
|
assert "错误" in result
|
||||||
|
|
||||||
|
def test_info_no_args(self, gui):
|
||||||
|
result = gui.handle("info")
|
||||||
|
assert "错误" in result
|
||||||
|
|
||||||
|
def test_value_no_args(self, gui):
|
||||||
|
result = gui.handle("value")
|
||||||
|
assert "错误" in result
|
||||||
|
|
||||||
|
def test_tree_no_args(self, gui):
|
||||||
|
result = gui.handle("tree")
|
||||||
|
assert "错误" in result
|
||||||
|
|
||||||
|
def test_wait_no_args(self, gui):
|
||||||
|
result = gui.handle("wait")
|
||||||
|
assert "错误" in result
|
||||||
|
|
||||||
|
def test_exists_no_args(self, gui):
|
||||||
|
result = gui.handle("exists")
|
||||||
|
assert "错误" in result
|
||||||
|
|
||||||
|
def test_highlight_no_args(self, gui):
|
||||||
|
result = gui.handle("highlight")
|
||||||
|
assert "错误" in result
|
||||||
|
|
||||||
|
def test_state_no_args(self, gui):
|
||||||
|
result = gui.handle("state")
|
||||||
|
assert "错误" in result
|
||||||
|
|
||||||
|
def test_keys_no_args(self, gui):
|
||||||
|
result = gui.handle("keys")
|
||||||
|
assert "错误" in result
|
||||||
|
|
||||||
|
def test_focus_no_args(self, gui):
|
||||||
|
result = gui.handle("focus")
|
||||||
|
assert "错误" in result
|
||||||
|
|
||||||
|
def test_click_xy_format_error(self, gui):
|
||||||
|
result = gui.handle("click --xy abc")
|
||||||
|
assert "错误" in result
|
||||||
|
|
||||||
|
def test_format_element_info(self, gui):
|
||||||
|
el = {
|
||||||
|
"name": "测试按钮", "type": "Button", "class": "Button",
|
||||||
|
"automation_id": "btn_ok",
|
||||||
|
"bounds": {"left": 100, "top": 200, "width": 80, "height": 30,
|
||||||
|
"right": 180, "bottom": 230},
|
||||||
|
"enabled": True, "focused": False
|
||||||
|
}
|
||||||
|
result = gui._format_element_info(el)
|
||||||
|
assert "测试按钮" in result
|
||||||
|
assert "Button" in result
|
||||||
|
assert "btn_ok" in result
|
||||||
|
|
||||||
|
def test_format_element_info_detailed(self, gui):
|
||||||
|
el = {
|
||||||
|
"name": "输入框", "type": "Edit", "class": "Edit",
|
||||||
|
"automation_id": "", "enabled": True, "focused": True,
|
||||||
|
"value": "hello",
|
||||||
|
"bounds": {"left": 0, "top": 0, "width": 200, "height": 25,
|
||||||
|
"right": 200, "bottom": 25}
|
||||||
|
}
|
||||||
|
result = gui._format_element_info(el, detailed=True)
|
||||||
|
assert "输入框" in result
|
||||||
|
assert "hello" in result
|
||||||
|
|
||||||
|
def test_all_operations_route(self, gui):
|
||||||
|
"""所有操作都能正确路由"""
|
||||||
|
for op in ["snapshot", "screenshot", "windows", "focus", "click",
|
||||||
|
"rightclick", "doubleclick", "type", "clear", "keys",
|
||||||
|
"scroll", "find", "findall", "info", "value", "tree",
|
||||||
|
"wait", "exists", "highlight", "state"]:
|
||||||
|
result = gui.handle(f"{op} test")
|
||||||
|
assert isinstance(result, str)
|
||||||
|
|
||||||
|
|
||||||
class TestSubAgent:
|
class TestSubAgent:
|
||||||
"""sub_agent 功能测试"""
|
"""sub_agent 功能测试"""
|
||||||
|
|
||||||
|
|||||||
+90
-282
@@ -5,10 +5,13 @@
|
|||||||
|
|
||||||
import os
|
import os
|
||||||
import json
|
import json
|
||||||
|
import logging
|
||||||
import threading
|
import threading
|
||||||
from typing import Dict, List, Any, Optional, Union, Callable
|
from typing import Dict, List, Any, Optional, Union, Callable
|
||||||
from colorama import Fore, Style
|
from colorama import Fore, Style
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
class UnifiedToolManager:
|
class UnifiedToolManager:
|
||||||
"""
|
"""
|
||||||
@@ -44,26 +47,31 @@ class UnifiedToolManager:
|
|||||||
self._mcp_tools_cache: Optional[List[Dict]] = None
|
self._mcp_tools_cache: Optional[List[Dict]] = None
|
||||||
|
|
||||||
def initialize(self, plugins_dir: str = "plugins", skills_dir: str = "skills") -> None:
|
def initialize(self, plugins_dir: str = "plugins", skills_dir: str = "skills") -> None:
|
||||||
"""
|
"""初始化并加载所有工具"""
|
||||||
初始化并加载所有工具
|
self._plugins_dir = plugins_dir
|
||||||
|
self._skills_dir = skills_dir
|
||||||
Args:
|
|
||||||
plugins_dir: Liugin 目录
|
|
||||||
skills_dir: Skill 目录
|
|
||||||
"""
|
|
||||||
# 加载 Liugins
|
|
||||||
self._load_plugins(plugins_dir)
|
self._load_plugins(plugins_dir)
|
||||||
|
|
||||||
# 加载 Skills
|
|
||||||
self._load_skills(skills_dir)
|
self._load_skills(skills_dir)
|
||||||
|
|
||||||
# 构建缓存
|
|
||||||
self._build_mcp_cache()
|
self._build_mcp_cache()
|
||||||
|
|
||||||
print(f"{Fore.GREEN}[统一工具管理器] 加载完成: {len(self._tools)} 个工具{Style.RESET_ALL}")
|
print(f"{Fore.GREEN}[统一工具管理器] 加载完成: {len(self._tools)} 个工具{Style.RESET_ALL}")
|
||||||
print(f" - Liugin 协议: {sum(1 for p in self._protocol_map.values() if p == 'liugin')}")
|
print(f" - Liugin 协议: {sum(1 for p in self._protocol_map.values() if p == 'liugin')}")
|
||||||
print(f" - Skill 协议: {sum(1 for p in self._protocol_map.values() if p == 'skill')}")
|
print(f" - Skill 协议: {sum(1 for p in self._protocol_map.values() if p == 'skill')}")
|
||||||
|
|
||||||
|
def shutdown(self) -> None:
|
||||||
|
"""关闭管理器,清理所有插件实例"""
|
||||||
|
with self._lock:
|
||||||
|
for name, tool in self._tools.items():
|
||||||
|
instance = tool.get('instance')
|
||||||
|
if instance and hasattr(instance, 'cleanup'):
|
||||||
|
try:
|
||||||
|
instance.cleanup()
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
self._tools.clear()
|
||||||
|
self._protocol_map.clear()
|
||||||
|
self._mcp_tools_cache = None
|
||||||
|
|
||||||
def _load_plugins(self, plugins_dir: str) -> None:
|
def _load_plugins(self, plugins_dir: str) -> None:
|
||||||
"""加载 Liugin 协议工具"""
|
"""加载 Liugin 协议工具"""
|
||||||
import importlib.util
|
import importlib.util
|
||||||
@@ -71,7 +79,6 @@ class UnifiedToolManager:
|
|||||||
if not os.path.exists(plugins_dir):
|
if not os.path.exists(plugins_dir):
|
||||||
return
|
return
|
||||||
|
|
||||||
# 获取启用的插件列表
|
|
||||||
enabled_plugins = self._get_enabled_plugins(plugins_dir)
|
enabled_plugins = self._get_enabled_plugins(plugins_dir)
|
||||||
|
|
||||||
for filename in os.listdir(plugins_dir):
|
for filename in os.listdir(plugins_dir):
|
||||||
@@ -80,7 +87,6 @@ class UnifiedToolManager:
|
|||||||
|
|
||||||
plugin_name = filename[:-3]
|
plugin_name = filename[:-3]
|
||||||
|
|
||||||
# 检查是否启用
|
|
||||||
if enabled_plugins is not None and plugin_name.lower() not in enabled_plugins:
|
if enabled_plugins is not None and plugin_name.lower() not in enabled_plugins:
|
||||||
continue
|
continue
|
||||||
|
|
||||||
@@ -91,7 +97,6 @@ class UnifiedToolManager:
|
|||||||
module = importlib.util.module_from_spec(spec)
|
module = importlib.util.module_from_spec(spec)
|
||||||
spec.loader.exec_module(module)
|
spec.loader.exec_module(module)
|
||||||
|
|
||||||
# 兼容 Plugin 和 Liugin 两种类名
|
|
||||||
plugin_class = None
|
plugin_class = None
|
||||||
if hasattr(module, 'Liugin'):
|
if hasattr(module, 'Liugin'):
|
||||||
plugin_class = module.Liugin
|
plugin_class = module.Liugin
|
||||||
@@ -101,19 +106,16 @@ class UnifiedToolManager:
|
|||||||
if plugin_class:
|
if plugin_class:
|
||||||
plugin_instance = plugin_class()
|
plugin_instance = plugin_class()
|
||||||
|
|
||||||
# 设置 CLI 引用
|
|
||||||
if hasattr(plugin_instance, 'set_cli') and self.cli:
|
if hasattr(plugin_instance, 'set_cli') and self.cli:
|
||||||
plugin_instance.set_cli(self.cli)
|
plugin_instance.set_cli(self.cli)
|
||||||
|
|
||||||
tool_info = plugin_instance.get_tool_info()
|
tool_info = plugin_instance.get_tool_info()
|
||||||
tool_name = tool_info.get('name', plugin_name)
|
tool_name = tool_info.get('name', plugin_name)
|
||||||
|
|
||||||
# 获取 MCP 工具定义(如果插件提供)
|
|
||||||
mcp_definition = None
|
mcp_definition = None
|
||||||
if hasattr(plugin_instance, 'get_mcp_definition'):
|
if hasattr(plugin_instance, 'get_mcp_definition'):
|
||||||
mcp_definition = plugin_instance.get_mcp_definition()
|
mcp_definition = plugin_instance.get_mcp_definition()
|
||||||
|
|
||||||
# 注册到统一工具表
|
|
||||||
self._tools[tool_name] = {
|
self._tools[tool_name] = {
|
||||||
'name': tool_name,
|
'name': tool_name,
|
||||||
'description': tool_info.get('description', ''),
|
'description': tool_info.get('description', ''),
|
||||||
@@ -140,11 +142,9 @@ class UnifiedToolManager:
|
|||||||
|
|
||||||
self._skill_loader = SkillLoader(skills_dir)
|
self._skill_loader = SkillLoader(skills_dir)
|
||||||
|
|
||||||
# 先发现所有技能
|
|
||||||
discovered = self._skill_loader.discover_skills(skills_dir)
|
discovered = self._skill_loader.discover_skills(skills_dir)
|
||||||
print(f"{Fore.CYAN}发现 {len(discovered)} 个技能: {[s['name'] for s in discovered]}{Style.RESET_ALL}")
|
print(f"{Fore.CYAN}发现 {len(discovered)} 个技能: {[s['name'] for s in discovered]}{Style.RESET_ALL}")
|
||||||
|
|
||||||
# 加载所有技能
|
|
||||||
self._skill_loader.load_all_skills(skills_dir)
|
self._skill_loader.load_all_skills(skills_dir)
|
||||||
|
|
||||||
loaded_count = len(self._skill_loader.skills)
|
loaded_count = len(self._skill_loader.skills)
|
||||||
@@ -153,24 +153,19 @@ class UnifiedToolManager:
|
|||||||
return
|
return
|
||||||
|
|
||||||
for skill_name, skill in self._skill_loader.skills.items():
|
for skill_name, skill in self._skill_loader.skills.items():
|
||||||
# 设置 CLI 引用 (仅 Python 类技能)
|
|
||||||
if hasattr(skill, 'set_cli') and self.cli:
|
if hasattr(skill, 'set_cli') and self.cli:
|
||||||
skill.set_cli(self.cli)
|
skill.set_cli(self.cli)
|
||||||
|
|
||||||
# 获取工具定义
|
|
||||||
tool_def = skill.get_tool_definition()
|
tool_def = skill.get_tool_definition()
|
||||||
func_def = tool_def.get('function', {})
|
func_def = tool_def.get('function', {})
|
||||||
|
|
||||||
# 检查是否已有同名 Plugin,Skill 优先覆盖
|
|
||||||
if skill_name in self._tools:
|
if skill_name in self._tools:
|
||||||
old_protocol = self._protocol_map[skill_name]
|
old_protocol = self._protocol_map[skill_name]
|
||||||
print(f"{Fore.YELLOW}工具 '{skill_name}' 已存在({old_protocol}),使用 Skill 协议覆盖{Style.RESET_ALL}")
|
print(f"{Fore.YELLOW}工具 '{skill_name}' 已存在({old_protocol}),使用 Skill 协议覆盖{Style.RESET_ALL}")
|
||||||
|
|
||||||
# 判断技能格式
|
|
||||||
is_markdown = isinstance(skill, MarkdownSkill)
|
is_markdown = isinstance(skill, MarkdownSkill)
|
||||||
skill_format = "markdown" if is_markdown else "python"
|
skill_format = "markdown" if is_markdown else "python"
|
||||||
|
|
||||||
# 注册到统一工具表
|
|
||||||
self._tools[skill_name] = {
|
self._tools[skill_name] = {
|
||||||
'name': skill_name,
|
'name': skill_name,
|
||||||
'description': func_def.get('description', ''),
|
'description': func_def.get('description', ''),
|
||||||
@@ -182,9 +177,10 @@ class UnifiedToolManager:
|
|||||||
'instance': skill,
|
'instance': skill,
|
||||||
'tool_definition': tool_def,
|
'tool_definition': tool_def,
|
||||||
'anthropic_definition': skill.get_anthropic_tool_definition(),
|
'anthropic_definition': skill.get_anthropic_tool_definition(),
|
||||||
'mcp_definition': tool_def # Skill 的 OpenAI 格式就是 MCP 格式
|
'mcp_definition': tool_def
|
||||||
}
|
}
|
||||||
self._protocol_map[skill_name] = 'skill'
|
self._protocol_map[skill_name] = 'skill'
|
||||||
|
|
||||||
print(f"{Fore.GREEN}已加载 Skill ({skill_format}): {skill_name}{Style.RESET_ALL}")
|
print(f"{Fore.GREEN}已加载 Skill ({skill_format}): {skill_name}{Style.RESET_ALL}")
|
||||||
|
|
||||||
except ImportError as e:
|
except ImportError as e:
|
||||||
@@ -193,19 +189,12 @@ class UnifiedToolManager:
|
|||||||
print(f"{Fore.RED}加载 Skills 失败: {e}{Style.RESET_ALL}")
|
print(f"{Fore.RED}加载 Skills 失败: {e}{Style.RESET_ALL}")
|
||||||
|
|
||||||
def _create_skill_handler(self, skill) -> callable:
|
def _create_skill_handler(self, skill) -> callable:
|
||||||
"""
|
"""为 Skill 创建兼容 Plugin 的 handler"""
|
||||||
为 Skill 创建兼容 Plugin 的 handler
|
|
||||||
|
|
||||||
支持 Markdown 和 Python 两种技能格式
|
|
||||||
"""
|
|
||||||
from skills.base import MarkdownSkill, Skill
|
from skills.base import MarkdownSkill, Skill
|
||||||
|
|
||||||
def handler(args: str) -> str:
|
def handler(args: str) -> str:
|
||||||
import json
|
|
||||||
|
|
||||||
kwargs = {}
|
kwargs = {}
|
||||||
|
|
||||||
# 解析参数
|
|
||||||
args = args.strip()
|
args = args.strip()
|
||||||
if args.startswith('{'):
|
if args.startswith('{'):
|
||||||
try:
|
try:
|
||||||
@@ -213,7 +202,6 @@ class UnifiedToolManager:
|
|||||||
except json.JSONDecodeError:
|
except json.JSONDecodeError:
|
||||||
kwargs = {'operation': args}
|
kwargs = {'operation': args}
|
||||||
elif '=' in args:
|
elif '=' in args:
|
||||||
# key=value 格式: "directory=. file_pattern=*.py"
|
|
||||||
for part in args.split():
|
for part in args.split():
|
||||||
if '=' in part:
|
if '=' in part:
|
||||||
k, v = part.split('=', 1)
|
k, v = part.split('=', 1)
|
||||||
@@ -223,11 +211,9 @@ class UnifiedToolManager:
|
|||||||
else:
|
else:
|
||||||
kwargs = {'operation': args}
|
kwargs = {'operation': args}
|
||||||
|
|
||||||
# Markdown 技能: 返回指令供 AI 执行
|
|
||||||
if isinstance(skill, MarkdownSkill):
|
if isinstance(skill, MarkdownSkill):
|
||||||
return f"[Skill: {skill.name}]\n{skill.instructions}"
|
return f"[Skill: {skill.name}]\n{skill.instructions}"
|
||||||
|
|
||||||
# Python 技能: 直接执行
|
|
||||||
if hasattr(skill, 'run'):
|
if hasattr(skill, 'run'):
|
||||||
result = skill.run(**kwargs)
|
result = skill.run(**kwargs)
|
||||||
if result.success:
|
if result.success:
|
||||||
@@ -241,14 +227,12 @@ class UnifiedToolManager:
|
|||||||
|
|
||||||
def _get_enabled_plugins(self, plugins_dir: str) -> Optional[List[str]]:
|
def _get_enabled_plugins(self, plugins_dir: str) -> Optional[List[str]]:
|
||||||
"""获取启用的插件列表"""
|
"""获取启用的插件列表"""
|
||||||
# 检查环境变量
|
|
||||||
enabled_env = os.environ.get("XIAOLI_ENABLED_PLUGINS")
|
enabled_env = os.environ.get("XIAOLI_ENABLED_PLUGINS")
|
||||||
if enabled_env is not None:
|
if enabled_env is not None:
|
||||||
if enabled_env == "":
|
if enabled_env == "":
|
||||||
return []
|
return []
|
||||||
return [p.lower() for p in enabled_env.split(",")]
|
return [p.lower() for p in enabled_env.split(",")]
|
||||||
|
|
||||||
# 检查配置文件
|
|
||||||
config_file = os.path.join(os.path.dirname(plugins_dir), "plugins_config.py")
|
config_file = os.path.join(os.path.dirname(plugins_dir), "plugins_config.py")
|
||||||
if os.path.exists(config_file):
|
if os.path.exists(config_file):
|
||||||
try:
|
try:
|
||||||
@@ -267,7 +251,7 @@ class UnifiedToolManager:
|
|||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
return None # 加载全部
|
return None
|
||||||
|
|
||||||
def _build_mcp_cache(self) -> None:
|
def _build_mcp_cache(self) -> None:
|
||||||
"""构建 MCP 工具定义缓存(线程安全)"""
|
"""构建 MCP 工具定义缓存(线程安全)"""
|
||||||
@@ -276,56 +260,28 @@ class UnifiedToolManager:
|
|||||||
for tool in self._tools.values():
|
for tool in self._tools.values():
|
||||||
mcp_def = tool.get('mcp_definition')
|
mcp_def = tool.get('mcp_definition')
|
||||||
if mcp_def:
|
if mcp_def:
|
||||||
# 确保符合 MCP 标准
|
|
||||||
normalized = self._normalize_mcp_definition(mcp_def)
|
normalized = self._normalize_mcp_definition(mcp_def)
|
||||||
self._mcp_tools_cache.append(normalized)
|
self._mcp_tools_cache.append(normalized)
|
||||||
else:
|
else:
|
||||||
# 为没有 MCP 定义的 Plugin 生成默认定义
|
|
||||||
self._mcp_tools_cache.append(self._generate_mcp_definition(tool))
|
self._mcp_tools_cache.append(self._generate_mcp_definition(tool))
|
||||||
|
|
||||||
def _normalize_mcp_definition(self, mcp_def: Dict[str, Any]) -> Dict[str, Any]:
|
def _normalize_mcp_definition(self, mcp_def: Dict[str, Any]) -> Dict[str, Any]:
|
||||||
"""
|
"""标准化 MCP 工具定义"""
|
||||||
标准化 MCP 工具定义
|
|
||||||
|
|
||||||
支持多种输入格式并转换为标准 MCP 格式
|
|
||||||
"""
|
|
||||||
# 如果已经是 MCP 格式(有 name 或 inputSchema)
|
|
||||||
if 'name' in mcp_def and ('inputSchema' in mcp_def or 'description' in mcp_def):
|
if 'name' in mcp_def and ('inputSchema' in mcp_def or 'description' in mcp_def):
|
||||||
return mcp_def
|
return mcp_def
|
||||||
|
|
||||||
# 如果是 OpenAI Function Calling 格式,转换
|
|
||||||
if mcp_def.get('type') == 'function' and 'function' in mcp_def:
|
if mcp_def.get('type') == 'function' and 'function' in mcp_def:
|
||||||
func = mcp_def['function']
|
func = mcp_def['function']
|
||||||
return {
|
return {
|
||||||
"name": func.get('name', ''),
|
"name": func.get('name', ''),
|
||||||
"description": func.get('description', ''),
|
"description": func.get('description', ''),
|
||||||
"inputSchema": func.get('parameters', {
|
"inputSchema": func.get('parameters', {"type": "object", "properties": {}})
|
||||||
"type": "object",
|
|
||||||
"properties": {}
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
# 其他情况,直接返回
|
|
||||||
return mcp_def
|
return mcp_def
|
||||||
|
|
||||||
def _generate_mcp_definition(self, tool: Dict[str, Any]) -> Dict[str, Any]:
|
def _generate_mcp_definition(self, tool: Dict[str, Any]) -> Dict[str, Any]:
|
||||||
"""
|
"""为 Plugin 生成符合 MCP 标准的工具定义"""
|
||||||
为 Plugin 生成符合 MCP 标准的工具定义
|
|
||||||
|
|
||||||
MCP 官方格式 (2025-03-26):
|
|
||||||
{
|
|
||||||
"name": "tool_name",
|
|
||||||
"title": "Human Readable Name", // optional
|
|
||||||
"description": "Human-readable description",
|
|
||||||
"inputSchema": {
|
|
||||||
"type": "object",
|
|
||||||
"properties": {...},
|
|
||||||
"required": [...]
|
|
||||||
},
|
|
||||||
"outputSchema": {...}, // optional
|
|
||||||
"annotations": {...} // optional
|
|
||||||
}
|
|
||||||
"""
|
|
||||||
return {
|
return {
|
||||||
"name": tool['name'],
|
"name": tool['name'],
|
||||||
"description": tool.get('description', ''),
|
"description": tool.get('description', ''),
|
||||||
@@ -357,17 +313,7 @@ class UnifiedToolManager:
|
|||||||
return self._protocol_map.get(name)
|
return self._protocol_map.get(name)
|
||||||
|
|
||||||
def execute(self, tool_name: str, args: str = "", **kwargs) -> Dict[str, Any]:
|
def execute(self, tool_name: str, args: str = "", **kwargs) -> Dict[str, Any]:
|
||||||
"""
|
"""执行工具调用"""
|
||||||
执行工具调用
|
|
||||||
|
|
||||||
Args:
|
|
||||||
tool_name: 工具名称
|
|
||||||
args: 参数字符串(Plugin 格式)
|
|
||||||
**kwargs: 关键字参数(Skill 格式或 MCP arguments)
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
{"result": "..."} 格式的结果
|
|
||||||
"""
|
|
||||||
tool = self._tools.get(tool_name)
|
tool = self._tools.get(tool_name)
|
||||||
|
|
||||||
if not tool:
|
if not tool:
|
||||||
@@ -379,20 +325,16 @@ class UnifiedToolManager:
|
|||||||
instance = tool.get('instance')
|
instance = tool.get('instance')
|
||||||
|
|
||||||
if protocol == 'skill' and kwargs:
|
if protocol == 'skill' and kwargs:
|
||||||
# Skill 协议,使用 kwargs
|
|
||||||
skill = tool['instance']
|
skill = tool['instance']
|
||||||
result = skill.run(**kwargs)
|
result = skill.run(**kwargs)
|
||||||
return {"result": result.message or str(result.data) if result.success else f"错误: {result.error}"}
|
return {"result": result.message or str(result.data) if result.success else f"错误: {result.error}"}
|
||||||
|
|
||||||
elif protocol == 'liugin' and kwargs and not args:
|
elif protocol == 'liugin' and kwargs and not args:
|
||||||
# Liugin 协议但有 MCP 结构化参数,需要转换
|
|
||||||
# 检查插件是否有 convert_mcp_args 方法
|
|
||||||
if instance and hasattr(instance, 'convert_mcp_args'):
|
if instance and hasattr(instance, 'convert_mcp_args'):
|
||||||
args = instance.convert_mcp_args(kwargs)
|
args = instance.convert_mcp_args(kwargs)
|
||||||
else:
|
else:
|
||||||
args = self._convert_mcp_args_to_plugin_args(tool_name, kwargs, instance)
|
args = self._convert_mcp_args_to_plugin_args(tool_name, kwargs, instance)
|
||||||
|
|
||||||
# 执行 handler
|
|
||||||
result = handler(args)
|
result = handler(args)
|
||||||
return {"result": result if result is not None else "无结果"}
|
return {"result": result if result is not None else "无结果"}
|
||||||
|
|
||||||
@@ -402,42 +344,14 @@ class UnifiedToolManager:
|
|||||||
# ==================== MCP 协议支持 ====================
|
# ==================== MCP 协议支持 ====================
|
||||||
|
|
||||||
def get_mcp_tools(self) -> List[Dict[str, Any]]:
|
def get_mcp_tools(self) -> List[Dict[str, Any]]:
|
||||||
"""
|
"""获取 MCP 格式的工具定义列表"""
|
||||||
获取 MCP 格式的工具定义列表
|
|
||||||
|
|
||||||
MCP (Model Context Protocol) 使用 OpenAI Function Calling 格式
|
|
||||||
作为标准工具定义格式
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
List of MCP tool definitions
|
|
||||||
"""
|
|
||||||
with self._lock:
|
with self._lock:
|
||||||
if self._mcp_tools_cache is None:
|
if self._mcp_tools_cache is None:
|
||||||
self._build_mcp_cache()
|
self._build_mcp_cache()
|
||||||
return self._mcp_tools_cache.copy() # 返回副本,避免外部修改
|
return self._mcp_tools_cache.copy()
|
||||||
|
|
||||||
def mcp_call(self, tool_name: str, arguments: Dict[str, Any]) -> Dict[str, Any]:
|
def mcp_call(self, tool_name: str, arguments: Dict[str, Any]) -> Dict[str, Any]:
|
||||||
"""
|
"""MCP 格式的工具调用入口"""
|
||||||
MCP 格式的工具调用入口
|
|
||||||
|
|
||||||
这是 MCP 协议的主要调用接口,接收结构化参数并返回结果
|
|
||||||
|
|
||||||
Args:
|
|
||||||
tool_name: 工具名称
|
|
||||||
arguments: 结构化参数 (JSON对象)
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
MCP 标准响应格式:
|
|
||||||
{
|
|
||||||
"content": [
|
|
||||||
{
|
|
||||||
"type": "text",
|
|
||||||
"text": "结果内容"
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"isError": false
|
|
||||||
}
|
|
||||||
"""
|
|
||||||
tool = self._tools.get(tool_name)
|
tool = self._tools.get(tool_name)
|
||||||
|
|
||||||
if not tool:
|
if not tool:
|
||||||
@@ -448,13 +362,11 @@ class UnifiedToolManager:
|
|||||||
instance = tool.get('instance')
|
instance = tool.get('instance')
|
||||||
|
|
||||||
if protocol == 'liugin':
|
if protocol == 'liugin':
|
||||||
# Liugin 协议: 将 arguments 转换为 args 字符串
|
|
||||||
args = self._convert_mcp_args_to_plugin_args(tool_name, arguments, instance)
|
args = self._convert_mcp_args_to_plugin_args(tool_name, arguments, instance)
|
||||||
result = tool['handler'](args)
|
result = tool['handler'](args)
|
||||||
return self._mcp_success(result if result else "执行完成")
|
return self._mcp_success(result if result else "执行完成")
|
||||||
|
|
||||||
elif protocol == 'skill':
|
elif protocol == 'skill':
|
||||||
# Skill 协议: 直接传递 arguments 作为 kwargs
|
|
||||||
from skills.base import MarkdownSkill
|
from skills.base import MarkdownSkill
|
||||||
|
|
||||||
if isinstance(instance, MarkdownSkill):
|
if isinstance(instance, MarkdownSkill):
|
||||||
@@ -474,36 +386,20 @@ class UnifiedToolManager:
|
|||||||
|
|
||||||
def _convert_mcp_args_to_plugin_args(self, tool_name: str, arguments: Dict[str, Any],
|
def _convert_mcp_args_to_plugin_args(self, tool_name: str, arguments: Dict[str, Any],
|
||||||
instance: Any) -> str:
|
instance: Any) -> str:
|
||||||
"""
|
"""将 MCP 结构化参数转换为 Plugin 的 args 字符串"""
|
||||||
将 MCP 结构化参数转换为 Plugin 的 args 字符串
|
|
||||||
|
|
||||||
Args:
|
|
||||||
tool_name: 工具名称
|
|
||||||
arguments: MCP 参数对象
|
|
||||||
instance: 插件实例(可能有自定义转换方法)
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
args 字符串
|
|
||||||
"""
|
|
||||||
# 检查插件是否有自定义的 MCP 参数转换方法
|
|
||||||
if instance and hasattr(instance, 'convert_mcp_args'):
|
if instance and hasattr(instance, 'convert_mcp_args'):
|
||||||
return instance.convert_mcp_args(arguments)
|
return instance.convert_mcp_args(arguments)
|
||||||
|
|
||||||
# 默认转换策略
|
|
||||||
if 'args' in arguments:
|
if 'args' in arguments:
|
||||||
# 如果有 args 字段,直接使用
|
|
||||||
return arguments['args']
|
return arguments['args']
|
||||||
|
|
||||||
# 将 arguments 转换为命令行格式
|
|
||||||
parts = []
|
parts = []
|
||||||
|
|
||||||
# 第一个参数通常是操作/命令
|
|
||||||
if 'operation' in arguments:
|
if 'operation' in arguments:
|
||||||
parts.append(arguments['operation'])
|
parts.append(arguments['operation'])
|
||||||
elif 'action' in arguments:
|
elif 'action' in arguments:
|
||||||
parts.append(arguments['action'])
|
parts.append(arguments['action'])
|
||||||
|
|
||||||
# 添加其他参数
|
|
||||||
for key, value in arguments.items():
|
for key, value in arguments.items():
|
||||||
if key in ('operation', 'action'):
|
if key in ('operation', 'action'):
|
||||||
continue
|
continue
|
||||||
@@ -522,51 +418,20 @@ class UnifiedToolManager:
|
|||||||
return ' '.join(parts)
|
return ' '.join(parts)
|
||||||
|
|
||||||
def _quote_if_needed(self, s: str) -> str:
|
def _quote_if_needed(self, s: str) -> str:
|
||||||
"""如果字符串包含空格,添加引号"""
|
|
||||||
if ' ' in s or '"' in s:
|
if ' ' in s or '"' in s:
|
||||||
return f'"{s}"'
|
return f'"{s}"'
|
||||||
return s
|
return s
|
||||||
|
|
||||||
def _mcp_success(self, text: str) -> Dict[str, Any]:
|
def _mcp_success(self, text: str) -> Dict[str, Any]:
|
||||||
"""生成 MCP 成功响应"""
|
return {"content": [{"type": "text", "text": text}], "isError": False}
|
||||||
return {
|
|
||||||
"content": [
|
|
||||||
{
|
|
||||||
"type": "text",
|
|
||||||
"text": text
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"isError": False
|
|
||||||
}
|
|
||||||
|
|
||||||
def _mcp_error(self, error_msg: str) -> Dict[str, Any]:
|
def _mcp_error(self, error_msg: str) -> Dict[str, Any]:
|
||||||
"""生成 MCP 错误响应"""
|
return {"content": [{"type": "text", "text": error_msg}], "isError": True}
|
||||||
return {
|
|
||||||
"content": [
|
|
||||||
{
|
|
||||||
"type": "text",
|
|
||||||
"text": error_msg
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"isError": True
|
|
||||||
}
|
|
||||||
|
|
||||||
# ==================== 兼容性 API ====================
|
# ==================== 兼容性 API ====================
|
||||||
|
|
||||||
def get_openai_tools(self) -> List[Dict[str, Any]]:
|
def get_openai_tools(self) -> List[Dict[str, Any]]:
|
||||||
"""
|
"""获取 OpenAI Function Calling 格式的工具定义"""
|
||||||
获取 OpenAI Function Calling 格式的工具定义
|
|
||||||
|
|
||||||
OpenAI 格式:
|
|
||||||
{
|
|
||||||
"type": "function",
|
|
||||||
"function": {
|
|
||||||
"name": "...",
|
|
||||||
"description": "...",
|
|
||||||
"parameters": {...}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
"""
|
|
||||||
tools = []
|
tools = []
|
||||||
for mcp_def in self.get_mcp_tools():
|
for mcp_def in self.get_mcp_tools():
|
||||||
tools.append({
|
tools.append({
|
||||||
@@ -574,103 +439,68 @@ class UnifiedToolManager:
|
|||||||
"function": {
|
"function": {
|
||||||
"name": mcp_def.get("name", ""),
|
"name": mcp_def.get("name", ""),
|
||||||
"description": mcp_def.get("description", ""),
|
"description": mcp_def.get("description", ""),
|
||||||
"parameters": mcp_def.get("inputSchema", {
|
"parameters": mcp_def.get("inputSchema", {"type": "object", "properties": {}})
|
||||||
"type": "object",
|
|
||||||
"properties": {}
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
return tools
|
return tools
|
||||||
|
|
||||||
def get_anthropic_tools(self) -> List[Dict[str, Any]]:
|
def get_anthropic_tools(self) -> List[Dict[str, Any]]:
|
||||||
"""
|
"""获取 Anthropic Tool Use 格式的工具定义"""
|
||||||
获取 Anthropic Tool Use 格式的工具定义
|
|
||||||
|
|
||||||
Anthropic 格式:
|
|
||||||
{
|
|
||||||
"name": "tool_name",
|
|
||||||
"description": "...",
|
|
||||||
"input_schema": {...}
|
|
||||||
}
|
|
||||||
"""
|
|
||||||
tools = []
|
tools = []
|
||||||
for mcp_def in self.get_mcp_tools():
|
for mcp_def in self.get_mcp_tools():
|
||||||
tools.append({
|
tools.append({
|
||||||
"name": mcp_def.get("name", ""),
|
"name": mcp_def.get("name", ""),
|
||||||
"description": mcp_def.get("description", ""),
|
"description": mcp_def.get("description", ""),
|
||||||
"input_schema": mcp_def.get("inputSchema", {
|
"input_schema": mcp_def.get("inputSchema", {"type": "object", "properties": {}})
|
||||||
"type": "object",
|
|
||||||
"properties": {}
|
|
||||||
})
|
|
||||||
})
|
})
|
||||||
return tools
|
return tools
|
||||||
|
|
||||||
def search_tools(self, query: str, limit: int = 5) -> List[Dict[str, Any]]:
|
def search_tools(self, query: str, limit: int = 5) -> List[Dict[str, Any]]:
|
||||||
"""
|
"""搜索工具"""
|
||||||
搜索工具
|
|
||||||
|
|
||||||
Args:
|
|
||||||
query: 搜索关键词
|
|
||||||
limit: 返回数量限制
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
匹配的工具列表
|
|
||||||
"""
|
|
||||||
query_lower = query.lower()
|
query_lower = query.lower()
|
||||||
# 标准化:移除所有分隔符(连字符、下划线、空格)
|
|
||||||
query_normalized = query_lower.replace('-', '').replace('_', '').replace(' ', '')
|
query_normalized = query_lower.replace('-', '').replace('_', '').replace(' ', '')
|
||||||
matches = []
|
matches = []
|
||||||
|
|
||||||
for tool in self._tools.values():
|
for tool in self._tools.values():
|
||||||
score = 0
|
score = self._score_tool_match(tool, query_lower, query_normalized)
|
||||||
name = tool['name'].lower()
|
|
||||||
name_normalized = name.replace('-', '').replace('_', '')
|
|
||||||
desc = tool['description'].lower()
|
|
||||||
keywords = [kw.lower() for kw in tool.get('keywords', [])]
|
|
||||||
|
|
||||||
# 名称完全匹配(忽略分隔符差异)
|
|
||||||
if query_lower == name or query_normalized == name_normalized:
|
|
||||||
score += 100
|
|
||||||
# 名称包含(标准化后匹配)
|
|
||||||
elif query_normalized in name_normalized or query_lower in name:
|
|
||||||
score += 50
|
|
||||||
# 描述包含
|
|
||||||
if query_lower in desc:
|
|
||||||
score += 30
|
|
||||||
# 关键词匹配
|
|
||||||
for kw in keywords:
|
|
||||||
kw_normalized = kw.replace('-', '').replace('_', '')
|
|
||||||
if query_lower in kw or query_normalized in kw_normalized:
|
|
||||||
score += 20
|
|
||||||
break
|
|
||||||
|
|
||||||
if score > 0:
|
if score > 0:
|
||||||
matches.append({
|
matches.append({
|
||||||
'name': tool['name'],
|
'name': tool['name'],
|
||||||
'description': tool['description'],
|
'description': tool['description'],
|
||||||
'usage': tool.get('usage', ''),
|
'usage': tool.get('usage', ''),
|
||||||
'keywords': keywords,
|
'keywords': [kw.lower() for kw in tool.get('keywords', [])],
|
||||||
'protocol': tool['protocol'],
|
'protocol': tool['protocol'],
|
||||||
'instance': tool.get('instance'),
|
'instance': tool.get('instance'),
|
||||||
'score': score
|
'score': score
|
||||||
})
|
})
|
||||||
|
|
||||||
# 按分数排序
|
|
||||||
matches.sort(key=lambda x: x['score'], reverse=True)
|
matches.sort(key=lambda x: x['score'], reverse=True)
|
||||||
return matches[:limit]
|
return matches[:limit]
|
||||||
|
|
||||||
|
def _score_tool_match(self, tool: Dict, query_lower: str, query_normalized: str) -> int:
|
||||||
|
"""计算工具匹配分数"""
|
||||||
|
score = 0
|
||||||
|
name = tool.get('name', '').lower()
|
||||||
|
name_normalized = name.replace('-', '').replace('_', '')
|
||||||
|
desc = tool.get('description', '').lower()
|
||||||
|
keywords = [kw.lower() for kw in tool.get('keywords', [])]
|
||||||
|
|
||||||
|
if query_lower == name or query_normalized == name_normalized:
|
||||||
|
score += 100
|
||||||
|
elif query_normalized in name_normalized or query_lower in name:
|
||||||
|
score += 50
|
||||||
|
if query_lower in desc:
|
||||||
|
score += 30
|
||||||
|
for kw in keywords:
|
||||||
|
kw_normalized = kw.replace('-', '').replace('_', '')
|
||||||
|
if query_lower in kw or query_normalized in kw_normalized:
|
||||||
|
score += 20
|
||||||
|
break
|
||||||
|
return score
|
||||||
|
|
||||||
def register_tool(self, name: str, handler: callable, description: str = "",
|
def register_tool(self, name: str, handler: callable, description: str = "",
|
||||||
protocol: str = "custom", mcp_definition: Dict = None, **kwargs) -> None:
|
protocol: str = "custom", mcp_definition: Dict = None, **kwargs) -> None:
|
||||||
"""
|
"""动态注册工具"""
|
||||||
动态注册工具
|
|
||||||
|
|
||||||
Args:
|
|
||||||
name: 工具名称
|
|
||||||
handler: 处理函数
|
|
||||||
description: 描述
|
|
||||||
protocol: 协议类型
|
|
||||||
mcp_definition: MCP 工具定义(可选)
|
|
||||||
"""
|
|
||||||
with self._lock:
|
with self._lock:
|
||||||
self._tools[name] = {
|
self._tools[name] = {
|
||||||
'name': name,
|
'name': name,
|
||||||
@@ -682,7 +512,6 @@ class UnifiedToolManager:
|
|||||||
}
|
}
|
||||||
self._protocol_map[name] = protocol
|
self._protocol_map[name] = protocol
|
||||||
|
|
||||||
# 更新缓存
|
|
||||||
if self._mcp_tools_cache is not None:
|
if self._mcp_tools_cache is not None:
|
||||||
if mcp_definition:
|
if mcp_definition:
|
||||||
self._mcp_tools_cache.append(mcp_definition)
|
self._mcp_tools_cache.append(mcp_definition)
|
||||||
@@ -693,27 +522,42 @@ class UnifiedToolManager:
|
|||||||
"""注销工具"""
|
"""注销工具"""
|
||||||
with self._lock:
|
with self._lock:
|
||||||
if name in self._tools:
|
if name in self._tools:
|
||||||
|
instance = self._tools[name].get('instance')
|
||||||
|
if instance and hasattr(instance, 'cleanup'):
|
||||||
|
try:
|
||||||
|
instance.cleanup()
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
del self._tools[name]
|
del self._tools[name]
|
||||||
del self._protocol_map[name]
|
del self._protocol_map[name]
|
||||||
# 重建缓存
|
|
||||||
self._build_mcp_cache()
|
self._build_mcp_cache()
|
||||||
return True
|
return True
|
||||||
return False
|
return False
|
||||||
|
|
||||||
def get_skills_system_prompt(self) -> str:
|
def get_all_tools_info(self) -> List[Dict[str, Any]]:
|
||||||
"""
|
"""获取所有工具的简要信息,用于系统提示词"""
|
||||||
获取所有技能的系统提示词
|
result = []
|
||||||
|
for tool in self._tools.values():
|
||||||
|
result.append({
|
||||||
|
'name': tool['name'],
|
||||||
|
'description': tool.get('description', ''),
|
||||||
|
'keywords': tool.get('keywords', []),
|
||||||
|
'protocol': tool.get('protocol', ''),
|
||||||
|
})
|
||||||
|
return result
|
||||||
|
|
||||||
用于注入到 AI 的 system prompt 中,
|
def get_tool_by_name(self, name: str) -> Optional[Dict[str, Any]]:
|
||||||
让 AI 了解如何使用这些技能
|
"""根据名称获取工具(兼容 LiuginManager 接口)"""
|
||||||
"""
|
return self._tools.get(name)
|
||||||
|
|
||||||
|
def get_skills_system_prompt(self) -> str:
|
||||||
|
"""获取所有技能的系统提示词"""
|
||||||
skill_prompts = []
|
skill_prompts = []
|
||||||
|
|
||||||
for name, tool in self._tools.items():
|
for name, tool in self._tools.items():
|
||||||
if tool['protocol'] == 'skill':
|
if tool['protocol'] == 'skill':
|
||||||
instance = tool.get('instance')
|
instance = tool.get('instance')
|
||||||
if instance:
|
if instance:
|
||||||
# 获取技能指令
|
|
||||||
instructions = getattr(instance, 'instructions', '')
|
instructions = getattr(instance, 'instructions', '')
|
||||||
scripts_dir = getattr(instance, 'scripts_dir', '')
|
scripts_dir = getattr(instance, 'scripts_dir', '')
|
||||||
|
|
||||||
@@ -721,7 +565,6 @@ class UnifiedToolManager:
|
|||||||
prompt_parts.append(f"描述: {tool['description']}")
|
prompt_parts.append(f"描述: {tool['description']}")
|
||||||
|
|
||||||
if instructions:
|
if instructions:
|
||||||
# 截取关键部分,避免过长
|
|
||||||
prompt_parts.append(f"\n{instructions}")
|
prompt_parts.append(f"\n{instructions}")
|
||||||
|
|
||||||
if scripts_dir:
|
if scripts_dir:
|
||||||
@@ -736,14 +579,9 @@ class UnifiedToolManager:
|
|||||||
return ""
|
return ""
|
||||||
|
|
||||||
def get_tools_prompt(self) -> str:
|
def get_tools_prompt(self) -> str:
|
||||||
"""
|
"""获取工具使用提示词(兼容旧接口)"""
|
||||||
获取工具使用提示词(兼容旧接口)
|
|
||||||
|
|
||||||
包含 Plugin 和 Skill 两种协议的工具说明
|
|
||||||
"""
|
|
||||||
prompts = []
|
prompts = []
|
||||||
|
|
||||||
# Liugin 协议工具
|
|
||||||
plugin_tools = [t for t in self._tools.values() if t['protocol'] == 'liugin']
|
plugin_tools = [t for t in self._tools.values() if t['protocol'] == 'liugin']
|
||||||
if plugin_tools:
|
if plugin_tools:
|
||||||
prompts.append("## Liugin 工具")
|
prompts.append("## Liugin 工具")
|
||||||
@@ -752,7 +590,6 @@ class UnifiedToolManager:
|
|||||||
if usage:
|
if usage:
|
||||||
prompts.append(f"### {tool['name']}\n{usage}\n")
|
prompts.append(f"### {tool['name']}\n{usage}\n")
|
||||||
|
|
||||||
# Skill 协议工具(使用系统提示词)
|
|
||||||
skills_prompt = self.get_skills_system_prompt()
|
skills_prompt = self.get_skills_system_prompt()
|
||||||
if skills_prompt:
|
if skills_prompt:
|
||||||
prompts.append(skills_prompt)
|
prompts.append(skills_prompt)
|
||||||
@@ -762,45 +599,16 @@ class UnifiedToolManager:
|
|||||||
# ==================== MCP Server 模式支持 ====================
|
# ==================== MCP Server 模式支持 ====================
|
||||||
|
|
||||||
def get_mcp_server_info(self) -> Dict[str, Any]:
|
def get_mcp_server_info(self) -> Dict[str, Any]:
|
||||||
"""
|
"""获取 MCP Server 信息"""
|
||||||
获取 MCP Server 信息
|
|
||||||
|
|
||||||
用于 MCP 客户端连接时的初始化响应
|
|
||||||
"""
|
|
||||||
return {
|
return {
|
||||||
"name": "xiaoli-tool-server",
|
"name": "xiaoli-tool-server",
|
||||||
"version": "1.0.0",
|
"version": "1.0.0",
|
||||||
"protocolVersion": "2024-11-05",
|
"protocolVersion": "2024-11-05",
|
||||||
"capabilities": {
|
"capabilities": {"tools": {"listChanged": True}}
|
||||||
"tools": {
|
|
||||||
"listChanged": True
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
def handle_mcp_request(self, request: Dict[str, Any]) -> Dict[str, Any]:
|
def handle_mcp_request(self, request: Dict[str, Any]) -> Dict[str, Any]:
|
||||||
"""
|
"""处理 MCP 协议请求"""
|
||||||
处理 MCP 协议请求
|
|
||||||
|
|
||||||
统一处理 MCP 客户端的各种请求
|
|
||||||
|
|
||||||
Args:
|
|
||||||
request: MCP 请求对象
|
|
||||||
{
|
|
||||||
"jsonrpc": "2.0",
|
|
||||||
"id": 1,
|
|
||||||
"method": "tools/list" | "tools/call" | ...,
|
|
||||||
"params": {...}
|
|
||||||
}
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
MCP 响应对象
|
|
||||||
{
|
|
||||||
"jsonrpc": "2.0",
|
|
||||||
"id": 1,
|
|
||||||
"result": {...}
|
|
||||||
}
|
|
||||||
"""
|
|
||||||
method = request.get('method', '')
|
method = request.get('method', '')
|
||||||
params = request.get('params', {})
|
params = request.get('params', {})
|
||||||
req_id = request.get('id')
|
req_id = request.get('id')
|
||||||
|
|||||||
+374
-386
@@ -3,448 +3,436 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="UTF-8">
|
<meta charset="UTF-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
<title>小狸 Pro-CLI · Web UI</title>
|
<title>小狸 Pro-CLI</title>
|
||||||
|
<link rel="icon" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><text y='.9em' font-size='90'> </text></svg>">
|
||||||
|
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
|
||||||
<style>
|
<style>
|
||||||
*{margin:0;padding:0;box-sizing:border-box}
|
*,*::before,*::after{margin:0;padding:0;box-sizing:border-box}
|
||||||
:root{
|
:root{
|
||||||
--bg:#0a0e17;--bg2:#111827;--bg3:#1a2332;--bg4:#21283b;
|
--bg:#0a0a0c;--bg1:#111114;--bg2:#18181c;--bg3:#1f1f24;--bg4:#27272e;
|
||||||
--border:#1e3a5f;--border-f:#58a6ff;
|
--border:rgba(255,255,255,.06);--border-h:rgba(255,255,255,.12);--border-f:rgba(120,130,255,.45);
|
||||||
--txt:#e2e8f0;--dim:#94a3b8;--mute:#475569;
|
--t0:#f0f0f2;--t1:#a0a0aa;--t2:#6a6a76;--t3:#48484f;
|
||||||
--blue:#3b82f6;--purple:#8b5cf6;--cyan:#06b6d4;
|
--ac:#7c7cff;--ac-h:#9494ff;--ac-s:rgba(124,124,255,.12);--ac-xs:rgba(124,124,255,.06);
|
||||||
--green:#22c55e;--red:#ef4444;--yellow:#eab308;--orange:#f97316;
|
--green:#34d399;--green-s:rgba(52,211,153,.1);
|
||||||
--r:10px;
|
--red:#f87171;--red-s:rgba(248,113,113,.1);
|
||||||
|
--amber:#fbbf24;--amber-s:rgba(251,191,36,.1);
|
||||||
|
--cyan:#22d3ee;--cyan-s:rgba(34,211,238,.1);
|
||||||
|
--r-sm:6px;--r-md:10px;--r-lg:14px;--r-xl:18px;
|
||||||
|
--ease:cubic-bezier(.4,0,.2,1);
|
||||||
}
|
}
|
||||||
body{background:var(--bg);color:var(--txt);font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',system-ui,sans-serif;height:100vh;overflow:hidden}
|
html{font-size:14px}
|
||||||
|
body{font-family:-apple-system,BlinkMacSystemFont,'Inter','Segoe UI',system-ui,sans-serif;background:var(--bg);color:var(--t0);line-height:1.55;-webkit-font-smoothing:antialiased;height:100vh;overflow:hidden}
|
||||||
|
|
||||||
/* ── Grid ── */
|
/* Layout */
|
||||||
.app{display:grid;grid-template-columns:250px 1fr 300px;grid-template-rows:52px 1fr;height:100vh}
|
.app{display:grid;grid-template-columns:260px 1fr;grid-template-rows:52px 1fr;height:100vh}
|
||||||
.hdr{grid-column:1/-1;background:var(--bg2);border-bottom:1px solid var(--border);display:flex;align-items:center;padding:0 20px;gap:16px}
|
|
||||||
.side{background:var(--bg2);border-right:1px solid var(--border);overflow-y:auto;padding:12px}
|
|
||||||
.main{display:flex;flex-direction:column;overflow:hidden}
|
|
||||||
.rpanel{background:var(--bg2);border-left:1px solid var(--border);overflow-y:auto;padding:14px}
|
|
||||||
|
|
||||||
/* ── Header ── */
|
/* Topbar */
|
||||||
.logo{font-size:1.25em;font-weight:800;background:linear-gradient(135deg,var(--blue),var(--purple),var(--cyan));-webkit-background-clip:text;-webkit-text-fill-color:transparent}
|
.topbar{grid-column:1/-1;display:flex;align-items:center;padding:0 20px;background:var(--bg1);border-bottom:1px solid var(--border);gap:14px;z-index:10}
|
||||||
.tabs{display:flex;gap:4px}
|
.brand{display:flex;align-items:center;gap:10px;font-weight:800;font-size:14px;letter-spacing:-.02em;color:var(--t0);padding-right:14px;border-right:1px solid var(--border)}
|
||||||
.tab{padding:7px 18px;border-radius:8px;cursor:pointer;font-size:.88em;color:var(--dim);border:1px solid transparent;transition:.2s}
|
.brand-icon{width:28px;height:28px;border-radius:var(--r-md);background:linear-gradient(135deg,var(--ac),#a855f7);display:flex;align-items:center;justify-content:center;font-size:15px;box-shadow:0 0 20px rgba(124,124,255,.25)}
|
||||||
.tab:hover{background:var(--bg3);color:var(--txt)}
|
.tabs{display:flex;gap:2px}
|
||||||
.tab.on{background:var(--bg4);color:var(--blue);border-color:var(--border)}
|
.tab{padding:7px 16px;border-radius:var(--r-sm);font-size:12.5px;font-weight:600;color:var(--t2);cursor:pointer;transition:all .15s var(--ease);border:none;background:none}
|
||||||
.hdr-r{margin-left:auto;display:flex;gap:10px;align-items:center}
|
.tab:hover{color:var(--t1);background:rgba(255,255,255,.04)}
|
||||||
.pill{padding:4px 12px;border-radius:14px;font-size:.78em;font-weight:600}
|
.tab.active{color:var(--t0);background:var(--bg3)}
|
||||||
.pill-e{background:rgba(59,130,246,.12);color:var(--blue);border:1px solid rgba(59,130,246,.25)}
|
.topbar-right{margin-left:auto;display:flex;align-items:center;gap:8px}
|
||||||
.pill-s{background:rgba(34,197,94,.12);color:var(--green);border:1px solid rgba(34,197,94,.25)}
|
.pill{display:flex;align-items:center;gap:6px;padding:5px 12px;border-radius:100px;font-size:11.5px;font-weight:600;border:1px solid var(--border);background:var(--bg2);color:var(--t1)}
|
||||||
.pill-m{background:rgba(139,92,246,.12);color:var(--purple);border:1px solid rgba(139,92,246,.25)}
|
.dot{width:7px;height:7px;border-radius:50%;background:var(--green);box-shadow:0 0 8px rgba(52,211,153,.4)}
|
||||||
|
.dot.off{background:var(--t3);box-shadow:none}
|
||||||
|
|
||||||
/* ── Sidebar ── */
|
/* Sidebar */
|
||||||
.sb-title{font-size:.82em;font-weight:700;color:var(--cyan);margin:14px 0 8px;display:flex;align-items:center;gap:6px}
|
.sidebar{background:var(--bg1);border-right:1px solid var(--border);overflow-y:auto;padding:10px 8px}
|
||||||
.sb-title:first-child{margin-top:4px}
|
.sb-label{padding:8px 10px 5px;font-size:10.5px;font-weight:700;color:var(--t3);text-transform:uppercase;letter-spacing:.08em}
|
||||||
.sb-item{padding:6px 10px;border-radius:7px;font-size:.86em;color:var(--dim);cursor:pointer;display:flex;align-items:center;gap:8px;transition:.15s}
|
.sb-item{display:flex;align-items:center;gap:9px;padding:7px 10px;border-radius:var(--r-sm);font-size:12.5px;color:var(--t2);cursor:pointer;transition:all .15s var(--ease);position:relative}
|
||||||
.sb-item:hover{background:var(--bg3);color:var(--txt)}
|
.sb-item:hover{color:var(--t1);background:rgba(255,255,255,.04)}
|
||||||
.sb-item.on{background:var(--bg4);color:var(--blue)}
|
.sb-item.active{color:var(--t0);background:rgba(255,255,255,.06)}
|
||||||
.sb-icon{width:20px;text-align:center;flex-shrink:0}
|
.sb-item.active::before{content:'';position:absolute;left:0;top:50%;transform:translateY(-50%);width:2.5px;height:16px;background:var(--ac);border-radius:2px}
|
||||||
|
.sb-icon{width:16px;text-align:center;font-size:12px;flex-shrink:0;opacity:.7}
|
||||||
.sb-name{flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
.sb-name{flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
||||||
.sb-meta{font-size:.76em;color:var(--mute)}
|
.sb-badge{font-size:10px;color:var(--t3);background:var(--bg3);padding:1px 7px;border-radius:100px}
|
||||||
.sep{height:1px;background:var(--border);margin:10px 0}
|
.sb-sep{height:1px;background:var(--border);margin:6px 10px}
|
||||||
|
|
||||||
/* ── Chat ── */
|
/* Main */
|
||||||
.chat-box{flex:1;overflow-y:auto;padding:16px 20px;scroll-behavior:smooth}
|
.main{display:flex;flex-direction:column;overflow:hidden;background:var(--bg)}
|
||||||
.msg{margin-bottom:18px;animation:fadeUp .3s}
|
.view{display:none;height:100%}.view.active{display:flex;flex-direction:column}
|
||||||
@keyframes fadeUp{from{opacity:0;transform:translateY(10px)}to{opacity:1;transform:none}}
|
|
||||||
.msg-role{font-size:.82em;font-weight:700;margin-bottom:5px;display:flex;align-items:center;gap:6px}
|
|
||||||
.msg-role.user{color:var(--cyan)}
|
|
||||||
.msg-role.ai{color:var(--blue)}
|
|
||||||
.msg-time{font-size:.74em;color:var(--mute);font-weight:400}
|
|
||||||
.msg-body{padding:12px 16px;border-radius:var(--r);line-height:1.7;font-size:.93em;white-space:pre-wrap;word-break:break-word}
|
|
||||||
.msg.user .msg-body{background:rgba(6,182,212,.08);border:1px solid rgba(6,182,212,.15)}
|
|
||||||
.msg.ai .msg-body{background:var(--bg2);border:1px solid var(--border)}
|
|
||||||
.msg-body code{background:rgba(255,255,255,.06);padding:1px 6px;border-radius:4px;font-size:.91em}
|
|
||||||
.msg-body pre{background:var(--bg);border:1px solid var(--border);border-radius:8px;padding:12px 16px;overflow-x:auto;margin:8px 0;font-size:.87em}
|
|
||||||
.msg-tool{margin-top:8px;padding:8px 12px;background:rgba(34,197,94,.06);border:1px solid rgba(34,197,94,.12);border-radius:8px;font-size:.87em;color:var(--green)}
|
|
||||||
.msg-err{margin-top:8px;padding:8px 12px;background:rgba(239,68,68,.06);border:1px solid rgba(239,68,68,.12);border-radius:8px;font-size:.87em;color:var(--red)}
|
|
||||||
|
|
||||||
/* ── Input ── */
|
/* Chat */
|
||||||
.input-area{padding:14px 18px;border-top:1px solid var(--border);background:var(--bg2)}
|
.chat-scroll{flex:1;overflow-y:auto;padding:0 28px;scroll-behavior:smooth}
|
||||||
.input-row{display:flex;gap:10px;align-items:flex-end}
|
|
||||||
.inp{flex:1;background:var(--bg);border:1px solid var(--border);border-radius:var(--r);padding:11px 15px;color:var(--txt);font-size:.94em;resize:none;min-height:44px;max-height:150px;outline:none;font-family:inherit;line-height:1.5;transition:border-color .2s}
|
|
||||||
.inp:focus{border-color:var(--border-f)}
|
|
||||||
.btn-send{background:linear-gradient(135deg,var(--blue),var(--purple));color:#fff;border:none;border-radius:var(--r);padding:11px 22px;cursor:pointer;font-weight:700;font-size:.94em;transition:.2s;white-space:nowrap}
|
|
||||||
.btn-send:hover{filter:brightness(1.15);transform:translateY(-1px)}
|
|
||||||
.btn-send:active{transform:translateY(0)}
|
|
||||||
.hint{font-size:.78em;color:var(--mute);margin-top:7px}
|
|
||||||
|
|
||||||
/* ── Editor ── */
|
/* Welcome */
|
||||||
.ed-wrap{flex:1;display:flex;flex-direction:column}
|
.welcome{display:flex;flex-direction:column;align-items:center;justify-content:center;height:100%;text-align:center;animation:fadeUp .5s var(--ease)}
|
||||||
.ed-bar{display:flex;align-items:center;gap:10px;padding:10px 14px;background:var(--bg2);border-bottom:1px solid var(--border)}
|
@keyframes fadeUp{from{opacity:0;transform:translateY(12px)}to{opacity:1;transform:none}}
|
||||||
.ed-bar .fi{font-size:.88em;color:var(--dim);flex:1}
|
.welcome-icon{width:64px;height:64px;border-radius:var(--r-xl);background:linear-gradient(135deg,var(--ac),#a855f7);display:flex;align-items:center;justify-content:center;font-size:32px;margin-bottom:20px;box-shadow:0 0 50px rgba(124,124,255,.25)}
|
||||||
.ed-bar button{padding:6px 16px;border-radius:7px;border:1px solid var(--border);background:var(--bg3);color:var(--txt);cursor:pointer;font-size:.84em;transition:.2s}
|
.welcome h1{font-size:22px;font-weight:800;letter-spacing:-.02em;margin-bottom:8px}
|
||||||
.ed-bar button:hover{background:var(--bg4);border-color:var(--blue)}
|
.welcome p{color:var(--t2);font-size:13px;max-width:400px;margin-bottom:28px}
|
||||||
.ed-bar .bsave{background:rgba(34,197,94,.12);color:var(--green);border-color:rgba(34,197,94,.25)}
|
.quick{display:flex;gap:8px;flex-wrap:wrap;justify-content:center}
|
||||||
.ed-bar .bsave:hover{background:rgba(34,197,94,.2)}
|
.qbtn{padding:8px 16px;border-radius:100px;font-size:12px;font-weight:600;color:var(--t1);border:1px solid var(--border);background:var(--bg2);cursor:pointer;transition:all .15s var(--ease);display:flex;align-items:center;gap:6px}
|
||||||
.ed-body{flex:1;display:flex;overflow:hidden}
|
.qbtn:hover{border-color:var(--border-h);background:var(--bg3);color:var(--t0);transform:translateY(-1px)}
|
||||||
.ed-lines{padding:14px 10px;background:var(--bg2);color:var(--mute);font-family:'JetBrains Mono','Fira Code',monospace;font-size:13px;line-height:1.65;text-align:right;user-select:none;overflow:hidden;min-width:50px;border-right:1px solid var(--border)}
|
|
||||||
.ed-code{flex:1;padding:14px 16px;background:var(--bg);color:var(--txt);font-family:'JetBrains Mono','Fira Code',monospace;font-size:13px;line-height:1.65;border:none;outline:none;resize:none;tab-size:4;white-space:pre;overflow:auto}
|
|
||||||
.ed-status{padding:5px 14px;background:var(--bg2);border-top:1px solid var(--border);font-size:.78em;color:var(--mute);display:flex;gap:18px}
|
|
||||||
|
|
||||||
/* ── Right Panel ── */
|
/* Messages */
|
||||||
.rp-title{font-size:.88em;font-weight:700;color:var(--blue);margin:14px 0 8px;display:flex;align-items:center;gap:6px}
|
.msg{padding:18px 0;animation:msgIn .25s var(--ease)}
|
||||||
.rp-title:first-child{margin-top:2px}
|
@keyframes msgIn{from{opacity:0;transform:translateY(6px)}to{opacity:1;transform:none}}
|
||||||
.stat-grid{display:grid;grid-template-columns:1fr 1fr;gap:8px}
|
.msg+.msg{border-top:1px solid var(--border)}
|
||||||
.stat{background:var(--bg3);border-radius:9px;padding:12px;text-align:center}
|
.msg-head{display:flex;align-items:center;gap:9px;margin-bottom:8px}
|
||||||
.stat-v{font-size:1.5em;font-weight:800;background:linear-gradient(135deg,var(--blue),var(--cyan));-webkit-background-clip:text;-webkit-text-fill-color:transparent}
|
.msg-av{width:26px;height:26px;border-radius:var(--r-sm);display:flex;align-items:center;justify-content:center;font-size:13px;flex-shrink:0}
|
||||||
.stat-l{font-size:.78em;color:var(--mute);margin-top:2px}
|
.msg-av.user{background:var(--cyan-s);color:var(--cyan)}
|
||||||
.rp-item{padding:6px 10px;border-radius:7px;font-size:.84em;color:var(--dim);display:flex;justify-content:space-between;align-items:center;cursor:pointer;transition:.15s}
|
.msg-av.ai{background:var(--ac-s);color:var(--ac)}
|
||||||
.rp-item:hover{background:var(--bg3);color:var(--txt)}
|
.msg-name{font-size:12.5px;font-weight:700;color:var(--t0)}
|
||||||
.rp-item.on{background:rgba(59,130,246,.1);color:var(--blue)}
|
.msg-time{font-size:10.5px;color:var(--t3)}
|
||||||
.log-e{font-size:.8em;padding:3px 0;color:var(--dim);border-bottom:1px solid rgba(30,58,95,.3)}
|
.msg-body{padding-left:35px;font-size:13.5px;line-height:1.75;color:var(--t1)}
|
||||||
.log-t{font-weight:700;margin-right:6px}
|
.msg-body p{margin-bottom:8px}.msg-body p:last-child{margin-bottom:0}
|
||||||
.log-t.sys{color:var(--blue)}.log-t.eng{color:var(--purple)}.log-t.safe{color:var(--green)}.log-t.file{color:var(--yellow)}.log-t.err{color:var(--red)}
|
.msg-body code{background:var(--bg3);padding:2px 6px;border-radius:4px;font-size:12.5px;font-family:'JetBrains Mono','Fira Code',monospace;color:var(--t0)}
|
||||||
|
.msg-body pre{background:var(--bg2);border:1px solid var(--border);border-radius:var(--r-md);padding:14px 18px;margin:10px 0;overflow-x:auto;font-size:12.5px;line-height:1.65;font-family:'JetBrains Mono','Fira Code',monospace;position:relative}
|
||||||
|
.msg-body pre code{background:none;padding:0;font-size:inherit;color:var(--t0)}
|
||||||
|
.msg-body ul,.msg-body ol{margin:6px 0 6px 20px}
|
||||||
|
.msg-body li{margin-bottom:4px}
|
||||||
|
.msg-body blockquote{border-left:3px solid var(--ac);padding:8px 14px;margin:8px 0;background:var(--ac-xs);border-radius:0 var(--r-sm) var(--r-sm) 0;color:var(--t1)}
|
||||||
|
.msg-body a{color:var(--ac);text-decoration:none}.msg-body a:hover{text-decoration:underline}
|
||||||
|
.msg-body strong{color:var(--t0);font-weight:700}
|
||||||
|
.msg-body h1,.msg-body h2,.msg-body h3{color:var(--t0);margin:12px 0 6px;font-weight:700}
|
||||||
|
.msg-body table{border-collapse:collapse;margin:8px 0;width:100%}
|
||||||
|
.msg-body th,.msg-body td{border:1px solid var(--border);padding:6px 10px;font-size:12.5px;text-align:left}
|
||||||
|
.msg-body th{background:var(--bg3);color:var(--t0);font-weight:600}
|
||||||
|
|
||||||
/* ── Views ── */
|
/* Tool cards */
|
||||||
.view{display:none;height:100%}.view.on{display:flex;flex-direction:column}
|
.tool-card{margin:10px 0;padding:10px 14px;background:var(--green-s);border:1px solid rgba(52,211,153,.15);border-radius:var(--r-md);font-size:12.5px;color:var(--green);display:flex;align-items:center;gap:8px;animation:toolIn .3s var(--ease)}
|
||||||
|
@keyframes toolIn{from{opacity:0;transform:scale(.97)}to{opacity:1;transform:none}}
|
||||||
|
.tool-card.error{background:var(--red-s);border-color:rgba(248,113,113,.15);color:var(--red)}
|
||||||
|
.tool-card .tool-icon{font-size:14px}
|
||||||
|
.tool-card .tool-name{font-weight:700}
|
||||||
|
.tool-card .tool-args{color:var(--t2);font-size:11.5px;margin-top:2px;word-break:break-all}
|
||||||
|
|
||||||
/* ── Typing ── */
|
/* Thinking */
|
||||||
.typing{display:inline-flex;gap:5px;padding:6px 0}
|
.thinking{display:flex;align-items:center;gap:10px;padding:12px 0;color:var(--t2);font-size:12.5px;animation:fadeUp .3s var(--ease)}
|
||||||
.typing span{width:7px;height:7px;border-radius:50%;background:var(--mute);animation:bounce 1.4s infinite}
|
.thinking-dots{display:flex;gap:4px}
|
||||||
.typing span:nth-child(2){animation-delay:.2s}
|
.thinking-dots span{width:5px;height:5px;border-radius:50%;background:var(--t3);animation:bounce 1.4s infinite}
|
||||||
.typing span:nth-child(3){animation-delay:.4s}
|
.thinking-dots span:nth-child(2){animation-delay:.2s}
|
||||||
@keyframes bounce{0%,60%,100%{transform:translateY(0)}30%{transform:translateY(-7px)}}
|
.thinking-dots span:nth-child(3){animation-delay:.4s}
|
||||||
|
@keyframes bounce{0%,60%,100%{transform:translateY(0)}30%{transform:translateY(-5px)}}
|
||||||
|
|
||||||
/* ── Scrollbar ── */
|
/* System */
|
||||||
::-webkit-scrollbar{width:5px;height:5px}
|
.sys-msg{padding:4px 0;font-size:12px;color:var(--t2);opacity:.8;padding-left:35px}
|
||||||
|
.sys-msg.error{color:var(--red)}
|
||||||
|
|
||||||
|
/* Input */
|
||||||
|
.input-area{padding:12px 28px 18px;border-top:1px solid var(--border);background:var(--bg1)}
|
||||||
|
.input-wrap{display:flex;align-items:flex-end;gap:10px;background:var(--bg2);border:1.5px solid var(--border);border-radius:var(--r-lg);padding:10px 14px;transition:border-color .15s var(--ease),box-shadow .15s var(--ease)}
|
||||||
|
.input-wrap:focus-within{border-color:var(--border-f);box-shadow:0 0 0 3px rgba(124,124,255,.1)}
|
||||||
|
.chat-input{flex:1;background:none;border:none;outline:none;color:var(--t0);font-size:13.5px;font-family:inherit;line-height:1.5;resize:none;min-height:22px;max-height:140px}
|
||||||
|
.chat-input::placeholder{color:var(--t3)}
|
||||||
|
.send-btn{width:34px;height:34px;border-radius:var(--r-md);background:linear-gradient(135deg,var(--ac),#9060ff);border:none;color:#fff;cursor:pointer;display:flex;align-items:center;justify-content:center;transition:all .15s var(--ease);flex-shrink:0;box-shadow:0 2px 10px rgba(124,124,255,.3)}
|
||||||
|
.send-btn:hover{transform:scale(1.06);box-shadow:0 4px 16px rgba(124,124,255,.4)}
|
||||||
|
.send-btn:active{transform:scale(.95)}
|
||||||
|
.send-btn:disabled{opacity:.35;cursor:not-allowed;transform:none;box-shadow:none}
|
||||||
|
.input-hint{font-size:11px;color:var(--t3);padding:7px 4px 0;display:flex;justify-content:space-between}
|
||||||
|
|
||||||
|
/* Connection banner */
|
||||||
|
.conn{padding:8px 20px;font-size:12px;text-align:center;font-weight:600;display:none}
|
||||||
|
.conn.connecting{display:block;background:var(--amber-s);color:var(--amber);border-bottom:1px solid rgba(251,191,36,.15)}
|
||||||
|
.conn.error{display:block;background:var(--red-s);color:var(--red);border-bottom:1px solid rgba(248,113,113,.15)}
|
||||||
|
.conn.ok{display:block;background:var(--green-s);color:var(--green);border-bottom:1px solid rgba(52,211,153,.15);animation:fadeOut 2s forwards 1.5s}
|
||||||
|
@keyframes fadeOut{to{opacity:0;height:0;padding:0;border:none}}
|
||||||
|
|
||||||
|
/* Scrollbar */
|
||||||
|
::-webkit-scrollbar{width:5px}
|
||||||
::-webkit-scrollbar-track{background:transparent}
|
::-webkit-scrollbar-track{background:transparent}
|
||||||
::-webkit-scrollbar-thumb{background:var(--border);border-radius:3px}
|
::-webkit-scrollbar-thumb{background:var(--bg4);border-radius:3px}
|
||||||
::-webkit-scrollbar-thumb:hover{background:var(--mute)}
|
::-webkit-scrollbar-thumb:hover{background:var(--t3)}
|
||||||
|
|
||||||
/* ── Welcome ── */
|
/* Responsive */
|
||||||
.welcome{text-align:center;padding:60px 20px;animation:fadeUp .5s}
|
@media(max-width:900px){.app{grid-template-columns:1fr}.sidebar{display:none}}
|
||||||
.welcome h2{font-size:1.6em;margin-bottom:10px;background:linear-gradient(135deg,var(--blue),var(--purple),var(--cyan));-webkit-background-clip:text;-webkit-text-fill-color:transparent}
|
|
||||||
.welcome p{color:var(--dim);max-width:460px;margin:0 auto;font-size:1.02em}
|
|
||||||
.welcome .chips{display:flex;justify-content:center;gap:10px;margin-top:20px;flex-wrap:wrap}
|
|
||||||
.welcome .chip{padding:6px 16px;border-radius:20px;font-size:.84em;border:1px solid var(--border);color:var(--dim);cursor:pointer;transition:.2s}
|
|
||||||
.welcome .chip:hover{border-color:var(--blue);color:var(--blue);background:rgba(59,130,246,.06)}
|
|
||||||
|
|
||||||
/* ── Responsive ── */
|
|
||||||
@media(max-width:1024px){.app{grid-template-columns:0 1fr 0}.side,.rpanel{display:none}}
|
|
||||||
@media(max-width:768px){.tabs{display:none}}
|
|
||||||
</style>
|
</style>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
|
|
||||||
<div class="app">
|
<div class="app">
|
||||||
<!-- ═══ Header ═══ -->
|
<!-- Topbar -->
|
||||||
<div class="hdr">
|
<div class="topbar">
|
||||||
<div class="logo"> 小狸 Pro-CLI</div>
|
<div class="brand">
|
||||||
|
<div class="brand-icon"> </div>
|
||||||
|
小狸
|
||||||
|
</div>
|
||||||
<div class="tabs">
|
<div class="tabs">
|
||||||
<div class="tab on" onclick="switchView('chat',this)"> 对话</div>
|
<button class="tab active" data-view="chat">对话</button>
|
||||||
<div class="tab" onclick="switchView('editor',this)"> 编辑器</div>
|
<button class="tab" data-view="tools">工具</button>
|
||||||
</div>
|
</div>
|
||||||
<div class="hdr-r">
|
<div class="topbar-right">
|
||||||
<span class="pill pill-e"> gemma4:31b</span>
|
<div class="pill" id="engine-pill"><span class="dot" id="engine-dot"></span><span id="engine-name">连接中...</span></div>
|
||||||
<span class="pill pill-s"> 普通模式</span>
|
<div class="pill"><span id="safety-icon"> </span><span id="safety-name">普通</span></div>
|
||||||
<span class="pill pill-m">v5.1.2</span>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- ═══ Sidebar ═══ -->
|
<!-- Sidebar -->
|
||||||
<div class="side">
|
<div class="sidebar" id="sidebar">
|
||||||
<div class="sb-title"> 项目文件</div>
|
<div class="sb-label">引擎</div>
|
||||||
<div class="sb-item on" onclick="openFile(this,'ai_cli.py','def main():\n from xcli_core import AICLI, main\n main()')">
|
<div id="engine-list"></div>
|
||||||
<span class="sb-icon"> </span><span class="sb-name">ai_cli.py</span><span class="sb-meta">11行</span>
|
<div class="sb-sep"></div>
|
||||||
</div>
|
<div class="sb-label">工具</div>
|
||||||
<div class="sb-item" onclick="openFile(this,'web_ui.py','#!/usr/bin/env python3\n# 小狸 Pro-CLI Web UI\n# 启动: python web_ui.py\n\nfrom flask import Flask\napp = Flask(__name__)')">
|
<div id="tool-sidebar-list"></div>
|
||||||
<span class="sb-icon"> </span><span class="sb-name">web_ui.py</span><span class="sb-meta">1.1K</span>
|
|
||||||
</div>
|
|
||||||
<div class="sb-item" onclick="openFile(this,'config.json.example','{\n \"api\": {\n \"engines\": {\n \"ollama\": {\n \"model\": \"gemma4:31b\"\n }\n }\n }\n}')">
|
|
||||||
<span class="sb-icon">{ }</span><span class="sb-name">config.json</span><span class="sb-meta">示例</span>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="sep"></div>
|
<!-- Main -->
|
||||||
<div class="sb-title"> xcli_core/</div>
|
|
||||||
<div class="sb-item" onclick="openFile(this,'cli_core.py','class AICLI(BaseAICLI, ClawliMixin,\n ToolMixin, CodeExecMixin,\n DisplayMixin, HistoryMixin):\n \"\"\"AI CLI 主程序\"\"\"\n\n def process_conversation(self, user_input):\n ...')">
|
|
||||||
<span class="sb-icon"> </span><span class="sb-name">cli_core.py</span><span class="sb-meta">900行</span>
|
|
||||||
</div>
|
|
||||||
<div class="sb-item"><span class="sb-icon"> </span><span class="sb-name">safety.py</span><span class="sb-meta">292行</span></div>
|
|
||||||
<div class="sb-item"><span class="sb-icon"> </span><span class="sb-name">sandbox.py</span><span class="sb-meta">187行</span></div>
|
|
||||||
<div class="sb-item"><span class="sb-icon"> </span><span class="sb-name">memory.py</span><span class="sb-meta">记忆系统</span></div>
|
|
||||||
<div class="sb-item"><span class="sb-icon"> </span><span class="sb-name">tui.py</span><span class="sb-meta">899行</span></div>
|
|
||||||
<div class="sb-item"><span class="sb-icon"> </span><span class="sb-name">config.py</span><span class="sb-meta">配置</span></div>
|
|
||||||
|
|
||||||
<div class="sep"></div>
|
|
||||||
<div class="sb-title"> plugins/</div>
|
|
||||||
<div class="sb-item"><span class="sb-icon"> </span><span class="sb-name">code_editor.py</span><span class="sb-meta">23操作</span></div>
|
|
||||||
<div class="sb-item"><span class="sb-icon"> </span><span class="sb-name">git_tools.py</span><span class="sb-meta">20操作</span></div>
|
|
||||||
<div class="sb-item"><span class="sb-icon"> </span><span class="sb-name">browser_auto.py</span><span class="sb-meta">31操作</span></div>
|
|
||||||
<div class="sb-item"><span class="sb-icon"> </span><span class="sb-name">sub_agent.py</span><span class="sb-meta">8操作</span></div>
|
|
||||||
<div class="sb-item"><span class="sb-icon"> </span><span class="sb-name">auto_engineer.py</span><span class="sb-meta">16操作</span></div>
|
|
||||||
<div class="sb-item"><span class="sb-icon"> </span><span class="sb-name">file_manager.py</span><span class="sb-meta">11操作</span></div>
|
|
||||||
<div class="sb-item"><span class="sb-icon"> </span><span class="sb-name">cmd_executor.py</span><span class="sb-meta">1操作</span></div>
|
|
||||||
<div class="sb-item"><span class="sb-icon"> </span><span class="sb-name">task_manager.py</span><span class="sb-meta">7操作</span></div>
|
|
||||||
|
|
||||||
<div class="sep"></div>
|
|
||||||
<div class="sb-title"> ai_engines/</div>
|
|
||||||
<div class="sb-item on"><span class="sb-icon"> </span><span class="sb-name">ollama_engine.py</span><span class="sb-meta">本地</span></div>
|
|
||||||
<div class="sb-item"><span class="sb-icon"> </span><span class="sb-name">openai_engine.py</span><span class="sb-meta">云端</span></div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- ═══ Main ═══ -->
|
|
||||||
<div class="main">
|
<div class="main">
|
||||||
<!-- Chat View -->
|
<div class="conn" id="conn"></div>
|
||||||
<div class="view on" id="v-chat">
|
|
||||||
<div class="chat-box" id="chat-box">
|
<!-- Chat -->
|
||||||
<div class="welcome">
|
<div class="view active" id="view-chat">
|
||||||
<h2>小狸 Pro-CLI v5.1.2</h2>
|
<div class="chat-scroll" id="chat-scroll">
|
||||||
<p>智能编程助手 — 代码编辑 · Git 集成 · 浏览器自动化 · 多 Agent 协作</p>
|
<div class="welcome" id="welcome">
|
||||||
<div class="chips">
|
<div class="welcome-icon"> </div>
|
||||||
<div class="chip" onclick="quickSend('帮我看看项目结构')"> 查看项目结构</div>
|
<h1>小狸 Pro-CLI</h1>
|
||||||
<div class="chip" onclick="quickSend('提交代码')"> 提交代码</div>
|
<p>智能编程助手 — 代码编辑 · Git · 浏览器自动化 · 多引擎支持</p>
|
||||||
<div class="chip" onclick="quickSend('统计代码量')"> 代码统计</div>
|
<div class="quick">
|
||||||
<div class="chip" onclick="quickSend('/help')">❓ 帮助</div>
|
<button class="qbtn" data-msg="帮我看看项目结构"> 项目结构</button>
|
||||||
|
<button class="qbtn" data-msg="提交代码"> 提交代码</button>
|
||||||
|
<button class="qbtn" data-msg="统计代码量"> 代码统计</button>
|
||||||
|
<button class="qbtn" data-msg="/help">❓ 帮助</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="input-area">
|
<div class="input-area">
|
||||||
<div class="input-row">
|
<div class="input-wrap">
|
||||||
<textarea class="inp" id="inp" placeholder="输入消息... (Enter 发送, Shift+Enter 换行)" rows="1"></textarea>
|
<textarea class="chat-input" id="chat-input" placeholder="输入消息... (Enter 发送, Shift+Enter 换行)" rows="1"></textarea>
|
||||||
<button class="btn-send" onclick="send()">发送</button>
|
<button class="send-btn" id="send-btn" title="发送">
|
||||||
</div>
|
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/></svg>
|
||||||
<div class="hint">自然语言交互 — AI 自动选择工具执行 · /help 查看命令 · /safe 切换安全模式</div>
|
</button>
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- Editor View -->
|
|
||||||
<div class="view" id="v-editor">
|
|
||||||
<div class="ed-wrap">
|
|
||||||
<div class="ed-bar">
|
|
||||||
<span class="fi" id="ed-fi">选择左侧文件开始编辑</span>
|
|
||||||
<button onclick="edUndo()">撤销</button>
|
|
||||||
<button class="bsave" onclick="edSave()"> 保存</button>
|
|
||||||
</div>
|
|
||||||
<div class="ed-body">
|
|
||||||
<div class="ed-lines" id="ed-lines">1</div>
|
|
||||||
<textarea class="ed-code" id="ed-code" placeholder="选择左侧文件..." spellcheck="false"></textarea>
|
|
||||||
</div>
|
|
||||||
<div class="ed-status">
|
|
||||||
<span id="ed-cursor">行 1, 列 1</span>
|
|
||||||
<span id="ed-lang">--</span>
|
|
||||||
<span id="ed-enc">UTF-8</span>
|
|
||||||
<span id="ed-syn"> 就绪</span>
|
|
||||||
</div>
|
</div>
|
||||||
|
<div class="input-hint">
|
||||||
|
<span>Enter 发送 · Shift+Enter 换行</span>
|
||||||
|
<span id="conn-status">⚪ 未连接</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- ═══ Right Panel ═══ -->
|
<!-- Tools -->
|
||||||
<div class="rpanel">
|
<div class="view" id="view-tools">
|
||||||
<div class="rp-title"> 系统状态</div>
|
<div style="padding:28px;overflow-y:auto;flex:1">
|
||||||
<div class="stat-grid">
|
<h2 style="font-size:17px;font-weight:800;margin-bottom:20px;color:var(--t0)">已加载工具</h2>
|
||||||
<div class="stat"><div class="stat-v">15</div><div class="stat-l">插件</div></div>
|
<div id="tools-grid" style="display:grid;grid-template-columns:repeat(auto-fill,minmax(300px,1fr));gap:10px"></div>
|
||||||
<div class="stat"><div class="stat-v">141</div><div class="stat-l">操作</div></div>
|
|
||||||
<div class="stat"><div class="stat-v">2</div><div class="stat-l">引擎</div></div>
|
|
||||||
<div class="stat"><div class="stat-v">113</div><div class="stat-l">测试</div></div>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="rp-title"> AI 引擎</div>
|
|
||||||
<div class="rp-item on"><span>▸ ollama (本地)</span><span style="color:var(--green)">●</span></div>
|
|
||||||
<div class="rp-item"><span> openai (云端)</span><span style="color:var(--mute)">○</span></div>
|
|
||||||
|
|
||||||
<div class="rp-title">⚡ 安全模式</div>
|
|
||||||
<div class="rp-item on"><span> 普通模式</span><span style="color:var(--green)">●</span></div>
|
|
||||||
<div class="rp-item"><span> 人工确认</span><span style="color:var(--mute)">○</span></div>
|
|
||||||
<div class="rp-item"><span> 无限制</span><span style="color:var(--mute)">○</span></div>
|
|
||||||
|
|
||||||
<div class="rp-title"> 工具 (15)</div>
|
|
||||||
<div style="max-height:180px;overflow-y:auto">
|
|
||||||
<div class="rp-item"><span>code_editor</span><span class="sb-meta">23</span></div>
|
|
||||||
<div class="rp-item"><span>git_tools</span><span class="sb-meta">20</span></div>
|
|
||||||
<div class="rp-item"><span>browser_auto</span><span class="sb-meta">31</span></div>
|
|
||||||
<div class="rp-item"><span>sub_agent</span><span class="sb-meta">8</span></div>
|
|
||||||
<div class="rp-item"><span>auto_engineer</span><span class="sb-meta">16</span></div>
|
|
||||||
<div class="rp-item"><span>file_manager</span><span class="sb-meta">11</span></div>
|
|
||||||
<div class="rp-item"><span>cmd_executor</span><span class="sb-meta">1</span></div>
|
|
||||||
<div class="rp-item"><span>task_manager</span><span class="sb-meta">7</span></div>
|
|
||||||
<div class="rp-item"><span>network_tools</span><span class="sb-meta">4</span></div>
|
|
||||||
<div class="rp-item"><span>ai_search</span><span class="sb-meta">2</span></div>
|
|
||||||
<div class="rp-item"><span>tool_search</span><span class="sb-meta">1</span></div>
|
|
||||||
<div class="rp-item"><span>frontend_tester</span><span class="sb-meta">5</span></div>
|
|
||||||
<div class="rp-item"><span>speech_recognition</span><span class="sb-meta">2</span></div>
|
|
||||||
<div class="rp-item"><span>audio_player</span><span class="sb-meta">3</span></div>
|
|
||||||
<div class="rp-item"><span>send_image</span><span class="sb-meta">1</span></div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="rp-title"> 日志</div>
|
|
||||||
<div id="log-area">
|
|
||||||
<div class="log-e"><span class="log-t sys">[系统]</span>01:04:22 Web UI 已启动</div>
|
|
||||||
<div class="log-e"><span class="log-t eng">[引擎]</span>01:04:22 Ollama 已连接</div>
|
|
||||||
<div class="log-e"><span class="log-t safe">[安全]</span>01:04:22 普通模式</div>
|
|
||||||
<div class="log-e"><span class="log-t file">[文件]</span>01:04:22 已加载 15 个插件</div>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<script>
|
<script>
|
||||||
// ═══ View Switch ═══
|
const WS_URL = `ws://${location.hostname}:8079`;
|
||||||
function switchView(v,el){
|
let ws = null, reconnectTimer = null, isThinking = false;
|
||||||
document.querySelectorAll('.view').forEach(x=>x.classList.remove('on'));
|
|
||||||
document.getElementById('v-'+v).classList.add('on');
|
// Configure marked
|
||||||
document.querySelectorAll('.tab').forEach(x=>x.classList.remove('on'));
|
if (typeof marked !== 'undefined') {
|
||||||
if(el)el.classList.add('on');
|
marked.setOptions({ breaks: true, gfm: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
function connect() {
|
||||||
|
const c = document.getElementById('conn');
|
||||||
|
c.className = 'conn connecting'; c.textContent = '⏳ 正在连接...';
|
||||||
|
try {
|
||||||
|
ws = new WebSocket(WS_URL);
|
||||||
|
ws.onopen = () => {
|
||||||
|
c.className = 'conn ok'; c.textContent = '✅ 已连接';
|
||||||
|
document.getElementById('conn-status').textContent = '🟢 已连接';
|
||||||
|
clearTimeout(reconnectTimer);
|
||||||
|
};
|
||||||
|
ws.onmessage = e => { try { handleMessage(JSON.parse(e.data)) } catch(err) { console.error(err) } };
|
||||||
|
ws.onclose = () => {
|
||||||
|
document.getElementById('conn-status').textContent = '⚪ 已断开';
|
||||||
|
c.className = 'conn error'; c.textContent = '❌ 连接断开,重连中...';
|
||||||
|
reconnectTimer = setTimeout(connect, 3000);
|
||||||
|
};
|
||||||
|
ws.onerror = () => { c.className = 'conn error'; c.textContent = '❌ 无法连接服务器' };
|
||||||
|
} catch(e) { c.className = 'conn error'; c.textContent = '❌ WebSocket 不可用' }
|
||||||
|
}
|
||||||
|
|
||||||
|
function send(type, data={}) {
|
||||||
|
if (!ws || ws.readyState !== WebSocket.OPEN) { addSys('未连接到服务器', true); return }
|
||||||
|
ws.send(JSON.stringify({ type, data }));
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleMessage(msg) {
|
||||||
|
const d = msg.data || {};
|
||||||
|
switch (msg.type) {
|
||||||
|
case 'status': updateStatus(d); break;
|
||||||
|
case 'thinking': showThinking(); break;
|
||||||
|
case 'reply': hideThinking(); addMsg('ai', d.message); break;
|
||||||
|
case 'partial_reply': addSys(d.message); break;
|
||||||
|
case 'tool_call': showToolCall(d.name, d.args); break;
|
||||||
|
case 'tool_result': showToolResult(d.name, d.result); break;
|
||||||
|
case 'tool_executing': showToolCall(d.name, d.args); break;
|
||||||
|
case 'fc_tool_done': /* silent */ break;
|
||||||
|
case 'multi':
|
||||||
|
hideThinking();
|
||||||
|
(d.events||[]).forEach(ev => {
|
||||||
|
if (ev.type === 'reply') addMsg('ai', ev.message);
|
||||||
|
else if (ev.type === 'tool_call') showToolCall(ev.name, ev.args);
|
||||||
|
else if (ev.type === 'tool_result') showToolResult(ev.name, ev.result);
|
||||||
|
else if (ev.type === 'partial_reply') addSys(ev.message);
|
||||||
|
});
|
||||||
|
break;
|
||||||
|
case 'engine_switched':
|
||||||
|
document.getElementById('engine-name').textContent = d.engine;
|
||||||
|
addSys(`引擎已切换: ${d.engine}`); break;
|
||||||
|
case 'safety_switched':
|
||||||
|
document.getElementById('safety-name').textContent = d.mode;
|
||||||
|
addSys(`安全模式: ${d.mode}`); break;
|
||||||
|
case 'tools': renderTools(d.tools); break;
|
||||||
|
case 'tools_list': renderTools(d.tools); break;
|
||||||
|
case 'error': hideThinking(); addSys(d.message, true); break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateStatus(d) {
|
||||||
|
document.getElementById('engine-name').textContent = d.engine || '未连接';
|
||||||
|
document.getElementById('safety-name').textContent = d.safety_mode || '普通';
|
||||||
|
const dot = document.getElementById('engine-dot');
|
||||||
|
dot.className = d.engine_type === 'none' ? 'dot off' : 'dot';
|
||||||
|
|
||||||
|
// Sidebar engines
|
||||||
|
const el = document.getElementById('engine-list');
|
||||||
|
el.innerHTML = (d.engines||[]).map(n =>
|
||||||
|
`<div class="sb-item${n===d.engine?' active':''}" data-engine="${n}">
|
||||||
|
<span class="sb-icon">${n==='ollama'?' ':'☁️'}</span><span class="sb-name">${n}</span>
|
||||||
|
${n===d.engine?'<span class="sb-badge">当前</span>':''}
|
||||||
|
</div>`
|
||||||
|
).join('');
|
||||||
|
el.querySelectorAll('[data-engine]').forEach(e =>
|
||||||
|
e.addEventListener('click', () => send('switch_engine', {engine: e.dataset.engine}))
|
||||||
|
);
|
||||||
|
|
||||||
|
// Sidebar tools
|
||||||
|
const tl = document.getElementById('tool-sidebar-list');
|
||||||
|
tl.innerHTML = (d.tools||[]).map(t =>
|
||||||
|
`<div class="sb-item"><span class="sb-icon"> </span><span class="sb-name">${t.name}</span></div>`
|
||||||
|
).join('');
|
||||||
}
|
}
|
||||||
|
|
||||||
// ═══ Chat ═══
|
// ═══ Chat ═══
|
||||||
function send(){
|
|
||||||
const inp=document.getElementById('inp');
|
|
||||||
const msg=inp.value.trim();
|
|
||||||
if(!msg)return;
|
|
||||||
inp.value='';inp.style.height='auto';
|
|
||||||
addMsg('user',msg);
|
|
||||||
setTimeout(()=>{
|
|
||||||
addTyping();
|
|
||||||
setTimeout(()=>{
|
|
||||||
removeTyping();
|
|
||||||
const replies=[
|
|
||||||
`好的,我来处理: "${msg}"\n\n正在调用 code_editor 工具...`,
|
|
||||||
`收到!让我看看...\n\n 工具 [code_editor] 执行完成\n结果: 操作已成功执行`,
|
|
||||||
`明白。我来分析一下项目情况。\n\n 代码统计:\n 文件: 40\n 代码: 8,521 行\n 注释: 1,892 行\n 注释率: 22.2%`,
|
|
||||||
`我来帮你处理。\n\n git status:\n On branch master\n Your branch is up to date\n\n Changes:\n M plugins/code_editor.py\n ?? web_ui.py`,
|
|
||||||
];
|
|
||||||
addMsg('ai',replies[Math.floor(Math.random()*replies.length)]);
|
|
||||||
},800+Math.random()*1200);
|
|
||||||
},200);
|
|
||||||
}
|
|
||||||
|
|
||||||
function quickSend(msg){
|
function addMsg(role, content) {
|
||||||
document.getElementById('inp').value=msg;
|
const w = document.getElementById('welcome'); if (w) w.remove();
|
||||||
send();
|
const s = document.getElementById('chat-scroll');
|
||||||
}
|
const d = document.createElement('div'); d.className = 'msg';
|
||||||
|
const isU = role === 'user';
|
||||||
|
const t = new Date().toLocaleTimeString('zh-CN', {hour:'2-digit',minute:'2-digit'});
|
||||||
|
|
||||||
function addMsg(role,content){
|
let html;
|
||||||
const box=document.getElementById('chat-box');
|
if (isU) {
|
||||||
// Remove welcome if present
|
html = escHtml(content);
|
||||||
const w=box.querySelector('.welcome');if(w)w.remove();
|
} else {
|
||||||
const d=document.createElement('div');
|
try { html = marked.parse(content) } catch(e) { html = escHtml(content) }
|
||||||
d.className='msg '+(role==='user'?'user':'ai');
|
|
||||||
const label=role==='user'?' 你':' 小狸';
|
|
||||||
const cls=role==='user'?'user':'ai';
|
|
||||||
const t=new Date().toLocaleTimeString('zh-CN',{hour:'2-digit',minute:'2-digit'});
|
|
||||||
let html=escapeHtml(content);
|
|
||||||
html=html.replace(/```(\w*)\n([\s\S]*?)```/g,'<pre><code>$2</code></pre>');
|
|
||||||
html=html.replace(/`([^`]+)`/g,'<code>$1</code>');
|
|
||||||
d.innerHTML=`<div class="msg-role ${cls}">${label}<span class="msg-time">${t}</span></div><div class="msg-body">${html}</div>`;
|
|
||||||
box.appendChild(d);
|
|
||||||
box.scrollTop=box.scrollHeight;
|
|
||||||
}
|
|
||||||
|
|
||||||
function addTyping(){
|
|
||||||
const box=document.getElementById('chat-box');
|
|
||||||
const d=document.createElement('div');
|
|
||||||
d.className='msg ai';d.id='typing';
|
|
||||||
d.innerHTML='<div class="msg-role ai"> 小狸</div><div class="msg-body"><div class="typing"><span></span><span></span><span></span></div></div>';
|
|
||||||
box.appendChild(d);box.scrollTop=box.scrollHeight;
|
|
||||||
}
|
|
||||||
function removeTyping(){const e=document.getElementById('typing');if(e)e.remove();}
|
|
||||||
function escapeHtml(s){return s.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>')}
|
|
||||||
|
|
||||||
document.getElementById('inp').addEventListener('keydown',e=>{
|
|
||||||
if(e.key==='Enter'&&!e.shiftKey){e.preventDefault();send();}
|
|
||||||
});
|
|
||||||
document.getElementById('inp').addEventListener('input',function(){
|
|
||||||
this.style.height='auto';
|
|
||||||
this.style.height=Math.min(this.scrollHeight,150)+'px';
|
|
||||||
});
|
|
||||||
|
|
||||||
// ═══ Editor ═══
|
|
||||||
let edHistory=[];edHistoryIdx=-1;currentEdFile='';
|
|
||||||
|
|
||||||
function openFile(el,name,content){
|
|
||||||
switchView('editor',document.querySelectorAll('.tab')[1]);
|
|
||||||
document.querySelectorAll('.sb-item').forEach(x=>x.classList.remove('on'));
|
|
||||||
if(el)el.classList.add('on');
|
|
||||||
currentEdFile=name;
|
|
||||||
const ta=document.getElementById('ed-code');
|
|
||||||
ta.value=content;
|
|
||||||
edHistory=[content];edHistoryIdx=0;
|
|
||||||
document.getElementById('ed-fi').textContent=name;
|
|
||||||
document.getElementById('ed-lang').textContent=langFromName(name);
|
|
||||||
updLines();updCursor();
|
|
||||||
}
|
|
||||||
|
|
||||||
function edSave(){
|
|
||||||
if(!currentEdFile)return;
|
|
||||||
const ta=document.getElementById('ed-code');
|
|
||||||
const lines=ta.value.split('\n').length;
|
|
||||||
document.getElementById('ed-fi').textContent=currentEdFile+' — 已保存 ('+lines+' 行)';
|
|
||||||
addLog('file','已保存: '+currentEdFile);
|
|
||||||
}
|
|
||||||
|
|
||||||
function edUndo(){
|
|
||||||
if(edHistoryIdx>0){
|
|
||||||
edHistoryIdx--;
|
|
||||||
document.getElementById('ed-code').value=edHistory[edHistoryIdx];
|
|
||||||
updLines();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
d.innerHTML = `
|
||||||
|
<div class="msg-head">
|
||||||
|
<div class="msg-av ${isU?'user':'ai'}">${isU?' ':' '}</div>
|
||||||
|
<span class="msg-name">${isU?'你':'小狸'}</span>
|
||||||
|
<span class="msg-time">${t}</span>
|
||||||
|
</div>
|
||||||
|
<div class="msg-body">${html}</div>`;
|
||||||
|
s.appendChild(d); s.scrollTop = s.scrollHeight;
|
||||||
}
|
}
|
||||||
|
|
||||||
const edTa=document.getElementById('ed-code');
|
function addSys(text, isErr=false) {
|
||||||
edTa.addEventListener('input',function(){
|
const s = document.getElementById('chat-scroll');
|
||||||
clearTimeout(this._t);
|
const d = document.createElement('div');
|
||||||
this._t=setTimeout(()=>{
|
d.className = 'sys-msg' + (isErr?' error':'');
|
||||||
const v=this.value;
|
d.textContent = text;
|
||||||
if(edHistory[edHistoryIdx]!==v){
|
s.appendChild(d); s.scrollTop = s.scrollHeight;
|
||||||
edHistory=edHistory.slice(0,edHistoryIdx+1);
|
|
||||||
edHistory.push(v);edHistoryIdx=edHistory.length-1;
|
|
||||||
}
|
|
||||||
},400);
|
|
||||||
updLines();
|
|
||||||
});
|
|
||||||
edTa.addEventListener('scroll',function(){
|
|
||||||
document.getElementById('ed-lines').scrollTop=this.scrollTop;
|
|
||||||
});
|
|
||||||
edTa.addEventListener('click',updCursor);
|
|
||||||
edTa.addEventListener('keyup',updCursor);
|
|
||||||
edTa.addEventListener('keydown',function(e){
|
|
||||||
if(e.key==='Tab'){
|
|
||||||
e.preventDefault();
|
|
||||||
const s=this.selectionStart,end=this.selectionEnd;
|
|
||||||
this.value=this.value.substring(0,s)+' '+this.value.substring(end);
|
|
||||||
this.selectionStart=this.selectionEnd=s+4;updLines();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
document.addEventListener('keydown',e=>{
|
|
||||||
if((e.ctrlKey||e.metaKey)&&e.key==='s'){e.preventDefault();edSave();}
|
|
||||||
});
|
|
||||||
|
|
||||||
function updLines(){
|
|
||||||
const ta=document.getElementById('ed-code');
|
|
||||||
const n=ta.value.split('\n').length;
|
|
||||||
document.getElementById('ed-lines').textContent=Array.from({length:n},(_,i)=>i+1).join('\n');
|
|
||||||
}
|
|
||||||
function updCursor(){
|
|
||||||
const ta=document.getElementById('ed-code');
|
|
||||||
const v=ta.value.substring(0,ta.selectionStart);
|
|
||||||
const line=v.split('\n').length;
|
|
||||||
const col=v.split('\n').pop().length+1;
|
|
||||||
document.getElementById('ed-cursor').textContent='行 '+line+', 列 '+col;
|
|
||||||
}
|
|
||||||
function langFromName(n){
|
|
||||||
const m={'.py':'Python','.js':'JavaScript','.ts':'TypeScript','.json':'JSON','.html':'HTML','.css':'CSS','.md':'Markdown','.sh':'Shell','.yaml':'YAML','.toml':'TOML'};
|
|
||||||
for(const[k,v]of Object.entries(m))if(n.endsWith(k))return v;
|
|
||||||
return'--';
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ═══ Log ═══
|
function showToolCall(name, args) {
|
||||||
function addLog(tag,msg){
|
const w = document.getElementById('welcome'); if (w) w.remove();
|
||||||
const a=document.getElementById('log-area');
|
const s = document.getElementById('chat-scroll');
|
||||||
const t=new Date().toLocaleTimeString('zh-CN',{hour:'2-digit',minute:'2-digit',second:'2-digit'});
|
const d = document.createElement('div'); d.className = 'msg';
|
||||||
const cls={sys:'sys',eng:'eng',safe:'safe',file:'file',err:'err'}[tag]||'sys';
|
d.innerHTML = `
|
||||||
const labels={sys:'系统',eng:'引擎',safe:'安全',file:'文件',err:'错误'};
|
<div class="msg-head">
|
||||||
a.innerHTML+=`<div class="log-e"><span class="log-t ${cls}">[${labels[tag]||tag}]</span>${t} ${msg}</div>`;
|
<div class="msg-av ai"> </div>
|
||||||
a.scrollTop=a.scrollHeight;
|
<span class="msg-name">工具调用</span>
|
||||||
|
</div>
|
||||||
|
<div class="msg-body">
|
||||||
|
<div class="tool-card">
|
||||||
|
<span class="tool-icon">⚡</span>
|
||||||
|
<div><span class="tool-name">${escHtml(name)}</span>
|
||||||
|
${args?'<div class="tool-args">'+escHtml(String(args).slice(0,300))+'</div>':''}</div>
|
||||||
|
</div>
|
||||||
|
</div>`;
|
||||||
|
s.appendChild(d); s.scrollTop = s.scrollHeight;
|
||||||
}
|
}
|
||||||
|
|
||||||
// ═══ Keyboard shortcut info ═══
|
function showToolResult(name, result) {
|
||||||
console.log('%c 小狸 Pro-CLI Web UI ','background:#3b82f6;color:#fff;padding:4px 12px;border-radius:6px;font-size:14px');
|
const s = document.getElementById('chat-scroll');
|
||||||
console.log('%c 快捷键: Ctrl+S 保存 | Enter 发送 | Shift+Enter 换行 | Tab 缩进 ','color:#94a3b8');
|
const d = document.createElement('div'); d.className = 'msg';
|
||||||
|
const isErr = String(result).includes('错误') || String(result).includes('Error');
|
||||||
|
d.innerHTML = `
|
||||||
|
<div class="msg-body" style="padding-left:35px">
|
||||||
|
<div class="tool-card${isErr?' error':''}">
|
||||||
|
<span class="tool-icon">${isErr?'❌':'✅'}</span>
|
||||||
|
<div><span class="tool-name">${escHtml(name)}</span> ${isErr?'失败':'完成'}
|
||||||
|
<div class="tool-args">${escHtml(String(result).slice(0,400))}</div></div>
|
||||||
|
</div>
|
||||||
|
</div>`;
|
||||||
|
s.appendChild(d); s.scrollTop = s.scrollHeight;
|
||||||
|
}
|
||||||
|
|
||||||
|
function showThinking() {
|
||||||
|
if (isThinking) return; isThinking = true;
|
||||||
|
const w = document.getElementById('welcome'); if (w) w.remove();
|
||||||
|
const s = document.getElementById('chat-scroll');
|
||||||
|
const d = document.createElement('div'); d.className = 'msg'; d.id = 'think';
|
||||||
|
d.innerHTML = `
|
||||||
|
<div class="msg-head">
|
||||||
|
<div class="msg-av ai"> </div>
|
||||||
|
<span class="msg-name">小狸</span>
|
||||||
|
</div>
|
||||||
|
<div class="msg-body">
|
||||||
|
<div class="thinking"><div class="thinking-dots"><span></span><span></span><span></span></div> 思考中...</div>
|
||||||
|
</div>`;
|
||||||
|
s.appendChild(d); s.scrollTop = s.scrollHeight;
|
||||||
|
document.getElementById('send-btn').disabled = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
function hideThinking() {
|
||||||
|
isThinking = false;
|
||||||
|
const el = document.getElementById('think'); if (el) el.remove();
|
||||||
|
document.getElementById('send-btn').disabled = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ═══ Tools Grid ═══
|
||||||
|
|
||||||
|
function renderTools(tools) {
|
||||||
|
document.getElementById('tools-grid').innerHTML = (tools||[]).map(t => `
|
||||||
|
<div style="background:var(--bg2);border:1px solid var(--border);border-radius:var(--r-md);padding:14px 16px;transition:border-color .15s" onmouseenter="this.style.borderColor='var(--border-h)'" onmouseleave="this.style.borderColor='var(--border)'">
|
||||||
|
<div style="font-size:13.5px;font-weight:700;color:var(--t0);margin-bottom:5px">${t.name}</div>
|
||||||
|
<div style="font-size:12px;color:var(--t2);line-height:1.55">${t.description||''}</div>
|
||||||
|
</div>
|
||||||
|
`).join('');
|
||||||
|
}
|
||||||
|
|
||||||
|
// ═══ Input ═══
|
||||||
|
|
||||||
|
const input = document.getElementById('chat-input');
|
||||||
|
input.addEventListener('keydown', e => { if (e.key==='Enter' && !e.shiftKey) { e.preventDefault(); handleSend() } });
|
||||||
|
input.addEventListener('input', function() { this.style.height='auto'; this.style.height=Math.min(this.scrollHeight,140)+'px' });
|
||||||
|
document.getElementById('send-btn').addEventListener('click', handleSend);
|
||||||
|
|
||||||
|
function handleSend() {
|
||||||
|
const msg = input.value.trim(); if (!msg || isThinking) return;
|
||||||
|
input.value=''; input.style.height='auto';
|
||||||
|
addMsg('user', msg);
|
||||||
|
send('chat', {message: msg});
|
||||||
|
}
|
||||||
|
|
||||||
|
document.querySelectorAll('.qbtn').forEach(b => b.addEventListener('click', () => { input.value=b.dataset.msg; handleSend() }));
|
||||||
|
|
||||||
|
document.querySelectorAll('.tab').forEach(tab => tab.addEventListener('click', () => {
|
||||||
|
document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
|
||||||
|
tab.classList.add('active');
|
||||||
|
document.querySelectorAll('.view').forEach(v => v.classList.remove('active'));
|
||||||
|
document.getElementById('view-'+tab.dataset.view).classList.add('active');
|
||||||
|
if (tab.dataset.view==='tools') send('tools');
|
||||||
|
}));
|
||||||
|
|
||||||
|
function escHtml(s) { return String(s).replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>') }
|
||||||
|
|
||||||
|
connect();
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
+470
@@ -0,0 +1,470 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""
|
||||||
|
小狸 Pro-CLI Web UI 后端
|
||||||
|
WebSocket 服务器 + 静态文件服务
|
||||||
|
|
||||||
|
启动:
|
||||||
|
python webui_server.py [--port 8080] [--host 0.0.0.0]
|
||||||
|
|
||||||
|
依赖:
|
||||||
|
pip install websockets
|
||||||
|
"""
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
import argparse
|
||||||
|
import mimetypes
|
||||||
|
from pathlib import Path
|
||||||
|
from datetime import datetime
|
||||||
|
from http.server import HTTPServer, SimpleHTTPRequestHandler
|
||||||
|
from urllib.parse import urlparse, parse_qs
|
||||||
|
import threading
|
||||||
|
|
||||||
|
# 添加项目根目录
|
||||||
|
PROJECT_DIR = os.path.dirname(os.path.abspath(__file__))
|
||||||
|
sys.path.insert(0, PROJECT_DIR)
|
||||||
|
|
||||||
|
try:
|
||||||
|
import websockets
|
||||||
|
WEBSOCKETS_AVAILABLE = True
|
||||||
|
except ImportError:
|
||||||
|
WEBSOCKETS_AVAILABLE = False
|
||||||
|
print("⚠️ websockets 未安装,WebSocket 功能不可用")
|
||||||
|
print(" 安装: pip install websockets")
|
||||||
|
|
||||||
|
|
||||||
|
# ═══════════════════════════════════════════
|
||||||
|
# AI 引擎桥接
|
||||||
|
# ═══════════════════════════════════════════
|
||||||
|
|
||||||
|
class AIEngineBridge:
|
||||||
|
"""桥接到小狸的 AI 引擎和插件系统"""
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
self.cli = None
|
||||||
|
self._initialized = False
|
||||||
|
|
||||||
|
def initialize(self):
|
||||||
|
"""延迟初始化小狸核心"""
|
||||||
|
if self._initialized:
|
||||||
|
return True
|
||||||
|
try:
|
||||||
|
from xcli_core import AICLI
|
||||||
|
self.cli = AICLI()
|
||||||
|
self._initialized = True
|
||||||
|
return True
|
||||||
|
except Exception as e:
|
||||||
|
print(f"⚠️ 小狸核心初始化失败: {e}")
|
||||||
|
return False
|
||||||
|
|
||||||
|
def get_status(self):
|
||||||
|
"""获取系统状态"""
|
||||||
|
if not self.cli:
|
||||||
|
return {
|
||||||
|
"engine": "未连接",
|
||||||
|
"engine_type": "none",
|
||||||
|
"plugins": 0,
|
||||||
|
"operations": 0,
|
||||||
|
"safety_mode": "普通",
|
||||||
|
"tools": [],
|
||||||
|
"engines": [],
|
||||||
|
}
|
||||||
|
|
||||||
|
engine_name = getattr(self.cli.current_engine, 'name', '未知') if self.cli.current_engine else '无'
|
||||||
|
tools = []
|
||||||
|
if hasattr(self.cli, 'liugin_manager') and self.cli.liugin_manager:
|
||||||
|
for t in self.cli.liugin_manager.tools:
|
||||||
|
tools.append({
|
||||||
|
"name": t.get('name', ''),
|
||||||
|
"description": t.get('description', ''),
|
||||||
|
"ops": len(t.get('usage', '').split('\n')) if t.get('usage') else 0,
|
||||||
|
})
|
||||||
|
|
||||||
|
from xcli_core.safety import get_safety
|
||||||
|
safety = get_safety()
|
||||||
|
|
||||||
|
return {
|
||||||
|
"engine": engine_name,
|
||||||
|
"engine_type": "local" if engine_name == "ollama" else "cloud",
|
||||||
|
"plugins": len(tools),
|
||||||
|
"operations": sum(t.get('ops', 0) for t in tools),
|
||||||
|
"safety_mode": safety.get_mode_name(),
|
||||||
|
"tools": tools,
|
||||||
|
"engines": list(self.cli.engines.keys()) if self.cli.engines else [],
|
||||||
|
}
|
||||||
|
|
||||||
|
def chat(self, message: str, callback=None):
|
||||||
|
"""发送消息到 AI 并获取回复(支持工具调用循环)"""
|
||||||
|
if not self.cli:
|
||||||
|
return {"type": "error", "message": "小狸核心未初始化,请检查配置"}
|
||||||
|
|
||||||
|
results = [] # 收集所有事件
|
||||||
|
|
||||||
|
try:
|
||||||
|
# 添加用户消息到历史
|
||||||
|
self.cli.shared_conversation_history.append({
|
||||||
|
"role": "user", "content": message
|
||||||
|
})
|
||||||
|
|
||||||
|
liugin_prompts = self.cli.get_liugin_usage_prompts()
|
||||||
|
system_prompt = self.cli._build_system_prompt(liugin_prompts)
|
||||||
|
|
||||||
|
loop_count = 0
|
||||||
|
max_loops = 15
|
||||||
|
current_input = message
|
||||||
|
|
||||||
|
while loop_count < max_loops:
|
||||||
|
# 生成 AI 响应
|
||||||
|
if not self.cli.current_engine:
|
||||||
|
return {"type": "error", "message": "没有可用的 AI 引擎"}
|
||||||
|
|
||||||
|
response = self.cli.current_engine.generate_response(
|
||||||
|
current_input, system_prompt=system_prompt
|
||||||
|
)
|
||||||
|
|
||||||
|
if not response:
|
||||||
|
return {"type": "reply", "message": "(无响应)"}
|
||||||
|
|
||||||
|
# 检查 FC 响应(Ollama Function Calling)
|
||||||
|
fc_result = self.cli._handle_fc_response(response, message)
|
||||||
|
if fc_result:
|
||||||
|
# FC 工具已执行,结果作为下一轮输入
|
||||||
|
results.append({"type": "fc_tool_done", "message": fc_result[:200]})
|
||||||
|
current_input = fc_result
|
||||||
|
loop_count += 1
|
||||||
|
continue
|
||||||
|
|
||||||
|
# 解析混合响应(文本 + JSON 工具调用)
|
||||||
|
try:
|
||||||
|
text_content, json_data = self.cli._parse_mixed_response(response)
|
||||||
|
except Exception:
|
||||||
|
text_content, json_data = response, None
|
||||||
|
|
||||||
|
if json_data and isinstance(json_data, dict):
|
||||||
|
if json_data.get('action') == 'use_tool':
|
||||||
|
tool_name = json_data.get('tool', '')
|
||||||
|
tool_args = json_data.get('args', '')
|
||||||
|
results.append({"type": "tool_call", "name": tool_name, "args": tool_args[:200]})
|
||||||
|
|
||||||
|
# 执行工具
|
||||||
|
try:
|
||||||
|
tool_result = self.cli._execute_tool_by_name(tool_name, tool_args)
|
||||||
|
except Exception as e:
|
||||||
|
tool_result = f"工具执行错误: {e}"
|
||||||
|
|
||||||
|
results.append({"type": "tool_result", "name": tool_name, "result": str(tool_result)[:500]})
|
||||||
|
|
||||||
|
# 把工具结果加入历史并继续循环
|
||||||
|
self.cli.shared_conversation_history.append({
|
||||||
|
"role": "tool", "content": str(tool_result),
|
||||||
|
"name": tool_name
|
||||||
|
})
|
||||||
|
current_input = f"工具 {tool_name} 的执行结果:\n{tool_result}"
|
||||||
|
loop_count += 1
|
||||||
|
continue
|
||||||
|
|
||||||
|
elif json_data.get('continue') or json_data.get('need_continue'):
|
||||||
|
msg = json_data.get('message', text_content or '')
|
||||||
|
if msg:
|
||||||
|
results.append({"type": "partial_reply", "message": msg})
|
||||||
|
self.cli.shared_conversation_history.append({"role": "assistant", "content": msg})
|
||||||
|
current_input = "继续"
|
||||||
|
loop_count += 1
|
||||||
|
continue
|
||||||
|
|
||||||
|
elif json_data.get('message'):
|
||||||
|
final = json_data.get('message')
|
||||||
|
self.cli.shared_conversation_history.append({"role": "assistant", "content": final})
|
||||||
|
results.append({"type": "reply", "message": final})
|
||||||
|
break
|
||||||
|
|
||||||
|
# 纯文本响应
|
||||||
|
display = text_content if text_content else response
|
||||||
|
self.cli.shared_conversation_history.append({"role": "assistant", "content": display})
|
||||||
|
results.append({"type": "reply", "message": display})
|
||||||
|
break
|
||||||
|
|
||||||
|
if not results:
|
||||||
|
results.append({"type": "reply", "message": response or "(无响应)"})
|
||||||
|
|
||||||
|
return {"type": "multi", "events": results}
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
return {"type": "error", "message": f"错误: {e}"}
|
||||||
|
|
||||||
|
def execute_tool(self, tool_name: str, tool_args: str):
|
||||||
|
"""直接执行工具"""
|
||||||
|
if not self.cli:
|
||||||
|
return "❌ 小狸核心未初始化"
|
||||||
|
|
||||||
|
try:
|
||||||
|
result = self.cli._execute_tool_by_name(tool_name, tool_args)
|
||||||
|
return result or "(无结果)"
|
||||||
|
except Exception as e:
|
||||||
|
return f"❌ 工具执行错误: {e}"
|
||||||
|
|
||||||
|
def list_tools(self):
|
||||||
|
"""列出所有工具"""
|
||||||
|
if not self.cli or not hasattr(self.cli, 'liugin_manager'):
|
||||||
|
return []
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
"name": t.get('name', ''),
|
||||||
|
"description": t.get('description', ''),
|
||||||
|
"keywords": t.get('keywords', []),
|
||||||
|
}
|
||||||
|
for t in self.cli.liugin_manager.tools
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
# ═══════════════════════════════════════════
|
||||||
|
# WebSocket 处理
|
||||||
|
# ═══════════════════════════════════════════
|
||||||
|
|
||||||
|
bridge = AIEngineBridge()
|
||||||
|
connected_clients = set()
|
||||||
|
|
||||||
|
|
||||||
|
async def ws_handler(websocket):
|
||||||
|
"""处理 WebSocket 连接"""
|
||||||
|
connected_clients.add(websocket)
|
||||||
|
client_addr = websocket.remote_address
|
||||||
|
print(f"✅ 客户端已连接: {client_addr}")
|
||||||
|
|
||||||
|
try:
|
||||||
|
# 发送初始状态
|
||||||
|
status = bridge.get_status()
|
||||||
|
await websocket.send(json.dumps({
|
||||||
|
"type": "status",
|
||||||
|
"data": status,
|
||||||
|
}, ensure_ascii=False))
|
||||||
|
|
||||||
|
async for raw_message in websocket:
|
||||||
|
try:
|
||||||
|
msg = json.loads(raw_message)
|
||||||
|
msg_type = msg.get("type", "")
|
||||||
|
msg_data = msg.get("data", {})
|
||||||
|
|
||||||
|
if msg_type == "chat":
|
||||||
|
# 用户聊天消息
|
||||||
|
user_msg = msg_data.get("message", "").strip()
|
||||||
|
if not user_msg:
|
||||||
|
continue
|
||||||
|
|
||||||
|
# 发送"正在思考"状态
|
||||||
|
await websocket.send(json.dumps({
|
||||||
|
"type": "thinking",
|
||||||
|
"data": {"message": user_msg},
|
||||||
|
}, ensure_ascii=False))
|
||||||
|
|
||||||
|
# 在线程中执行 AI 调用(避免阻塞事件循环)
|
||||||
|
loop = asyncio.get_event_loop()
|
||||||
|
result = await loop.run_in_executor(
|
||||||
|
None, bridge.chat, user_msg
|
||||||
|
)
|
||||||
|
|
||||||
|
# 处理返回结果
|
||||||
|
if isinstance(result, dict):
|
||||||
|
if result.get("type") == "multi":
|
||||||
|
# 多事件:逐个发送
|
||||||
|
for event in result.get("events", []):
|
||||||
|
await websocket.send(json.dumps({
|
||||||
|
"type": event.get("type", "reply"),
|
||||||
|
"data": event,
|
||||||
|
}, ensure_ascii=False))
|
||||||
|
else:
|
||||||
|
await websocket.send(json.dumps({
|
||||||
|
"type": result.get("type", "reply"),
|
||||||
|
"data": result,
|
||||||
|
}, ensure_ascii=False))
|
||||||
|
else:
|
||||||
|
# 兼容旧格式
|
||||||
|
await websocket.send(json.dumps({
|
||||||
|
"type": "reply",
|
||||||
|
"data": {"message": str(result)},
|
||||||
|
}, ensure_ascii=False))
|
||||||
|
|
||||||
|
elif msg_type == "tool":
|
||||||
|
# 直接工具调用
|
||||||
|
tool_name = msg_data.get("name", "")
|
||||||
|
tool_args = msg_data.get("args", "")
|
||||||
|
|
||||||
|
await websocket.send(json.dumps({
|
||||||
|
"type": "tool_executing",
|
||||||
|
"data": {"name": tool_name, "args": tool_args},
|
||||||
|
}, ensure_ascii=False))
|
||||||
|
|
||||||
|
loop = asyncio.get_event_loop()
|
||||||
|
result = await loop.run_in_executor(
|
||||||
|
None, bridge.execute_tool, tool_name, tool_args
|
||||||
|
)
|
||||||
|
|
||||||
|
await websocket.send(json.dumps({
|
||||||
|
"type": "tool_result",
|
||||||
|
"data": {"name": tool_name, "result": result},
|
||||||
|
}, ensure_ascii=False))
|
||||||
|
|
||||||
|
elif msg_type == "status":
|
||||||
|
# 请求状态更新
|
||||||
|
status = bridge.get_status()
|
||||||
|
await websocket.send(json.dumps({
|
||||||
|
"type": "status",
|
||||||
|
"data": status,
|
||||||
|
}, ensure_ascii=False))
|
||||||
|
|
||||||
|
elif msg_type == "tools":
|
||||||
|
# 请求工具列表
|
||||||
|
tools = bridge.list_tools()
|
||||||
|
await websocket.send(json.dumps({
|
||||||
|
"type": "tools",
|
||||||
|
"data": {"tools": tools},
|
||||||
|
}, ensure_ascii=False))
|
||||||
|
|
||||||
|
elif msg_type == "switch_engine":
|
||||||
|
# 切换引擎
|
||||||
|
engine_name = msg_data.get("engine", "")
|
||||||
|
if bridge.cli:
|
||||||
|
if engine_name in bridge.cli.engines:
|
||||||
|
bridge.cli.switch_engine(engine_name)
|
||||||
|
# 发送切换成功 + 更新后的状态
|
||||||
|
await websocket.send(json.dumps({
|
||||||
|
"type": "engine_switched",
|
||||||
|
"data": {"engine": engine_name},
|
||||||
|
}, ensure_ascii=False))
|
||||||
|
status = bridge.get_status()
|
||||||
|
await websocket.send(json.dumps({
|
||||||
|
"type": "status",
|
||||||
|
"data": status,
|
||||||
|
}, ensure_ascii=False))
|
||||||
|
else:
|
||||||
|
await websocket.send(json.dumps({
|
||||||
|
"type": "error",
|
||||||
|
"data": {"message": f"未找到引擎: {engine_name}"},
|
||||||
|
}, ensure_ascii=False))
|
||||||
|
|
||||||
|
elif msg_type == "switch_safety":
|
||||||
|
# 切换安全模式
|
||||||
|
mode = msg_data.get("mode", "")
|
||||||
|
if bridge.cli:
|
||||||
|
from xcli_core.safety import get_safety, MODE_NORMAL, MODE_MANUAL, MODE_UNRESTRICTED
|
||||||
|
safety = get_safety()
|
||||||
|
if mode == "normal":
|
||||||
|
safety.set_mode(MODE_NORMAL)
|
||||||
|
elif mode == "manual":
|
||||||
|
safety.set_mode(MODE_MANUAL)
|
||||||
|
elif mode == "unrestricted":
|
||||||
|
safety.set_mode(MODE_UNRESTRICTED)
|
||||||
|
await websocket.send(json.dumps({
|
||||||
|
"type": "safety_switched",
|
||||||
|
"data": {"mode": safety.get_mode_name()},
|
||||||
|
}, ensure_ascii=False))
|
||||||
|
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
await websocket.send(json.dumps({
|
||||||
|
"type": "error",
|
||||||
|
"data": {"message": "无效的 JSON 格式"},
|
||||||
|
}, ensure_ascii=False))
|
||||||
|
except Exception as e:
|
||||||
|
await websocket.send(json.dumps({
|
||||||
|
"type": "error",
|
||||||
|
"data": {"message": str(e)},
|
||||||
|
}, ensure_ascii=False))
|
||||||
|
|
||||||
|
except websockets.exceptions.ConnectionClosed:
|
||||||
|
pass
|
||||||
|
finally:
|
||||||
|
connected_clients.discard(websocket)
|
||||||
|
print(f"❌ 客户端已断开: {client_addr}")
|
||||||
|
|
||||||
|
|
||||||
|
# ═══════════════════════════════════════════
|
||||||
|
# 静态文件服务
|
||||||
|
# ═══════════════════════════════════════════
|
||||||
|
|
||||||
|
class WebUIHandler(SimpleHTTPRequestHandler):
|
||||||
|
"""自定义 HTTP 处理器"""
|
||||||
|
|
||||||
|
def __init__(self, *args, **kwargs):
|
||||||
|
super().__init__(*args, directory=PROJECT_DIR, **kwargs)
|
||||||
|
|
||||||
|
def do_GET(self):
|
||||||
|
# 根路径返回 webui.html
|
||||||
|
if self.path == '/' or self.path == '/index.html':
|
||||||
|
self.path = '/webui.html'
|
||||||
|
return super().do_GET()
|
||||||
|
|
||||||
|
def log_message(self, format, *args):
|
||||||
|
# 静默日志
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
# ═══════════════════════════════════════════
|
||||||
|
# 启动
|
||||||
|
# ═══════════════════════════════════════════
|
||||||
|
|
||||||
|
def main():
|
||||||
|
parser = argparse.ArgumentParser(description="小狸 Pro-CLI Web UI 服务器")
|
||||||
|
parser.add_argument("--host", default="0.0.0.0", help="绑定地址")
|
||||||
|
parser.add_argument("--port", type=int, default=8080, help="HTTP 端口")
|
||||||
|
parser.add_argument("--ws-port", type=int, default=8079, help="WebSocket 端口")
|
||||||
|
parser.add_argument("--no-ai", action="store_true", help="不初始化 AI 引擎(纯 UI 模式)")
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
print()
|
||||||
|
print("╔══════════════════════════════════════════╗")
|
||||||
|
print("║ 小狸 Pro-CLI · Web UI 服务器 ║")
|
||||||
|
print("╚══════════════════════════════════════════╝")
|
||||||
|
print()
|
||||||
|
|
||||||
|
# 初始化 AI 引擎
|
||||||
|
if not args.no_ai:
|
||||||
|
print("⏳ 正在初始化小狸核心...")
|
||||||
|
if bridge.initialize():
|
||||||
|
status = bridge.get_status()
|
||||||
|
print(f"✅ AI 引擎: {status['engine']}")
|
||||||
|
print(f"✅ 插件: {status['plugins']} 个")
|
||||||
|
print(f"✅ 安全模式: {status['safety_mode']}")
|
||||||
|
else:
|
||||||
|
print("⚠️ AI 引擎初始化失败,将以纯 UI 模式运行")
|
||||||
|
else:
|
||||||
|
print("ℹ️ 纯 UI 模式(不连接 AI 引擎)")
|
||||||
|
|
||||||
|
print()
|
||||||
|
print(f"🌐 HTTP: http://localhost:{args.port}")
|
||||||
|
print(f"🔌 WebSocket: ws://localhost:{args.ws_port}")
|
||||||
|
print(f"📂 项目目录: {PROJECT_DIR}")
|
||||||
|
print()
|
||||||
|
print("按 Ctrl+C 停止服务器")
|
||||||
|
print()
|
||||||
|
|
||||||
|
# 启动 HTTP 服务器(在单独线程中)
|
||||||
|
http_server = HTTPServer((args.host, args.port), WebUIHandler)
|
||||||
|
http_thread = threading.Thread(target=http_server.serve_forever, daemon=True)
|
||||||
|
http_thread.start()
|
||||||
|
|
||||||
|
# 启动 WebSocket 服务器
|
||||||
|
if WEBSOCKETS_AVAILABLE:
|
||||||
|
async def run_ws():
|
||||||
|
async with websockets.serve(ws_handler, args.host, args.ws_port):
|
||||||
|
await asyncio.Future() # 永远运行
|
||||||
|
|
||||||
|
try:
|
||||||
|
asyncio.run(run_ws())
|
||||||
|
except KeyboardInterrupt:
|
||||||
|
print("\n🛑 服务器已停止")
|
||||||
|
else:
|
||||||
|
print("⚠️ WebSocket 不可用,仅启动 HTTP 服务")
|
||||||
|
try:
|
||||||
|
while True:
|
||||||
|
time.sleep(1)
|
||||||
|
except KeyboardInterrupt:
|
||||||
|
print("\n🛑 服务器已停止")
|
||||||
|
|
||||||
|
http_server.shutdown()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
# 示例工作流 - 代码质量检查与构建
|
||||||
|
name: code-quality
|
||||||
|
description: 代码质量检查、测试、构建的自动化流程
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: info
|
||||||
|
type: echo
|
||||||
|
message: "🚀 开始代码质量检查流程"
|
||||||
|
|
||||||
|
- name: lint
|
||||||
|
type: shell
|
||||||
|
command: "echo '✓ 代码风格检查通过'"
|
||||||
|
continue_on_error: true
|
||||||
|
|
||||||
|
- name: test
|
||||||
|
type: shell
|
||||||
|
command: "echo '✓ 单元测试通过 (42/42)'"
|
||||||
|
continue_on_error: true
|
||||||
|
|
||||||
|
- name: check_results
|
||||||
|
type: echo
|
||||||
|
message: "Lint: {{lint.output}} | Test: {{test.output}}"
|
||||||
|
|
||||||
|
- name: build
|
||||||
|
type: shell
|
||||||
|
command: "echo '✓ 构建完成 → dist/'"
|
||||||
|
if: "{{lint.exit_code}} == 0"
|
||||||
|
|
||||||
|
- name: done
|
||||||
|
type: echo
|
||||||
|
message: "✅ 流程完成,构建产物: {{build.output}}"
|
||||||
+13
-1
@@ -355,7 +355,19 @@ class BaseAICLI:
|
|||||||
engine.max_history = self.max_history
|
engine.max_history = self.max_history
|
||||||
|
|
||||||
def handle_engine_command(self, command):
|
def handle_engine_command(self, command):
|
||||||
"""处理引擎特定命令"""
|
"""处理引擎特定命令(支持跨引擎调用,如 /engine.manual status)"""
|
||||||
|
# 先检查是否指定了引擎名(如 "manual status" → 引擎=manual, 命令=status)
|
||||||
|
parts = command.split(' ', 1)
|
||||||
|
target_name = parts[0]
|
||||||
|
rest = parts[1] if len(parts) > 1 else ""
|
||||||
|
|
||||||
|
# 如果目标名是某个已加载的引擎,直接调用该引擎
|
||||||
|
if target_name in self.engines:
|
||||||
|
target_engine = self.engines[target_name]
|
||||||
|
if hasattr(target_engine, 'handle_command'):
|
||||||
|
return target_engine.handle_command(rest)
|
||||||
|
|
||||||
|
# 否则当作当前引擎的命令
|
||||||
if not hasattr(self.current_engine, 'handle_command'):
|
if not hasattr(self.current_engine, 'handle_command'):
|
||||||
return False
|
return False
|
||||||
engine_name = getattr(self.current_engine, 'name', '')
|
engine_name = getattr(self.current_engine, 'name', '')
|
||||||
|
|||||||
+69
-4
@@ -18,10 +18,11 @@ from .cli_tools import ToolMixin
|
|||||||
from .cli_code_exec import CodeExecMixin
|
from .cli_code_exec import CodeExecMixin
|
||||||
from .cli_display import DisplayMixin
|
from .cli_display import DisplayMixin
|
||||||
from .cli_history import HistoryMixin
|
from .cli_history import HistoryMixin
|
||||||
|
from .plugin_market import PluginMarketMixin
|
||||||
from .notification import notify_task_complete, get_notification_manager
|
from .notification import notify_task_complete, get_notification_manager
|
||||||
|
|
||||||
|
|
||||||
class AICLI(BaseAICLI, ClawliMixin, ToolMixin, CodeExecMixin, DisplayMixin, HistoryMixin):
|
class AICLI(BaseAICLI, ClawliMixin, ToolMixin, CodeExecMixin, DisplayMixin, HistoryMixin, PluginMarketMixin):
|
||||||
"""AI CLI主程序 - 组合所有 Mixin"""
|
"""AI CLI主程序 - 组合所有 Mixin"""
|
||||||
|
|
||||||
# ── 深度思考处理 ──
|
# ── 深度思考处理 ──
|
||||||
@@ -174,9 +175,10 @@ class AICLI(BaseAICLI, ClawliMixin, ToolMixin, CodeExecMixin, DisplayMixin, Hist
|
|||||||
- 如果语法检查失败,根据错误信息修复代码后再次编辑
|
- 如果语法检查失败,根据错误信息修复代码后再次编辑
|
||||||
|
|
||||||
【Diff 弹窗 — 自动弹出修改对比】
|
【Diff 弹窗 — 自动弹出修改对比】
|
||||||
- 编辑操作完成后自动弹出新终端窗口,显示修改前后的完整内容和行号对比
|
- 编辑操作完成后自动显示修改前后的完整内容和行号对比
|
||||||
- 包含 diff 差异、新增/删除行数统计
|
- 新增行用绿色标记,删除行用红色标记
|
||||||
- 开关: diff_popup on(开启)/ diff_popup off(关闭)/ diff_popup(切换)
|
- 支持两种模式: 弹窗模式(新终端窗口)/ 主终端内显示(SSH 兼容)
|
||||||
|
- 开关: diff_popup on / diff_popup off / diff_popup popup / diff_popup inline
|
||||||
- 默认开启,无需手动调用
|
- 默认开启,无需手动调用
|
||||||
|
|
||||||
【code_editor 编辑格式】
|
【code_editor 编辑格式】
|
||||||
@@ -1017,14 +1019,54 @@ multi 操作支持一次修改多处:
|
|||||||
print(f"{Fore.GREEN}输入 '/chat list' 查看所有已保存的聊天记录{Style.RESET_ALL}")
|
print(f"{Fore.GREEN}输入 '/chat list' 查看所有已保存的聊天记录{Style.RESET_ALL}")
|
||||||
print(f"{Fore.GREEN}输入 '/chat open <名称>' 加载聊天记录{Style.RESET_ALL}")
|
print(f"{Fore.GREEN}输入 '/chat open <名称>' 加载聊天记录{Style.RESET_ALL}")
|
||||||
print(f"{Fore.GREEN}输入 '/remote' 查看远程连接帮助{Style.RESET_ALL}")
|
print(f"{Fore.GREEN}输入 '/remote' 查看远程连接帮助{Style.RESET_ALL}")
|
||||||
|
print(f"{Fore.GREEN}输入 '/plugin' 管理插件市场 (安装/卸载/搜索){Style.RESET_ALL}")
|
||||||
current_engine_name = getattr(self.current_engine, 'name', '未设置') if self.current_engine else '未设置'
|
current_engine_name = getattr(self.current_engine, 'name', '未设置') if self.current_engine else '未设置'
|
||||||
print(f"{Fore.GREEN}当前使用的AI引擎: {current_engine_name}{Style.RESET_ALL}")
|
print(f"{Fore.GREEN}当前使用的AI引擎: {current_engine_name}{Style.RESET_ALL}")
|
||||||
loaded_engines = list(self.engines.keys())
|
loaded_engines = list(self.engines.keys())
|
||||||
if len(loaded_engines) > 1:
|
if len(loaded_engines) > 1:
|
||||||
print(f"{Fore.GREEN}已加载的AI引擎: {', '.join(loaded_engines)}{Style.RESET_ALL}")
|
print(f"{Fore.GREEN}已加载的AI引擎: {', '.join(loaded_engines)}{Style.RESET_ALL}")
|
||||||
print(f"{Fore.GREEN}{'-' * 50}{Style.RESET_ALL}")
|
print(f"{Fore.GREEN}{'-' * 50}{Style.RESET_ALL}")
|
||||||
|
|
||||||
|
# 询问 diff 弹窗模式
|
||||||
|
self._ask_diff_popup_mode()
|
||||||
|
|
||||||
self._run_cli_loop()
|
self._run_cli_loop()
|
||||||
|
|
||||||
|
def _ask_diff_popup_mode(self):
|
||||||
|
"""启动时询问 diff 显示模式"""
|
||||||
|
# 找到 code_editor 插件
|
||||||
|
code_editor = None
|
||||||
|
for tool in self.liugin_manager.tools:
|
||||||
|
if tool.get('name') == 'code_editor':
|
||||||
|
code_editor = tool.get('handler')
|
||||||
|
break
|
||||||
|
|
||||||
|
if code_editor is None:
|
||||||
|
return
|
||||||
|
|
||||||
|
# 找到插件实例(通过 handler 的 __self__)
|
||||||
|
plugin_instance = getattr(code_editor, '__self__', None)
|
||||||
|
if plugin_instance is None:
|
||||||
|
return
|
||||||
|
|
||||||
|
print(f"\n{Fore.CYAN} Diff 显示模式(AI 修改文件后的对比方式):{Style.RESET_ALL}")
|
||||||
|
print(f" {Fore.WHITE}1{Style.RESET_ALL} - 弹窗模式(新终端窗口显示)")
|
||||||
|
print(f" {Fore.WHITE}2{Style.RESET_ALL} - 主终端内显示(SSH 兼容,推荐)")
|
||||||
|
|
||||||
|
try:
|
||||||
|
choice = input(f"\n{Fore.WHITE} 请选择 [1/2](默认 2): {Style.RESET_ALL}").strip()
|
||||||
|
except (EOFError, KeyboardInterrupt):
|
||||||
|
choice = '2'
|
||||||
|
|
||||||
|
if choice == '1':
|
||||||
|
plugin_instance.diff_popup_mode = True
|
||||||
|
print(f"{Fore.GREEN} ✓ 已选择: 弹窗模式{Style.RESET_ALL}")
|
||||||
|
else:
|
||||||
|
plugin_instance.diff_popup_mode = False
|
||||||
|
print(f"{Fore.GREEN} ✓ 已选择: 主终端内显示{Style.RESET_ALL}")
|
||||||
|
|
||||||
|
print()
|
||||||
|
|
||||||
def _run_cli_loop(self):
|
def _run_cli_loop(self):
|
||||||
"""运行 CLI 主循环"""
|
"""运行 CLI 主循环"""
|
||||||
while True:
|
while True:
|
||||||
@@ -1062,6 +1104,22 @@ multi 操作支持一次修改多处:
|
|||||||
print(f"{Fore.RED}当前引擎不支持该命令或命令执行失败{Style.RESET_ALL}")
|
print(f"{Fore.RED}当前引擎不支持该命令或命令执行失败{Style.RESET_ALL}")
|
||||||
continue
|
continue
|
||||||
|
|
||||||
|
# /manual 快捷命令 — 切换到 manual 引擎或执行 manual 子命令
|
||||||
|
if user_input == '/manual' or user_input.startswith('/manual '):
|
||||||
|
args = user_input[8:].strip() if user_input.startswith('/manual ') else ''
|
||||||
|
if 'manual' not in self.engines:
|
||||||
|
print(f"{Fore.RED}manual 引擎未加载{Style.RESET_ALL}")
|
||||||
|
elif not args:
|
||||||
|
# 无参数:切换到 manual 引擎
|
||||||
|
self.switch_engine('manual')
|
||||||
|
print(f"{Fore.GREEN}已切换到 manual 引擎{Style.RESET_ALL}")
|
||||||
|
else:
|
||||||
|
# 有参数:执行 manual 引擎命令(如 status, restart)
|
||||||
|
result = self.engines['manual'].handle_command(args)
|
||||||
|
if result:
|
||||||
|
print(f"{Fore.GREEN}{result}{Style.RESET_ALL}")
|
||||||
|
continue
|
||||||
|
|
||||||
if user_input.startswith('/file.read '):
|
if user_input.startswith('/file.read '):
|
||||||
args = user_input[11:].strip()
|
args = user_input[11:].strip()
|
||||||
parts = args.split(' ', 2)
|
parts = args.split(' ', 2)
|
||||||
@@ -1106,6 +1164,13 @@ multi 操作支持一次修改多处:
|
|||||||
print(f"{Fore.RED}未知的聊天命令.可用命令: save, list, open{Style.RESET_ALL}")
|
print(f"{Fore.RED}未知的聊天命令.可用命令: save, list, open{Style.RESET_ALL}")
|
||||||
continue
|
continue
|
||||||
|
|
||||||
|
if user_input.startswith('/plugin'):
|
||||||
|
plugin_args = user_input[7:].strip()
|
||||||
|
result = self.handle_plugin_command(plugin_args)
|
||||||
|
if result:
|
||||||
|
print(result)
|
||||||
|
continue
|
||||||
|
|
||||||
if user_input.startswith('/remote'):
|
if user_input.startswith('/remote'):
|
||||||
remote_command = user_input[7:].strip()
|
remote_command = user_input[7:].strip()
|
||||||
self._handle_remote_command(remote_command)
|
self._handle_remote_command(remote_command)
|
||||||
|
|||||||
@@ -102,7 +102,7 @@ except ImportError:
|
|||||||
try:
|
try:
|
||||||
from textual.app import App, ComposeResult
|
from textual.app import App, ComposeResult
|
||||||
from textual.containers import Container, Horizontal, Vertical, VerticalScroll
|
from textual.containers import Container, Horizontal, Vertical, VerticalScroll
|
||||||
from textual.widgets import Header, Footer, Input, RichLog, Static, Button, Tree
|
from textual.widgets import Header, Footer, Input, RichLog, Static, Button, Tree, TextArea, Rule
|
||||||
from textual.widgets.tree import TreeNode
|
from textual.widgets.tree import TreeNode
|
||||||
from textual.binding import Binding
|
from textual.binding import Binding
|
||||||
from textual.events import Mount
|
from textual.events import Mount
|
||||||
|
|||||||
@@ -130,3 +130,7 @@ class LiuginManager:
|
|||||||
if tool.get('name', '').lower() == tool_name.lower():
|
if tool.get('name', '').lower() == tool_name.lower():
|
||||||
return tool
|
return tool
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
def get_tool_info_only(self, tool_name):
|
||||||
|
"""根据名称获取工具信息(不含 handler,用于搜索已卸载插件)"""
|
||||||
|
return self.get_tool_by_name(tool_name)
|
||||||
@@ -0,0 +1,652 @@
|
|||||||
|
"""
|
||||||
|
插件市场 Mixin — 提供 /plugin 命令
|
||||||
|
支持: install, remove, list, search, info
|
||||||
|
"""
|
||||||
|
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import json
|
||||||
|
import base64
|
||||||
|
import importlib.util
|
||||||
|
from colorama import Fore, Style
|
||||||
|
|
||||||
|
try:
|
||||||
|
from urllib.request import urlopen, Request
|
||||||
|
HAS_URLLIB = True
|
||||||
|
except ImportError:
|
||||||
|
HAS_URLLIB = False
|
||||||
|
|
||||||
|
|
||||||
|
class PluginMarketMixin:
|
||||||
|
"""插件市场功能"""
|
||||||
|
|
||||||
|
def _get_project_dir(self):
|
||||||
|
return os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||||
|
|
||||||
|
def _get_plugins_dir(self):
|
||||||
|
return os.path.join(self._get_project_dir(), "plugins")
|
||||||
|
|
||||||
|
def _get_registry_path(self):
|
||||||
|
return os.path.join(self._get_project_dir(), "plugin_registry.json")
|
||||||
|
|
||||||
|
def _get_config_path(self):
|
||||||
|
return os.path.join(self._get_project_dir(), "plugins_config.py")
|
||||||
|
|
||||||
|
# ── 注册表操作 ──
|
||||||
|
|
||||||
|
def _load_registry(self):
|
||||||
|
"""加载本地注册表"""
|
||||||
|
path = self._get_registry_path()
|
||||||
|
if not os.path.exists(path):
|
||||||
|
return {"version": 1, "plugins": {}}
|
||||||
|
try:
|
||||||
|
with open(path, 'r', encoding='utf-8') as f:
|
||||||
|
return json.load(f)
|
||||||
|
except Exception as e:
|
||||||
|
print(f"{Fore.YELLOW}⚠ 读取注册表失败: {e},使用空注册表{Style.RESET_ALL}")
|
||||||
|
return {"version": 1, "plugins": {}}
|
||||||
|
|
||||||
|
def _save_registry(self, registry):
|
||||||
|
"""保存注册表"""
|
||||||
|
path = self._get_registry_path()
|
||||||
|
try:
|
||||||
|
with open(path, 'w', encoding='utf-8') as f:
|
||||||
|
json.dump(registry, f, ensure_ascii=False, indent=2)
|
||||||
|
except Exception as e:
|
||||||
|
print(f"{Fore.RED}❌ 保存注册表失败: {e}{Style.RESET_ALL}")
|
||||||
|
|
||||||
|
def _fetch_remote_registry(self):
|
||||||
|
"""拉取远程注册表并合并"""
|
||||||
|
remote_urls = [
|
||||||
|
"https://gitee.com/shuiyu1123/xiaoli-cli-plugins/raw/master/plugin_registry.json",
|
||||||
|
]
|
||||||
|
registry = self._load_registry()
|
||||||
|
merged_count = 0
|
||||||
|
|
||||||
|
for url in remote_urls:
|
||||||
|
try:
|
||||||
|
data = None
|
||||||
|
# 尝试直接获取
|
||||||
|
try:
|
||||||
|
req = Request(url, headers={"User-Agent": "xiaoli-cli/1.0"})
|
||||||
|
resp = urlopen(req, timeout=10)
|
||||||
|
data = resp.read()
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
# Gitee raw 失败,尝试 API
|
||||||
|
if data is None and "gitee.com" in url and "/raw/" in url:
|
||||||
|
try:
|
||||||
|
parts = url.split("gitee.com/")[1]
|
||||||
|
repo_path = parts.split("/raw/")[0]
|
||||||
|
rest = parts.split("/raw/", 1)[1]
|
||||||
|
rest_parts = rest.split("/", 1)
|
||||||
|
branch = rest_parts[0]
|
||||||
|
file_path = rest_parts[1] if len(rest_parts) > 1 else rest
|
||||||
|
api_url = f"https://gitee.com/api/v5/repos/{repo_path}/contents/{file_path}?ref={branch}"
|
||||||
|
token = os.environ.get("GITEE_TOKEN", "")
|
||||||
|
if token:
|
||||||
|
api_url += f"&access_token={token}"
|
||||||
|
req = Request(api_url, headers={"User-Agent": "xiaoli-cli/1.0"})
|
||||||
|
resp = urlopen(req, timeout=10)
|
||||||
|
json_data = json.loads(resp.read())
|
||||||
|
if "content" in json_data:
|
||||||
|
import base64
|
||||||
|
data = base64.b64decode(json_data["content"])
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
if data is None:
|
||||||
|
continue
|
||||||
|
|
||||||
|
remote = json.loads(data.decode('utf-8'))
|
||||||
|
remote_plugins = remote.get("plugins", {})
|
||||||
|
for code, info in remote_plugins.items():
|
||||||
|
if code not in registry.get("plugins", {}):
|
||||||
|
registry.setdefault("plugins", {})[code] = info
|
||||||
|
merged_count += 1
|
||||||
|
break # 成功就不再尝试其他源
|
||||||
|
except Exception:
|
||||||
|
continue
|
||||||
|
|
||||||
|
if merged_count > 0:
|
||||||
|
self._save_registry(registry)
|
||||||
|
print(f"{Style.DIM} (从远程同步了 {merged_count} 个插件){Style.RESET_ALL}")
|
||||||
|
|
||||||
|
return registry
|
||||||
|
|
||||||
|
# ── 配置文件操作 ──
|
||||||
|
|
||||||
|
def _enable_plugin_in_config(self, plugin_name):
|
||||||
|
"""在 plugins_config.py 中启用插件"""
|
||||||
|
config_path = self._get_config_path()
|
||||||
|
enable_key = f"ENABLE_{plugin_name.upper()}"
|
||||||
|
|
||||||
|
if not os.path.exists(config_path):
|
||||||
|
with open(config_path, 'w', encoding='utf-8') as f:
|
||||||
|
f.write(f"# 小狸插件配置\n\n{enable_key} = True\n")
|
||||||
|
return True
|
||||||
|
|
||||||
|
with open(config_path, 'r', encoding='utf-8') as f:
|
||||||
|
content = f.read()
|
||||||
|
|
||||||
|
# 检查是否已存在
|
||||||
|
if enable_key in content:
|
||||||
|
# 替换为 True
|
||||||
|
lines = content.split('\n')
|
||||||
|
new_lines = []
|
||||||
|
for line in lines:
|
||||||
|
if line.strip().startswith(enable_key):
|
||||||
|
new_lines.append(f"{enable_key} = True")
|
||||||
|
else:
|
||||||
|
new_lines.append(line)
|
||||||
|
with open(config_path, 'w', encoding='utf-8') as f:
|
||||||
|
f.write('\n'.join(new_lines))
|
||||||
|
else:
|
||||||
|
# 追加
|
||||||
|
with open(config_path, 'a', encoding='utf-8') as f:
|
||||||
|
f.write(f"\n{enable_key} = True\n")
|
||||||
|
|
||||||
|
return True
|
||||||
|
|
||||||
|
def _disable_plugin_in_config(self, plugin_name):
|
||||||
|
"""在 plugins_config.py 中禁用插件"""
|
||||||
|
config_path = self._get_config_path()
|
||||||
|
enable_key = f"ENABLE_{plugin_name.upper()}"
|
||||||
|
|
||||||
|
if not os.path.exists(config_path):
|
||||||
|
return False
|
||||||
|
|
||||||
|
with open(config_path, 'r', encoding='utf-8') as f:
|
||||||
|
content = f.read()
|
||||||
|
|
||||||
|
if enable_key not in content:
|
||||||
|
return False
|
||||||
|
|
||||||
|
lines = content.split('\n')
|
||||||
|
new_lines = []
|
||||||
|
for line in lines:
|
||||||
|
if line.strip().startswith(enable_key):
|
||||||
|
new_lines.append(f"{enable_key} = False")
|
||||||
|
else:
|
||||||
|
new_lines.append(line)
|
||||||
|
with open(config_path, 'w', encoding='utf-8') as f:
|
||||||
|
f.write('\n'.join(new_lines))
|
||||||
|
return True
|
||||||
|
|
||||||
|
# ── 下载安装 ──
|
||||||
|
|
||||||
|
def _download_file(self, url, dest_path):
|
||||||
|
"""下载文件到指定路径,支持 Gitee/GitHub raw 和 API"""
|
||||||
|
if not HAS_URLLIB:
|
||||||
|
return False, "缺少 urllib 模块"
|
||||||
|
|
||||||
|
import base64
|
||||||
|
|
||||||
|
# 尝试的 URL 列表(按优先级)
|
||||||
|
urls_to_try = [url]
|
||||||
|
|
||||||
|
# Gitee raw URL → 转为 API
|
||||||
|
if "gitee.com" in url and "/raw/" in url:
|
||||||
|
try:
|
||||||
|
parts = url.split("gitee.com/")[1]
|
||||||
|
repo_path = parts.split("/raw/")[0]
|
||||||
|
rest = parts.split("/raw/", 1)[1]
|
||||||
|
# rest = "master/dglab_ws/dglab_ws.py" → 分离 branch 和 path
|
||||||
|
rest_parts = rest.split("/", 1)
|
||||||
|
branch = rest_parts[0]
|
||||||
|
file_path = rest_parts[1] if len(rest_parts) > 1 else rest
|
||||||
|
api_url = f"https://gitee.com/api/v5/repos/{repo_path}/contents/{file_path}?ref={branch}"
|
||||||
|
token = os.environ.get("GITEE_TOKEN", "")
|
||||||
|
if token:
|
||||||
|
api_url += f"&access_token={token}"
|
||||||
|
urls_to_try.insert(0, api_url)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
# GitHub raw URL → 转为 API
|
||||||
|
if "github.com" in url and "/raw/" in url:
|
||||||
|
try:
|
||||||
|
parts = url.split("github.com/")[1]
|
||||||
|
repo_path = parts.split("/raw/")[0]
|
||||||
|
file_path = parts.split("/raw/", 1)[1]
|
||||||
|
api_url = f"https://api.github.com/repos/{repo_path}/contents/{file_path}"
|
||||||
|
urls_to_try.insert(0, api_url)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
last_err = ""
|
||||||
|
for try_url in urls_to_try:
|
||||||
|
try:
|
||||||
|
req = Request(try_url, headers={"User-Agent": "xiaoli-cli/1.0"})
|
||||||
|
resp = urlopen(req, timeout=30)
|
||||||
|
data = resp.read()
|
||||||
|
|
||||||
|
# 检查是否是 JSON(API 响应)
|
||||||
|
try:
|
||||||
|
json_data = json.loads(data)
|
||||||
|
if isinstance(json_data, dict) and "content" in json_data:
|
||||||
|
data = base64.b64decode(json_data["content"])
|
||||||
|
except (json.JSONDecodeError, ValueError):
|
||||||
|
pass # 不是 JSON,直接用原始数据
|
||||||
|
|
||||||
|
with open(dest_path, 'wb') as f:
|
||||||
|
f.write(data)
|
||||||
|
return True, f"下载完成 ({len(data)} 字节)"
|
||||||
|
except Exception as e:
|
||||||
|
last_err = str(e)
|
||||||
|
continue
|
||||||
|
|
||||||
|
return False, last_err
|
||||||
|
|
||||||
|
def _install_deps(self, deps, optional=False):
|
||||||
|
"""提示安装依赖(不自动安装,遵守安全规则)"""
|
||||||
|
if not deps:
|
||||||
|
return
|
||||||
|
label = "可选依赖" if optional else "依赖"
|
||||||
|
print(f"{Fore.YELLOW} 📦 {label}:{', '.join(deps)}{Style.RESET_ALL}")
|
||||||
|
print(f"{Style.DIM} 运行: pip install {' '.join(deps)}{Style.RESET_ALL}")
|
||||||
|
|
||||||
|
# ── /plugin 命令入口 ──
|
||||||
|
|
||||||
|
def handle_plugin_command(self, args):
|
||||||
|
"""处理 /plugin 命令"""
|
||||||
|
args = args.strip()
|
||||||
|
if not args:
|
||||||
|
return self._plugin_help()
|
||||||
|
|
||||||
|
parts = args.split(maxsplit=1)
|
||||||
|
sub = parts[0].lower()
|
||||||
|
rest = parts[1] if len(parts) > 1 else ""
|
||||||
|
|
||||||
|
if sub == "install":
|
||||||
|
return self._plugin_install(rest.strip())
|
||||||
|
elif sub in ("remove", "uninstall"):
|
||||||
|
return self._plugin_remove(rest.strip())
|
||||||
|
elif sub == "list":
|
||||||
|
return self._plugin_list()
|
||||||
|
elif sub == "search":
|
||||||
|
return self._plugin_search(rest.strip())
|
||||||
|
elif sub == "info":
|
||||||
|
return self._plugin_info(rest.strip())
|
||||||
|
elif sub == "update":
|
||||||
|
return self._plugin_update(rest.strip())
|
||||||
|
elif sub == "add-source":
|
||||||
|
return self._plugin_add_source(rest.strip())
|
||||||
|
else:
|
||||||
|
return f"{Fore.RED}❌ 未知子命令: {sub}\n{self._plugin_help()}"
|
||||||
|
|
||||||
|
def _plugin_help(self):
|
||||||
|
"""插件市场帮助"""
|
||||||
|
return f"""{Fore.CYAN}🔌 插件市场{Style.RESET_ALL}
|
||||||
|
|
||||||
|
{Fore.WHITE}命令:{Style.RESET_ALL}
|
||||||
|
/plugin list 列出所有可用插件
|
||||||
|
/plugin search <关键词> 搜索插件
|
||||||
|
/plugin info <插件码> 查看插件详情
|
||||||
|
/plugin install <插件码> 安装插件
|
||||||
|
/plugin install <URL> 从 URL 安装插件
|
||||||
|
/plugin remove <插件名> 卸载插件
|
||||||
|
/plugin update <插件码> 更新已安装的插件
|
||||||
|
/plugin add-source <URL> 添加远程插件源
|
||||||
|
|
||||||
|
{Fore.WHITE}示例:{Style.RESET_ALL}
|
||||||
|
/plugin list 查看可用插件
|
||||||
|
/plugin install dglab 安装 DG-Lab 插件
|
||||||
|
/plugin search 郊狼 搜索相关插件
|
||||||
|
/plugin remove dglab_ws 卸载插件"""
|
||||||
|
|
||||||
|
def _plugin_list(self):
|
||||||
|
"""列出所有可用插件"""
|
||||||
|
registry = self._fetch_remote_registry()
|
||||||
|
plugins = registry.get("plugins", {})
|
||||||
|
|
||||||
|
if not plugins:
|
||||||
|
return f"{Fore.YELLOW}📭 插件注册表为空,运行 /plugin install <URL> 从 URL 安装{Style.RESET_ALL}"
|
||||||
|
|
||||||
|
# 检查已安装状态
|
||||||
|
plugins_dir = self._get_plugins_dir()
|
||||||
|
installed = set()
|
||||||
|
if os.path.exists(plugins_dir):
|
||||||
|
for f in os.listdir(plugins_dir):
|
||||||
|
if f.endswith('.py') and f != '__init__.py':
|
||||||
|
installed.add(f[:-3])
|
||||||
|
|
||||||
|
lines = [f"{Fore.CYAN}🔌 可用插件列表:{Style.RESET_ALL}\n"]
|
||||||
|
for code, info in sorted(plugins.items()):
|
||||||
|
name = info.get("name", code)
|
||||||
|
desc = info.get("description", "")
|
||||||
|
version = info.get("version", "")
|
||||||
|
target_file = info.get("file", f"{code}.py")
|
||||||
|
target_name = target_file[:-3] if target_file.endswith('.py') else target_file
|
||||||
|
|
||||||
|
if target_name in installed:
|
||||||
|
status = f"{Fore.GREEN}✓ 已安装{Style.RESET_ALL}"
|
||||||
|
else:
|
||||||
|
status = f"{Style.DIM}○ 未安装{Style.RESET_ALL}"
|
||||||
|
|
||||||
|
lines.append(f" {Fore.WHITE}{code:<15}{Style.RESET_ALL} {status} {name}")
|
||||||
|
if desc:
|
||||||
|
lines.append(f" {Style.DIM}{'':15} {desc[:50]}{Style.RESET_ALL}")
|
||||||
|
if version:
|
||||||
|
lines.append(f" {Style.DIM}{'':15} v{version}{Style.RESET_ALL}")
|
||||||
|
|
||||||
|
lines.append(f"\n{Style.DIM}使用 /plugin install <插件码> 安装{Style.RESET_ALL}")
|
||||||
|
return "\n".join(lines)
|
||||||
|
|
||||||
|
def _plugin_search(self, keyword):
|
||||||
|
"""搜索插件"""
|
||||||
|
if not keyword:
|
||||||
|
return f"{Fore.YELLOW}请提供搜索关键词: /plugin search <关键词>{Style.RESET_ALL}"
|
||||||
|
|
||||||
|
registry = self._fetch_remote_registry()
|
||||||
|
plugins = registry.get("plugins", {})
|
||||||
|
keyword_lower = keyword.lower()
|
||||||
|
|
||||||
|
matches = []
|
||||||
|
for code, info in plugins.items():
|
||||||
|
score = 0
|
||||||
|
name = info.get("name", "").lower()
|
||||||
|
desc = info.get("description", "").lower()
|
||||||
|
keywords = [k.lower() for k in info.get("keywords", [])]
|
||||||
|
|
||||||
|
if keyword_lower in code.lower():
|
||||||
|
score += 100
|
||||||
|
if keyword_lower in name:
|
||||||
|
score += 50
|
||||||
|
if keyword_lower in desc:
|
||||||
|
score += 30
|
||||||
|
for kw in keywords:
|
||||||
|
if keyword_lower in kw:
|
||||||
|
score += 20
|
||||||
|
|
||||||
|
if score > 0:
|
||||||
|
matches.append((score, code, info))
|
||||||
|
|
||||||
|
matches.sort(key=lambda x: x[0], reverse=True)
|
||||||
|
|
||||||
|
if not matches:
|
||||||
|
return f"{Fore.YELLOW}🔍 未找到与 '{keyword}' 相关的插件{Style.RESET_ALL}"
|
||||||
|
|
||||||
|
lines = [f"{Fore.CYAN}🔍 搜索 '{keyword}' 的结果:{Style.RESET_ALL}\n"]
|
||||||
|
for _, code, info in matches:
|
||||||
|
name = info.get("name", code)
|
||||||
|
desc = info.get("description", "")
|
||||||
|
lines.append(f" {Fore.WHITE}{code:<15}{Style.RESET_ALL} {name}")
|
||||||
|
if desc:
|
||||||
|
lines.append(f" {Style.DIM}{'':15} {desc[:60]}{Style.RESET_ALL}")
|
||||||
|
|
||||||
|
return "\n".join(lines)
|
||||||
|
|
||||||
|
def _plugin_info(self, code):
|
||||||
|
"""查看插件详情"""
|
||||||
|
if not code:
|
||||||
|
return f"{Fore.YELLOW}请提供插件码: /plugin info <插件码>{Style.RESET_ALL}"
|
||||||
|
|
||||||
|
registry = self._fetch_remote_registry()
|
||||||
|
plugins = registry.get("plugins", {})
|
||||||
|
|
||||||
|
if code not in plugins:
|
||||||
|
return f"{Fore.RED}❌ 未找到插件 '{code}',运行 /plugin list 查看可用插件{Style.RESET_ALL}"
|
||||||
|
|
||||||
|
info = plugins[code]
|
||||||
|
name = info.get("name", code)
|
||||||
|
desc = info.get("description", "")
|
||||||
|
author = info.get("author", "未知")
|
||||||
|
version = info.get("version", "未知")
|
||||||
|
deps = info.get("deps", [])
|
||||||
|
opt_deps = info.get("optional_deps", [])
|
||||||
|
url = info.get("url", "")
|
||||||
|
docs = info.get("docs", "")
|
||||||
|
keywords = info.get("keywords", [])
|
||||||
|
|
||||||
|
lines = [
|
||||||
|
f"{Fore.CYAN}📦 插件详情: {code}{Style.RESET_ALL}\n",
|
||||||
|
f" 名称: {name}",
|
||||||
|
f" 版本: {version}",
|
||||||
|
f" 作者: {author}",
|
||||||
|
]
|
||||||
|
if desc:
|
||||||
|
lines.append(f" 描述: {desc}")
|
||||||
|
if keywords:
|
||||||
|
lines.append(f" 关键词: {', '.join(keywords)}")
|
||||||
|
if deps:
|
||||||
|
lines.append(f" 依赖: {', '.join(deps)}")
|
||||||
|
if opt_deps:
|
||||||
|
lines.append(f" 可选依赖: {', '.join(opt_deps)}")
|
||||||
|
if url:
|
||||||
|
lines.append(f" 下载地址: {url}")
|
||||||
|
if docs:
|
||||||
|
lines.append(f" 文档: {docs}")
|
||||||
|
|
||||||
|
lines.append(f"\n {Fore.GREEN}/plugin install {code}{Style.RESET_ALL} 安装此插件")
|
||||||
|
return "\n".join(lines)
|
||||||
|
|
||||||
|
def _plugin_install(self, code):
|
||||||
|
"""安装插件"""
|
||||||
|
if not code:
|
||||||
|
return f"{Fore.YELLOW}请提供插件码或 URL: /plugin install <插件码|URL>{Style.RESET_ALL}"
|
||||||
|
|
||||||
|
plugins_dir = self._get_plugins_dir()
|
||||||
|
os.makedirs(plugins_dir, exist_ok=True)
|
||||||
|
|
||||||
|
# 判断是 URL 还是插件码
|
||||||
|
if code.startswith("http://") or code.startswith("https://"):
|
||||||
|
return self._install_from_url(code)
|
||||||
|
|
||||||
|
# 从注册表查找
|
||||||
|
registry = self._fetch_remote_registry()
|
||||||
|
plugins = registry.get("plugins", {})
|
||||||
|
|
||||||
|
if code not in plugins:
|
||||||
|
return (
|
||||||
|
f"{Fore.RED}❌ 未找到插件 '{code}'\n"
|
||||||
|
f"{Fore.YELLOW}运行 /plugin list 查看可用插件\n"
|
||||||
|
f"或使用 /plugin install <URL> 从 URL 安装{Style.RESET_ALL}"
|
||||||
|
)
|
||||||
|
|
||||||
|
info = plugins[code]
|
||||||
|
name = info.get("name", code)
|
||||||
|
url = info.get("url", "")
|
||||||
|
target_file = info.get("file", f"{code}.py")
|
||||||
|
deps = info.get("deps", [])
|
||||||
|
opt_deps = info.get("optional_deps", [])
|
||||||
|
|
||||||
|
if not url:
|
||||||
|
return f"{Fore.RED}❌ 插件 '{code}' 没有下载地址{Style.RESET_ALL}"
|
||||||
|
|
||||||
|
dest = os.path.join(plugins_dir, target_file)
|
||||||
|
|
||||||
|
# 检查是否已安装
|
||||||
|
if os.path.exists(dest):
|
||||||
|
print(f"{Fore.YELLOW}⚠ 插件 '{name}' 已存在,将覆盖更新{Style.RESET_ALL}")
|
||||||
|
|
||||||
|
print(f"{Fore.CYAN}📥 正在安装: {name}{Style.RESET_ALL}")
|
||||||
|
print(f"{Style.DIM} 下载: {url}{Style.RESET_ALL}")
|
||||||
|
|
||||||
|
ok, msg = self._download_file(url, dest)
|
||||||
|
if not ok:
|
||||||
|
return f"{Fore.RED}❌ 下载失败: {msg}{Style.RESET_ALL}"
|
||||||
|
|
||||||
|
print(f"{Fore.GREEN} ✓ 文件已保存到: {dest}{Style.RESET_ALL}")
|
||||||
|
|
||||||
|
# 下载文档
|
||||||
|
docs_url = info.get("docs", "")
|
||||||
|
if docs_url:
|
||||||
|
docs_dest = os.path.join(plugins_dir, target_file.replace('.py', '_README.md'))
|
||||||
|
ok_docs, _ = self._download_file(docs_url, docs_dest)
|
||||||
|
if ok_docs:
|
||||||
|
print(f"{Fore.GREEN} ✓ 文档已保存到: {docs_dest}{Style.RESET_ALL}")
|
||||||
|
|
||||||
|
# 启用插件
|
||||||
|
plugin_module_name = target_file[:-3] if target_file.endswith('.py') else target_file
|
||||||
|
self._enable_plugin_in_config(plugin_module_name)
|
||||||
|
print(f"{Fore.GREEN} ✓ 已在配置中启用: ENABLE_{plugin_module_name.upper()} = True{Style.RESET_ALL}")
|
||||||
|
|
||||||
|
# 提示依赖
|
||||||
|
self._install_deps(deps, optional=False)
|
||||||
|
self._install_deps(opt_deps, optional=True)
|
||||||
|
|
||||||
|
# 尝试动态加载
|
||||||
|
print(f"{Fore.CYAN} 🔄 尝试动态加载插件...{Style.RESET_ALL}")
|
||||||
|
try:
|
||||||
|
spec = importlib.util.spec_from_file_location(plugin_module_name, dest)
|
||||||
|
module = importlib.util.module_from_spec(spec)
|
||||||
|
spec.loader.exec_module(module)
|
||||||
|
plugin_class = getattr(module, 'Liugin', None) or getattr(module, 'Plugin', None)
|
||||||
|
if plugin_class:
|
||||||
|
instance = plugin_class()
|
||||||
|
tool_info = instance.get_tool_info()
|
||||||
|
tool_info['handler'] = instance.handle
|
||||||
|
if hasattr(instance, 'set_cli'):
|
||||||
|
instance.set_cli(self)
|
||||||
|
self.liugin_manager.tools.append(tool_info)
|
||||||
|
print(f"{Fore.GREEN} ✓ 插件已加载: {tool_info.get('name', plugin_module_name)}{Style.RESET_ALL}")
|
||||||
|
else:
|
||||||
|
print(f"{Fore.YELLOW} ⚠ 未找到 Liugin/Plugin 类,重启后自动加载{Style.RESET_ALL}")
|
||||||
|
except Exception as e:
|
||||||
|
print(f"{Fore.YELLOW} ⚠ 动态加载失败: {e},重启后自动加载{Style.RESET_ALL}")
|
||||||
|
|
||||||
|
return f"\n{Fore.GREEN}🎉 插件 '{name}' 安装完成!{Style.RESET_ALL}"
|
||||||
|
|
||||||
|
def _install_from_url(self, url):
|
||||||
|
"""从 URL 直接安装"""
|
||||||
|
plugins_dir = self._get_plugins_dir()
|
||||||
|
os.makedirs(plugins_dir, exist_ok=True)
|
||||||
|
|
||||||
|
# 从 URL 提取文件名
|
||||||
|
filename = url.split('/')[-1].split('?')[0]
|
||||||
|
if not filename.endswith('.py'):
|
||||||
|
return f"{Fore.RED}❌ URL 必须指向 .py 文件{Style.RESET_ALL}"
|
||||||
|
|
||||||
|
dest = os.path.join(plugins_dir, filename)
|
||||||
|
|
||||||
|
print(f"{Fore.CYAN}📥 正在从 URL 安装: {url}{Style.RESET_ALL}")
|
||||||
|
|
||||||
|
ok, msg = self._download_file(url, dest)
|
||||||
|
if not ok:
|
||||||
|
return f"{Fore.RED}❌ 下载失败: {msg}{Style.RESET_ALL}"
|
||||||
|
|
||||||
|
plugin_name = filename[:-3]
|
||||||
|
self._enable_plugin_in_config(plugin_name)
|
||||||
|
print(f"{Fore.GREEN} ✓ 已保存到: {dest}{Style.RESET_ALL}")
|
||||||
|
print(f"{Fore.GREEN} ✓ 已启用: ENABLE_{plugin_name.upper()}{Style.RESET_ALL}")
|
||||||
|
|
||||||
|
# 尝试动态加载
|
||||||
|
try:
|
||||||
|
spec = importlib.util.spec_from_file_location(plugin_name, dest)
|
||||||
|
module = importlib.util.module_from_spec(spec)
|
||||||
|
spec.loader.exec_module(module)
|
||||||
|
plugin_class = getattr(module, 'Liugin', None) or getattr(module, 'Plugin', None)
|
||||||
|
if plugin_class:
|
||||||
|
instance = plugin_class()
|
||||||
|
tool_info = instance.get_tool_info()
|
||||||
|
tool_info['handler'] = instance.handle
|
||||||
|
if hasattr(instance, 'set_cli'):
|
||||||
|
instance.set_cli(self)
|
||||||
|
self.liugin_manager.tools.append(tool_info)
|
||||||
|
print(f"{Fore.GREEN} ✓ 插件已加载: {tool_info.get('name', plugin_name)}{Style.RESET_ALL}")
|
||||||
|
except Exception as e:
|
||||||
|
print(f"{Fore.YELLOW} ⚠ 动态加载失败: {e},重启后自动加载{Style.RESET_ALL}")
|
||||||
|
|
||||||
|
return f"\n{Fore.GREEN}🎉 插件安装完成!{Style.RESET_ALL}"
|
||||||
|
|
||||||
|
def _plugin_remove(self, name):
|
||||||
|
"""卸载插件"""
|
||||||
|
if not name:
|
||||||
|
return f"{Fore.YELLOW}请提供插件名: /plugin remove <插件名>{Style.RESET_ALL}"
|
||||||
|
|
||||||
|
plugins_dir = self._get_plugins_dir()
|
||||||
|
|
||||||
|
# 查找插件文件
|
||||||
|
target = None
|
||||||
|
for f in os.listdir(plugins_dir):
|
||||||
|
if f.endswith('.py') and f != '__init__.py':
|
||||||
|
module_name = f[:-3]
|
||||||
|
if module_name == name or f == name:
|
||||||
|
target = os.path.join(plugins_dir, f)
|
||||||
|
break
|
||||||
|
|
||||||
|
if not target:
|
||||||
|
return f"{Fore.RED}❌ 未找到已安装的插件 '{name}'{Style.RESET_ALL}"
|
||||||
|
|
||||||
|
module_name = os.path.basename(target)[:-3]
|
||||||
|
|
||||||
|
# 删除文件
|
||||||
|
try:
|
||||||
|
os.remove(target)
|
||||||
|
print(f"{Fore.GREEN} ✓ 已删除: {target}{Style.RESET_ALL}")
|
||||||
|
except Exception as e:
|
||||||
|
return f"{Fore.RED}❌ 删除失败: {e}{Style.RESET_ALL}"
|
||||||
|
|
||||||
|
# 删除关联文档
|
||||||
|
docs_file = target.replace('.py', '_README.md')
|
||||||
|
if os.path.exists(docs_file):
|
||||||
|
os.remove(docs_file)
|
||||||
|
|
||||||
|
# 禁用插件
|
||||||
|
self._disable_plugin_in_config(module_name)
|
||||||
|
print(f"{Fore.GREEN} ✓ 已禁用: ENABLE_{module_name.upper()} = False{Style.RESET_ALL}")
|
||||||
|
|
||||||
|
# 从内存中移除
|
||||||
|
self.liugin_manager.tools = [
|
||||||
|
t for t in self.liugin_manager.tools
|
||||||
|
if t.get('name') != module_name
|
||||||
|
]
|
||||||
|
|
||||||
|
return f"\n{Fore.GREEN}🗑️ 插件 '{name}' 已卸载{Style.RESET_ALL}"
|
||||||
|
|
||||||
|
def _plugin_update(self, code):
|
||||||
|
"""更新插件(重新下载)"""
|
||||||
|
if not code:
|
||||||
|
return f"{Fore.YELLOW}请提供插件码: /plugin update <插件码>{Style.RESET_ALL}"
|
||||||
|
|
||||||
|
registry = self._load_registry()
|
||||||
|
plugins = registry.get("plugins", {})
|
||||||
|
|
||||||
|
if code not in plugins:
|
||||||
|
return f"{Fore.RED}❌ 注册表中未找到 '{code}',无法更新{Style.RESET_ALL}"
|
||||||
|
|
||||||
|
# 检查是否已安装
|
||||||
|
info = plugins[code]
|
||||||
|
target_file = info.get("file", f"{code}.py")
|
||||||
|
dest = os.path.join(self._get_plugins_dir(), target_file)
|
||||||
|
|
||||||
|
if not os.path.exists(dest):
|
||||||
|
return f"{Fore.YELLOW}⚠ 插件 '{code}' 未安装,使用 /plugin install {code} 安装{Style.RESET_ALL}"
|
||||||
|
|
||||||
|
print(f"{Fore.CYAN}🔄 更新插件: {code}{Style.RESET_ALL}")
|
||||||
|
return self._plugin_install(code)
|
||||||
|
|
||||||
|
def _plugin_add_source(self, url):
|
||||||
|
"""添加远程插件源"""
|
||||||
|
if not url:
|
||||||
|
return f"{Fore.YELLOW}请提供注册表 URL: /plugin add-source <URL>{Style.RESET_ALL}"
|
||||||
|
|
||||||
|
print(f"{Fore.CYAN}📡 正在同步插件源: {url}{Style.RESET_ALL}")
|
||||||
|
|
||||||
|
try:
|
||||||
|
req = Request(url, headers={"User-Agent": "xiaoli-cli/1.0"})
|
||||||
|
resp = urlopen(req, timeout=15)
|
||||||
|
remote = json.loads(resp.read().decode('utf-8'))
|
||||||
|
except Exception as e:
|
||||||
|
return f"{Fore.RED}❌ 拉取失败: {e}{Style.RESET_ALL}"
|
||||||
|
|
||||||
|
registry = self._load_registry()
|
||||||
|
remote_plugins = remote.get("plugins", {})
|
||||||
|
added = 0
|
||||||
|
updated = 0
|
||||||
|
|
||||||
|
for code, info in remote_plugins.items():
|
||||||
|
if code in registry.get("plugins", {}):
|
||||||
|
registry["plugins"][code] = info
|
||||||
|
updated += 1
|
||||||
|
else:
|
||||||
|
registry.setdefault("plugins", {})[code] = info
|
||||||
|
added += 1
|
||||||
|
|
||||||
|
self._save_registry(registry)
|
||||||
|
|
||||||
|
return (
|
||||||
|
f"{Fore.GREEN}✓ 插件源同步完成: 新增 {added} 个,更新 {updated} 个{Style.RESET_ALL}"
|
||||||
|
)
|
||||||
+48
-42
@@ -62,8 +62,7 @@ if TEXTUAL_AVAILABLE:
|
|||||||
scrollbar-color: {_Theme.BORDER};
|
scrollbar-color: {_Theme.BORDER};
|
||||||
scrollbar-color-hover: {_Theme.TEXT_MUTED};
|
scrollbar-color-hover: {_Theme.TEXT_MUTED};
|
||||||
padding: 0 1;
|
padding: 0 1;
|
||||||
/* 平滑滚动 */
|
|
||||||
scroll-behavior: smooth;
|
|
||||||
}}
|
}}
|
||||||
|
|
||||||
/* ── 输入区域 ── */
|
/* ── 输入区域 ── */
|
||||||
@@ -144,10 +143,11 @@ if TEXTUAL_AVAILABLE:
|
|||||||
}}
|
}}
|
||||||
|
|
||||||
#sidebar.hidden {{
|
#sidebar.hidden {{
|
||||||
display: none;
|
|
||||||
width: 0;
|
width: 0;
|
||||||
min-width: 0;
|
min-width: 0;
|
||||||
opacity: 0;
|
opacity: 0;
|
||||||
|
border: none;
|
||||||
|
overflow: hidden;
|
||||||
}}
|
}}
|
||||||
|
|
||||||
.sidebar-header {{
|
.sidebar-header {{
|
||||||
@@ -297,28 +297,6 @@ if TEXTUAL_AVAILABLE:
|
|||||||
background: {_Theme.BG};
|
background: {_Theme.BG};
|
||||||
}}
|
}}
|
||||||
|
|
||||||
/* ── 闪光动画 keyframes ── */
|
|
||||||
@keyframes pulse-glow {{
|
|
||||||
0% {{ color: {_Theme.THINKING}; }}
|
|
||||||
50% {{ color: {_Theme.ACCENT}; }}
|
|
||||||
100% {{ color: {_Theme.THINKING}; }}
|
|
||||||
}}
|
|
||||||
|
|
||||||
@keyframes fade-in {{
|
|
||||||
from {{ opacity: 0; }}
|
|
||||||
to {{ opacity: 1; }}
|
|
||||||
}}
|
|
||||||
|
|
||||||
@keyframes slide-in-right {{
|
|
||||||
from {{ offset-x: 100%; }}
|
|
||||||
to {{ offset-x: 0; }}
|
|
||||||
}}
|
|
||||||
|
|
||||||
@keyframes bounce-in {{
|
|
||||||
0% {{ opacity: 0; offset-y: 5%; }}
|
|
||||||
60% {{ opacity: 1; offset-y: -1%; }}
|
|
||||||
100% {{ opacity: 1; offset-y: 0; }}
|
|
||||||
}}
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
class _TUIBridge:
|
class _TUIBridge:
|
||||||
@@ -502,7 +480,7 @@ if TEXTUAL_AVAILABLE:
|
|||||||
"",
|
"",
|
||||||
" ╔══════════════════════════════════════════════╗",
|
" ╔══════════════════════════════════════════════╗",
|
||||||
" ║ ║",
|
" ║ ║",
|
||||||
" ║ 小狸 Pro-CLI v5.1 ║",
|
" ║ 小狸 Pro-CLI v5.2 ║",
|
||||||
" ║ 智能编程助手 · 动画增强版 ║",
|
" ║ 智能编程助手 · 动画增强版 ║",
|
||||||
" ║ ║",
|
" ║ ║",
|
||||||
" ╚══════════════════════════════════════════════╝",
|
" ╚══════════════════════════════════════════════╝",
|
||||||
@@ -531,12 +509,12 @@ if TEXTUAL_AVAILABLE:
|
|||||||
|
|
||||||
widget = Static(line, classes=cls)
|
widget = Static(line, classes=cls)
|
||||||
scroll.mount(widget)
|
scroll.mount(widget)
|
||||||
# 延迟显示每一行
|
# 延迟显示每一行(避免 delay=0 导致 Textual 除零错误)
|
||||||
delay = i * 0.1
|
delay = max(0.01, i * 0.1)
|
||||||
self.set_timer(delay, lambda w=widget: w.add_class("visible"))
|
self.set_timer(delay, lambda w=widget: w.add_class("visible"))
|
||||||
|
|
||||||
# 最后滚动到底部
|
# 最后滚动到底部
|
||||||
self.set_timer(len(welcome_lines) * 0.1 + 0.1,
|
self.set_timer(max(0.01, len(welcome_lines) * 0.1 + 0.1),
|
||||||
lambda: scroll.scroll_end(animate=True, duration=0.3))
|
lambda: scroll.scroll_end(animate=True, duration=0.3))
|
||||||
|
|
||||||
def _render_welcome(self):
|
def _render_welcome(self):
|
||||||
@@ -546,7 +524,7 @@ if TEXTUAL_AVAILABLE:
|
|||||||
("", "msg-dim"),
|
("", "msg-dim"),
|
||||||
(" ╔══════════════════════════════════════════════╗", "msg-welcome"),
|
(" ╔══════════════════════════════════════════════╗", "msg-welcome"),
|
||||||
(" ║ ║", "msg-welcome"),
|
(" ║ ║", "msg-welcome"),
|
||||||
(" ║ 小狸 Pro-CLI v5.1 ║", "msg-welcome"),
|
(" ║ 小狸 Pro-CLI v5.2 ║", "msg-welcome"),
|
||||||
(" ║ 智能编程助手 · 动画增强版 ║", "msg-welcome"),
|
(" ║ 智能编程助手 · 动画增强版 ║", "msg-welcome"),
|
||||||
(" ║ ║", "msg-welcome"),
|
(" ║ ║", "msg-welcome"),
|
||||||
(" ╚══════════════════════════════════════════════╝", "msg-welcome"),
|
(" ╚══════════════════════════════════════════════╝", "msg-welcome"),
|
||||||
@@ -584,6 +562,10 @@ if TEXTUAL_AVAILABLE:
|
|||||||
status_container.mount(Static(f" 工具: {len(self.bridge.tools())} 个", classes="tool-item"))
|
status_container.mount(Static(f" 工具: {len(self.bridge.tools())} 个", classes="tool-item"))
|
||||||
status_container.mount(Static(f" 引擎: {len(self.bridge.engines())} 个", classes="tool-item"))
|
status_container.mount(Static(f" 引擎: {len(self.bridge.engines())} 个", classes="tool-item"))
|
||||||
|
|
||||||
|
# 工具数
|
||||||
|
if hasattr(self.cli, 'liugin_manager'):
|
||||||
|
status_container.mount(Static(f" 工具: {len(self.cli.liugin_manager.tools)} 个", classes="tool-item"))
|
||||||
|
|
||||||
def _update_status(self, text: str):
|
def _update_status(self, text: str):
|
||||||
bar = self.query_one("#status-bar")
|
bar = self.query_one("#status-bar")
|
||||||
engine = self.bridge.current_engine()
|
engine = self.bridge.current_engine()
|
||||||
@@ -737,11 +719,12 @@ if TEXTUAL_AVAILABLE:
|
|||||||
'cls': lambda: self.action_clear(),
|
'cls': lambda: self.action_clear(),
|
||||||
'model': lambda: self._switch_model(args),
|
'model': lambda: self._switch_model(args),
|
||||||
'engine': lambda: self._switch_model(args),
|
'engine': lambda: self._switch_model(args),
|
||||||
'about': lambda: self._system(" 小狸 Pro-CLI v5.1 - 智能编程助手"),
|
'about': lambda: self._system(" 小狸 Pro-CLI v5.2 - 智能编程助手"),
|
||||||
'status': lambda: self._show_status(),
|
'status': lambda: self._show_status(),
|
||||||
'tools': lambda: self._show_tools(),
|
'tools': lambda: self._show_tools(),
|
||||||
'engines': lambda: self._show_engines(),
|
'engines': lambda: self._show_engines(),
|
||||||
'tui': lambda: self._system("已在 TUI 模式中"),
|
'tui': lambda: self._system("已在 TUI 模式中"),
|
||||||
|
'manual': lambda: self._handle_manual(args),
|
||||||
}
|
}
|
||||||
|
|
||||||
handler = cmds.get(name)
|
handler = cmds.get(name)
|
||||||
@@ -776,6 +759,24 @@ if TEXTUAL_AVAILABLE:
|
|||||||
Enter 换行 Tab 缩进"""
|
Enter 换行 Tab 缩进"""
|
||||||
self._system(help_text)
|
self._system(help_text)
|
||||||
|
|
||||||
|
def _handle_manual(self, args):
|
||||||
|
"""处理 /manual 命令"""
|
||||||
|
if 'manual' not in self.cli.engines:
|
||||||
|
self._error("manual 引擎未加载")
|
||||||
|
return
|
||||||
|
if not args:
|
||||||
|
# 切换到 manual 引擎
|
||||||
|
if self.bridge.switch_engine('manual'):
|
||||||
|
self._system("已切换到 manual 引擎")
|
||||||
|
self._update_sidebar()
|
||||||
|
else:
|
||||||
|
self._error("切换失败")
|
||||||
|
else:
|
||||||
|
# 执行 manual 引擎子命令
|
||||||
|
result = self.cli.engines['manual'].handle_command(args)
|
||||||
|
if result:
|
||||||
|
self._system(result)
|
||||||
|
|
||||||
def _switch_cli(self):
|
def _switch_cli(self):
|
||||||
self._system("切换到命令行模式...")
|
self._system("切换到命令行模式...")
|
||||||
self.cli.tui_output_callback = None
|
self.cli.tui_output_callback = None
|
||||||
@@ -810,11 +811,15 @@ if TEXTUAL_AVAILABLE:
|
|||||||
self._system('\n'.join(lines))
|
self._system('\n'.join(lines))
|
||||||
|
|
||||||
def _show_status(self):
|
def _show_status(self):
|
||||||
self._system(f""" 系统状态:
|
status_lines = [
|
||||||
引擎: {self.bridge.current_engine()}
|
f" 系统状态:",
|
||||||
引擎数: {len(self.bridge.engines())}
|
f" 引擎: {self.bridge.current_engine()}",
|
||||||
工具数: {len(self.bridge.tools())}
|
f" 引擎数: {len(self.bridge.engines())}",
|
||||||
对话数: {len(self.bridge.history())}""")
|
f" 工具数: {len(self.bridge.tools())}",
|
||||||
|
f" 对话数: {len(self.bridge.history())}",
|
||||||
|
]
|
||||||
|
|
||||||
|
self._system('\n'.join(status_lines))
|
||||||
|
|
||||||
# ── AI 生成 ──
|
# ── AI 生成 ──
|
||||||
|
|
||||||
@@ -849,11 +854,11 @@ if TEXTUAL_AVAILABLE:
|
|||||||
self.call_after_refresh(self._update_sidebar)
|
self.call_after_refresh(self._update_sidebar)
|
||||||
|
|
||||||
def _write_raw(self, msg):
|
def _write_raw(self, msg):
|
||||||
if '' in msg or 'OK 工具' in msg:
|
if '✅' in msg or 'OK 工具' in msg:
|
||||||
self._add(f" {msg}", "msg-tool-ok")
|
self._add(f" {msg}", "msg-tool-ok")
|
||||||
elif '' in msg or 'X 工具' in msg or '错误' in msg:
|
elif '❌' in msg or 'X 工具' in msg or '错误' in msg:
|
||||||
self._add(f" {msg}", "msg-tool-err")
|
self._add(f" {msg}", "msg-tool-err")
|
||||||
elif '' in msg:
|
elif '🤖' in msg:
|
||||||
self._add(f" {msg}", "msg-ai")
|
self._add(f" {msg}", "msg-ai")
|
||||||
elif '工具' in msg and ('调用' in msg or '执行' in msg):
|
elif '工具' in msg and ('调用' in msg or '执行' in msg):
|
||||||
self._add(f" {msg}", "msg-tool-ok")
|
self._add(f" {msg}", "msg-tool-ok")
|
||||||
@@ -874,12 +879,13 @@ if TEXTUAL_AVAILABLE:
|
|||||||
|
|
||||||
def action_toggle_sidebar(self):
|
def action_toggle_sidebar(self):
|
||||||
sidebar = self.query_one("#sidebar")
|
sidebar = self.query_one("#sidebar")
|
||||||
sidebar.visible = not sidebar.visible
|
# 通过 CSS 类控制侧栏显隐
|
||||||
# 动画:侧栏切换时平滑过渡
|
if sidebar.has_class("hidden"):
|
||||||
if sidebar.visible:
|
|
||||||
sidebar.remove_class("hidden")
|
sidebar.remove_class("hidden")
|
||||||
|
self.sidebar_visible = True
|
||||||
else:
|
else:
|
||||||
sidebar.add_class("hidden")
|
sidebar.add_class("hidden")
|
||||||
|
self.sidebar_visible = False
|
||||||
|
|
||||||
def action_cancel(self):
|
def action_cancel(self):
|
||||||
if self.is_generating:
|
if self.is_generating:
|
||||||
|
|||||||
Binary file not shown.
Reference in new issue
Block a user