按《智能体系统需求文档 v1.1》实现。这一阶段打通了"内核数据 → 接口 → 界面"整条链路。 ## 内核 - 新增 agentdb.py:智能体系统的 SQLite 层(记忆 / 情绪 / Token 统计 / Skill 绑定)。 **为什么这次用 SQLite 而别处还是 JSON**(store.py 顶上写着 JSON 的理由): 记忆是"条目无上限 + 每轮全量注入 + 要 LIKE 检索 + 要行级改删", 那三条都指向 SQLite;而设置/会话/智能体的量级仍然是"几个到几十个"、 且要人肉可读,继续留在 JSON。分界线写在 agentdb.py 的文件头。 - 新增 agent_context.py:按需求附录 C 拼 system prompt (人设 → skills → worldview → emotion → memory → peer_emotions,**空段整段删掉**,每轮重拼)。 - 新增 agent_tools.py:7 个内置工具(memory_add/update/forget/search、 memory_suggest_summary、emotion_set、get_token_usage)。 走进程内实现是因为它们要读写 agent.db,而电脑端的文件工具是子进程。 共享记忆的写入限权(只能改自己写的)+ pinned 保护都在这里。 - 新增 agent_api.py:20+ 个 HTTP 接口(记忆 CRUD/导出导入/整理、情绪、 Token 用量、世界观/模型列表/Skill 的 CRUD 与包导入导出)。 app.py 的老 /api/agents 三个路由删掉,统一由它处理(顺便补上"内置不能删")。 - store.py:Agent 字段按类型分开的 _apply_agent_patch(create/update 共用)、 三种资源的通用 CRUD、create_agent 改用 **UUID**(需求附录 A)、 delete_agent 清理绑定关系但**不删记忆**。 - Token:usage 从"只留最后一轮"改成**累加**(多轮工具调用的消耗是大头, 以前全丢);落库时按轮记在消息上(会话级 = 加起来,重新生成不会虚高) + 计入智能体累计(按模型分桶、输入输出分开);超限时**发起前**拦住, 附一条带语气的告别消息并给界面明确的 token_limit 错误(需求 3.1)。 - 会议节点的 system prompt 也改用 agent_context(以前是自己拼的, 同一个智能体在会议里没有记忆/情绪/世界观)。 - doubao_entry:web_search.py 补进 BUNDLED_TOOL_FILES(对拍脚本抓出的清单不一致)。 ## 安卓 - AgentSelectScreen:智能体选择界面(需求第二章)—— 左列表 + 右侧四层叠加(背景/主体边框/角色图/介绍边框), 1.5s 四阶段切换动画(0.3 出 / 0.5 间隔 / 0.4 边框 / 0.3 入,方向按列表顺序, 连点立即打断并从当前视觉状态续走),圆形「更多」按钮,默认资源回退。 - AssetImage:本地图片显示。**不引 Coil/Glide**(项目零第三方依赖)—— PNG/JPG 走 BitmapFactory,GIF 走 ImageDecoder(API28+ 能播动图,以下退化成首帧), SVG 走 WebView(原生解不了)。 - TokenUsageScreen / MemoryScreen:用量详情(输入输出分列、按模型分行、 限额进度、配了单价才估费用)+ 记忆管理(情绪编辑、整理、导入导出、 pinned 开关、共享记忆提示)。 - Models.kt / KernelClient.kt / AppViewModel.kt:全部新字段与新接口。 - 入口:抽屉「智能体」→ 选择界面;聊天页顶栏点名字 → 选择界面 (以前点开的是「模型」面板 —— 那是"换脑子"不是"换人")。 - 需求文档给的两张默认资源图进 res/drawable(2.3MB)。 ## 验证 - 新增 scripts/probe-agent-system.py:11 节 60+ 项断言,**不装机**跑完整链路 (临时数据目录 + 假 Handler)。覆盖:UUID 主键、记忆增删改查检索、 pinned 保护、共享记忆与写入限权、system prompt 五段注入与顺序、 20 多个接口、包的导出导入边界(模型引用/世界观/限额**不进包**)、 记忆导入的合并去重、资源 CRUD。全绿。 - 装机验证:选择界面四层叠加、默认资源回退、切换动画与高亮。 ## 还没做(下一阶段) 世界观/Skill/模型列表的管理界面、对话页会话级用量显示、智能体编辑界面扩展 (介绍/外观/模型引用/世界观/限额/技能绑定)、包的导入导出界面、 幻觉调用检测、不支持 function calling 的兼容降级、Node 端跟上。
492 lines
19 KiB
Python
492 lines
19 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 hashlib
|
||
import importlib.util
|
||
import json
|
||
import os
|
||
import shutil
|
||
import sys
|
||
import threading
|
||
|
||
# 超时全部收在 timeouts.py 里(用户可在「设置 → 超时」调)。
|
||
# 它读不到设置时会回落默认值,所以在启动早期 import 也是安全的。
|
||
import timeouts
|
||
|
||
# 内置工具(构建时由 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',
|
||
# AI 主动往当前会话里发一条消息(带防死循环的闸,见 app.py /api/session-message)
|
||
'send_message.py',
|
||
# 操作手机:读通知 / 开 App / 调音量
|
||
'notifications.py',
|
||
'apps.py',
|
||
'volume.py',
|
||
# ★ web_search.py 以前漏在清单外(对拍脚本抓出来的)。
|
||
# 它其实**照样会被播种**(构建脚本遍历整个 tools/ 目录,
|
||
# _seed_tools 又用那份源码整体补齐),所以功能上没缺 ——
|
||
# 但清单是"内置工具一览"的文档,和现实不一致就会误导下一个人。
|
||
'web_search.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': '超时秒数。不传就用设置里「超时 → Termux 命令」那个值',
|
||
},
|
||
},
|
||
'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 = timeouts.budget(args, 'termux')
|
||
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 _src_hash(text: str) -> str:
|
||
"""源码指纹前 16 位(够用,还短)"""
|
||
return hashlib.sha256(text.encode('utf-8')).hexdigest()[:16]
|
||
|
||
|
||
def _seed_tools(tools_dir: str) -> int:
|
||
"""
|
||
把内置工具写到手机上的可写目录。之后用户就能自己改、自己加
|
||
(设置里的"工具目录"指向这里)。
|
||
|
||
源码来源优先级:
|
||
1) bundled_tool_sources(构建时嵌进来的 base64 源码)—— 安卓上唯一可靠的来源,
|
||
因为 Chaquopy 只留 .pyc,loader.get_source() 拿不到源码
|
||
2) 直接从模块读源码 —— 电脑上跑时用这条
|
||
|
||
## ★★★ 升级时会重新播种(这是修的一个真 bug)
|
||
|
||
以前这里是 `if os.path.exists(dest): continue` —— **只写不存在的文件**。
|
||
后果:**每一次发版更新的内置工具,在老设备上一律不生效**。
|
||
|
||
这个 bug 的表现极具误导性:代码明明改了、APK 明明是新编的、
|
||
`app.imy` 里也确实有新的 .pyc,但设备上跑的还是几个月前那份 ——
|
||
因为内核加载的是**落盘的那份旧源码**。
|
||
实测踩到:v2.0.37 加了 `show_ui` 的 `wait` 参数,设备上报的 spec 里
|
||
根本没有这个参数,我一度以为是构建没生效。
|
||
|
||
## 怎么判断该不该覆盖 —— 这是这一版真正修对的地方
|
||
|
||
先看第一版(错的):只看一个本地指纹文件 `.doubao-seed.json`。
|
||
|
||
· 指纹对得上 → 我们写的 → 可以覆盖
|
||
· 对不上 → 用户改过 → 不覆盖
|
||
|
||
**但老设备上那个指纹文件是空的**(第一版播种逻辑从来没写过它),
|
||
于是所有文件都被判成"用户改过",**升级永远不生效**。
|
||
实测 v2.0.37 给 show_ui 加了 `wait` 参数,真机上死活拿不到 ——
|
||
12 个没改过的文件"内容相同"跳过,唯一改过的 show_ui 被判成用户改的。
|
||
|
||
第二版(现在):加一份**构建时累积的"历史版本哈希登记表"**
|
||
(`tools/.shipped-hashes.json`,打包时嵌进 `bundled_tool_sources.shipped()`)。
|
||
判断顺序:
|
||
|
||
1. 内容和我们这一版一样 → 什么都不做
|
||
2. 内容**在历史登记表里** → 是我们以前发的某个版本 → **安全覆盖**
|
||
3. 内容等于我们本地指纹记的 → 是我们写的 → **安全覆盖**
|
||
4. 都不是 → 用户改过 → **绝不覆盖**
|
||
|
||
第 2 条是关键:它让"老设备上那份我们几个月前发的旧源码"能被认出来。
|
||
没有它就只能靠"指纹文件",而老设备上那个是空的。
|
||
"""
|
||
os.makedirs(tools_dir, exist_ok=True)
|
||
wanted = {name: _module_source(name[:-3]) for name in BUNDLED_TOOL_FILES}
|
||
|
||
shipped: dict = {}
|
||
try:
|
||
import bundled_tool_sources # type: ignore[import-not-found]
|
||
|
||
for name, source in bundled_tool_sources.sources().items():
|
||
wanted[name] = source
|
||
# ★ 历史版本哈希表:靠它认出"盘上这份是我们以前发的"
|
||
try:
|
||
shipped = bundled_tool_sources.shipped()
|
||
except Exception: # noqa: BLE001 - 老版本生成的文件里没有这个函数
|
||
shipped = {}
|
||
except Exception: # noqa: BLE001 - 电脑上没有这个生成文件,正常
|
||
pass
|
||
|
||
# 读上次写下的指纹
|
||
stamp_path = os.path.join(tools_dir, '.doubao-seed.json')
|
||
seeded: dict = {}
|
||
try:
|
||
with open(stamp_path, encoding='utf-8') as fh:
|
||
loaded = json.load(fh)
|
||
if isinstance(loaded, dict):
|
||
seeded = loaded
|
||
except Exception: # noqa: BLE001 - 没有/坏了都当第一版处理
|
||
seeded = {}
|
||
|
||
copied = 0
|
||
skipped_user = 0
|
||
for filename, source in wanted.items():
|
||
if not source:
|
||
continue
|
||
dest = os.path.join(tools_dir, filename)
|
||
new_hash = _src_hash(source)
|
||
|
||
if os.path.exists(dest):
|
||
try:
|
||
with open(dest, encoding='utf-8') as fh:
|
||
current = fh.read()
|
||
except Exception: # noqa: BLE001
|
||
continue
|
||
cur_hash = _src_hash(current)
|
||
if cur_hash == new_hash:
|
||
# 已经是这一版了。**顺手把指纹补上** ——
|
||
# 老设备上指纹是空的,不补的话下次还会走"用户改过"那条。
|
||
seeded[filename] = cur_hash
|
||
continue
|
||
# 是我们以前发的某个版本?→ 可以覆盖
|
||
ours_history = cur_hash in (shipped.get(filename) or [])
|
||
ours_stamp = seeded.get(filename) == cur_hash
|
||
if not ours_history and not ours_stamp:
|
||
# 用户自己改过 —— 不覆盖。留个日志方便排查
|
||
skipped_user += 1
|
||
print(f'[tools] {filename} 被用户改过,保留不覆盖', file=sys.stderr, flush=True)
|
||
continue
|
||
# 没改过,且我们的版本变了 → 覆盖
|
||
try:
|
||
with open(dest, 'w', encoding='utf-8') as fh:
|
||
fh.write(source)
|
||
seeded[filename] = new_hash
|
||
copied += 1
|
||
except Exception as exc: # noqa: BLE001
|
||
print(f'[tools] 写 {filename} 失败:{exc}', file=sys.stderr, flush=True)
|
||
|
||
if copied or skipped_user:
|
||
print(f'[tools] 播种:更新 {copied} 个,保留用户改过的 {skipped_user} 个',
|
||
file=sys.stderr, flush=True)
|
||
|
||
try:
|
||
with open(stamp_path, 'w', encoding='utf-8') as fh:
|
||
json.dump(seeded, fh, ensure_ascii=False, indent=2)
|
||
except Exception: # noqa: BLE001
|
||
pass
|
||
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,
|
||
)
|