Files
doubao-clone/android/kernel/builtin_tools.py
l c7fed95650 feat: 所有超时收成一份、全部可调(设置 → 超时,18 项)
用户要求"全部超时做成可调"。改造前 15 个超时散在 10 个文件里当模块级常量,
说不清一共有几个,也答不了"哪些能调"。

内核
- 新增 android/kernel/timeouts.py:**超时的唯一一份定义**(DEFAULT + SPECS),
  带每项的 名字/分组/说明/默认值/上下界;get() 一律夹取,用户填什么都不炸
- 新增 GET/POST /api/timeouts(清单 + 当前值 + 保存 + 恢复默认)
- 各处改现读:tools_runtime(tool)、builtin_tools(shell/pythonRun)、
  doubao_entry(termux)、providers(model)、speech(tts/stt)、
  mcp_client(请求/连接/调用)、meeting(meetingNode)、custom_nodes(customNode)、
  app.py 的 SSE 心跳
- ask_user / show_ui 用 TIMEOUT_KEYS 声明"哪个参数该用设置里的值",
  内核调用前注入(工具的默认值退化成单独跑时的兜底)
- store.py:timeouts 走**整体替换**而不是深合并 —— 深合并会让"改回默认"删不掉

安卓
- data/AppTimeouts.kt:客户端缓存(OkHttp 的 readTimeout、文件选择没法现问内核)
- KernelClient:readTimeout 跟着 sseRead 走,改完重建连接池;新增 timeouts 接口
- ui/TimeoutsScreen.kt:全屏界面,按分组列出、-/+ 与输入框、恢复默认
- 设置页加「超时」卡片入口;NativeBridge 的本地接口请求 / 选文件等待接上
- Settings 模型加 TimeoutItem / TimeoutsState(字段全部来自内核)

Node 端(Web/exe)
- 新增 server/src/timeouts.mjs(和 Python 那份逐字对应)
- config.mjs 加 timeouts(同样整体替换);speech / python-tools / mcp / providers
  各处改读;index.mjs 加 /api/timeouts

验证
- 新增 scripts/verify-timeouts.py:清单完整性、边界容错(文字/空串/负数/超大值/
  带单位/None)、**扫内核有没有漏网的硬编码超时**(带白名单)、
  工具侧声明、以及和 Node 端逐项对拍
- 实测真机:界面显示 18 项来自内核 → 点 + 保存 → 内核 heartbeat 15→25 →
  恢复默认 → 回 15;askUser 显示"不限时"

文档:README §3.13;docs/AI界面能力.md 的"不限时要三处一起改"补上可调入口。
版本 2.0.46。
2026-10-16 10:29:46 +08:00

347 lines
13 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.

"""
内置工具: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
import timeouts
# --------------------------------------------------------------------------- #
# 工具定义(与 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': '超时秒数。不传就用设置里「超时 → shell 命令」那个值',
},
},
'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': '超时秒数。不传就用设置里「超时 → 跑 Python 代码」那个值',
},
},
},
}
# 明显会搞坏机器的模式(可用 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')
# 超时:模型传了就用它的,没传就用设置里的(设置 → 超时 → shell 命令)
timeout = timeouts.budget(args, 'shell')
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 线程,不阻塞进程退出)。
这个取舍必须让用户知道,所以超时消息里写清楚。
★★ `timeout_s <= 0` = **不限时**(一直等到它跑完)。
给"停下来等用户"的那类工具用(`ask_user` / `show_ui` 的 wait 模式)——
它们的耗时**完全取决于用户什么时候点**,60 秒的上限只会造成:
弹窗还开着、用户 5 分钟后才选,而模型早就收到"工具执行超时"、
于是按自己猜的答案往下写了。
为什么默认仍然是 60 秒:这是"工具里写了死循环"的安全网
(不让整个内核跟着卡死)。会等用户的工具属于**设计上就该慢**,
由工具自己声明 `WAIT_FOR_USER = True` 来豁免,见 tools_runtime。
"""
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()
if timeout_s and timeout_s > 0:
thread.join(timeout_s)
if thread.is_alive():
return None
else:
# 不限时:join() 不带参数就是一直等
thread.join()
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 = timeouts.budget(args, 'pythonRun')
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},
}