Files
doubao-clone/android/kernel/tools_runtime.py
l 4850ea12af fix: "等用户的工具"要豁免 60 秒的工具执行超时(v2.0.44 的"不限时"只做了一半)
用户要求"AI 询问界面不要限时"。v2.0.44 改了界面侧(AiSurface 无限等)和
工具侧(ask_user 的 timeout 默认 0),但**漏了内核的工具执行超时**:

  实测:弹窗 135 秒确实还在,但工具调用在 60.0 秒返回
  {"ok":false,"error":"工具执行超时(60s)"} —— 用户后来点的选项根本
  回不到模型手里,模型已经拿着"超时"自己往下写了。

改动:
- builtin_tools.run_with_timeout:timeout_s <= 0 = 不限时(thread.join() 不带参)
- tools/ask_user.py、tools/show_ui.py:声明 WAIT_FOR_USER = True
- tools_runtime:新增 _waits_for_user(),会等用户的工具把超时预算设成 0;
  普通工具仍是 60 秒(死循环的安全网没丢)

验证(scripts/probe-ask-user-forever.py,真机跑):
  修之前 60.0 秒 → {"ok":false,"error":"工具执行超时(60s)"}
  修之后 66.2 秒 → {"ok":true,"result":{...,"choice":"B","timeout":false}}

守门:scripts/verify-ui-tools.py 新增一节(声明在不在、豁免逻辑在不在、
预算 0 是不是真的无限等、普通工具的 60 秒还在不在)。

文档:docs/AI界面能力.md 补"不限时要三处一起改"和客户端长连接为什么不断
(15 秒心跳 vs 120 秒 readTimeout)。

版本 2.0.45。
2026-10-16 09:42:13 +08:00

535 lines
22 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 = '<内置>'
# --------------------------------------------------------------------------- #
# 会"停下来等用户"的工具:执行超时对它们不适用
# --------------------------------------------------------------------------- #
#
# ★★ 这个坑很隐蔽,记下来:
#
# 用户要求"AI 询问界面不要限时",我把弹窗那侧改成了无限等(`AiSurface.ask`),
# 实测弹窗确实 135 秒还在 —— **但工具调用在 60 秒时就被内核判超时了**,
# 模型收到的是"工具执行超时(60s)",用户五分钟后点的那个选项**根本回不到
# 模型手里**。表现就是"弹窗还在、但 AI 已经自己往下写了"。
#
# 所以"不限时"必须**三处一起改**才算数:
# ① 界面侧等多久(AiSurface)
# ② 内核侧给工具多少时间(这里)
# ③ 工具自己声明的 timeout(tools/ask_user.py、tools/show_ui.py)
#
# 判定方式:工具模块里声明 `WAIT_FOR_USER = True`。
# 放在工具文件里而不是在这个列表里硬编码 —— 加新工具时不会漏(写工具的人
# 自己知道它会不会等用户)。
def _waits_for_user(name: str, spec: dict, module) -> bool:
"""这个工具会不会停下来等用户交互"""
if spec.get('_builtin'):
return bool((BUILTIN_TOOLS.get(name) or {}).get('WAIT_FOR_USER'))
return bool(getattr(module, 'WAIT_FOR_USER', False))
# --------------------------------------------------------------------------- #
# 界面工具的开关
# --------------------------------------------------------------------------- #
# 这些工具由 AI 主动驱动界面 / 主动说话,属于"会打扰用户"的能力,
# 所以**默认关**,用户要在「技能」页显式打开。名字要和 tools/ 下的文件名一致。
#
# ★ send_message 也在里面:它会让 AI **主动往对话里塞消息**(用户没说话它也说),
# 同样是打扰性能力。而且它带"顺手跑一轮回复"的选项,能让模型连锁调用自己 ——
# 默认开着的风险比前三个还大。
UI_TOOLS = ('show_ui', 'ask_user', 'end_conversation', 'send_message')
# 开关在 settings 里的位置。用嵌套 dict 而不是散落的顶层键,
# 以后加界面工具不必再动 settings 的形状。
UI_TOOL_SETTINGS_KEY = 'uiTools'
# --------------------------------------------------------------------------- #
# 当前调用上下文(线程局部)
# --------------------------------------------------------------------------- #
#
# ★ 为什么需要它:工具要拿到"当前是哪次对话"才能结束对话,但工具签名是
# run(args) —— 只有模型给的参数,没有对话信息。
#
# 已有先例是往 settings 里塞 `nodeTools`(会议节点工具),但那是**工具定义**,
# 不是**运行时上下文**;上下文每轮都在变,塞进 settings 会和"设置"的语义混在一起。
#
# 所以单独开一个 thread-local:agent_loop 在执行工具前 push,
# 执行完 pop。HTTP 是每请求一线程,thread-local 天然隔离,不会串。
_ctx = threading.local()
def push_context(**kw) -> None:
"""进入一次工具调用(agent_loop 在 execute_tool 前调用)"""
_ctx.value = dict(kw)
def clear_context() -> None:
_ctx.value = None
def current_context() -> dict:
"""当前工具调用的上下文;不在调用中时返回空 dict"""
return dict(getattr(_ctx, 'value', None) or {})
def ui_tools_enabled(settings: dict) -> bool:
"""
界面工具开了没有。
★ 默认 **False**:这三个工具会让 AI 主动弹界面/弹窗、甚至结束对话,
对用户是"打扰性"能力,不该装好就默认打开。
"""
box = (settings or {}).get(UI_TOOL_SETTINGS_KEY)
if isinstance(box, dict):
return box.get('enabled') is True
if isinstance(box, bool):
return box
return False
def filter_ui_tools(specs: list, settings: dict) -> list:
"""开关关着时,把界面工具从工具表里摘掉(模型根本看不到,也就不会调)。"""
if ui_tools_enabled(settings):
return specs
return [s for s in specs if s.get('name') not in UI_TOOLS]
# --------------------------------------------------------------------------- #
# 目录与文件
# --------------------------------------------------------------------------- #
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 {}
# ★★★ **先抓住当前线程的上下文**,因为 run_with_timeout 会在**另一个线程**里
# 跑工具,而 threading.local() 是**不跨线程继承**的 —— 不搬过去的话,
# 工作线程里 current_context() 永远是空的。
#
# 这个坑的表现特别隐蔽:工具照常执行(参数都对),只有"当前是哪次对话"
# 拿不到,于是 end_conversation 报"拿不到当前对话 id"。我一开始以为是
# app.py 没传 conversationId,查了一圈才发现是线程的问题。
ctx = current_context()
def _invoke():
if ctx:
_ctx.value = dict(ctx)
try:
return runner(payload)
finally:
if ctx:
_ctx.value = None
try:
# 进程内执行同样加超时:工具里死循环时至少让对话能返回错误,而不是整个内核卡死。
# ★ 会等用户的工具(ask_user / show_ui 的 wait 模式)**不限时** ——
# 它们的耗时取决于用户什么时候点,给上限等于"用户想久了 AI 就自己编"。
# 见 _waits_for_user 的注释。
budget = 0 if _waits_for_user(name, spec, module) else TOOL_TIMEOUT_S
outcome = run_with_timeout(_invoke, budget)
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)
# 界面工具(AI 弹界面 / 弹窗 / 结束对话)开关关着时对模型隐藏
defs = filter_ui_tools(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} 未授权'}
# ★ 界面工具的第二道拦截:开关关着时,即使模型硬编名字也不执行。
# (第一道是 build_tool_defs 里根本不把它给模型看。)
# 两道都要有 —— 只藏不给看的话,用户把工具关掉之后模型仍可能
# 从历史消息里学会这个名字再调一次。
if name in UI_TOOLS and not ui_tools_enabled(settings):
return {
'ok': False,
'error': f'界面工具「{name}」已关闭。请在「技能」页打开"AI 界面能力"后再用。',
}
# 会议节点工具优先(它是这次会议里用户刚写的东西,不会有重名歧义)
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)