三个工具,**默认关**(「技能」页可开)。都是 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 落盘,横幅显示原因
380 lines
14 KiB
Python
380 lines
14 KiB
Python
"""
|
||
安卓端入口:Kotlin 侧通过 Chaquopy 调 `start(data_dir, work_dir, port)`。
|
||
|
||
为什么要有这个文件:
|
||
Chaquopy 把 CPython 嵌进 App 主进程,没有 `python` 可执行文件,
|
||
所以不能像电脑上那样 `python main.py --port 5199`,只能由 Kotlin 直接调函数。
|
||
这里把「准备目录 → 播种内置工具 → 注册原生能力 → 起 HTTP 服务」串起来。
|
||
|
||
与电脑端 Node 内核的关系:
|
||
接口完全一致,Lynx 前端不用改,只是把 apiBase 指到 http://127.0.0.1:<port>。
|
||
"""
|
||
|
||
import importlib.util
|
||
import json
|
||
import os
|
||
import shutil
|
||
import sys
|
||
import threading
|
||
|
||
# 内置工具(构建时由 scripts/build-apk.mjs 拷进 Python 源集根目录)
|
||
BUNDLED_TOOL_FILES = [
|
||
'_protocol.py',
|
||
# 界面工具三件套共用的安卓桥 + 上下文读取(被下面三个 import,必须先播种)
|
||
'_ui_bridge.py',
|
||
'calc.py',
|
||
'now.py',
|
||
'weather.py',
|
||
'notes.py',
|
||
'web_fetch.py',
|
||
'shell.py',
|
||
'python_run.py',
|
||
# AI 主动弹界面 / 弹选择框 / 永久结束对话(默认关,见 settings.uiTools)
|
||
'show_ui.py',
|
||
'ask_user.py',
|
||
'end_conversation.py',
|
||
'_mcp_python_example.py',
|
||
]
|
||
|
||
_state = {'port': 0, 'handle': None, 'error': None}
|
||
_android = None
|
||
_lock = threading.Lock()
|
||
|
||
|
||
# --------------------------------------------------------------------------- #
|
||
# 原生能力桥
|
||
# --------------------------------------------------------------------------- #
|
||
|
||
def set_android_bridge(bridge) -> None:
|
||
"""
|
||
Kotlin 传一个 NativeBridge 对象进来(Chaquopy 允许 Python 直接调它的方法)。
|
||
这里把它接到内核的钩子和 device 工具上。
|
||
"""
|
||
global _android
|
||
_android = bridge
|
||
try:
|
||
import app as kernel_app
|
||
|
||
kernel_app.set_native_hooks(
|
||
clipboard=lambda text: bridge.setClipboard(str(text)),
|
||
pick_file=lambda: list(bridge.pickFile() or []),
|
||
reveal=lambda path: bridge.reveal(str(path)),
|
||
)
|
||
except Exception as exc: # noqa: BLE001 - 钩子挂不上不该拦住内核启动
|
||
print(f'[entry] 注册原生钩子失败:{exc}', file=sys.stderr, flush=True)
|
||
|
||
_install_device_tool()
|
||
|
||
|
||
DEVICE_TOOL_SPEC = {
|
||
'name': 'device',
|
||
'description': (
|
||
'读取这台手机/平板的设备能力:位置(GPS)、运动传感器(加速度计/陀螺仪/磁场/气压/光线等)、'
|
||
'电量、系统信息、剪贴板。安卓端专属;电脑上会返回"不支持"。'
|
||
'用法:action 选 info/location/sensors/sensor/battery/clipboard_get/clipboard_set。'
|
||
'读某个传感器时传 sensor 参数(如 accelerometer / gyroscope / magnetic / light / pressure / proximity),'
|
||
'duration 是采样秒数(默认 1.5,最多 10)。'
|
||
),
|
||
'parameters': {
|
||
'type': 'object',
|
||
'properties': {
|
||
'action': {
|
||
'type': 'string',
|
||
'enum': [
|
||
'info', 'location', 'sensors', 'sensor', 'battery',
|
||
'clipboard_get', 'clipboard_set', 'termux_available', 'termux_run',
|
||
],
|
||
'description': '要做的事,默认 info',
|
||
},
|
||
'sensor': {'type': 'string', 'description': '传感器名,见 action=sensors 的返回'},
|
||
'duration': {'type': 'number', 'description': '采样秒数,默认 1.5'},
|
||
'text': {'type': 'string', 'description': 'action=clipboard_set 时要写入的内容'},
|
||
'command': {'type': 'string', 'description': 'action=termux_run 时要在 Termux 里跑的命令'},
|
||
'cwd': {'type': 'string', 'description': 'action=termux_run 的工作目录'},
|
||
'timeout': {'type': 'number', 'description': 'action=termux_run 的超时秒数'},
|
||
},
|
||
},
|
||
}
|
||
|
||
|
||
def device_run(args: dict) -> dict:
|
||
if _android is None:
|
||
return {'error': '当前环境没有安卓原生桥(电脑端请用 shell 工具)'}
|
||
action = str(args.get('action') or 'info')
|
||
payload = json.dumps(
|
||
{
|
||
'action': action,
|
||
'sensor': args.get('sensor') or '',
|
||
'duration': float(args.get('duration') or 1.5),
|
||
'text': args.get('text') or '',
|
||
},
|
||
ensure_ascii=False,
|
||
)
|
||
raw = _android.device(payload)
|
||
try:
|
||
return json.loads(str(raw))
|
||
except (ValueError, TypeError):
|
||
return {'raw': str(raw)}
|
||
|
||
|
||
def _install_device_tool() -> None:
|
||
"""把 device 工具塞进内核的内置工具表,并把 shell 换成「优先走 Termux」的版本"""
|
||
try:
|
||
import builtin_tools
|
||
|
||
builtin_tools.BUILTIN_TOOLS['device'] = {'spec': DEVICE_TOOL_SPEC, 'run': device_run}
|
||
builtin_tools.BUILTIN_TOOLS['shell'] = {'spec': SHELL_TOOL_SPEC, 'run': shell_run}
|
||
except Exception as exc: # noqa: BLE001
|
||
print(f'[entry] 注册 device 工具失败:{exc}', file=sys.stderr, flush=True)
|
||
|
||
|
||
SHELL_TOOL_SPEC = {
|
||
'name': 'shell',
|
||
'description': (
|
||
'在手机的终端里执行一条 shell 命令,返回退出码、标准输出和标准错误。'
|
||
'装了 Termux 就走 Termux(完整 Linux 用户态,bash/apt/pip 都能用);'
|
||
'没装则退回到系统自带的 toybox shell(命令比 GNU 少,比如没有 grep -P、没有 apt)。'
|
||
'危险命令会被拦截。'
|
||
),
|
||
'parameters': {
|
||
'type': 'object',
|
||
'properties': {
|
||
'command': {'type': 'string', 'description': '要执行的命令'},
|
||
'cwd': {'type': 'string', 'description': '工作目录,可留空'},
|
||
'timeout': {'type': 'number', 'description': '超时秒数,默认 30,最大 300'},
|
||
},
|
||
'required': ['command'],
|
||
},
|
||
}
|
||
|
||
|
||
# Termux 探测状态:
|
||
# None = 还没试过;True = 可用;False = 试过但不可用
|
||
# 不可用时会在 _TERMUX_RETRY_AFTER 秒内直接走系统 shell,
|
||
# 否则每条命令都要先干等一次超时(实测 user 装了 Termux 但没开
|
||
# allow-external-apps 时,每条命令白等 30 秒,体验极差)。
|
||
_termux_ok = None
|
||
_termux_fail_until = 0.0
|
||
_TERMUX_FIRST_PROBE_S = 8
|
||
_TERMUX_RETRY_AFTER = 300
|
||
|
||
|
||
def _try_termux(command: str, cwd: str, timeout: int):
|
||
"""能走 Termux 就走,返回结果 dict;走不了返回 None"""
|
||
global _termux_ok, _termux_fail_until
|
||
|
||
import time as _time
|
||
|
||
now = _time.time()
|
||
if _termux_ok is False and now < _termux_fail_until:
|
||
return None
|
||
if _android is None:
|
||
return None
|
||
|
||
# 第一次只等很短:装了但没开外部命令时会秒回 errmsg,没装则更快
|
||
wait = min(timeout, _TERMUX_FIRST_PROBE_S) if _termux_ok is None else timeout
|
||
try:
|
||
raw = _android.device(
|
||
json.dumps(
|
||
{
|
||
'action': 'termux_run',
|
||
'command': command,
|
||
'cwd': cwd,
|
||
'timeout': wait,
|
||
},
|
||
ensure_ascii=False,
|
||
)
|
||
)
|
||
res = json.loads(str(raw))
|
||
except Exception as exc: # noqa: BLE001
|
||
res = {'error': f'{type(exc).__name__}: {exc}'}
|
||
|
||
if res.get('available') and not res.get('error'):
|
||
_termux_ok = True
|
||
return res
|
||
|
||
if res.get('installed') is False:
|
||
# 压根没装,以后别再试了(本次进程内)
|
||
_termux_ok = False
|
||
_termux_fail_until = now + 1e9
|
||
else:
|
||
_termux_ok = False
|
||
_termux_fail_until = now + _TERMUX_RETRY_AFTER
|
||
return None
|
||
|
||
|
||
def shell_run(args: dict) -> dict:
|
||
"""
|
||
安卓上的 shell:优先交给 Termux(有真 bash/apt/pip),没有就退回 /system/bin/sh。
|
||
|
||
为什么要这么绕:APK 自带的 CPython 是嵌在主进程里的,没有可执行文件、起不了子进程;
|
||
而 Termux 是个完整 Linux 用户态,借它的 bash 能跑通绝大多数命令。
|
||
"""
|
||
from builtin_tools import shell_run as fallback_shell # 内置实现(toybox / cmd)
|
||
|
||
command = str(args.get('command') or '').strip()
|
||
if not command or _android is None:
|
||
return fallback_shell(args)
|
||
|
||
timeout = max(1, min(300, int(args.get('timeout', 30) or 30)))
|
||
hit = _try_termux(command, str(args.get('cwd') or ''), timeout)
|
||
if hit is not None:
|
||
return {
|
||
'exit_code': hit.get('exit_code', 0),
|
||
'stdout': str(hit.get('stdout') or '')[-8000:],
|
||
'stderr': str(hit.get('stderr') or '')[-4000:],
|
||
'via': 'termux',
|
||
}
|
||
|
||
out = fallback_shell(args)
|
||
if isinstance(out, dict):
|
||
out['via'] = 'toybox'
|
||
if _termux_ok is False:
|
||
out['termux_note'] = (
|
||
'Termux 没能接管(装的没装、或没开 allow-external-apps)。'
|
||
'想要完整 Linux 环境:在 Termux 里执行 '
|
||
'echo "allow-external-apps=true" >> ~/.termux/termux.properties 然后重开 Termux。'
|
||
)
|
||
return out
|
||
|
||
|
||
# --------------------------------------------------------------------------- #
|
||
# 目录准备
|
||
# --------------------------------------------------------------------------- #
|
||
|
||
def _module_source(name: str):
|
||
"""取内置 py 工具的源码。Chaquopy 里文件在 APK 内,不能直接 open(),得走 loader。"""
|
||
try:
|
||
spec = importlib.util.find_spec(name)
|
||
except (ImportError, ValueError):
|
||
return None
|
||
if spec is None:
|
||
return None
|
||
loader = spec.loader
|
||
if loader is not None and hasattr(loader, 'get_source'):
|
||
try:
|
||
return loader.get_source(name)
|
||
except Exception: # noqa: BLE001
|
||
pass
|
||
origin = getattr(spec, 'origin', None)
|
||
if origin and os.path.isfile(origin):
|
||
with open(origin, encoding='utf-8') as fh:
|
||
return fh.read()
|
||
return None
|
||
|
||
|
||
def _seed_tools(tools_dir: str) -> int:
|
||
"""
|
||
首次运行把内置工具写到手机上的可写目录。
|
||
之后用户就能自己改、自己加(设置里的"工具目录"指向这里)。
|
||
|
||
源码来源优先级:
|
||
1) bundled_tool_sources(构建时嵌进来的 base64 源码)—— 安卓上唯一可靠的来源,
|
||
因为 Chaquopy 只留 .pyc,loader.get_source() 拿不到源码
|
||
2) 直接从模块读源码 —— 电脑上跑时用这条
|
||
"""
|
||
os.makedirs(tools_dir, exist_ok=True)
|
||
wanted = {name: _module_source(name[:-3]) for name in BUNDLED_TOOL_FILES}
|
||
|
||
try:
|
||
import bundled_tool_sources # type: ignore[import-not-found]
|
||
|
||
for name, source in bundled_tool_sources.sources().items():
|
||
wanted[name] = source
|
||
except Exception: # noqa: BLE001 - 电脑上没有这个生成文件,正常
|
||
pass
|
||
|
||
copied = 0
|
||
for filename, source in wanted.items():
|
||
if not source:
|
||
continue
|
||
dest = os.path.join(tools_dir, filename)
|
||
if os.path.exists(dest):
|
||
continue
|
||
with open(dest, 'w', encoding='utf-8') as fh:
|
||
fh.write(source)
|
||
copied += 1
|
||
return copied
|
||
|
||
|
||
def _ensure_mcp_config(data_dir: str) -> None:
|
||
"""
|
||
安卓上默认不配任何 MCP 服务。
|
||
为什么:出厂那份配置里的 npx/filesystem 在手机上根本跑不起来,
|
||
自动连接只会每次都报错,不如留空让用户自己加(设置页有图形化编辑)。
|
||
"""
|
||
target = os.path.join(data_dir, 'mcp.servers.json')
|
||
if os.path.exists(target):
|
||
return
|
||
with open(target, 'w', encoding='utf-8') as fh:
|
||
json.dump({'servers': []}, fh, ensure_ascii=False, indent=2)
|
||
|
||
|
||
def tools_dir_for(work_dir: str) -> str:
|
||
return os.path.join(work_dir, 'tools')
|
||
|
||
|
||
# --------------------------------------------------------------------------- #
|
||
# 启动
|
||
# --------------------------------------------------------------------------- #
|
||
|
||
def start(data_dir: str, work_dir: str, port: int = 5199) -> int:
|
||
"""
|
||
起内核(不阻塞)。返回**实际**监听的端口。
|
||
Kotlin 侧在子线程里调它,然后在主线程轮询 /api/health 再挂载 LynxView。
|
||
"""
|
||
with _lock:
|
||
if _state['port']:
|
||
return _state['port']
|
||
|
||
os.makedirs(data_dir, exist_ok=True)
|
||
os.makedirs(work_dir, exist_ok=True)
|
||
tools_dir = tools_dir_for(work_dir)
|
||
copied = _seed_tools(tools_dir)
|
||
_ensure_mcp_config(data_dir)
|
||
|
||
# 让 import 能找到可写目录里的工具(用户自己加的)
|
||
if tools_dir not in sys.path:
|
||
sys.path.insert(0, tools_dir)
|
||
|
||
_install_device_tool()
|
||
|
||
import main as kernel_main
|
||
|
||
last_error = None
|
||
for candidate in (port, 0):
|
||
try:
|
||
handle = kernel_main.start_kernel(
|
||
host='127.0.0.1',
|
||
port=candidate,
|
||
data_dir=data_dir,
|
||
tools_dir=tools_dir,
|
||
quiet=True,
|
||
autostart_mcp=True,
|
||
)
|
||
_state.update({'port': handle.port, 'handle': handle})
|
||
print(
|
||
f'[entry] 内核已启动 127.0.0.1:{handle.port} '
|
||
f'工具目录={tools_dir}(新播种 {copied} 个)',
|
||
file=sys.stderr,
|
||
flush=True,
|
||
)
|
||
return handle.port
|
||
except OSError as exc: # 端口被占:再试一次随机端口
|
||
last_error = exc
|
||
print(f'[entry] 端口 {candidate} 起不来({exc}),换个端口重试', file=sys.stderr, flush=True)
|
||
except Exception as exc: # noqa: BLE001
|
||
last_error = exc
|
||
_state['error'] = f'{type(exc).__name__}: {exc}'
|
||
print(f'[entry] 内核启动失败:{exc!r}', file=sys.stderr, flush=True)
|
||
raise
|
||
|
||
raise RuntimeError(f'内核起不来:{last_error}')
|
||
|
||
|
||
def status() -> str:
|
||
return json.dumps(
|
||
{'port': _state['port'], 'error': _state['error'], 'android': _android is not None},
|
||
ensure_ascii=False,
|
||
)
|