""" 工具运行时:发现、过滤、执行。 对应 Node 版 server/src/python-tools.mjs + agent.mjs 里的工具部分。 ★ 最重要的安卓取舍:用 importlib 直接 import 工具模块,绝不用 subprocess 调 python。 Node 版是 `python tool.py --spec` / `python tool.py --input args.json`, 因为桌面上一定有解释器。安卓(Chaquopy)里**没有独立的 python 可执行文件**, 解释器只存在于本进程内,spawn('python') 一定 ENOENT。 所以这里改成: importlib.util.spec_from_file_location(...) → exec_module → 取模块的 TOOL(工具描述)和 run(执行函数) 代价是工具代码和内核同进程(崩溃会一起死、全局状态会互相影响), 但对"安卓上必须能跑"这个目标,这是唯一可行的路。 """ import importlib.util import json import os import re import sys import threading import mcp_client import paths from builtin_tools import BUILTIN_TOOLS, run_with_timeout # 文件工具的缓存:path -> {'mtime':..., 'spec':..., 'error':...} _spec_cache: dict = {} _cache_lock = threading.Lock() # 已经 import 过的模块名(重载时要先从 sys.modules 里摘掉) _loaded_modules: dict = {} TOOL_TIMEOUT_S = 60 BUILTIN_FILE_LABEL = '<内置>' # --------------------------------------------------------------------------- # # 目录与文件 # --------------------------------------------------------------------------- # def tools_dir() -> str: """ 工具目录:settings.toolsDir 优先(安卓端指到手机上的目录), 否则用内置 tools/(--tools-dir / DOUBAO_TOOLS 指定)。 """ import store # 局部导入:store 不依赖本模块,但放在顶部会让 import 顺序更难读 custom = (store.read_settings() or {}).get('toolsDir') if custom and os.path.isdir(custom): return os.path.abspath(custom) return paths.get().tools_dir def python_files() -> list: folder = tools_dir() if not os.path.isdir(folder): return [] # 排序:Node 那边 readdir 在 NTFS 上正好是字典序,这里显式排序保证工具顺序稳定 names = sorted( n for n in os.listdir(folder) if n.endswith('.py') and not n.startswith('_') ) return [os.path.join(folder, n) for n in names] # --------------------------------------------------------------------------- # # 导入工具模块 # --------------------------------------------------------------------------- # def _import_tool_module(file_path: str, folder: str): """ 用 importlib 按文件路径导入工具模块。 要点: * 模块名带 `_doubao_tool_` 前缀 + 文件名哈希,避免和内核自己的模块重名; * 把工具目录插进 sys.path —— tools/*.py 里有 `from _protocol import serve`, 它们自己也会 insert 一次,但我们先插好更稳(顺序:我们自己在前); * 重新 import 前先 sys.modules.pop,否则拿到的是改了文件也没更新的旧模块。 """ stem = os.path.splitext(os.path.basename(file_path))[0] safe_stem = re.sub(r'\W', '_', stem) mod_name = f'_doubao_tool_{safe_stem}_{abs(hash(os.path.abspath(file_path))) % 100000}' old = _loaded_modules.get(file_path) if old and old in sys.modules: sys.modules.pop(old, None) if folder and folder not in sys.path: sys.path.insert(0, folder) spec = importlib.util.spec_from_file_location(mod_name, file_path) if spec is None or spec.loader is None: raise ImportError(f'无法为 {file_path} 建立模块 spec') module = importlib.util.module_from_spec(spec) sys.modules[mod_name] = module try: spec.loader.exec_module(module) except BaseException: sys.modules.pop(mod_name, None) raise _loaded_modules[file_path] = mod_name return module def _spec_from_module(module, file_path: str) -> dict: tool = getattr(module, 'TOOL', None) if not isinstance(tool, dict) or not tool.get('name'): raise ValueError('模块里没有合法的 TOOL(需要 {name, description, parameters})') if not callable(getattr(module, 'run', None)): raise ValueError('模块里没有可调用的 run(args)') spec = dict(tool) spec.setdefault('description', spec['name']) spec.setdefault('parameters', {'type': 'object', 'properties': {}}) spec['file'] = os.path.basename(file_path) spec['_path'] = file_path return spec def _builtin_spec(name: str, file_path: str = '') -> dict: """ 内置工具的工具描述。 file 字段:如果工具目录里存在同名文件(例如 tools/shell.py),就沿用它的文件名, 这样 /api/state 的 python.tools 和 Node 版逐字段一致(前端 Skills 页显示的就是它); 找不到同名文件时才写 <内置>。另外附一个 builtin=true 供调试识别(前端不读它)。 """ entry = BUILTIN_TOOLS[name] spec = dict(entry['spec']) spec['file'] = os.path.basename(file_path) if file_path else BUILTIN_FILE_LABEL spec['builtin'] = True spec['_path'] = '' spec['_builtin'] = True return spec def discover_python_tools(force: bool = False) -> dict: """ 扫描并加载全部 Python 工具。 返回 {'tools': [...], 'errors': [{'file','error'}], 'python': {'bin','prefix'}|None} 语义与 Node 版 discoverPythonTools 一致;区别是用 import 代替子进程 --spec。 """ folder = tools_dir() files = python_files() tools, errors = [], [] emitted_builtins = set() for file_path in files: try: mtime = os.path.getmtime(file_path) except OSError as exc: errors.append({'file': os.path.basename(file_path), 'error': f'无法读取文件:{exc}'}) continue with _cache_lock: cached = _spec_cache.get(file_path) if not force and cached and cached.get('mtime') == mtime: spec, error, module = cached.get('spec'), cached.get('error'), cached.get('module') else: spec, error, module = None, None, None try: module = _import_tool_module(file_path, folder) spec = _spec_from_module(module, file_path) except BaseException as exc: # noqa: BLE001 - 单个工具坏掉不能拖垮内核 module = None error = f'{type(exc).__name__}: {exc}' with _cache_lock: # 缓存里同时留着模块对象:执行时不必再 import 一遍 _spec_cache[file_path] = {'mtime': mtime, 'spec': spec, 'error': error, 'module': module} if error: errors.append({'file': os.path.basename(file_path), 'error': str(error)[:400]}) continue if not spec: continue name = spec.get('name') # 内置工具优先:同名文件工具被替换(安卓上 shell/python_run 必须走进程内实现), # 但 file 字段仍沿用同名文件,保持和 Node 版一致的用户可见信息 if name in BUILTIN_TOOLS: tools.append(_builtin_spec(name, file_path)) emitted_builtins.add(name) else: tools.append(spec) # 文件目录里没有、但内置提供的工具(比如用户把 tools/ 指到空目录) for name in BUILTIN_TOOLS: if name not in emitted_builtins: tools.append(_builtin_spec(name)) return { 'tools': tools, 'errors': errors, 'python': {'bin': sys.executable or '<进程内>', 'prefix': []}, } def _find_entry(name: str): """按名字找工具(内置优先),返回 (spec, module);找不到返回 (None, None)。""" if name in BUILTIN_TOOLS: file_path = '' for candidate in python_files(): if os.path.splitext(os.path.basename(candidate))[0] == name: file_path = candidate break return _builtin_spec(name, file_path), None found = discover_python_tools() for spec in found['tools']: if spec.get('name') == name: file_path = spec.get('_path') or '' with _cache_lock: module = (_spec_cache.get(file_path) or {}).get('module') if module is None and file_path: # 缓存里没模块(进程重启 / force 刷新过),重新 import 一次 module = _import_tool_module(file_path, os.path.dirname(file_path)) return spec, module return None, None # --------------------------------------------------------------------------- # # 执行 # --------------------------------------------------------------------------- # def run_python_tool(name: str, args: dict) -> dict: """ 执行一个进程内工具,返回 {'ok':bool, 'result':..., 'error':...}。 结构与 Node 版 runPythonTool 的返回值保持兼容。 """ spec, module = _find_entry(name) if not spec: raise RuntimeError(f'没有名为 {name} 的 Python 工具') if spec.get('_builtin'): runner = BUILTIN_TOOLS[name]['run'] else: if module is None: raise RuntimeError(f'工具 {name} 的模块已失效,请重新加载') runner = getattr(module, 'run') payload = args if isinstance(args, dict) else {} try: # 进程内执行同样加超时:工具里死循环时至少让对话能返回错误,而不是整个内核卡死 outcome = run_with_timeout(lambda: runner(payload), TOOL_TIMEOUT_S) except BaseException as exc: # noqa: BLE001 - 工具抛错要当成"工具失败",不是接口 500 # 与 Node 版一致:_protocol 把异常转成 {"ok":false,"error":"ValueError: xxx"}, # 这里在进程内直接捕获,格式保持一致(前端/模型看到的东西不变)。 return {'ok': False, 'error': f'{type(exc).__name__}: {exc}'} if outcome is None: return {'ok': False, 'error': f'工具执行超时({TOOL_TIMEOUT_S}s)'} result = outcome # 工具可以像 _protocol 那样返回 {"ok":..,"result":..},也可以直接返回业务结果 if isinstance(result, dict) and 'ok' in result: return { 'ok': bool(result.get('ok')), 'result': result.get('result'), 'error': result.get('error'), } return {'ok': True, 'result': result} def to_openai_tool(spec: dict) -> dict: """转成 OpenAI tools 定义(与 Node 版 toOpenAITool 一致)。""" return { 'type': 'function', 'function': { 'name': spec.get('name'), 'description': spec.get('description') or spec.get('name'), 'parameters': spec.get('parameters') or {'type': 'object', 'properties': {}}, }, } def public_spec(spec: dict) -> dict: """去掉内部字段(下划线开头),得到能直接塞进 JSON 响应的工具描述。""" return {k: v for k, v in spec.items() if not k.startswith('_')} def dump_specs_json(specs: list) -> str: """调试用:把工具描述打成 JSON(避免直接 print 中文在窄编码终端炸掉)。""" return json.dumps([public_spec(s) for s in specs], ensure_ascii=False, indent=2) # --------------------------------------------------------------------------- # # 汇总 / 安全模式 # --------------------------------------------------------------------------- # def list_all_tools(settings: dict) -> dict: """汇总当前可用的全部工具(Python + MCP),与 Node 版 listAllTools 对齐。""" out = {'python': [], 'mcp': [], 'errors': [], 'pythonInfo': None} if (settings.get('tools') or {}).get('python', True) is not False: res = discover_python_tools() out['python'] = res['tools'] out['errors'] = res['errors'] out['pythonInfo'] = res['python'] if (settings.get('tools') or {}).get('mcp', True) is not False: out['mcp'] = mcp_client.mcp_tool_defs() return out # 只读工具的名字特征,用来给"限制模式"生成一份保守的默认白名单 READONLY_NAME = re.compile( r'^(read|list|get|search|open|find|fetch|show|describe|query|inspect|calc|now|web_fetch)', re.IGNORECASE, ) def suggest_allowlist(tool_names: list) -> list: return [n for n in tool_names if READONLY_NAME.match((n.split('__') or [n])[-1] or n)] def apply_security(defs: list, settings: dict) -> list: """按安全模式过滤工具定义(restricted 时只留白名单)。""" mode = (settings.get('security') or {}).get('mode') or 'open' if mode != 'restricted': return defs allow = set((settings.get('security') or {}).get('allow') or []) return [d for d in defs if d.get('function', {}).get('name') in allow] def node_tool_defs(settings: dict) -> list: """ 会议里的 **Python 节点**当工具用。 ★ 用户要求"智能体可以调用节点工具":在会议里写一个 Python 节点、 在智能体节点上勾选它,这个智能体就能调用那段代码。 为什么走 settings 而不是直接传会议:工具定义是在 agent_loop 里 统一组装的(它只拿得到 settings),把节点工具塞进 settings 是最短的路径 —— 也为的是**只有一份组装逻辑**(分成两处就会像之前几次那样, 改了这边忘了那边)。 """ defs = [] for t in (settings or {}).get('nodeTools') or []: name = str(t.get('name') or '').strip() if not name: continue defs.append({ 'type': 'function', 'function': { 'name': name, 'description': str(t.get('description') or '会议里的自定义 Python 工具'), 'parameters': { 'type': 'object', 'properties': { 'input': { 'type': 'string', 'description': '传给这个工具的文本输入', }, }, 'required': [], }, }, }) return defs def node_tool_names(settings: dict) -> set: return {str(t.get('name')) for t in ((settings or {}).get('nodeTools') or [])} def run_node_tool(name: str, args: dict, settings: dict) -> dict: """执行一个会议节点工具""" for t in (settings or {}).get('nodeTools') or []: if str(t.get('name')) != name: continue import meeting as meeting_mod variables = t.get('variables') or {} logs = [] out, err = meeting_mod.run_py_node( t.get('code') or '', str((args or {}).get('input') or ''), variables, t.get('node') or {}, logs, ) if err: return {'ok': False, 'error': err} return {'ok': True, 'output': out, 'logs': logs} return {'ok': False, 'error': f'没有这个节点工具:{name}'} def build_tool_defs(settings: dict) -> list: all_tools = list_all_tools(settings) defs = [to_openai_tool(t) for t in all_tools['python']] + list(all_tools['mcp']) # 会议里的 Python 节点工具并进来(受限模式也走同一个白名单) defs = defs + node_tool_defs(settings) return apply_security(defs, settings) def execute_tool(name: str, args: dict, settings: dict) -> dict: """ 执行任意工具(Python 或 MCP)。 限制模式下即使模型硬编出工具名也不能执行(第二道拦截,与 Node 版一致)。 """ if ((settings or {}).get('security') or {}).get('mode', 'open') == 'restricted': allow = ((settings or {}).get('security') or {}).get('allow') or [] if name not in allow: return {'ok': False, 'error': f'限制模式:工具 {name} 未授权'} # 会议节点工具优先(它是这次会议里用户刚写的东西,不会有重名歧义) if name in node_tool_names(settings): return run_node_tool(name, args, settings) if mcp_client.is_mcp_tool(name): res = mcp_client.call_mcp_tool(name, args) parts = [] for item in (res or {}).get('content') or []: if item.get('type') == 'text': parts.append(item.get('text') or '') else: parts.append(f"[{item.get('type')}]") return {'ok': not (res or {}).get('isError'), 'result': '\n'.join(parts) or '(空结果)'} return run_python_tool(name, args)