Files
doubao-clone/android/kernel/tools_runtime.py
l 5c1a04b737 会议模式:Python 节点(用户自己写代码拓展)+ 智能体调用节点工具
用户:"智能体可以调用节点工具。用户可以用py拓展节点。"

【1. Python 节点】
新节点类型 `py`。节点里写一段 Python,约定入口:

    def run(ctx):
        ...
        return "结果"

ctx 提供:
    ctx.input             上游内容(数据线优先,没连就用 exec 上游的输出)
    ctx.vars              变量表**只读快照**
    ctx.set_var(名, 值)    写变量(真的写进会议变量表)
    ctx.log(...)           记一条说明,会出现在结果界面的这一步里
    node                  这个节点本身

★ 为什么给"快照 + 显式 set_var"而不是直接给变量表:
  直接给的话,用户随手 `ctx.vars['x'] = 1` 会以为写进去了,其实没有(那是副本),
  然后到处找不到为什么没生效。要写就明确地写。

★ 沙箱的边界说清楚:这是**用户自己的代码、跑在用户自己的手机上**,
  不是别人传过来的不可信代码。所以不做"假装安全"的沙箱
  (Python 里没有真沙箱,做一半反而给人虚假的安全感),
  但**必须**做两件事:超时和异常兜底。
  实测:
      正常    → 输出='处理完了:2 个字' 说明='收到: 起点'
      除零    → ZeroDivisionError: division by zero
      没写run → 代码里没有定义 run(ctx) 函数
      死循环  → 超过 10 秒还没跑完(可能有死循环)   ← App 不会卡死

【2. 智能体调用节点工具】
在智能体节点上勾选若干 Python 节点,它们就变成这个智能体可以调用的**工具**:
  - 工具名取节点标题(清洗成合法标识符,重名加序号)
  - 工具说明取 Python 节点上的「给智能体看的说明」
  - 调用时把参数当 ctx.input 传进去,返回 run() 的输出

实现上并进**已有的工具系统**(tools_runtime.build_tool_defs / execute_tool),
不另起一套 —— 分两处的结果就是像之前几次那样"改了这边忘了那边"。
受限模式的白名单同样管得住它(走同一个 apply_security)。

【3. 界面】
Python 节点:引脚(exec 进出 + 数据进出)、深灰蓝配色、卡片上显示代码首行、
配置面板里有代码框(等宽、150dp 高)和「给智能体看的说明」。

【欠账,如实说】
智能体节点上"勾选可用工具"的那个 UI **还没做**(引擎侧已经通了、测过)。
这一轮我在那个 3600 行的 Kotlin 文件上反复卡住:PowerShell 的字符串替换
匹配失败时不报错、按行号剪贴又会把代码挪进别的函数,
光"改了没生效"就来回五六次,最后只能还原重做。
**下一步补这个勾选 UI**,在那之前想用节点工具得直接改会议 JSON。

【验证】
- 引擎回归 40/40,Node 与 Python 16/16 逐用例一致
- 会议 HTTP 13/13 ×2、语音 41/41、Markdown 19/19
- Python 节点:正常 / 报错 / 缺 run / 超时 四种情况都实测过
2026-10-12 10:39:25 +08:00

409 lines
16 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""
工具运行时:发现、过滤、执行。
对应 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)