Files
doubao-clone/android/kernel/tools_runtime.py
doubao 52680b9eb7 AI 界面能力:主动弹界面 / 弹窗 / 永久结束对话 (v2.0.35)
三个工具,**默认关**(「技能」页可开)。都是 AI 主动驱动界面,
属于"打扰性"能力 —— 装好就默认打开是产品事故。

## show_ui —— AI 自己写 HTML 弹一个全屏界面

有些东西用文字说不清:一张算出来的图表、排版好的报告卡片、宽对比表。
以前模型只能吐 markdown,表格一宽就乱。现在它能直接写 HTML。

  · html 写**片段**即可,自动套一层带样式的骨架(暗色主题、表格、代码块),
    模型不用每次重复写 viewport/字体/边距;想完全控制传 full_html=true
  · **不阻塞**:弹出来就返回,用户看完自己关(展示语义,不该卡住对话)
  · 界面里可以放 `<button data-doubao-result="值">`,用户点了那个值回到模型手里

★ 两个安全决定:
  1. **禁 JS**。允许 JS 的话模型生成的一段脚本就能拿到 `@JavascriptInterface`
     那个桥,等于把 App 内部接口暴露给模型。纯 CSS 足够渲染内容。
  2. **可点按钮不用 JS**:App 侧把 `data-doubao-result` 做**纯字符串替换**,
     改成 `doubao://pick?value=...` 链接,由 WebViewClient 拦下来。

## ask_user —— 弹选择框,等用户选完再继续

  · **阻塞**(最多 120 秒):问询语义,必须拿到答案才能继续。
    安卓侧用 CountDownLatch 等,跟已有的 pickFile 同一套路。
  · 超时必须有 —— 用户可能锁屏走了,不能让内核工作线程永远挂着
  · options 两种写法都收:对象数组 `[{label,value,description}]`
    和**裸字符串数组** `["A","B"]`(模型经常这么写,只认一种就平白报错)
  · 支持多选(multiple=true),选项超过 8 个自动截断并告诉模型

## end_conversation —— 永久结束这次对话

**用户明确要求的界面**:屏幕中间一个横幅,写 AI 关闭的原因。

  · 落盘(PATCH /api/conversations/<id> 写 `ended` / `endedReason`),
    不是界面状态 —— 只放 Compose 里的话一刷新就没了,用户重进会看到
    一个能继续输入的框,而模型以为自己已经结束了
  · 输入框整个不渲染,换成居中的横幅:「这次对话已结束」+ 原因 + 「开始新对话」
  · 拿不到对话 id 时**明确报错**,绝不假装成功

## 动画(用户要求)

  · HTML 界面:从中心长大 + 淡入(像开一扇门),退出反向
  · 选择弹窗:从下方滑上来 + 淡入 + 轻微放大;遮罩淡入
  · 结束横幅:从下方滑到**屏幕中间**停住 + 淡入 + 轻微放大,**不自动消失**
    (它是状态不是提示,消失了用户就不知道为什么发不出消息)
  · 选项选中:弹性放大 + 蓝底 + 勾

## 开关(两道拦截)

  settings.uiTools.enabled,默认 false。
  ① 关掉时工具**对模型隐藏**(build_tool_defs 里滤掉)
  ② 关掉时即使模型硬编名字**也拒绝执行** —— 只做①的话,用户关掉之后
     模型仍可能从历史消息里学会这个名字再调一次
  界面能力的用法说明**只在开关打开时**才追加到系统提示词 —— 写进
  DEFAULT_SYSTEM_PROMPT 的话会被存进用户的 settings.json,
  关着的时候还在教模型"你可以用 show_ui"。

## 顺带修的两个真 bug

1. **thread-local 不跨线程**(这个最隐蔽)
   `run_with_timeout` 把工具丢到**新线程**里跑,而 `threading.local()`
   不跨线程继承 —— 于是工具照常执行(参数都对),只有"当前是哪次对话"
   拿不到,`end_conversation` 报"拿不到当前对话 id"。
   我一开始以为是 app.py 没传 conversationId,查了一圈才发现是线程。
   修法:`run_python_tool` 执行前把父线程的上下文搬进工作线程。

2. **/api/tools/run 传的是假 settings**
   以前传 `{'security': {'mode': 'open'}}` 空壳(为了"手动试运行不受安全模式
   限制"),但界面工具的开关也在 settings 里 —— 于是用户在技能页点"试运行",
   明明开关是开的却收到"已关闭"。改成拿真实设置、只覆盖 security。

## 验证

`scripts/verify-ui-tools.py`(34 项)守:开关默认关、两道拦截都在、
选项两种写法都收、拿不到对话 id 必须报错、**上下文能跨线程**、
提示词按开关追加。`scripts/probe-ai-surfaces.py` 打
`adb forward` 之后的内核接口做端到端。

真机实测(Android 14 x86_64):
  show_ui        → 界面渲染正常(标题栏 + 暗色表格 + 可点按钮)
  ask_user 单选   → 等 21s,返回 {"choice":"B","values":["B"],"timeout":false}
  ask_user 多选   → 选 2 个,返回 {"values":["python","git"]}
  end_conversation → ended=True 落盘,横幅显示原因
2026-10-14 15:36:52 +08:00

500 lines
20 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 主动驱动界面,属于"会打扰用户"的能力,所以**默认关**,
# 用户要在「技能」页显式打开。名字要和 tools/ 下的文件名一致。
UI_TOOLS = ('show_ui', 'ask_user', 'end_conversation')
# 开关在 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:
# 进程内执行同样加超时:工具里死循环时至少让对话能返回错误,而不是整个内核卡死
outcome = run_with_timeout(_invoke, 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)
# 界面工具(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)