""" 内置工具:shell 与 python_run。 为什么要内置,而不是直接复用 tools/shell.py、tools/python_run.py: * 那两个文件是"子进程 + 解释器"模型:`python tool.py --input x.json`, 安卓上根本没有独立的 python 可执行文件(唯一解释器就在 Kern 进程里), 所以必须把这两个能力做成进程内实现。 * 内置版本在工具发现阶段**优先于同名文件工具**(和"安卓端优先"的取舍一致), 用户在 tools/ 里放自己的 shell.py 也不会把内核搞挂。 安全说明:python_run 在**内核进程内** exec 用户代码,这是安卓端的必然取舍 (没有子进程可以隔离)。因此只保留超时(线程 + 放弃)和 stdout/stderr 捕获, 真正要沙箱只能靠 settings.security.mode = restricted 的白名单。 """ import builtins import contextlib import importlib.util import io import os import platform import subprocess import sys import threading import time import traceback import paths # --------------------------------------------------------------------------- # # 工具定义(与 tools/shell.py、tools/python_run.py 的 TOOL 完全一致, # 这样模型看到的 description / parameters 在两端一模一样) # --------------------------------------------------------------------------- # SHELL_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'], }, } PYTHON_RUN_TOOL = { 'name': 'python_run', 'description': ( '运行一段 Python 代码或指定 .py 文件,返回标准输出/错误。' '适合做计算、数据处理、调用网络接口(requests/httpx/urllib 可用)。' 'action=libs 可以查看当前环境装了哪些库。' ), 'parameters': { 'type': 'object', 'properties': { 'action': { 'type': 'string', 'enum': ['run', 'libs'], 'description': 'run=执行代码/文件(默认);libs=列出可用库', }, 'code': {'type': 'string', 'description': '要执行的 Python 代码(action=run 时二选一)'}, 'file': {'type': 'string', 'description': '要执行的 .py 文件路径(action=run 时二选一)'}, 'stdin': {'type': 'string', 'description': '传给脚本的标准输入,可留空'}, 'timeout': {'type': 'number', 'description': '超时秒数,默认 60,最大 600'}, }, }, } # 明显会搞坏机器的模式(可用 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:\\', ] # python_run action=libs 里检查的常用库 WATCHED = [ 'requests', 'httpx', 'aiohttp', 'urllib3', 'bs4', 'lxml', 'pandas', 'numpy', 'PIL', 'openpyxl', 'docx', 'pptx', 'yaml', 'dotenv', 'mcp', 'flask', 'fastapi', ] # 进程内 exec 会临时切换 cwd(Python 没有"给这段代码单独设 cwd"的机制), # 加锁只是为了让切换尽量短,不能解决并发请求看到临时 cwd 的问题,故在此说明。 _cwd_lock = threading.Lock() @contextlib.contextmanager def _redirect_stdin(buffer): """标准库只有 redirect_stdout/redirect_stderr,没有 redirect_stdin,只能自己换。""" saved = sys.stdin sys.stdin = buffer try: yield buffer finally: sys.stdin = saved # --------------------------------------------------------------------------- # # shell # --------------------------------------------------------------------------- # def shell_run(args: dict) -> dict: command = str(args.get('command') or '').strip() if not command: raise ValueError('command 不能为空') if len(command) > 4000: raise ValueError('命令过长') if os.environ.get('DOUBAO_SHELL_UNSAFE') != '1': 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') or 30))) cwd = args.get('cwd') or None if cwd and not os.path.isdir(cwd): raise ValueError(f'工作目录不存在:{cwd}') if paths.IS_WINDOWS: argv = ['cmd', '/c', command] else: # 安卓系统里 /bin/sh 通常存在(是 /system/bin/sh 的软链),没有就退回真实路径 shell = '/bin/sh' if os.path.exists('/bin/sh') else '/system/bin/sh' argv = [shell, '-c', command] try: proc = subprocess.run( argv, cwd=cwd, capture_output=True, timeout=timeout, text=True, errors='replace', ) except subprocess.TimeoutExpired: return {'error': f'命令超时({timeout}s)', 'timeout': True} except OSError as exc: # 安卓上可能完全没有可执行权限/没有 shell,这里要给模型一个能读懂的原因 raise RuntimeError(f'无法启动命令({argv[0]}):{exc}') from exc return { 'exit_code': proc.returncode, 'stdout': (proc.stdout or '')[-8000:], 'stderr': (proc.stderr or '')[-4000:], 'platform': f'{platform.system()} {platform.release()}', } # --------------------------------------------------------------------------- # # python_run # --------------------------------------------------------------------------- # def _libs_report() -> dict: available, missing = [], [] for name in WATCHED: try: found = importlib.util.find_spec(name) is not None except (ImportError, ValueError): found = False (available if found else missing).append(name) return { 'python': sys.version.split()[0], 'executable': sys.executable or '<进程内>', 'available': available, 'missing': missing, 'hint': '缺库时可以用 shell 工具执行 pip install <包名>' if missing else '常用库齐全', } def _exec_source(source: str, filename: str, cwd: str, stdin_text: str) -> tuple: """ 在进程内执行 Python 源码,返回 (exit_code, stdout, stderr)。 - stdout/stderr 用 contextlib.redirect_* 捕获; - sys.exit()/SystemExit 的 code 当作退出码; - 其它异常打印完整 traceback 到 stderr(模型据此自我修正); - cwd 临时切到脚本目录,跑完恢复(Python 没有更细粒度的办法)。 """ out_buf, err_buf = io.StringIO(), io.StringIO() namespace = { '__name__': '__main__', '__file__': filename, '__builtins__': builtins, '__doc__': None, '__package__': None, } exit_code = 0 def _work(): nonlocal exit_code try: code_obj = compile(source, filename, 'exec') except SyntaxError: traceback.print_exc(file=err_buf) exit_code = 1 return try: exec(code_obj, namespace) # noqa: S102 - 这就是本工具存在的意义 except SystemExit as exc: value = exc.code exit_code = 0 if value is None else (value if isinstance(value, int) else 1) except BaseException: # noqa: BLE001 - 用户代码什么都能抛,包括 KeyboardInterrupt traceback.print_exc(file=err_buf) exit_code = 1 saved_cwd = os.getcwd() changed = bool(cwd) and os.path.isdir(cwd) and os.path.abspath(cwd) != os.path.abspath(saved_cwd) # 注意:redirect_stdout/stderr 和 chdir 都是"进程级"的(Python 没有线程级实现), # 因此在同一进程里并发跑 python_run 时,另一个请求的 print 也可能被收进本次结果。 # 安卓上内核是单用户本地服务,这个代价可以接受;桌面/服务器场景请改用独立进程。 with contextlib.ExitStack() as stack: stack.enter_context(contextlib.redirect_stdout(out_buf)) stack.enter_context(contextlib.redirect_stderr(err_buf)) # 标准库里没有 redirect_stdin(只有 stdout/stderr),只能自己换 sys.stdin: # Node 版是靠子进程的 stdin 参数,安卓上没子进程,这里就是等价实现。 stack.enter_context(_redirect_stdin(io.StringIO(stdin_text or ''))) try: if changed: with _cwd_lock: os.chdir(cwd) _work() finally: if changed: with _cwd_lock: os.chdir(saved_cwd) return exit_code, out_buf.getvalue(), err_buf.getvalue() def run_with_timeout(fn, timeout_s: float): """ 线程 + join(timeout) 实现超时。 为什么不用 signal.alarm / SIGALRM:安卓主线程之外信号不可用, 而且 CPython 根本杀不掉一个正在跑的线程。超时后我们只能"放弃等待", 被放弃的线程会继续在后台跑完(daemon 线程,不阻塞进程退出)。 这个取舍必须让用户知道,所以超时消息里写清楚。 """ box = {} def worker(): try: box['value'] = fn() except BaseException as exc: # noqa: BLE001 - 转成错误对象回主线程 box['error'] = exc thread = threading.Thread(target=worker, name='doubao-python-run', daemon=True) thread.start() thread.join(timeout_s) if thread.is_alive(): return None if 'error' in box: raise box['error'] return box.get('value') def python_run(args: dict) -> dict: action = str(args.get('action') or 'run').lower() if action == 'libs': return _libs_report() code = args.get('code') file_path = args.get('file') if not code and not file_path: raise ValueError('code 和 file 至少要给一个') timeout = max(1, min(600, int(args.get('timeout') or 60))) stdin_text = args.get('stdin') or '' if file_path: target = str(file_path) if not os.path.isfile(target): raise ValueError(f'文件不存在:{target}') with open(target, 'r', encoding='utf-8', errors='replace') as fh: source = fh.read() filename = os.path.abspath(target) cwd = os.path.dirname(filename) else: source = str(code) # 用与安卓缓存目录同级的位置当"脚本目录",避免把临时文件写进只读的 assets filename = os.path.join(paths.get().tmp_dir, f'doubao_run_{int(time.time() * 1000)}.py') cwd = paths.get().tmp_dir result = run_with_timeout( lambda: _exec_source(source, filename, cwd, stdin_text), timeout, ) if result is None: return { 'error': f'执行超时({timeout}s)', 'timeout': True, 'note': '进程内执行无法强杀线程,被放弃的代码可能仍在后台运行', } exit_code, stdout_text, stderr_text = result return { 'exit_code': exit_code, 'stdout': stdout_text[-12000:], 'stderr': stderr_text[-6000:], } # --------------------------------------------------------------------------- # # 注册表 # --------------------------------------------------------------------------- # BUILTIN_TOOLS = { 'shell': {'spec': SHELL_TOOL, 'run': shell_run}, 'python_run': {'spec': PYTHON_RUN_TOOL, 'run': python_run}, }