"""终端工具:在系统 shell 里执行命令,拿回 stdout/stderr。 - Windows 走 cmd /c,Linux/macOS/Android 走 /bin/sh -c - 有超时和一份最小黑名单(防止一条命令把机器搞没) - 想放开限制:把环境变量 DOUBAO_SHELL_UNSAFE=1 打开(或在设置里关掉限制模式) """ import os import platform import subprocess import sys sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from _protocol import serve # noqa: E402 TOOL = { "name": "shell", "description": ( "在用户电脑/手机的终端里执行一条 shell 命令,返回退出码、标准输出和标准错误。" "适合查看文件、跑脚本、装依赖、查系统信息。危险命令会被拦截。" ), "parameters": { "type": "object", "properties": { "command": {"type": "string", "description": "要执行的命令,例如 ls -la 或 python --version"}, "cwd": {"type": "string", "description": "工作目录,可留空"}, "timeout": {"type": "number", "description": "超时秒数,默认 30,最大 300"}, }, "required": ["command"], }, } # 明显会搞坏机器的模式(可用 DOUBAO_SHELL_UNSAFE=1 关闭) BLOCKED = [ "rm -rf /", "rm -rf /*", "mkfs", "dd if=/dev/zero", ":(){:|:&};:", "shutdown", "reboot", "format c:", "del /f /s /q c:\\", "rmdir /s /q c:\\", ] def run(args): command = str(args.get("command", "")).strip() if not command: raise ValueError("command 不能为空") if len(command) > 4000: raise ValueError("命令过长") unsafe = os.environ.get("DOUBAO_SHELL_UNSAFE") == "1" if not unsafe: lowered = command.lower() for bad in BLOCKED: if bad in lowered: raise ValueError(f"命令命中黑名单({bad}),已拒绝执行。确实需要请设置 DOUBAO_SHELL_UNSAFE=1") timeout = max(1, min(300, int(args.get("timeout", 30) or 30))) cwd = args.get("cwd") or None if cwd and not os.path.isdir(cwd): raise ValueError(f"工作目录不存在:{cwd}") system = platform.system().lower() if system == "windows": # ★ Windows 的 cmd 默认用 GBK 输出,直接按 UTF-8 解会变乱码、按 GBK 解又和后端不一致。 # 这里强制切到 65001(UTF-8) 再执行,后面统一按 UTF-8 解码。 argv = ["cmd", "/c", f"chcp 65001 >nul && {command}"] encoding = "utf-8" via = "cmd" else: argv = ["/bin/sh", "-c", command] encoding = "utf-8" via = "sh" if os.path.exists("/system/bin/sh") or "ANDROID_ROOT" in os.environ: via = "toybox" try: proc = subprocess.run( argv, cwd=cwd, capture_output=True, timeout=timeout, text=True, encoding=encoding, errors="replace", ) except subprocess.TimeoutExpired: return {"error": f"命令超时({timeout}s)", "timeout": True} return { "exit_code": proc.returncode, "stdout": (proc.stdout or "")[-8000:], "stderr": (proc.stderr or "")[-4000:], "platform": f"{platform.system()} {platform.release()}", "via": via, } if __name__ == "__main__": serve(TOOL, run)