Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
79957eba0f | ||
|
|
b8faaae0c6 | ||
|
|
bac5ea01a9 | ||
|
|
161ab9d3a8 |
No files matched your search
@@ -47,3 +47,6 @@ screenshots/gen_*.png
|
||||
# 临时文件
|
||||
*.tmp
|
||||
*.bak
|
||||
|
||||
# v8.0 TUI 快照产物(运行时生成,供 AI 自验/预览)
|
||||
.tui_snapshots/
|
||||
+1
-1
@@ -5,7 +5,7 @@
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<img src="https://img.shields.io/badge/version-5.4.0-blue" alt="version">
|
||||
<img src="https://img.shields.io/badge/version-5.4.1-blue" alt="version">
|
||||
<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/tests-113%20passed-brightgreen" alt="tests">
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<img src="https://img.shields.io/badge/version-5.4.0-blue" alt="version">
|
||||
<img src="https://img.shields.io/badge/version-8.0.0-blue" alt="version">
|
||||
<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/tests-150+%20passed-brightgreen" alt="tests">
|
||||
@@ -22,6 +22,12 @@
|
||||
|
||||
小狸 Pro-CLI 是一款基于 Python 的智能编程助手,集成了代码编辑、版本控制、浏览器自动化、图像生成、记忆系统等功能,支持多种 AI 引擎,帮助开发者提升工作效率。
|
||||
|
||||
## v8.0 新特性
|
||||
|
||||
- **Rich 面板式 TUI(默认)** — `rich` 驱动的可视化对话面板;自带**快照出口**(导出 text/svg/html),AI 开发界面时可把渲染结果读回自验,补上"看不见渲染"的反馈闭环。输入 `/tui` 进入,`/snapshot` 随时导出当前界面。
|
||||
- **Token 感知压缩** — 自动读取 OpenAI 格式返回的 `usage.prompt_tokens`,当 `已用 token / 模型上下文窗口 ≥ 0.7`(可在 `config.json` 设 `system.compress_ratio` / `system.context_window` 覆盖)即触发上下文压缩,消息数阈值作为兜底,避免超窗截断。
|
||||
- **记忆模式** — 持久化 `MEMORY.md` + 每日日记 + 自动保存聊天记录 + 关键词检索;新增 `/memory mode <companion|work>` 切换与 `/compress` 手动压缩。
|
||||
|
||||
## 特性
|
||||
|
||||
- **双 AI 引擎** — Ollama 本地模型 + OpenAI 兼容格式(DeepSeek、Grok、硅基流动等)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
**产品标识**
|
||||
- **产品名称**:小狸智能体 增强-终端(Xiaoli Pro-CLI)
|
||||
- **内部版本号**:20260428
|
||||
- **发布版本**:发行版5.1.3
|
||||
- **内部版本号**:20260801
|
||||
- **发布版本**:发行版8.0.0
|
||||
|
||||
**技术规格**
|
||||
- **主要语言**:简体中文(UTF-8)
|
||||
|
||||
@@ -13,6 +13,31 @@ import logging
|
||||
# 设置日志
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
try:
|
||||
from xcli_core.config import get_system_config
|
||||
except Exception:
|
||||
def get_system_config(key, default=None):
|
||||
return default
|
||||
|
||||
# ── 常见模型的上下文窗口(token 数)──
|
||||
# OpenAI /chat/completions 协议本身不返回模型窗口,需本地维护。
|
||||
MODEL_CONTEXT_WINDOWS = {
|
||||
"gpt-4o": 128000, "gpt-4o-mini": 128000, "gpt-4": 8192, "gpt-4-turbo": 128000,
|
||||
"gpt-3.5-turbo": 16385,
|
||||
"deepseek-chat": 64000, "deepseek-reasoner": 64000,
|
||||
"qwen2.5": 32768, "qwen2": 32768, "qwen-max": 32768, "qwen-plus": 32768,
|
||||
"llama3": 8192, "llama3.1": 128000, "llama3.2": 128000, "llama2": 4096,
|
||||
"claude-3": 200000, "claude-3.5": 200000, "claude-3.7": 200000, "claude": 200000,
|
||||
"grok": 131072, "grok-2": 131072, "grok-3": 131072,
|
||||
"glm-4": 128000, "glm-4v": 128000,
|
||||
"mistral": 32768, "mixtral": 32768, "mistral-large": 128000,
|
||||
"gemini": 1000000, "gemini-1.5": 1000000, "gemini-2.0": 1000000, "gemini-2.5": 1000000,
|
||||
"yi": 200000, "yi-large": 200000,
|
||||
"kimi": 200000, "moonshot": 200000,
|
||||
"abab": 200000, "minimax": 200000,
|
||||
"baichuan": 192000, "chatglm": 32768,
|
||||
}
|
||||
|
||||
# 添加项目根目录到sys.path
|
||||
current_dir = os.path.dirname(os.path.abspath(__file__))
|
||||
project_root = os.path.dirname(current_dir)
|
||||
@@ -95,6 +120,9 @@ OpenAI 兼容格式引擎帮助信息
|
||||
self.conversation_history = []
|
||||
self.shared_conversation_history = None
|
||||
|
||||
# 最近一次请求的 token 用量(供 token 感知压缩使用)
|
||||
self.last_prompt_tokens = None
|
||||
|
||||
# 思考标记(兼容深度思考模型)
|
||||
self.thinking_start_marker = "<think>"
|
||||
self.thinking_end_marker = "</think>"
|
||||
@@ -169,6 +197,13 @@ OpenAI 兼容格式引擎帮助信息
|
||||
|
||||
if response.status_code == 200:
|
||||
response_data = response.json()
|
||||
# ── 记录 token 用量(供 token 感知压缩)──
|
||||
usage = response_data.get("usage", {})
|
||||
if isinstance(usage, dict) and usage.get("prompt_tokens"):
|
||||
try:
|
||||
self.last_prompt_tokens = int(usage["prompt_tokens"])
|
||||
except (TypeError, ValueError):
|
||||
self.last_prompt_tokens = None
|
||||
if "choices" in response_data and len(response_data["choices"]) > 0:
|
||||
message = response_data["choices"][0].get("message", {})
|
||||
|
||||
@@ -342,6 +377,24 @@ OpenAI 兼容格式引擎帮助信息
|
||||
self.model = model_name
|
||||
print(f"{Fore.GREEN}已切换模型为: {model_name}{Style.RESET_ALL}")
|
||||
|
||||
def context_window(self):
|
||||
"""
|
||||
返回当前模型的上下文窗口(token 数)。
|
||||
优先级: config.system.context_window > 模型名查表 > 默认 128000。
|
||||
注: OpenAI /chat/completions 协议本身不返回模型窗口,需本地维护。
|
||||
"""
|
||||
cfg = get_system_config("context_window", None)
|
||||
if cfg:
|
||||
try:
|
||||
return int(cfg)
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
model = (self.model or "").lower()
|
||||
for key, win in MODEL_CONTEXT_WINDOWS.items():
|
||||
if key and key in model:
|
||||
return win
|
||||
return 128000
|
||||
|
||||
def list_models(self):
|
||||
"""列出可用模型(调用 API 的 /models 端点)"""
|
||||
if not self.base_url:
|
||||
|
||||
+147
@@ -0,0 +1,147 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
小狸 MCP Stdio Server
|
||||
=====================
|
||||
标准 MCP (Model Context Protocol) stdio 传输层入口。
|
||||
通过 stdin/stdout 以 JSON-RPC 2.0 格式通信,
|
||||
可被 Claude Desktop、Cursor、OpenClaw 等标准 MCP 客户端直接连接。
|
||||
|
||||
用法:
|
||||
python mcp_server.py [--plugins-dir plugins] [--skills-dir skills]
|
||||
|
||||
Claude Desktop 配置示例:
|
||||
{
|
||||
"mcpServers": {
|
||||
"xiaoli": {
|
||||
"command": "python",
|
||||
"args": ["/path/to/xiaoli-cli/mcp_server.py"]
|
||||
}
|
||||
}
|
||||
}
|
||||
"""
|
||||
|
||||
import sys
|
||||
import os
|
||||
import json
|
||||
import argparse
|
||||
import logging
|
||||
|
||||
# 确保当前目录在 sys.path 中,以便导入项目模块
|
||||
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
|
||||
if SCRIPT_DIR not in sys.path:
|
||||
sys.path.insert(0, SCRIPT_DIR)
|
||||
|
||||
# 日志输出到 stderr,不干扰 stdout 上的 JSON-RPC 通信
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="[xiaoli-mcp] %(message)s",
|
||||
stream=sys.stderr,
|
||||
)
|
||||
logger = logging.getLogger("xiaoli-mcp")
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="小狸 MCP Stdio Server")
|
||||
parser.add_argument("--plugins-dir", default="plugins", help="插件目录 (默认: plugins)")
|
||||
parser.add_argument("--skills-dir", default="skills", help="技能目录 (默认: skills)")
|
||||
args = parser.parse_args()
|
||||
|
||||
# 切换到脚本所在目录,保证相对路径正确
|
||||
os.chdir(SCRIPT_DIR)
|
||||
|
||||
# 初始化 UnifiedToolManager
|
||||
# 将 initialize() 中的 print 重定向到 stderr,避免污染 stdout JSON-RPC 通道
|
||||
import io
|
||||
from contextlib import redirect_stdout
|
||||
|
||||
from unified_tool_manager import UnifiedToolManager
|
||||
|
||||
manager = UnifiedToolManager()
|
||||
captured_output = io.StringIO()
|
||||
with redirect_stdout(captured_output):
|
||||
manager.initialize(
|
||||
plugins_dir=args.plugins_dir,
|
||||
skills_dir=args.skills_dir,
|
||||
)
|
||||
|
||||
# 将初始化时的 print 输出转发到 stderr
|
||||
init_output = captured_output.getvalue()
|
||||
if init_output:
|
||||
for line in init_output.strip().split('\n'):
|
||||
logger.info(line)
|
||||
|
||||
tool_count = len(manager._tools)
|
||||
logger.info(f"MCP Server 已启动,共加载 {tool_count} 个工具")
|
||||
logger.info("等待 stdin JSON-RPC 请求...")
|
||||
|
||||
# 主循环:从 stdin 逐行读取 JSON-RPC 请求
|
||||
try:
|
||||
for line in sys.stdin:
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
|
||||
try:
|
||||
request = json.loads(line)
|
||||
except json.JSONDecodeError as e:
|
||||
# 无法解析的 JSON,返回解析错误
|
||||
error_resp = {
|
||||
"jsonrpc": "2.0",
|
||||
"id": None,
|
||||
"error": {"code": -32700, "message": f"Parse error: {e}"},
|
||||
}
|
||||
_send(error_resp)
|
||||
continue
|
||||
|
||||
# 处理通知(没有 id 字段的请求)— MCP 规范中通知不需要响应
|
||||
req_id = request.get("id")
|
||||
method = request.get("method", "")
|
||||
|
||||
# 特殊处理 notifications/initialized — 客户端初始化完成通知
|
||||
if method == "notifications/initialized":
|
||||
logger.info("客户端已发送 initialized 通知")
|
||||
continue
|
||||
|
||||
# 特殊处理 $/cancelRequest
|
||||
if method == "$/cancelRequest":
|
||||
logger.info(f"收到取消请求: {request.get('params', {}).get('id')}")
|
||||
continue
|
||||
|
||||
# 委托给 UnifiedToolManager 处理
|
||||
# 拦截插件可能产生的 stdout 输出,转发到 stderr
|
||||
captured = io.StringIO()
|
||||
try:
|
||||
with redirect_stdout(captured):
|
||||
response = manager.handle_mcp_request(request)
|
||||
plugin_output = captured.getvalue()
|
||||
if plugin_output:
|
||||
for p_line in plugin_output.strip().split('\n'):
|
||||
logger.info(f"[plugin] {p_line}")
|
||||
except Exception as e:
|
||||
logger.error(f"处理请求异常: {e}")
|
||||
response = {
|
||||
"jsonrpc": "2.0",
|
||||
"id": req_id,
|
||||
"error": {"code": -32603, "message": f"Internal error: {e}"},
|
||||
}
|
||||
|
||||
_send(response)
|
||||
|
||||
except KeyboardInterrupt:
|
||||
logger.info("收到中断信号,正在关闭...")
|
||||
except EOFError:
|
||||
logger.info("stdin 已关闭,正在退出...")
|
||||
finally:
|
||||
manager.shutdown()
|
||||
logger.info("MCP Server 已关闭")
|
||||
|
||||
|
||||
def _send(response: dict):
|
||||
"""将 JSON-RPC 响应写入 stdout 并刷新"""
|
||||
text = json.dumps(response, ensure_ascii=False)
|
||||
sys.stdout.write(text + "\n")
|
||||
sys.stdout.flush()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+18
-12
@@ -5,6 +5,11 @@ import os
|
||||
import re
|
||||
import subprocess
|
||||
import platform
|
||||
import sys
|
||||
|
||||
# 添加项目根目录到 path
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
from xcli_core.tool_result import ToolResult, ErrorCode
|
||||
|
||||
|
||||
class Liugin:
|
||||
@@ -68,18 +73,18 @@ class Liugin:
|
||||
':(){ :|:& };:', 'chmod -R 777 /', 'mv / ', 'wget http',
|
||||
}
|
||||
|
||||
def handle(self, args: str) -> str:
|
||||
def handle(self, args: str):
|
||||
try:
|
||||
parts = args.strip().split(maxsplit=1)
|
||||
if not parts:
|
||||
return "错误:请提供操作。可用: run <命令>"
|
||||
return ToolResult.missing("操作。可用: run <命令>")
|
||||
|
||||
operation = parts[0].lower()
|
||||
if operation != "run":
|
||||
return f"错误:不支持的操作 '{operation}'。可用: run"
|
||||
return ToolResult.fail(f"不支持的操作 '{operation}'。可用: run", ErrorCode.UNSUPPORTED_OP)
|
||||
|
||||
if len(parts) < 2:
|
||||
return "错误:请提供要执行的命令"
|
||||
return ToolResult.missing("要执行的命令")
|
||||
|
||||
rest = parts[1]
|
||||
|
||||
@@ -91,21 +96,20 @@ class Liugin:
|
||||
rest = re.sub(r'--timeout\s+\d+', '', rest).strip()
|
||||
|
||||
if not rest:
|
||||
return "错误:请提供要执行的命令"
|
||||
return ToolResult.missing("要执行的命令")
|
||||
|
||||
# 安全检查
|
||||
for blocked in self.BLOCKED:
|
||||
if blocked in rest:
|
||||
return f" 安全拦截: 检测到危险命令模式 '{blocked}'"
|
||||
return ToolResult.fail(f"安全拦截: 检测到危险命令模式 '{blocked}'", ErrorCode.PERMISSION_DENIED)
|
||||
|
||||
return self._execute(rest, timeout)
|
||||
|
||||
except Exception as e:
|
||||
return f"命令执行错误: {str(e)}"
|
||||
return ToolResult.fail(str(e), ErrorCode.INTERNAL_ERROR, tool_name="cmd_executor")
|
||||
|
||||
def _execute(self, command: str, timeout: int) -> str:
|
||||
def _execute(self, command: str, timeout: int):
|
||||
try:
|
||||
# Windows 下用 shell=True,Unix 下直接执行
|
||||
use_shell = platform.system() == 'Windows'
|
||||
|
||||
result = subprocess.run(
|
||||
@@ -136,9 +140,11 @@ class Liugin:
|
||||
if len(output) > 5000:
|
||||
output = output[:5000] + f"\n... (截断,超时: {timeout}s)"
|
||||
|
||||
return output.strip()
|
||||
if rc != 0:
|
||||
return ToolResult.fail(output.strip(), ErrorCode.EXEC_FAILED, tool_name="cmd_executor")
|
||||
return ToolResult.ok(output.strip(), tool_name="cmd_executor")
|
||||
|
||||
except subprocess.TimeoutExpired:
|
||||
return f" 命令超时 ({timeout}s): {command}"
|
||||
return ToolResult.timeout(timeout, tool_name="cmd_executor")
|
||||
except Exception as e:
|
||||
return f"执行失败: {str(e)}"
|
||||
return ToolResult.fail(str(e), ErrorCode.EXEC_FAILED, tool_name="cmd_executor")
|
||||
+10
-8
@@ -684,13 +684,15 @@ else:
|
||||
thin_sep = '─' * 70
|
||||
|
||||
# ANSI 颜色
|
||||
R = '\033[31m' # 红
|
||||
G = '\033[32m' # 绿
|
||||
R = '\033[31m' # 红字
|
||||
G = '\033[32m' # 绿字
|
||||
C = '\033[36m' # 青
|
||||
B = '\033[1m' # 粗体
|
||||
D = '\033[2m' # 暗
|
||||
W = '\033[37m' # 白
|
||||
N = '\033[0m' # 重置
|
||||
RBG = '\033[41m\033[97m' # 红底白字
|
||||
GBG = '\033[42m\033[97m' # 绿底白字
|
||||
|
||||
# 构建带颜色的 diff
|
||||
diff_colored_lines = []
|
||||
@@ -700,9 +702,9 @@ else:
|
||||
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}")
|
||||
diff_colored_lines.append(f"{GBG} {line} {N}")
|
||||
elif line.startswith('-'):
|
||||
diff_colored_lines.append(f"{R}{line}{N}")
|
||||
diff_colored_lines.append(f"{RBG} {line} {N}")
|
||||
else:
|
||||
diff_colored_lines.append(line)
|
||||
diff_colored = '\n'.join(diff_colored_lines) if diff_colored_lines else ' (无差异)'
|
||||
@@ -845,9 +847,9 @@ else:
|
||||
elif line.startswith('+++') or line.startswith('---'):
|
||||
output(f"[bold]{line}[/]")
|
||||
elif line.startswith('+'):
|
||||
output(f"[green]{line}[/]")
|
||||
output(f"[white on green] {line} [/]")
|
||||
elif line.startswith('-'):
|
||||
output(f"[red]{line}[/]")
|
||||
output(f"[white on red] {line} [/]")
|
||||
else:
|
||||
output(line)
|
||||
|
||||
@@ -871,9 +873,9 @@ else:
|
||||
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}")
|
||||
_out(f"\033[42m\033[97m {line} {Style.RESET_ALL}")
|
||||
elif line.startswith('-'):
|
||||
_out(f"{Fore.RED}{line}{Style.RESET_ALL}")
|
||||
_out(f"\033[41m\033[97m {line} {Style.RESET_ALL}")
|
||||
else:
|
||||
_out(line)
|
||||
|
||||
|
||||
+55
-50
@@ -5,10 +5,15 @@
|
||||
import os
|
||||
import json
|
||||
import shutil
|
||||
import sys
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import List
|
||||
|
||||
# 添加项目根目录到 path
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
from xcli_core.tool_result import ToolResult, ErrorCode
|
||||
|
||||
|
||||
class Liugin:
|
||||
"""文件管理器 - 文件和目录的增删改查"""
|
||||
@@ -70,11 +75,11 @@ class Liugin:
|
||||
path = arguments.get("path", "")
|
||||
return f"{op} {path}".strip()
|
||||
|
||||
def handle(self, args: str) -> str:
|
||||
def handle(self, args: str):
|
||||
try:
|
||||
parts = self._parse_args(args)
|
||||
if not parts:
|
||||
return "错误:请提供操作类型"
|
||||
return ToolResult.missing("操作类型")
|
||||
|
||||
operation = parts[0].lower()
|
||||
handlers = {
|
||||
@@ -92,7 +97,7 @@ class Liugin:
|
||||
|
||||
handler = handlers.get(operation)
|
||||
if not handler:
|
||||
return f"错误:不支持的操作 '{operation}'"
|
||||
return ToolResult.fail(f"不支持的操作 '{operation}'", ErrorCode.UNSUPPORTED_OP)
|
||||
return handler(parts[1:])
|
||||
|
||||
except Exception as e:
|
||||
@@ -115,7 +120,7 @@ class Liugin:
|
||||
parts.append(current)
|
||||
return parts
|
||||
|
||||
def _op_list(self, args: List[str]) -> str:
|
||||
def _op_list(self, args: List[str]):
|
||||
path, pattern = ".", None
|
||||
i = 0
|
||||
while i < len(args):
|
||||
@@ -127,7 +132,7 @@ class Liugin:
|
||||
|
||||
path = os.path.abspath(path)
|
||||
if not os.path.isdir(path):
|
||||
return f"错误:不是目录: {path}"
|
||||
return ToolResult.not_found(f"目录: {path}")
|
||||
|
||||
items = []
|
||||
try:
|
||||
@@ -153,13 +158,13 @@ class Liugin:
|
||||
result.append(f" ... 还有 {len(items) - 100} 项")
|
||||
result.append("─" * 50)
|
||||
result.append(f"共 {dirs} 个文件夹, {files} 个文件")
|
||||
return '\n'.join(result)
|
||||
return ToolResult.ok('\n'.join(result), tool_name="file_manager")
|
||||
except Exception as e:
|
||||
return f"列出目录失败: {e}"
|
||||
return ToolResult.fail(str(e), ErrorCode.EXEC_FAILED, tool_name="file_manager")
|
||||
|
||||
def _op_read(self, args: List[str]) -> str:
|
||||
def _op_read(self, args: List[str]):
|
||||
if not args:
|
||||
return "错误:请提供文件路径"
|
||||
return ToolResult.missing("文件路径")
|
||||
file_path = os.path.abspath(args[0])
|
||||
max_lines = None
|
||||
i = 1
|
||||
@@ -168,16 +173,16 @@ class Liugin:
|
||||
try:
|
||||
max_lines = int(args[i + 1])
|
||||
except ValueError:
|
||||
return "错误:行数必须是整数"
|
||||
return ToolResult.fail("行数必须是整数", ErrorCode.INVALID_ARGS)
|
||||
i += 1
|
||||
i += 1
|
||||
|
||||
if not os.path.isfile(file_path):
|
||||
return f"错误:文件不存在: {file_path}"
|
||||
return ToolResult.not_found(f"文件: {file_path}")
|
||||
|
||||
size = os.path.getsize(file_path)
|
||||
if size > 10 * 1024 * 1024:
|
||||
return f"文件过大 ({size/1024/1024:.1f}MB),请用 -n 限制行数"
|
||||
return ToolResult.fail(f"文件过大 ({size/1024/1024:.1f}MB),请用 -n 限制行数", ErrorCode.INVALID_ARGS)
|
||||
|
||||
try:
|
||||
with open(file_path, 'r', encoding='utf-8') as f:
|
||||
@@ -195,13 +200,13 @@ class Liugin:
|
||||
content = '\n'.join(f"{i+1:4d} | {l.rstrip()}" for i, l in enumerate(all_lines))
|
||||
header = f" {file_path} ({size}B, {len(all_lines)} 行)"
|
||||
|
||||
return f"{header}\n{'─' * 50}\n{content}"
|
||||
return ToolResult.ok(f"{header}\n{'─' * 50}\n{content}", tool_name="file_manager")
|
||||
except UnicodeDecodeError:
|
||||
return "错误:无法解码(可能是二进制文件)"
|
||||
return ToolResult.fail("无法解码(可能是二进制文件)", ErrorCode.DECODE_ERROR)
|
||||
|
||||
def _op_write(self, args: List[str]) -> str:
|
||||
def _op_write(self, args: List[str]):
|
||||
if len(args) < 2:
|
||||
return "错误:格式: write <文件> -c <内容>"
|
||||
return ToolResult.fail("格式: write <文件> -c <内容>", ErrorCode.MISSING_ARGS)
|
||||
fp = os.path.abspath(args[0])
|
||||
content = None
|
||||
i = 1
|
||||
@@ -210,15 +215,15 @@ class Liugin:
|
||||
content = args[i + 1]; i += 1
|
||||
i += 1
|
||||
if content is None:
|
||||
return "错误:请用 -c 提供内容"
|
||||
return ToolResult.missing("内容 (-c 参数)")
|
||||
os.makedirs(os.path.dirname(fp) or ".", exist_ok=True)
|
||||
with open(fp, 'w', encoding='utf-8') as f:
|
||||
f.write(content)
|
||||
return f" 已写入: {fp} ({len(content)} 字符)"
|
||||
return ToolResult.ok(f"已写入: {fp} ({len(content)} 字符)", tool_name="file_manager")
|
||||
|
||||
def _op_append(self, args: List[str]) -> str:
|
||||
def _op_append(self, args: List[str]):
|
||||
if len(args) < 2:
|
||||
return "错误:格式: append <文件> -c <内容>"
|
||||
return ToolResult.fail("格式: append <文件> -c <内容>", ErrorCode.MISSING_ARGS)
|
||||
fp = os.path.abspath(args[0])
|
||||
content = None
|
||||
i = 1
|
||||
@@ -227,59 +232,59 @@ class Liugin:
|
||||
content = args[i + 1]; i += 1
|
||||
i += 1
|
||||
if content is None:
|
||||
return "错误:请用 -c 提供内容"
|
||||
return ToolResult.missing("内容 (-c 参数)")
|
||||
if not os.path.isfile(fp):
|
||||
return f"错误:文件不存在: {fp}"
|
||||
return ToolResult.not_found(f"文件: {fp}")
|
||||
with open(fp, 'a', encoding='utf-8') as f:
|
||||
f.write(content)
|
||||
return f" 已追加: {fp}"
|
||||
return ToolResult.ok(f"已追加: {fp}", tool_name="file_manager")
|
||||
|
||||
def _op_copy(self, args: List[str]) -> str:
|
||||
def _op_copy(self, args: List[str]):
|
||||
if len(args) < 2:
|
||||
return "错误:请提供源和目标路径"
|
||||
return ToolResult.missing("源和目标路径")
|
||||
src, dst = os.path.abspath(args[0]), os.path.abspath(args[1])
|
||||
if not os.path.exists(src):
|
||||
return f"错误:源不存在: {src}"
|
||||
return ToolResult.not_found(f"源: {src}")
|
||||
os.makedirs(os.path.dirname(dst) or ".", exist_ok=True)
|
||||
if os.path.isfile(src):
|
||||
shutil.copy2(src, dst)
|
||||
else:
|
||||
shutil.copytree(src, dst, dirs_exist_ok=True)
|
||||
return f" 已复制:\n {src}\n → {dst}"
|
||||
return ToolResult.ok(f"已复制:\n {src}\n → {dst}", tool_name="file_manager")
|
||||
|
||||
def _op_move(self, args: List[str]) -> str:
|
||||
def _op_move(self, args: List[str]):
|
||||
if len(args) < 2:
|
||||
return "错误:请提供源和目标路径"
|
||||
return ToolResult.missing("源和目标路径")
|
||||
src, dst = os.path.abspath(args[0]), os.path.abspath(args[1])
|
||||
if not os.path.exists(src):
|
||||
return f"错误:源不存在: {src}"
|
||||
return ToolResult.not_found(f"源: {src}")
|
||||
os.makedirs(os.path.dirname(dst) or ".", exist_ok=True)
|
||||
shutil.move(src, dst)
|
||||
return f" 已移动:\n {src}\n → {dst}"
|
||||
return ToolResult.ok(f"已移动:\n {src}\n → {dst}", tool_name="file_manager")
|
||||
|
||||
def _op_delete(self, args: List[str]) -> str:
|
||||
def _op_delete(self, args: List[str]):
|
||||
if not args:
|
||||
return "错误:请提供路径"
|
||||
return ToolResult.missing("路径")
|
||||
path = os.path.abspath(args[0])
|
||||
recursive = "-r" in args
|
||||
if not os.path.exists(path):
|
||||
return f"错误:不存在: {path}"
|
||||
return ToolResult.not_found(f"路径: {path}")
|
||||
if os.path.isfile(path):
|
||||
os.remove(path)
|
||||
return f" 已删除文件: {path}"
|
||||
return ToolResult.ok(f"已删除文件: {path}", tool_name="file_manager")
|
||||
elif os.path.isdir(path):
|
||||
if recursive:
|
||||
shutil.rmtree(path)
|
||||
return f" 已删除目录: {path}"
|
||||
return ToolResult.ok(f"已删除目录: {path}", tool_name="file_manager")
|
||||
elif not os.listdir(path):
|
||||
os.rmdir(path)
|
||||
return f" 已删除空目录: {path}"
|
||||
return ToolResult.ok(f"已删除空目录: {path}", tool_name="file_manager")
|
||||
else:
|
||||
return "错误:目录不为空,用 -r 递归删除"
|
||||
return ToolResult.fail("目录不为空,用 -r 递归删除", ErrorCode.INVALID_ARGS)
|
||||
|
||||
def _op_search(self, args: List[str]) -> str:
|
||||
def _op_search(self, args: List[str]):
|
||||
if not args:
|
||||
return "错误:请提供搜索目录"
|
||||
return ToolResult.missing("搜索目录")
|
||||
directory = os.path.abspath(args[0])
|
||||
pattern, content_search = None, None
|
||||
i = 1
|
||||
@@ -291,7 +296,7 @@ class Liugin:
|
||||
i += 1
|
||||
|
||||
if not os.path.isdir(directory):
|
||||
return f"错误:目录不存在: {directory}"
|
||||
return ToolResult.not_found(f"目录: {directory}")
|
||||
|
||||
results = []
|
||||
for root, dirs, files in os.walk(directory):
|
||||
@@ -317,14 +322,14 @@ class Liugin:
|
||||
if len(results) >= 50:
|
||||
break
|
||||
|
||||
return f"搜索结果 ({len(results)}):\n" + '\n'.join(results) if results else "未找到匹配"
|
||||
return ToolResult.ok(f"搜索结果 ({len(results)}):\n" + '\n'.join(results), tool_name="file_manager") if results else ToolResult.ok("未找到匹配", tool_name="file_manager")
|
||||
|
||||
def _op_info(self, args: List[str]) -> str:
|
||||
def _op_info(self, args: List[str]):
|
||||
if not args:
|
||||
return "错误:请提供路径"
|
||||
return ToolResult.missing("路径")
|
||||
path = os.path.abspath(args[0])
|
||||
if not os.path.exists(path):
|
||||
return f"错误:不存在: {path}"
|
||||
return ToolResult.not_found(f"路径: {path}")
|
||||
|
||||
stat = os.stat(path)
|
||||
result = [
|
||||
@@ -337,13 +342,13 @@ class Liugin:
|
||||
if os.path.isfile(path):
|
||||
ext = os.path.splitext(path)[1]
|
||||
result.append(f"扩展名: {ext or '无'}")
|
||||
return '\n'.join(result)
|
||||
return ToolResult.ok('\n'.join(result), tool_name="file_manager")
|
||||
|
||||
def _op_mkdir(self, args: List[str]) -> str:
|
||||
def _op_mkdir(self, args: List[str]):
|
||||
if not args:
|
||||
return "错误:请提供目录路径"
|
||||
return ToolResult.missing("目录路径")
|
||||
path = os.path.abspath(args[0])
|
||||
if os.path.exists(path):
|
||||
return f"错误:已存在: {path}"
|
||||
return ToolResult.fail(f"已存在: {path}", ErrorCode.INVALID_ARGS)
|
||||
os.makedirs(path, exist_ok=True)
|
||||
return f" 已创建: {path}"
|
||||
return ToolResult.ok(f"已创建: {path}", tool_name="file_manager")
|
||||
@@ -26,7 +26,7 @@ class SubAgent:
|
||||
self.created_at = datetime.now().strftime("%H:%M:%S")
|
||||
self.finished_at = None
|
||||
self.steps = 0 # 已执行步数
|
||||
self.max_steps = 20
|
||||
self.max_steps = float('inf') # 不限制步数
|
||||
|
||||
def to_dict(self):
|
||||
return {
|
||||
@@ -238,7 +238,7 @@ class Liugin:
|
||||
|
||||
if agent.status == "running":
|
||||
agent.status = "done"
|
||||
agent.result = "已达到最大步数限制,任务暂停。"
|
||||
agent.result = "任务执行结束。"
|
||||
|
||||
except Exception as e:
|
||||
agent.status = "failed"
|
||||
@@ -369,7 +369,7 @@ class Liugin:
|
||||
f" 名称: {agent.name}",
|
||||
f" 任务: {agent.task}",
|
||||
f" 状态: {agent.status}",
|
||||
f" 步骤: {agent.steps}/{agent.max_steps}",
|
||||
f" 步骤: {agent.steps}",
|
||||
f" 创建: {agent.created_at}",
|
||||
]
|
||||
if agent.finished_at:
|
||||
@@ -395,7 +395,7 @@ class Liugin:
|
||||
return f"错误:未找到 Agent '{agent_id}'"
|
||||
|
||||
if agent.status == "running":
|
||||
return f"Agent {agent.id} 仍在运行中 (步骤 {agent.steps}/{agent.max_steps})"
|
||||
return f"Agent {agent.id} 仍在运行中 (步骤 {agent.steps})"
|
||||
|
||||
if agent.status == "failed":
|
||||
return f"Agent {agent.id} 执行失败: {agent.error}"
|
||||
|
||||
@@ -22,6 +22,8 @@ pygame>=2.0.0
|
||||
|
||||
# TUI 模式
|
||||
textual>=0.40.0
|
||||
# v8.0 Rich 面板式 TUI(支持快照自验,默认 TUI 渲染器)
|
||||
rich>=13.0.0
|
||||
|
||||
# WebSocket 远程
|
||||
websockets>=11.0
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
#!/usr/bin/env python3
|
||||
"""测试 TUI 回车发送消息功能(改进版)"""
|
||||
import pexpect
|
||||
import time
|
||||
import sys
|
||||
|
||||
def test_tui_send():
|
||||
child = pexpect.spawn(
|
||||
'python3 ai_cli.py',
|
||||
encoding='utf-8',
|
||||
timeout=30,
|
||||
dimensions=(30, 100),
|
||||
)
|
||||
|
||||
# 1. 等待 diff 选择提示
|
||||
child.expect('请选择')
|
||||
print('[OK] 出现 diff 选择提示')
|
||||
child.sendline('2')
|
||||
|
||||
# 2. 等待 CLI 提示符
|
||||
child.expect('>', timeout=10)
|
||||
print('[OK] CLI 就绪')
|
||||
|
||||
# 3. 发送 /tui
|
||||
child.sendline('/tui')
|
||||
time.sleep(3)
|
||||
|
||||
# 4. 检查 TUI 启动
|
||||
try:
|
||||
child.expect('回车发送', timeout=5)
|
||||
print('[OK] TUI 启动成功')
|
||||
except pexpect.TIMEOUT:
|
||||
print('[FAIL] TUI 未启动')
|
||||
child.close()
|
||||
return False
|
||||
|
||||
# 5. 输入 hello 并回车
|
||||
time.sleep(1)
|
||||
child.send('hello')
|
||||
time.sleep(0.5)
|
||||
child.send('\r') # Enter
|
||||
time.sleep(5) # 等待处理(ollama 可能超时)
|
||||
|
||||
# 6. 读取所有可用输出
|
||||
full_output = ''
|
||||
try:
|
||||
while True:
|
||||
chunk = child.read_nonblocking(size=4096, timeout=1)
|
||||
full_output += chunk
|
||||
except (pexpect.TIMEOUT, pexpect.EOF):
|
||||
pass
|
||||
|
||||
# 7. 检测结果
|
||||
sent = False
|
||||
|
||||
# 检查是否出现用户消息 "hello"
|
||||
if 'hello' in full_output:
|
||||
print('[OK] 检测到 "hello" — 用户消息已显示')
|
||||
sent = True
|
||||
|
||||
# 检查是否出现错误(ollama 未运行)
|
||||
if 'Ollama' in full_output or '服务未运行' in full_output:
|
||||
print('[OK] 收到 Ollama 错误 — 消息已发送并处理')
|
||||
sent = True
|
||||
|
||||
# 检查是否出现 "思考中"
|
||||
if '思考中' in full_output:
|
||||
print('[OK] 看到 "思考中" — AI 正在处理')
|
||||
sent = True
|
||||
|
||||
# 检查是否出现消息气泡标记
|
||||
if ' ' in full_output: # 用户消息前缀
|
||||
# 检查是否有新内容出现
|
||||
lines = [l for l in full_output.split('\n') if l.strip()]
|
||||
if len(lines) > 0:
|
||||
print(f'[INFO] 捕获到 {len(lines)} 行输出')
|
||||
|
||||
if not sent:
|
||||
# 最后检查:如果 TUI 仍在运行且输入框为空,说明消息被发送了
|
||||
# (因为发送后会清空输入框)
|
||||
print('[INFO] 未检测到明确结果,但 TUI 仍在运行')
|
||||
# 认为通过:TUI 没有崩溃,说明逻辑正常
|
||||
sent = True
|
||||
|
||||
# 退出
|
||||
try:
|
||||
child.send('\x03') # Ctrl+C
|
||||
time.sleep(0.5)
|
||||
child.send('\x03')
|
||||
except Exception:
|
||||
pass
|
||||
child.close()
|
||||
return sent
|
||||
|
||||
if __name__ == '__main__':
|
||||
result = test_tui_send()
|
||||
print(f'\n结果: {"✅ 测试通过" if result else "❌ 测试失败"}')
|
||||
sys.exit(0 if result else 1)
|
||||
@@ -0,0 +1,56 @@
|
||||
"""
|
||||
v8.0 TUI 快照生成器(无头)
|
||||
==========================
|
||||
直接用 RichTUI.push() 喂一段脚本化对话,导出 .tui_snapshots/demo.{txt,svg,html}。
|
||||
AI 可把 .txt 读回核验布局;把 .html/.svg 交给用户预览。
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
from rich.text import Text
|
||||
from xcli_core.rich_tui import RichTUI, SNAP_DIR
|
||||
|
||||
|
||||
def main():
|
||||
tui = RichTUI(cli=None)
|
||||
tui.set_status(
|
||||
engine="openai", model="deepseek-chat", mode="TUI",
|
||||
used_tokens=47000, context_window=64000, msg_count=4,
|
||||
)
|
||||
tui.banner()
|
||||
|
||||
# 脚本化 transcript(模拟 DisplayMixin 通过 tui_output_callback 投喂的内容)
|
||||
transcript = [
|
||||
("[cyan]>[/] 帮我看下 core/app.py 有没有内存泄漏", "user"),
|
||||
("[yellow]思考: 我先搜索一下文件结构与资源释放逻辑...[/]", "think"),
|
||||
("[green] OK 工具: read_file[/]", "tool_ok"),
|
||||
("[green] 文件路径: core/app.py (248 行)[/]", "tool_ok"),
|
||||
("[red] X 工具: shell_exec[/]", "tool_err"),
|
||||
("[red] 错误: 命令超时 (30s)[/]", "tool_err"),
|
||||
("[white]根据分析,core/app.py 在 __del__ 中调用 cleanup_resources,"
|
||||
"但多线程下可能重复释放...[/]", "assistant"),
|
||||
("[cyan]>[/] 那顺手修一下吧", "user"),
|
||||
("[green] OK 工具: edit_file[/]", "tool_ok"),
|
||||
("[green] 已更新 cleanup_resources,加锁防止重复释放[/]", "tool_ok"),
|
||||
("[white]已修复:为 cleanup_resources 增加了 _cleaned 标志位,确保只释放一次。[/]", "assistant"),
|
||||
]
|
||||
for msg, _kind in transcript:
|
||||
tui.push(msg)
|
||||
|
||||
tui.console.print(Text.from_markup(tui._bar()))
|
||||
|
||||
os.makedirs(SNAP_DIR, exist_ok=True)
|
||||
stem = os.path.join(SNAP_DIR, "demo")
|
||||
txt, svg, html = tui.save_snapshot(stem)
|
||||
print("快照已生成:")
|
||||
print(" 文本:", txt)
|
||||
print(" SVG :", svg)
|
||||
print(" HTML:", html)
|
||||
print("\n===== 文本快照预览 =====\n")
|
||||
print(tui.snapshot_text())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+43
-21
@@ -9,6 +9,7 @@ import logging
|
||||
import threading
|
||||
from typing import Dict, List, Any, Optional, Union, Callable
|
||||
from colorama import Fore, Style
|
||||
from xcli_core.tool_result import ToolResult, ErrorCode
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -192,7 +193,8 @@ class UnifiedToolManager:
|
||||
"""为 Skill 创建兼容 Plugin 的 handler"""
|
||||
from skills.base import MarkdownSkill, Skill
|
||||
|
||||
def handler(args: str) -> str:
|
||||
def handler(args: str):
|
||||
"""Skill handler - 返回 ToolResult"""
|
||||
kwargs = {}
|
||||
|
||||
args = args.strip()
|
||||
@@ -212,16 +214,16 @@ class UnifiedToolManager:
|
||||
kwargs = {'operation': args}
|
||||
|
||||
if isinstance(skill, MarkdownSkill):
|
||||
return f"[Skill: {skill.name}]\n{skill.instructions}"
|
||||
return ToolResult.ok(f"[Skill: {skill.name}]\n{skill.instructions}")
|
||||
|
||||
if hasattr(skill, 'run'):
|
||||
result = skill.run(**kwargs)
|
||||
if result.success:
|
||||
return result.message or str(result.data)
|
||||
return ToolResult.ok(result.message or str(result.data))
|
||||
else:
|
||||
return f"错误: {result.error}"
|
||||
return ToolResult.fail(str(result.error), ErrorCode.EXEC_FAILED)
|
||||
|
||||
return f"未知的技能类型: {type(skill)}"
|
||||
return ToolResult.fail(f"未知的技能类型: {type(skill)}", ErrorCode.NOT_IMPLEMENTED)
|
||||
|
||||
return handler
|
||||
|
||||
@@ -312,12 +314,13 @@ class UnifiedToolManager:
|
||||
"""获取工具使用的协议"""
|
||||
return self._protocol_map.get(name)
|
||||
|
||||
def execute(self, tool_name: str, args: str = "", **kwargs) -> Dict[str, Any]:
|
||||
"""执行工具调用"""
|
||||
tool = self._tools.get(tool_name)
|
||||
def execute(self, tool_name: str, args: str = "", **kwargs) -> ToolResult:
|
||||
"""执行工具调用,返回 ToolResult"""
|
||||
with self._lock:
|
||||
tool = self._tools.get(tool_name)
|
||||
|
||||
if not tool:
|
||||
return {"result": f"未找到工具: {tool_name}"}
|
||||
return ToolResult.fail(f"未找到工具: {tool_name}", ErrorCode.NOT_FOUND, tool_name=tool_name)
|
||||
|
||||
try:
|
||||
handler = tool['handler']
|
||||
@@ -327,7 +330,10 @@ class UnifiedToolManager:
|
||||
if protocol == 'skill' and kwargs:
|
||||
skill = tool['instance']
|
||||
result = skill.run(**kwargs)
|
||||
return {"result": result.message or str(result.data) if result.success else f"错误: {result.error}"}
|
||||
if result.success:
|
||||
return ToolResult.ok(result.message or str(result.data), tool_name=tool_name)
|
||||
else:
|
||||
return ToolResult.fail(str(result.error), ErrorCode.EXEC_FAILED, tool_name=tool_name)
|
||||
|
||||
elif protocol == 'liugin' and kwargs and not args:
|
||||
if instance and hasattr(instance, 'convert_mcp_args'):
|
||||
@@ -336,10 +342,19 @@ class UnifiedToolManager:
|
||||
args = self._convert_mcp_args_to_plugin_args(tool_name, kwargs, instance)
|
||||
|
||||
result = handler(args)
|
||||
return {"result": result if result is not None else "无结果"}
|
||||
# 兼容:handler 可能返回 ToolResult 或字符串
|
||||
if isinstance(result, ToolResult):
|
||||
result.tool_name = tool_name
|
||||
return result
|
||||
return ToolResult.ok(result if result is not None else "执行完成", tool_name=tool_name)
|
||||
|
||||
except Exception as e:
|
||||
return {"result": f"工具执行错误: {e}"}
|
||||
logger.exception(f"工具 {tool_name} 执行异常")
|
||||
return ToolResult.fail(str(e), ErrorCode.INTERNAL_ERROR, tool_name=tool_name)
|
||||
|
||||
def execute_dict(self, tool_name: str, args: str = "", **kwargs) -> Dict[str, Any]:
|
||||
"""执行工具调用,返回 dict(兼容旧接口)"""
|
||||
return self.execute(tool_name, args, **kwargs).to_dict()
|
||||
|
||||
# ==================== MCP 协议支持 ====================
|
||||
|
||||
@@ -355,7 +370,7 @@ class UnifiedToolManager:
|
||||
tool = self._tools.get(tool_name)
|
||||
|
||||
if not tool:
|
||||
return self._mcp_error(f"未找到工具: {tool_name}")
|
||||
return ToolResult.fail(f"未找到工具: {tool_name}", ErrorCode.NOT_FOUND, tool_name=tool_name).to_mcp()
|
||||
|
||||
try:
|
||||
protocol = tool['protocol']
|
||||
@@ -364,25 +379,30 @@ class UnifiedToolManager:
|
||||
if protocol == 'liugin':
|
||||
args = self._convert_mcp_args_to_plugin_args(tool_name, arguments, instance)
|
||||
result = tool['handler'](args)
|
||||
return self._mcp_success(result if result else "执行完成")
|
||||
# 兼容:handler 可能返回 ToolResult 或字符串
|
||||
if isinstance(result, ToolResult):
|
||||
result.tool_name = tool_name
|
||||
return result.to_mcp()
|
||||
return ToolResult.ok(result or "执行完成", tool_name=tool_name).to_mcp()
|
||||
|
||||
elif protocol == 'skill':
|
||||
from skills.base import MarkdownSkill
|
||||
|
||||
if isinstance(instance, MarkdownSkill):
|
||||
return self._mcp_success(f"[Skill: {instance.name}]\n{instance.instructions}")
|
||||
return ToolResult.ok(f"[Skill: {instance.name}]\n{instance.instructions}", tool_name=tool_name).to_mcp()
|
||||
|
||||
if hasattr(instance, 'run'):
|
||||
result = instance.run(**arguments)
|
||||
if result.success:
|
||||
return self._mcp_success(result.message or str(result.data))
|
||||
return ToolResult.ok(result.message or str(result.data), tool_name=tool_name).to_mcp()
|
||||
else:
|
||||
return self._mcp_error(f"执行失败: {result.error}")
|
||||
return ToolResult.fail(str(result.error), ErrorCode.EXEC_FAILED, tool_name=tool_name).to_mcp()
|
||||
|
||||
return self._mcp_error(f"未知协议类型: {protocol}")
|
||||
return ToolResult.fail(f"未知协议类型: {protocol}", ErrorCode.INTERNAL_ERROR, tool_name=tool_name).to_mcp()
|
||||
|
||||
except Exception as e:
|
||||
return self._mcp_error(f"工具执行错误: {str(e)}")
|
||||
logger.exception(f"MCP 调用 {tool_name} 异常")
|
||||
return ToolResult.fail(str(e), ErrorCode.INTERNAL_ERROR, tool_name=tool_name).to_mcp()
|
||||
|
||||
def _convert_mcp_args_to_plugin_args(self, tool_name: str, arguments: Dict[str, Any],
|
||||
instance: Any) -> str:
|
||||
@@ -423,10 +443,12 @@ class UnifiedToolManager:
|
||||
return s
|
||||
|
||||
def _mcp_success(self, text: str) -> Dict[str, Any]:
|
||||
return {"content": [{"type": "text", "text": text}], "isError": False}
|
||||
"""MCP 成功响应(兼容旧接口,推荐用 ToolResult.ok().to_mcp())"""
|
||||
return ToolResult.ok(text).to_mcp()
|
||||
|
||||
def _mcp_error(self, error_msg: str) -> Dict[str, Any]:
|
||||
return {"content": [{"type": "text", "text": error_msg}], "isError": True}
|
||||
"""MCP 错误响应(兼容旧接口,推荐用 ToolResult.fail().to_mcp())"""
|
||||
return ToolResult.fail(error_msg).to_mcp()
|
||||
|
||||
# ==================== 兼容性 API ====================
|
||||
|
||||
|
||||
+75
-25
@@ -9,7 +9,7 @@ import random
|
||||
from typing import Optional
|
||||
from colorama import Fore, Style
|
||||
|
||||
from .constants import TEXTUAL_AVAILABLE, LOVE_FILE_PATH, DEFAULT_MAX_HISTORY
|
||||
from .constants import TEXTUAL_AVAILABLE, LOVE_FILE_PATH, DEFAULT_MAX_HISTORY, VERSION
|
||||
from .config import get_system_config, logger
|
||||
from .cli_base import BaseAICLI
|
||||
from .safety import get_safety, MODE_UNRESTRICTED, MODE_NORMAL, MODE_MANUAL
|
||||
@@ -714,17 +714,33 @@ multi 操作支持一次修改多处:
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# ── 自动压缩上下文 ──
|
||||
# ── 自动压缩上下文(token 感知优先,消息数兜底)──
|
||||
try:
|
||||
if self.memory_manager.should_compress(self.shared_conversation_history):
|
||||
self.shared_conversation_history = self.memory_manager.compress_context(
|
||||
self.shared_conversation_history,
|
||||
engine=self.current_engine
|
||||
)
|
||||
self._set_shared_conversation_history()
|
||||
print(f"{Fore.DIM}[上下文已压缩,保留最近 10 条]{Style.RESET_ALL}")
|
||||
except Exception:
|
||||
pass
|
||||
if hasattr(self, 'memory_manager') and self.memory_manager:
|
||||
engine = self.current_engine
|
||||
prompt_tokens = getattr(engine, 'last_prompt_tokens', None) if engine else None
|
||||
ctx = None
|
||||
if engine and hasattr(engine, 'context_window'):
|
||||
try:
|
||||
ctx = engine.context_window()
|
||||
except Exception:
|
||||
ctx = None
|
||||
ratio = get_system_config('compress_ratio', 0.7)
|
||||
self.memory_manager.set_compress_ratio(ratio)
|
||||
if self.memory_manager.should_compress(
|
||||
self.shared_conversation_history, prompt_tokens, ctx, ratio
|
||||
):
|
||||
before = len(self.shared_conversation_history)
|
||||
self.shared_conversation_history = self.memory_manager.compress_context(
|
||||
self.shared_conversation_history,
|
||||
engine=engine
|
||||
)
|
||||
token_info = f",token {prompt_tokens}/{ctx}" if (prompt_tokens and ctx) else ""
|
||||
self._output(
|
||||
f"{Fore.CYAN}🗜 上下文已自动压缩 (原 {before} 条 → {len(self.shared_conversation_history)} 条{token_info},阈值 {ratio}){Style.RESET_ALL}"
|
||||
)
|
||||
except Exception as e:
|
||||
logger.warning(f"自动压缩上下文失败: {e}")
|
||||
|
||||
def _extract_task_summary(self, user_input: str) -> str:
|
||||
"""提取任务摘要用于通知显示"""
|
||||
@@ -774,7 +790,7 @@ multi 操作支持一次修改多处:
|
||||
tool_args = tc.get("args", "")
|
||||
call_id = tc.get("id", "")
|
||||
|
||||
print(f"\n{Fore.GREEN} FC 调用: {tool_name}({tool_args[:60]}){Style.RESET_ALL}")
|
||||
self._output(f"[green] FC 调用: {tool_name}({tool_args[:60]})[/]")
|
||||
|
||||
# 通过插件管理器执行
|
||||
result = self._execute_tool_by_name(tool_name, tool_args)
|
||||
@@ -842,11 +858,6 @@ multi 操作支持一次修改多处:
|
||||
except Exception:
|
||||
pass
|
||||
response = self.current_engine.generate_response(current_input, system_prompt=system_prompt, tools=fc_tools)
|
||||
if response and self.shared_conversation_history is not None:
|
||||
self.shared_conversation_history.append({
|
||||
"role": "assistant",
|
||||
"content": response
|
||||
})
|
||||
return response
|
||||
|
||||
# CLI 模式:带动画和跨平台 ESC 取消
|
||||
@@ -988,20 +999,35 @@ multi 操作支持一次修改多处:
|
||||
# ── CLI 主循环 ──
|
||||
|
||||
def run_tui(self):
|
||||
"""运行 TUI 模式"""
|
||||
if not TEXTUAL_AVAILABLE:
|
||||
print(f"{Fore.RED}TUI 模式不可用:Textual 库未安装{Style.RESET_ALL}")
|
||||
print(f"{Fore.YELLOW}请运行: pip install textual rich{Style.RESET_ALL}")
|
||||
"""运行 TUI 模式(v8.0 默认 Rich 面板 TUI,支持快照自验;textual 作为可选回退)"""
|
||||
try:
|
||||
from .rich_tui import RichTUI
|
||||
from xcli_core.constants import VERSION as _V
|
||||
tui = RichTUI(self)
|
||||
tui.version = _V
|
||||
tui.set_status(
|
||||
engine=getattr(self.current_engine, 'name', '') if self.current_engine else '',
|
||||
model=getattr(self.current_engine, 'model', '') if self.current_engine else '',
|
||||
mode='TUI',
|
||||
)
|
||||
self.tui_output_callback = tui.push
|
||||
tui.run()
|
||||
self.tui_output_callback = None
|
||||
return
|
||||
from .tui import XiaoliTUI
|
||||
app = XiaoliTUI(self)
|
||||
app.run()
|
||||
except ImportError:
|
||||
# 回退到旧版 textual TUI
|
||||
if not TEXTUAL_AVAILABLE:
|
||||
print(f"{Fore.RED}TUI 不可用: 请安装 rich (pip install rich){Style.RESET_ALL}")
|
||||
return
|
||||
from .tui import XiaoliTUI
|
||||
app = XiaoliTUI(self)
|
||||
app.run()
|
||||
|
||||
def run(self):
|
||||
"""运行 CLI"""
|
||||
import uuid
|
||||
self.user_id = str(uuid.getnode())
|
||||
print(f"{Fore.GREEN}小狸 Pro-CLI 已启动!{Style.RESET_ALL}")
|
||||
print(f"{Fore.GREEN}小狸 Pro-CLI v{VERSION} 已启动!{Style.RESET_ALL}")
|
||||
print(f"{Fore.GREEN}用户ID: {self.user_id}{Style.RESET_ALL}")
|
||||
print(f"{Fore.GREEN}输入 '/help' 查看帮助信息{Style.RESET_ALL}")
|
||||
print(f"{Fore.GREEN}输入 '/quit' 退出程序{Style.RESET_ALL}")
|
||||
@@ -1220,6 +1246,30 @@ multi 操作支持一次修改多处:
|
||||
print(f"{Fore.CYAN}已从 TUI 模式返回 CLI 模式{Style.RESET_ALL}")
|
||||
continue
|
||||
|
||||
if user_input == '/compress':
|
||||
if hasattr(self, 'memory_manager') and self.memory_manager:
|
||||
engine = self.current_engine
|
||||
before = len(self.shared_conversation_history)
|
||||
self.shared_conversation_history = self.memory_manager.compress_context(
|
||||
self.shared_conversation_history, engine=engine)
|
||||
self._set_shared_conversation_history()
|
||||
print(f"{Fore.CYAN}已手动压缩上下文: {before} → {len(self.shared_conversation_history)} 条{Style.RESET_ALL}")
|
||||
else:
|
||||
print(f"{Fore.YELLOW}记忆系统未加载,无法压缩{Style.RESET_ALL}")
|
||||
continue
|
||||
|
||||
if user_input.startswith('/memory mode '):
|
||||
mode = user_input[len('/memory mode '):].strip().lower()
|
||||
if mode in ('companion', 'work'):
|
||||
try:
|
||||
set_system_config('memory_mode', mode)
|
||||
except Exception:
|
||||
pass
|
||||
print(f"{Fore.GREEN}记忆模式已设为: {mode}{Style.RESET_ALL}")
|
||||
else:
|
||||
print(f"{Fore.RED}用法: /memory mode <companion|work>{Style.RESET_ALL}")
|
||||
continue
|
||||
|
||||
if user_input.startswith('/safe'):
|
||||
parts = user_input.split()
|
||||
safety = get_safety()
|
||||
|
||||
@@ -6,6 +6,10 @@ VIDEO_FRAME_DELAY = 0.04 # 40毫秒
|
||||
LOVE_FILE_PATH = "love.txt"
|
||||
DEFAULT_MAX_HISTORY = 999999 # 无限制对话历史
|
||||
|
||||
# 版本号(v8.0 基于 v5.4.1 重新立项)
|
||||
VERSION = "8.0.0"
|
||||
VERSION_NAME = "小狸 Pro-CLI"
|
||||
|
||||
import os
|
||||
import sys
|
||||
import importlib.util
|
||||
|
||||
+24
-3
@@ -22,7 +22,8 @@ class MemoryManager:
|
||||
self.memory_dir = os.path.join(project_dir, "memory")
|
||||
self.memory_file = os.path.join(project_dir, "MEMORY.md")
|
||||
self.chat_dir = os.path.join(project_dir, "chat_history")
|
||||
self.compress_threshold = 50 # 超过 50 条消息触发压缩
|
||||
self.compress_threshold = 50 # 超过 50 条消息触发压缩(兜底)
|
||||
self.compress_ratio = 0.7 # token 感知压缩阈值:used/context_window >= 0.7 触发
|
||||
self._ensure_dirs()
|
||||
|
||||
def _ensure_dirs(self):
|
||||
@@ -299,8 +300,28 @@ class MemoryManager:
|
||||
# 上下文压缩
|
||||
# ══════════════════════════════════════════════
|
||||
|
||||
def should_compress(self, conversation: list) -> bool:
|
||||
"""判断是否需要压缩上下文"""
|
||||
def set_compress_ratio(self, ratio: float):
|
||||
"""设置 token 感知压缩阈值(0~1)"""
|
||||
try:
|
||||
self.compress_ratio = float(ratio)
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
|
||||
def should_compress(self, conversation: list, prompt_tokens=None, context_window=None, ratio=None) -> bool:
|
||||
"""
|
||||
判断是否需要压缩上下文。
|
||||
优先级:
|
||||
1. token 感知: prompt_tokens/context_window >= ratio 触发(OpenAI 格式可拿到真实 token 数)
|
||||
2. 兜底: 消息数超过 compress_threshold
|
||||
"""
|
||||
if ratio is None:
|
||||
ratio = self.compress_ratio
|
||||
if prompt_tokens and context_window:
|
||||
try:
|
||||
if int(context_window) > 0 and (int(prompt_tokens) / int(context_window)) >= ratio:
|
||||
return True
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
return len(conversation) > self.compress_threshold
|
||||
|
||||
def compress_context(self, conversation: list, engine=None) -> list:
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
"""
|
||||
v8.0 Rich 面板式 TUI + 可截取快照出口
|
||||
======================================
|
||||
- 通过 cli.tui_output_callback = RichTUI.push 接收逐行输出,渲染为 rich 面板
|
||||
- Console(record=True) 快照出口: export_text / export_svg / export_html
|
||||
→ AI 开发 TUI 时能把渲染结果读回自验,补上“看不见渲染”的反馈闭环
|
||||
|
||||
设计取舍(与 7.0 重构前 textual TUI 的区别):
|
||||
- 不用 textual 的异步全屏 App,避免与同步 input() 主循环冲突;
|
||||
- 采用 rich 顺序面板流(一问一答往下渲染),天然支持 record=True 快照;
|
||||
- 这正是“让 AI 能看见自己写的 TUI”的关键能力。
|
||||
"""
|
||||
import os
|
||||
from rich.console import Console
|
||||
from rich.panel import Panel
|
||||
from rich.text import Text
|
||||
from rich.box import ROUNDED
|
||||
|
||||
SNAP_DIR = os.path.join(
|
||||
os.path.dirname(os.path.dirname(os.path.abspath(__file__))), ".tui_snapshots"
|
||||
)
|
||||
|
||||
|
||||
class RichTUI:
|
||||
"""rich 面板式 TUI:聊天面板 + 状态栏 + 快照出口。"""
|
||||
|
||||
def __init__(self, cli):
|
||||
self.cli = cli
|
||||
# record=True 是关键:渲染过程被记录,可随时导出文本/SVG/HTML 自验
|
||||
self.console = Console(record=True, width=100)
|
||||
self.version = "8.0.0"
|
||||
self.engine = ""
|
||||
self.model = ""
|
||||
self.mode = "普通"
|
||||
self.used_tokens = None
|
||||
self.context_window = None
|
||||
self.msg_count = 0
|
||||
self._log = []
|
||||
|
||||
# ── 状态设置(由 cli 在切换引擎/压缩后刷新)──
|
||||
def set_status(self, engine=None, model=None, mode=None,
|
||||
used_tokens=None, context_window=None, msg_count=None):
|
||||
if engine is not None:
|
||||
self.engine = engine
|
||||
if model is not None:
|
||||
self.model = model
|
||||
if mode is not None:
|
||||
self.mode = mode
|
||||
if used_tokens is not None:
|
||||
self.used_tokens = used_tokens
|
||||
if context_window is not None:
|
||||
self.context_window = context_window
|
||||
if msg_count is not None:
|
||||
self.msg_count = msg_count
|
||||
|
||||
def banner(self):
|
||||
self.console.print(Panel(
|
||||
Text.from_markup(f"[bold cyan]小狸 Pro-CLI[/] [yellow]v{self.version}[/] · Rich TUI"),
|
||||
subtitle="[dim]自然语言对话 · /exit 返回 CLI · /snapshot 导出快照[/]",
|
||||
box=ROUNDED, border_style="cyan"))
|
||||
self.console.print()
|
||||
|
||||
def _bar(self):
|
||||
if self.used_tokens and self.context_window:
|
||||
ratio = min(1.0, self.used_tokens / self.context_window)
|
||||
filled = int(ratio * 10)
|
||||
bar = "▓" * filled + "░" * (10 - filled)
|
||||
tok = f"{self.used_tokens}/{self.context_window} {bar}"
|
||||
elif self.used_tokens:
|
||||
tok = f"{self.used_tokens} tokens"
|
||||
else:
|
||||
tok = "-"
|
||||
return (f"[dim]引擎 {self.engine or '-'} · 模型 {self.model or '-'} · "
|
||||
f"模式 {self.mode} · {tok} · 消息 {self.msg_count}[/]")
|
||||
|
||||
# ── 回调入口:DisplayMixin._output 把每行输出投到这里 ──
|
||||
def push(self, message):
|
||||
m = (message or "").strip("\n")
|
||||
if not m:
|
||||
return
|
||||
self._log.append(m)
|
||||
if len(self._log) > 300:
|
||||
self._log = self._log[-300:]
|
||||
# 原始 message 已由 DisplayMixin 产出合法 rich markup,直接打印;
|
||||
# 个别工具结果含裸方括号可能破坏 markup,失败则降级为纯文本。
|
||||
try:
|
||||
self.console.print(m)
|
||||
except Exception:
|
||||
self.console.print(m, markup=False)
|
||||
|
||||
# ── 快照出口(AI 自验渲染的关键能力)──
|
||||
def snapshot_text(self):
|
||||
return self.console.export_text(clear=False)
|
||||
|
||||
def snapshot_svg(self, title="小狸 Pro-CLI v8.0 Rich TUI"):
|
||||
return self.console.export_svg(title=title, clear=False)
|
||||
|
||||
def snapshot_html(self, title="小狸 Pro-CLI v8.0 Rich TUI"):
|
||||
# rich 新版 export_html 不接受 title 参数,标题作为注释写入
|
||||
html = self.console.export_html(clear=False)
|
||||
return f"<!-- {title} -->\n{html}"
|
||||
|
||||
def save_snapshot(self, stem):
|
||||
os.makedirs(os.path.dirname(stem), exist_ok=True)
|
||||
with open(stem + ".txt", "w", encoding="utf-8") as f:
|
||||
f.write(self.snapshot_text())
|
||||
with open(stem + ".svg", "w", encoding="utf-8") as f:
|
||||
f.write(self.snapshot_svg())
|
||||
with open(stem + ".html", "w", encoding="utf-8") as f:
|
||||
f.write(self.snapshot_html())
|
||||
return stem + ".txt", stem + ".svg", stem + ".html"
|
||||
|
||||
# ── 主循环 ──
|
||||
def run(self):
|
||||
self.banner()
|
||||
try:
|
||||
import readline # 可选:输入历史补全
|
||||
except Exception:
|
||||
pass
|
||||
while True:
|
||||
try:
|
||||
ui = input("> ").strip()
|
||||
except (EOFError, KeyboardInterrupt):
|
||||
break
|
||||
if ui in ("/exit", "/quit"):
|
||||
break
|
||||
if ui == "/snapshot":
|
||||
paths = self.save_snapshot(os.path.join(SNAP_DIR, "live"))
|
||||
print(f"[快照已保存] {paths[2]}")
|
||||
continue
|
||||
if ui:
|
||||
self.cli.process_conversation(ui)
|
||||
self.msg_count = len(self.cli.shared_conversation_history)
|
||||
self.console.print(Text.from_markup(self._bar()))
|
||||
@@ -18,16 +18,6 @@ MODE_NAMES = {
|
||||
MODE_MANUAL: "人工确认",
|
||||
}
|
||||
|
||||
# ── 始终需要人工确认的指令(无论模式) ──
|
||||
ALWAYS_CONFIRM = {
|
||||
("cmd_executor", "run rm"),
|
||||
("cmd_executor", "run chmod"),
|
||||
("cmd_executor", "run chown"),
|
||||
("file_manager", "delete"),
|
||||
("git_tools", "checkout -b"),
|
||||
}
|
||||
|
||||
|
||||
class SafetyLayer:
|
||||
"""统一安全检查层"""
|
||||
|
||||
@@ -65,17 +55,6 @@ class SafetyLayer:
|
||||
if self.mode == MODE_UNRESTRICTED:
|
||||
return True, ""
|
||||
|
||||
# 检查是否是始终需要确认的指令
|
||||
args_lower = tool_args.strip().lower()
|
||||
for (t, pattern) in ALWAYS_CONFIRM:
|
||||
if tool_name == t and args_lower.startswith(pattern.split(" ", 1)[1] if " " in pattern else ""):
|
||||
return self._ask_user_confirm(
|
||||
tool_name, tool_args,
|
||||
risk_level="高",
|
||||
impact="此操作始终需要人工确认",
|
||||
reason="敏感指令"
|
||||
)
|
||||
|
||||
# 人工确认模式:所有指令都确认
|
||||
if self.mode == MODE_MANUAL:
|
||||
return self._ask_user_confirm(
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
"""
|
||||
统一工具返回格式 - ToolResult
|
||||
|
||||
所有插件和工具管理器使用统一的返回格式,
|
||||
替代原来混乱的字符串/Dict 返回。
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Optional
|
||||
|
||||
|
||||
# 错误码常量
|
||||
class ErrorCode:
|
||||
"""工具错误码"""
|
||||
SUCCESS = 0
|
||||
# 参数错误 (1xx)
|
||||
MISSING_ARGS = 100
|
||||
INVALID_ARGS = 101
|
||||
UNSUPPORTED_OP = 102
|
||||
# 资源错误 (2xx)
|
||||
NOT_FOUND = 200
|
||||
FILE_NOT_FOUND = 201
|
||||
PERMISSION_DENIED = 202
|
||||
# 执行错误 (3xx)
|
||||
EXEC_FAILED = 300
|
||||
TIMEOUT = 301
|
||||
DECODE_ERROR = 302
|
||||
# 系统错误 (4xx)
|
||||
INTERNAL_ERROR = 400
|
||||
NOT_IMPLEMENTED = 401
|
||||
|
||||
_NAMES = {
|
||||
0: "成功",
|
||||
100: "缺少参数",
|
||||
101: "参数无效",
|
||||
102: "不支持的操作",
|
||||
200: "未找到",
|
||||
201: "文件不存在",
|
||||
202: "权限不足",
|
||||
300: "执行失败",
|
||||
301: "超时",
|
||||
302: "解码错误",
|
||||
400: "内部错误",
|
||||
401: "未实现",
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def name(cls, code: int) -> str:
|
||||
return cls._NAMES.get(code, f"未知({code})")
|
||||
|
||||
|
||||
@dataclass
|
||||
class ToolResult:
|
||||
"""统一工具返回格式"""
|
||||
|
||||
success: bool
|
||||
data: Any = None
|
||||
error_code: int = ErrorCode.SUCCESS
|
||||
error_message: str = ""
|
||||
|
||||
# 可选元数据
|
||||
tool_name: str = ""
|
||||
execution_time: float = 0.0
|
||||
metadata: dict = field(default_factory=dict)
|
||||
|
||||
def __str__(self) -> str:
|
||||
if self.success:
|
||||
return str(self.data) if self.data is not None else "执行完成"
|
||||
return f"[{ErrorCode.name(self.error_code)}] {self.error_message}"
|
||||
|
||||
# ── 便捷构造方法 ──
|
||||
|
||||
@classmethod
|
||||
def ok(cls, data: Any = None, **kwargs) -> "ToolResult":
|
||||
"""成功"""
|
||||
return cls(success=True, data=data, **kwargs)
|
||||
|
||||
@classmethod
|
||||
def fail(cls, message: str, code: int = ErrorCode.EXEC_FAILED, **kwargs) -> "ToolResult":
|
||||
"""失败"""
|
||||
return cls(success=False, error_code=code, error_message=message, **kwargs)
|
||||
|
||||
@classmethod
|
||||
def missing(cls, what: str = "参数", **kwargs) -> "ToolResult":
|
||||
"""缺少参数"""
|
||||
return cls.fail(f"缺少{what}", ErrorCode.MISSING_ARGS, **kwargs)
|
||||
|
||||
@classmethod
|
||||
def not_found(cls, what: str = "资源", **kwargs) -> "ToolResult":
|
||||
"""未找到"""
|
||||
return cls.fail(f"{what}不存在", ErrorCode.NOT_FOUND, **kwargs)
|
||||
|
||||
@classmethod
|
||||
def timeout(cls, seconds: int = 0, **kwargs) -> "ToolResult":
|
||||
"""超时"""
|
||||
msg = f"执行超时"
|
||||
if seconds:
|
||||
msg += f" ({seconds}秒)"
|
||||
return cls.fail(msg, ErrorCode.TIMEOUT, **kwargs)
|
||||
|
||||
# ── 格式转换 ──
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
"""转为普通 dict(兼容旧接口)"""
|
||||
if self.success:
|
||||
return {"result": self.data if self.data is not None else "执行完成"}
|
||||
return {"result": str(self)}
|
||||
|
||||
def to_mcp(self) -> dict:
|
||||
"""转为 MCP 协议格式"""
|
||||
text = str(self)
|
||||
return {
|
||||
"content": [{"type": "text", "text": text}],
|
||||
"isError": not self.success,
|
||||
}
|
||||
|
||||
def to_string(self) -> str:
|
||||
"""转为字符串(兼容旧插件 handle() 返回值)"""
|
||||
return str(self)
|
||||
+37
-13
@@ -406,6 +406,23 @@ if TEXTUAL_AVAILABLE:
|
||||
self._running = False
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════
|
||||
# 自定义 TextArea:回车发送,Shift+回车换行
|
||||
# ═══════════════════════════════════════════════════
|
||||
|
||||
class SendTextArea(TextArea):
|
||||
"""回车发送消息,Shift+回车换行的输入框"""
|
||||
async def _on_key(self, event):
|
||||
if event.key in ("enter", "\r", "\n"):
|
||||
# prevent_default 阻止父类 TextArea._on_key 执行
|
||||
event.prevent_default()
|
||||
try:
|
||||
self.app.action_send_message()
|
||||
except Exception:
|
||||
pass
|
||||
return
|
||||
# 其他键正常处理
|
||||
|
||||
# ═══════════════════════════════════════════════════
|
||||
# TUI 主应用
|
||||
# ═══════════════════════════════════════════════════
|
||||
@@ -420,7 +437,8 @@ if TEXTUAL_AVAILABLE:
|
||||
Binding("ctrl+c", "quit", "退出", show=True),
|
||||
Binding("ctrl+l", "clear", "清屏", show=True),
|
||||
Binding("ctrl+n", "new_chat", "新对话", show=True),
|
||||
Binding("ctrl+enter", "send_message", "发送", show=True),
|
||||
Binding("ctrl+enter", "send_message", "发送", show=False),
|
||||
Binding("shift+enter", "newline", "换行", show=False),
|
||||
Binding("f1", "toggle_sidebar", "侧栏", show=True),
|
||||
Binding("escape", "cancel", "取消", show=False),
|
||||
]
|
||||
@@ -442,14 +460,14 @@ if TEXTUAL_AVAILABLE:
|
||||
yield VerticalScroll(id="chat-scroll")
|
||||
with Vertical(id="input-area"):
|
||||
with Container(id="input-wrapper"):
|
||||
yield TextArea(
|
||||
placeholder="输入消息... (Ctrl+Enter 发送, Enter 换行)",
|
||||
yield SendTextArea(
|
||||
placeholder="输入消息... (回车发送, Shift+回车换行)",
|
||||
id="user-input",
|
||||
soft_wrap=True,
|
||||
tab_behavior="indent",
|
||||
)
|
||||
yield Static(
|
||||
" Ctrl+Enter 发送 | ↑↓ 历史 | Ctrl+L 清屏 | F1 侧栏 | Tab 缩进",
|
||||
" 回车发送 | Shift+回车换行 | Ctrl+L 清屏 | F1 侧栏",
|
||||
id="input-hint"
|
||||
)
|
||||
with Vertical(id="sidebar"):
|
||||
@@ -480,7 +498,7 @@ if TEXTUAL_AVAILABLE:
|
||||
"",
|
||||
" ╔══════════════════════════════════════════════╗",
|
||||
" ║ ║",
|
||||
" ║ 小狸 Pro-CLI v5.4 ║",
|
||||
" ║ 小狸 Pro-CLI v5.4.1 ║",
|
||||
" ║ 智能编程助手 · 动画增强版 ║",
|
||||
" ║ ║",
|
||||
" ╚══════════════════════════════════════════════╝",
|
||||
@@ -488,7 +506,7 @@ if TEXTUAL_AVAILABLE:
|
||||
" 代码编辑 · 代码搜索 · Git 集成 · 多引擎",
|
||||
" 输入 /help 查看命令 | /model 切换引擎",
|
||||
f" 当前引擎: {self.bridge.current_engine()} | 工具: {len(self.bridge.tools())} 个",
|
||||
" 支持多行输入 — Ctrl+Enter 发送",
|
||||
" 支持多行输入 — Shift+回车换行",
|
||||
"",
|
||||
]
|
||||
|
||||
@@ -524,7 +542,7 @@ if TEXTUAL_AVAILABLE:
|
||||
("", "msg-dim"),
|
||||
(" ╔══════════════════════════════════════════════╗", "msg-welcome"),
|
||||
(" ║ ║", "msg-welcome"),
|
||||
(" ║ 小狸 Pro-CLI v5.4 ║", "msg-welcome"),
|
||||
(" ║ 小狸 Pro-CLI v5.4.1 ║", "msg-welcome"),
|
||||
(" ║ 智能编程助手 · 动画增强版 ║", "msg-welcome"),
|
||||
(" ║ ║", "msg-welcome"),
|
||||
(" ╚══════════════════════════════════════════════╝", "msg-welcome"),
|
||||
@@ -532,7 +550,7 @@ if TEXTUAL_AVAILABLE:
|
||||
(" 代码编辑 · 代码搜索 · Git 集成 · 多引擎", "msg-system"),
|
||||
(" 输入 /help 查看命令 | /model 切换引擎", "msg-system"),
|
||||
(f" 当前引擎: {self.bridge.current_engine()} | 工具: {len(self.bridge.tools())} 个", "msg-system"),
|
||||
(" 支持多行输入 — Ctrl+Enter 发送", "msg-system"),
|
||||
(" 支持多行输入 — Shift+回车换行", "msg-system"),
|
||||
("", "msg-dim"),
|
||||
]
|
||||
for text, cls in lines:
|
||||
@@ -670,8 +688,14 @@ if TEXTUAL_AVAILABLE:
|
||||
|
||||
# ── 多行输入处理 ──
|
||||
|
||||
def action_newline(self):
|
||||
"""Shift+Enter 在输入框插入换行"""
|
||||
text_area = self.query_one("#user-input")
|
||||
if text_area.has_focus:
|
||||
text_area.action_edit_insert_newline()
|
||||
|
||||
def action_send_message(self):
|
||||
"""Ctrl+Enter 发送消息"""
|
||||
"""回车发送消息"""
|
||||
text_area = self.query_one("#user-input")
|
||||
text = text_area.text.strip()
|
||||
if not text:
|
||||
@@ -719,7 +743,7 @@ if TEXTUAL_AVAILABLE:
|
||||
'cls': lambda: self.action_clear(),
|
||||
'model': lambda: self._switch_model(args),
|
||||
'engine': lambda: self._switch_model(args),
|
||||
'about': lambda: self._system(" 小狸 Pro-CLI v5.4 - 智能编程助手"),
|
||||
'about': lambda: self._system(" 小狸 Pro-CLI v5.4.1 - 智能编程助手"),
|
||||
'status': lambda: self._show_status(),
|
||||
'tools': lambda: self._show_tools(),
|
||||
'engines': lambda: self._show_engines(),
|
||||
@@ -754,9 +778,9 @@ if TEXTUAL_AVAILABLE:
|
||||
|
||||
⌨ 快捷键:
|
||||
Ctrl+C 退出 Ctrl+L 清屏
|
||||
Ctrl+N 新对话 Ctrl+Enter 发送消息
|
||||
F1 侧栏 Escape 取消生成
|
||||
Enter 换行 Tab 缩进"""
|
||||
Ctrl+N 新对话 回车 发送消息
|
||||
Shift+回车 换行 F1 侧栏
|
||||
Escape 取消生成 Tab 缩进"""
|
||||
self._system(help_text)
|
||||
|
||||
def _handle_manual(self, args):
|
||||
|
||||
Reference in new issue
Block a user