Files
doubao-clone/android/kernel/tools_runtime.py
doubao b1dd740b0d AI 界面可以再点开 + 新接口「给会话发消息」(v2.0.40)
用户两条需求:

  ① "AI 写的界面可以再点开"(并纠正:是 AI 写的界面本身,不是它提到的链接)
  ② "给 ai 加个接口:给本次会话发送消息"

## ① AI 界面再点开

以前界面**只活在内存里** —— 用户一关(或退出 App)就没了。
想再看只能让 AI 重新生成,而**重新生成的内容不一定一样**(模型有随机性),
用户会觉得"我明明看过的东西怎么变了"。

现在每次 `show_ui` 都存一份:

  · 正文存 `<app files>/ai-screens/<id>.html`,索引存同目录 `index.json`
  · `screenId` 随工具返回值回到模型 → 再进 App 的工具痕迹记录
  · **消息操作栏据此出现「界面」按钮**(只有这条回复真弹过界面才出现)
  · 另外在抽屉里加了「AI 界面」入口 = 独立全屏列表,能翻看/删除所有存过的界面

★ 为什么存 App 侧(Kotlin)而不是内核(Python):
  内核有 store 能落盘,但它**拿不到 HTML** —— HTML 是 Kotlin 手里的
  `device()` 参数。要走内核就得 Kotlin 再 POST 一次,多一次往返、多一个失败点。
  而 App 私有目录本来就是 Kotlin 最顺手的地方。

★ 每个会话只留最近 30 个(超了删最旧的正文),否则聊久了列表没法看、磁盘白占。

## ② 新工具 send_message:AI 主动往当前会话发消息

```
send_message(text="在干嘛呢", reply=false, role="user")
```

消息**像用户说的话一样进历史**,显示在聊天里。适合角色扮演主动找话题、
长任务先贴个中间结果、用户在界面上点了东西要在对话里留个记录。

### ★★★ 这个工具最危险的是死循环,做了三道闸

    模型发消息 → 内核顺手跑回复 → 那一轮里模型又发消息 → 无限套娃
    一个下午能把 API 额度烧光,用户看到满屏自己没发过的消息

  · **闸① 嵌套深度**:`send_message` 触发的回复里最多再发 2 层。
    深度经 `tools_runtime.push_context(sendDepth=…)` → Kotlin 桥 → 内核一路传下去。
    (那个上下文是**跨线程搬过去**的 —— `threading.local` 不跨线程继承,
      这个坑之前踩过,所以 `run_python_tool` 里专门搬了一次。)
  · **闸② 每会话条数上限**:20 条。即使深度那条因为某个环节没传到而失效,
    条数上限也能兜住。
  · **闸③ 默认不触发回复**:`reply` 默认 false。
    默认 true 的话,界面上一次 `Doubao.sendToAi` 就会连锁跑起模型 ——
    用户会觉得"它怎么自己说起来了",而且很容易撞额度。

★ 计数**从会话历史里数**(靠消息上的 `aiSent` 内部标记),不用内存计数器。
第一版就是内存计数,两个毛病:重启 App 就清零(上限形同虚设)、
写失败时可能多计(拒绝信息里的数字和实际条数对不上)。数历史自洽、跨重启。

★ 要顺手回一轮时,回复**必须放后台线程** —— 当前线程正被 `send_message`
工具占着(模型还在等返回值),在这里同步跑一轮回复会**死锁**(等自己)。
用 poll 那条路,事件进 `_RUNS`,界面能收到。

★ `send_message` 也归到 `UI_TOOLS` 里(默认关):
它会让 AI 主动塞消息,同样是打扰性能力,而且能连锁调模型 ——
默认开着的风险比 show_ui / ask_user / end_conversation 还大。

## 实测(真机 Android 14 x86_64)

界面再点开:
  · `show_ui` 返回 `screenId: s_70ca75ac13bb`
  · `ui_screen_list` 列出它,预览文字正确(标题 + 正文片段)
  · `ui_screen_reopen` 读磁盘那份重新显示 → 界面上的 MARKER 和图形都在 ✓

send_message 三道闸:
  · 正常发送 → 进历史、内容/角色都对 ✓
  · assistant 角色也能发 ✓
  · 空 text / 缺 conversationId → 拒绝 ✓
  · **闸①** depth=9 → 拒绝,且**没有写进会话** ✓
  · **闸②** 发到第 20 条被拒,拒绝理由说清上限 ✓
  · 到上限后再发仍然被拒(不会因为计数器重置而复活)✓

## 顺带

 · 修 `extractUrls` 时发现的 Kotlin 字符串模板坑:`"$owner里提到的网页"`
   会把后面几个汉字当成变量名的一部分(报未解析引用),必须写 `${owner}`。
 · `rememberAppViewModel` 里 `viewModel(...)` 必须写 `viewModel<AppViewModel>(...)`,
   不写类型推断会挂,报的是"Not enough information to infer type argument",
   下面那句 `vm.appContext` 跟着报未解析引用 —— 看着完全不像泛型问题。
2026-10-15 14:11:44 +08:00

504 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/ 下的文件名一致。
#
# ★ 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:
# 进程内执行同样加超时:工具里死循环时至少让对话能返回错误,而不是整个内核卡死
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)