Files
doubao-clone/android/kernel/app.py
l 18919fd84c 边生成边读:内核流式路由 + 安卓 AudioTrack 边收边播
接上一条(内核已有 synthesize_stream,实测厂商接口本身就在流式下发)。
这次把剩下三步做完,整条链路打通。

【内核路由 /api/tts/stream】
两份内核各一份,都是"音频块一到就写出去",不是攒完再发。
新增 scripts/verify-tts-route.mjs 起内核实测:Node 首块 964ms / 末块 2797ms,
Python 首块 997ms / 末块 2571ms,都判定为流式。

★ 一个关键设计:**先把第一块取出来,再发响应头**。
  合成失败(Key 不对、音色不存在)基本都发生在第一块之前,这时候还没发头,
  就能照常返回 JSON 错误,客户端拿得到具体原因并退回系统 TTS。
  要是先把头发出去就只能截断连接,用户看到的是"啥也没说就断了"。
  中途失败没法改状态码,只能截断,客户端会把已收到的部分播完。

  另外引擎是"设备自带"时直接返回"这轮该用系统 TTS",不走流式 ——
  那种情况内核根本不参与合成,否则客户端会收到一个莫名其妙的空音频错误。

【安卓 AudioTrack 边收边播】
- PcmPlayer 从 MODE_STATIC 改成 MODE_STREAM:write() 多少播多少,
  缓冲区满时 write 会阻塞,天然形成背压,不用自己控速。
- 采样率固定 24000(火山大模型音色的输出率)。写成录音那个 16000 会变调。
- 收尾用 drainAndRelease:不能立刻 stop(),MODE_STREAM 下 stop() 会把缓冲区里
  还没播的音频丢掉,最后半句就没了。
- KernelClient.streamTts 返回 Response 而不是 ByteArray —— 一旦在那里面
  readBytes() 就退回成"整段收完再播",正是要避免的。

★ 写的时候差点犯一个致命错误:okio 的 readByteArray() 不带参数是
  "一直读到流结束",写成那样等于整段收完再播,流式白做。必须用 read(buffer, n)。

【验了最担心的一点】
PC 上能流式不代表手机上能 —— Python 的 urllib 在有些环境下会缓冲。
所以专门在真机环境(模拟器上的 Chaquopy 进程)里量了一遍:
  首块 750ms / 末块 2261ms,23 块 / 422KB  → 安卓上确实是边读边给。
新增 scripts/verify-tts-device.mjs 把这条固化成验收。
(最初写成调 adb shell 的 python3,设备上根本没这个命令;改成走内核自己的
 python_run,在同一进程里直接调 synthesize_stream,反而更贴近要验的东西。)

【顺带修的】
/api/speech 的 voices 里漏了 volcv3,和 /api/state 那处不一致 ——
界面读那个接口时 V3 会一个音色都选不出来。

回归:Markdown 剥离对拍 19/19、语音验收 36/36 ×2、流式路由两份内核都过、
设备端 Chaquopy 流式通过。
2026-10-09 19:25:46 +08:00

986 lines
42 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.

"""
HTTP 路由:把 Node 版 server/src/index.mjs 的接口逐条搬到 stdlib 上。
用的是 http.server.ThreadingHTTPServer + BaseHTTPRequestHandler:
* 零依赖(安卓上不用打 flask/fastapi/aiohttp 的包,APK 小很多);
* 每个连接一个线程,阻塞式上游读取正好合适;
* SSE 用 chunked 传输编码手写(http.server 不会自动帮你分块),
帧格式和 Node 版完全一样:`data: {json}\n\n`。
接口清单(与 Node 版逐字段一致):
GET /api/health
GET /api/state PUT/POST /api/settings GET /api/models
GET /api/conversations POST /api/conversations
GET/PATCH/PUT/DELETE /api/conversations/<id>
GET /api/tools POST /api/tools/run
GET /api/mcp PUT/POST /api/mcp/config
POST /api/mcp/reveal POST /api/mcp/connect POST /api/mcp/disconnect
GET /api/agents POST /api/agents PATCH/PUT/DELETE /api/agents/<id>
POST /api/upload POST /api/pick-file GET /api/uploads/pending
POST /api/clipboard POST /api/chat(SSE)
静态:/ /main.web.bundle /lynx-web/* /static/* /uploads/*
"""
import json
import os
import sys
import threading
import time
import uuid
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import unquote, urlsplit
import agent_loop
import mcp_client
import paths
import providers
import speech
import store
import tools_runtime
import uploads
from defaults import PROVIDER_PRESETS
QUIET = False
# 轮询式对话任务:runId -> {'events': [...], 'done': bool, 'at': 时间戳}
# 安卓上 Lynx 原生 fetch 没有 response.body,只能靠这个通道做"准流式"
_RUNS = {}
_RUNS_LOCK = threading.Lock()
_RUN_TTL_S = 600
def _reap_runs() -> None:
"""清掉过期任务,别一直占内存"""
now = time.time()
with _RUNS_LOCK:
for key in [k for k, v in _RUNS.items() if now - v.get('at', now) > _RUN_TTL_S]:
_RUNS.pop(key, None)
def chat_error_hint(exc, settings) -> str:
"""把常见报错翻成一句人话,前端直接展示"""
import re as _re
msg = str(exc)
if _re.search(r'401|Unauthorized|invalid.*api.?key', msg, _re.IGNORECASE):
return 'API Key 不对或没填:右上角 ✎ → AI 内核设置 → 粘贴 Key 后保存'
if _re.search(r'404|model.*not.*found|does not exist|InvalidEndpoint', msg, _re.IGNORECASE):
model = (settings or {}).get('model')
return f'模型或接入点不存在:当前是 {model},去「模型」那一栏换一个,或填方舟的 ep- 接入点 ID'
if _re.search(r'429|rate.?limit|quota|insufficient', msg, _re.IGNORECASE):
return '被限流或余额不足,等一会儿或去控制台看额度'
if _re.search(r'timed? ?out|URLError|Connection refused|Name or service|getaddrinfo', msg, _re.IGNORECASE):
return '网络不通:检查手机网络;远程内核模式下还要确认内网地址可达'
if '400' in msg:
return '请求被拒:多半是模型名/参数不匹配,试试把思考强度调成「自动」'
return ''
MIME = {
'.html': 'text/html; charset=utf-8',
'.js': 'text/javascript; charset=utf-8',
'.mjs': 'text/javascript; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.json': 'application/json; charset=utf-8',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.webp': 'image/webp',
'.svg': 'image/svg+xml',
'.ico': 'image/x-icon',
'.bundle': 'application/octet-stream',
'.wasm': 'application/wasm',
'.woff2': 'font/woff2',
'.txt': 'text/plain; charset=utf-8',
'.map': 'application/json; charset=utf-8',
}
INDEX_MISSING_HINT = (
'宿主页不存在。请先运行 npm run build(app/),或在 app/ 里跑 npm run dev 用 Rspeedy 开发服务器预览。'
)
# 安卓侧(Kotlin/Chaquopy)可以挂上原生能力钩子,等价于 Electron 主进程挂的 __doubaoXxx
_hooks = {'clipboard': None, 'pick_file': None, 'reveal': None}
def set_native_hooks(clipboard=None, pick_file=None, reveal=None) -> None:
"""注册原生钩子:clipboard(text) / pick_file()->[路径] / reveal(路径)->错误串或 None。"""
_hooks.update({'clipboard': clipboard, 'pick_file': pick_file, 'reveal': reveal})
# --------------------------------------------------------------------------- #
# 工具函数
# --------------------------------------------------------------------------- #
def safe_join(root: str, url_path: str):
"""
把 URL 路径安全地拼到 root 下(挡住 ../ 穿越)。
等价于 Node 版 safeJoin:先规范化再拼,最后确认还在 root 里面。
"""
decoded = unquote((url_path or '').split('?')[0]).replace('\\', '/')
relative = decoded.lstrip('/')
target = os.path.abspath(os.path.join(root, relative))
root_abs = os.path.abspath(root)
if target != root_abs and not target.startswith(root_abs + os.sep):
return None
return target
class SseChannel:
"""
一条 SSE 连接。
写 chunked 编码而不是"直接写、靠关连接表示结束":
HTTP/1.1 下没有 Content-Length 就必须分块,否则前端 fetch 会一直等 EOF。
所有写操作加锁,因为心跳线程和请求线程都会写。
"""
def __init__(self, handler):
self.handler = handler
self.closed = False
self.aborted = False
self._lock = threading.Lock()
self._stop_event = threading.Event()
self._heartbeat = None
def start(self) -> None:
self.handler.send_response(200)
self.handler.send_header('Content-Type', 'text/event-stream; charset=utf-8')
self.handler.send_header('Cache-Control', 'no-cache, no-transform')
self.handler.send_header('Connection', 'keep-alive')
self.handler.send_header('X-Accel-Buffering', 'no')
self.handler.send_header('Transfer-Encoding', 'chunked')
for key, value in self.handler.cors_headers().items():
self.handler.send_header(key, value)
self.handler.end_headers()
self._write(': connected\n\n')
self._heartbeat = threading.Thread(target=self._ping_loop, name='sse-heartbeat', daemon=True)
self._heartbeat.start()
def _write(self, text: str) -> None:
if self.closed:
return
data = text.encode('utf-8')
with self._lock:
try:
self.handler.wfile.write(b'%x\r\n' % len(data) + data + b'\r\n')
self.handler.wfile.flush()
except (OSError, ValueError):
# 客户端断了:标记 + 让上游停止生成(由 should_stop 接手)
self.aborted = True
self.closed = True
self.handler.close_connection = True
def send(self, event: dict) -> None:
if self.closed:
return
payload = json.dumps(event, ensure_ascii=False, separators=(',', ':'))
self._write(f'data: {payload}\n\n')
def _ping_loop(self) -> None:
while not self.closed:
# 用 Event.wait 代替 sleep,结束时会立刻退出,不用等满 15 秒
if self._stop_event.wait(15):
return
if self.closed:
return
self._write(': ping\n\n')
def end(self) -> None:
if self.closed:
return
self.closed = True
self._stop_event.set()
with self._lock:
try:
self.handler.wfile.write(b'0\r\n\r\n')
self.handler.wfile.flush()
except (OSError, ValueError):
self.handler.close_connection = True
def should_stop(self) -> bool:
return self.aborted or self.closed
# --------------------------------------------------------------------------- #
# 请求处理
# --------------------------------------------------------------------------- #
class KernelHandler(BaseHTTPRequestHandler):
protocol_version = 'HTTP/1.1'
server_version = 'doubao-kernel-py/0.1'
sys_version = ''
# 每个请求进来时由 _dispatch 填:请求体缓存(None 表示还没读)
_raw_body = None
# ------------------------------ 基础设施 ------------------------------ #
def log_message(self, fmt, *args): # noqa: A003 - 覆盖基类
if not QUIET:
print(f'[http] {self.address_string()} {fmt % args}', file=sys.stderr)
def cors_headers(self) -> dict:
return {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
'Access-Control-Allow-Methods': 'GET, POST, PUT, PATCH, DELETE, OPTIONS',
}
def _head(self, status: int, headers: dict) -> None:
self.send_response(status)
for key, value in {**self.cors_headers(), **headers}.items():
self.send_header(key, value)
self.end_headers()
def send_json(self, status: int, payload) -> None:
# 与 Node 的 JSON.stringify(payload, null, 2) 对齐:缩进 2,中文原样输出
body = json.dumps(payload, ensure_ascii=False, indent=2).encode('utf-8')
self._head(status, {'Content-Type': 'application/json; charset=utf-8',
'Content-Length': str(len(body))})
if self.command != 'HEAD' and status != 204:
self.wfile.write(body)
def send_text(self, status: int, text: str) -> None:
body = text.encode('utf-8')
self._head(status, {'Content-Type': 'text/plain; charset=utf-8',
'Content-Length': str(len(body))})
if self.command != 'HEAD':
self.wfile.write(body)
# ------------------------------------------------------------------ 流式音频
def _write_chunk(self, data: bytes) -> None:
"""写一块 chunked 数据并立刻 flush —— 不 flush 的话会被攒在缓冲区里,
"边合成边播"就退化成"整段合成完再播"了。"""
self.wfile.write(b'%x\r\n' % len(data) + data + b'\r\n')
self.wfile.flush()
def stream_tts(self, text: str, settings) -> None:
"""
边合成边下发音频。
★ 关键设计:**先把第一块取出来,再发响应头**。
合成失败(Key 不对、音色不存在……)基本都发生在第一块之前,
这时候还没发头,就能照常返回一个 JSON 错误,客户端能拿到具体原因并
退回系统 TTS。要是先把头发出去了,就只能截断连接,
客户端看到的是"啥也没说就断了",没法告诉用户为什么。
中途失败(已经出了几块)就只能截断了 —— 头都发出去了,改不了状态码。
这种半截音频客户端会自然播完已收到的部分,不会崩。
"""
# 引擎是"设备自带"时不走流式:那种情况内核根本不参与合成,
# 直接告诉客户端"这轮该用系统 TTS",别让它收到一个莫名其妙的空音频错误。
state = speech.speech_state(settings)
if state.get('ttsEngine') == 'system':
self.send_json(200, {'ok': False, 'engine': 'system', 'error': '当前是系统朗读,不用云端合成'})
return
gen = speech.synthesize_stream(text, settings)
try:
mime, first = next(gen)
except StopIteration:
self.send_json(200, {'ok': False, 'error': '没有要朗读的内容'})
return
except speech.SpeechError as exc:
self.send_json(200, {'ok': False, 'error': str(exc)})
return
headers = {
'Content-Type': mime or 'audio/L16',
'Cache-Control': 'no-store',
'X-Audio-Stream': '1',
# HTTP/1.1 下没有 Content-Length 就必须分块,否则客户端会一直等 EOF
'Transfer-Encoding': 'chunked',
}
self.send_response(200)
for key, value in {**headers, **self.cors_headers()}.items():
self.send_header(key, value)
self.end_headers()
try:
self._write_chunk(first)
for _mime, chunk in gen:
self._write_chunk(chunk)
except (BrokenPipeError, ConnectionResetError):
# 用户点了停止 / 退出了页面:正常情况,不用报错
self.close_connection = True
except speech.SpeechError:
# 已经出了几块,头改不了,只能截断(见方法注释)
pass
finally:
try:
self.wfile.write(b'0\r\n\r\n')
self.wfile.flush()
except (OSError, ValueError):
self.close_connection = True
def read_body(self, limit: int = 4 * 1024 * 1024) -> bytes:
"""
取请求体。注意:底层读取在 _dispatch 里就已经做完了(见那里的注释),
这里只负责按各接口自己的上限做校验。
"""
raw = self._read_raw_body()
if len(raw) > limit:
raise ValueError('请求体过大')
return raw
def _read_raw_body(self) -> bytes:
if self._raw_body is None:
self._raw_body = self._read_body_raw(40 * 1024 * 1024)
return self._raw_body
def _read_body_raw(self, limit: int) -> bytes:
if (self.headers.get('Transfer-Encoding') or '').lower() == 'chunked':
return self._read_chunked(limit)
try:
length = int(self.headers.get('Content-Length') or 0)
except ValueError:
length = 0
if length <= 0:
return b''
if length > limit:
raise ValueError('请求体过大')
return self.rfile.read(length)
def _read_chunked(self, limit: int) -> bytes:
chunks = []
total = 0
while True:
line = self.rfile.readline().strip()
if not line:
break
try:
size = int(line.split(b';')[0], 16)
except ValueError:
break
if size == 0:
self.rfile.readline()
break
total += size
if total > limit:
raise ValueError('请求体过大')
chunks.append(self.rfile.read(size))
self.rfile.readline()
return b''.join(chunks)
def read_json_body(self, limit: int = 4 * 1024 * 1024) -> dict:
raw = self.read_body(limit)
if not raw:
return {}
try:
payload = json.loads(raw.decode('utf-8'))
except (ValueError, UnicodeDecodeError) as exc:
raise ValueError('请求体不是合法 JSON') from exc
return payload if isinstance(payload, dict) else {}
# ------------------------------ HTTP 方法 ------------------------------ #
def do_GET(self): # noqa: N802 - 基类约定
self._dispatch('GET')
def do_POST(self): # noqa: N802
self._dispatch('POST')
def do_PUT(self): # noqa: N802
self._dispatch('PUT')
def do_PATCH(self): # noqa: N802
self._dispatch('PATCH')
def do_DELETE(self): # noqa: N802
self._dispatch('DELETE')
def do_HEAD(self): # noqa: N802
self._dispatch('GET')
def do_OPTIONS(self): # noqa: N802
self._dispatch('OPTIONS')
def _dispatch(self, method: str) -> None:
try:
pathname = urlsplit(self.path).path
# 先把请求体整块读掉再路由。
# 为什么必须提前读:HTTP/1.1 是长连接,没被消费的字节会留在 socket 里,
# 被下一次请求解析成请求行(实测表现为 `{}PUT /api/settings` → 501)。
# Node 的 http 模块会在响应结束时自动丢弃未读数据,Python 的 http.server 不会。
#
# 注意 _raw_body 必须"每个请求"重置:BaseHTTPRequestHandler 的长连接
# 复用同一个 handler 实例(handle_one_request 循环),不重置就会把
# 上一个请求的 body 当成这一个的(GET 之后接 POST 会拿到空 body)。
self._raw_body = None
self._read_raw_body()
if os.environ.get('DOUBAO_HTTP_DEBUG'):
# 排查长连接错位时用:把每个请求实际读到的 body 前 80 字节打出来
print(
f'[req] {method} {pathname} clen={self.headers.get("Content-Length")} '
f'body={self._raw_body[:80]!r}',
file=sys.stderr,
flush=True,
)
if pathname.startswith('/api/'):
if not self.handle_api(method, pathname):
self.send_json(404, {'error': f'未知接口 {pathname}'})
return
if not self.handle_static(pathname):
self.send_text(404, '404 Not Found')
except Exception as exc: # noqa: BLE001 - 兜底,绝不让线程带着异常死掉
print(f'[http] 处理失败:{exc}', file=sys.stderr, flush=True)
try:
if not self.wfile.closed:
self.send_json(500, {'error': str(exc)})
except OSError:
self.close_connection = True
# -------------------------------- API -------------------------------- #
def handle_api(self, method: str, pathname: str) -> bool: # noqa: C901 - 就是一个大路由表
if method == 'OPTIONS':
self._head(204, {})
return True
if pathname == '/api/health':
self.send_json(200, {'ok': True, 'pid': os.getpid(), 'cwd': os.getcwd()})
return True
# 当前状态:设置(脱敏)+ 工具 + MCP + 会话列表 + 智能体
if pathname == '/api/state' and method == 'GET':
settings = store.read_settings()
tools = tools_runtime.list_all_tools(settings)
tool_names = [t.get('name') for t in tools['python']] + \
[d['function']['name'] for d in tools['mcp']]
self.send_json(200, {
'settings': store.mask_settings(settings),
'provider': store.provider_info(settings),
'providers': PROVIDER_PRESETS,
'speech': speech.speech_state(settings),
'speechVoices': {
'volc': speech.VOLC_VOICES,
'volcv3': speech.VOLC_V3_SPEAKERS,
'openai': speech.OPENAI_VOICES,
'system': [],
},
'python': {
'tools': [tools_runtime.public_spec(t) for t in tools['python']],
'errors': tools['errors'],
'interpreter': (tools['pythonInfo'] or {}).get('bin') if tools['pythonInfo'] else None,
},
'mcp': mcp_client.get_mcp_state(),
'mcpConfig': mcp_client.read_mcp_config(),
'conversations': store.list_conversations(),
'agents': store.list_agents(),
'toolNames': tool_names,
'suggestedAllow': tools_runtime.suggest_allowlist(tool_names),
# 前端用它挑终端里的预设命令(安卓的 getprop / Windows 的 dir 不通用)
'platform': 'android' if paths.IS_ANDROID else ('win32' if paths.IS_WINDOWS else 'linux'),
'shellKind': 'toybox' if paths.IS_ANDROID else ('cmd' if paths.IS_WINDOWS else 'sh'),
})
return True
if pathname == '/api/settings' and method in ('PUT', 'POST'):
patch = self.read_json_body()
nxt = store.write_settings(patch)
self.send_json(200, {'ok': True, 'settings': store.mask_settings(nxt)})
return True
if pathname == '/api/models' and method == 'GET':
settings = store.read_settings()
try:
models = providers.list_models(base_url=settings.get('baseUrl') or '',
api_key=settings.get('apiKey') or '')
self.send_json(200, {'ok': True, 'models': models})
except Exception as exc: # noqa: BLE001 - 拉模型失败不是致命错误
preset = PROVIDER_PRESETS.get(settings.get('provider')) or {}
self.send_json(200, {'ok': False, 'error': str(exc), 'fallback': preset.get('models') or []})
return True
# ---------------------------------------------------------------- #
# 语音
#
# 两个接口都刻意**失败也返回 HTTP 200 + ok:false**:
# 缺 Key、厂商报错这些都是"预期内的失败",界面要的是把原因显示出来,
# 而不是让 fetch 抛一个网络异常(那样错误信息就丢了)。
# ---------------------------------------------------------------- #
if pathname == '/api/tts' and method == 'POST':
try:
body = self.read_json_body()
except ValueError:
body = {}
settings = store.read_settings()
try:
result = speech.synthesize(body.get('text') or '', settings)
self.send_json(200, {'ok': True, **result})
except speech.SpeechError as exc:
self.send_json(200, {'ok': False, 'error': str(exc)})
return True
if pathname == '/api/tts/stream' and method == 'POST':
# 边合成边下发:音频块一到就写出去,客户端能立刻开始播,
# 不用等整段合成完(实测长句首块 ~0.9s 到、末块 ~2.7s 到)。
try:
body = self.read_json_body()
except ValueError:
body = {}
settings = store.read_settings()
self.stream_tts(body.get('text') or '', settings)
return True
if pathname == '/api/stt' and method == 'POST':
# 音频是原始字节(不套 JSON/base64):省一次编解码,安卓那边录完直接发
audio = self._read_raw_body()
settings = store.read_settings()
try:
result = speech.transcribe(
audio,
self.headers.get('X-Audio-Filename') or 'audio.wav',
self.headers.get('X-Audio-Type') or 'audio/wav',
settings,
)
self.send_json(200, {'ok': True, **result})
except speech.SpeechError as exc:
self.send_json(200, {'ok': False, 'error': str(exc)})
return True
if pathname == '/api/speech' and method == 'GET':
settings = store.read_settings()
state = speech.speech_state(settings)
self.send_json(200, {
'ok': True,
'speech': state,
'voices': {
# ★ 三个引擎都要给全:漏掉一个,界面那边对应引擎就一个音色都选不出来。
# (volcv3 曾经漏过,跟 /api/state 那处不一致)
'volc': speech.VOLC_VOICES,
'volcv3': speech.VOLC_V3_SPEAKERS,
'openai': speech.OPENAI_VOICES,
'system': [],
},
})
return True
# 会话
if pathname == '/api/conversations' and method == 'GET':
self.send_json(200, {'conversations': store.list_conversations()})
return True
if pathname == '/api/conversations' and method == 'POST':
try:
body = self.read_json_body()
except ValueError:
body = {}
self.send_json(200, {'conversation': store.create_conversation(body.get('title') or '新对话')})
return True
conv_id = self._match_id(pathname, '/api/conversations/')
if conv_id is not None:
if method == 'GET':
conv = store.get_conversation(conv_id)
if conv:
self.send_json(200, {'conversation': conv})
else:
self.send_json(404, {'error': '会话不存在'})
return True
if method in ('PATCH', 'PUT'):
body = self.read_json_body()
conv = store.update_conversation(conv_id, body)
if conv:
self.send_json(200, {'conversation': conv})
else:
self.send_json(404, {'error': '会话不存在'})
return True
if method == 'DELETE':
ok = store.delete_conversation(conv_id)
self.send_json(200 if ok else 404, {'ok': ok})
return True
# 工具
if pathname == '/api/tools' and method == 'GET':
settings = store.read_settings()
tools = tools_runtime.list_all_tools(settings)
tool_names = [t.get('name') for t in tools['python']] + \
[d['function']['name'] for d in tools['mcp']]
self.send_json(200, {
'python': [tools_runtime.public_spec(t) for t in tools['python']],
'errors': tools['errors'],
'mcp': mcp_client.get_mcp_state(),
'toolNames': tool_names,
'suggestedAllow': tools_runtime.suggest_allowlist(tool_names),
})
return True
if pathname == '/api/tools/run' and method == 'POST':
body = self.read_json_body()
name = body.get('name')
if not name:
self.send_json(400, {'error': '缺少 name'})
return True
try:
# 手动试运行不受安全模式限制(是用户自己点的),但仍要能报错
result = tools_runtime.execute_tool(name, body.get('args') or {},
{'security': {'mode': 'open'}})
self.send_json(200, result)
except Exception as exc: # noqa: BLE001
self.send_json(500, {'ok': False, 'error': str(exc)})
return True
# MCP
if pathname == '/api/mcp' and method == 'GET':
config_path = mcp_client.mcp_config_path()
self.send_json(200, {
'servers': mcp_client.get_mcp_state(),
'config': mcp_client.read_mcp_config(),
'path': config_path,
'dir': os.path.dirname(config_path),
'text': mcp_client.read_mcp_config_text(),
# 安卓上没有"打开文件夹"这回事,除非 Kotlin 侧挂了钩子
'canReveal': callable(_hooks.get('reveal')),
'placeholders': {
'DOUBAO_DATA': paths.get().data_dir,
'APPDATA': os.environ.get('APPDATA', ''),
'USERPROFILE': os.environ.get('USERPROFILE', ''),
},
})
return True
if pathname == '/api/mcp/config' and method in ('PUT', 'POST'):
body = self.read_json_body()
try:
count = mcp_client.write_mcp_config_text(str(body.get('text') or ''))
mcp_client.disconnect_all()
results = mcp_client.connect_all_enabled()
self.send_json(200, {
'ok': True,
'count': count,
'results': results,
'servers': mcp_client.get_mcp_state(),
})
except Exception as exc: # noqa: BLE001
self.send_json(400, {'ok': False, 'error': str(exc)})
return True
if pathname == '/api/mcp/reveal' and method == 'POST':
target = mcp_client.mcp_config_path()
reveal = _hooks.get('reveal')
if callable(reveal):
error = reveal(target)
self.send_json(200, {'ok': not error, 'error': error or None, 'path': target})
else:
self.send_json(200, {'ok': False, 'error': '当前运行方式不支持打开文件夹', 'path': target})
return True
if pathname == '/api/mcp/connect' and method == 'POST':
body = self.read_json_body()
if body.get('name'):
record = mcp_client.connect(body['name'], force=True)
self.send_json(200, {'ok': not record.get('error'), 'error': record.get('error'),
'toolCount': len(record.get('tools') or [])})
else:
results = mcp_client.connect_all_enabled()
self.send_json(200, {'ok': all(r.get('ok') for r in results), 'results': results})
return True
if pathname == '/api/mcp/disconnect' and method == 'POST':
body = self.read_json_body()
mcp_client.disconnect(body.get('name'))
self.send_json(200, {'ok': True})
return True
# 智能体
if pathname == '/api/agents' and method == 'GET':
self.send_json(200, {'agents': store.list_agents()})
return True
if pathname == '/api/agents' and method == 'POST':
body = self.read_json_body()
self.send_json(200, {'agent': store.create_agent(body)})
return True
agent_id = self._match_id(pathname, '/api/agents/')
if agent_id is not None:
if method in ('PATCH', 'PUT'):
body = self.read_json_body()
agent = store.update_agent(agent_id, body)
if agent:
self.send_json(200, {'agent': agent})
else:
self.send_json(404, {'error': '智能体不存在'})
return True
if method == 'DELETE':
self.send_json(200 if store.delete_agent(agent_id) else 404, {'ok': True})
return True
# 附件
if pathname == '/api/upload' and method == 'POST':
body = self.read_json_body(40 * 1024 * 1024)
try:
item = uploads.save_upload(body.get('name'), body.get('dataUrl') or body.get('base64'))
if body.get('pending'):
uploads.add_pending([item])
self.send_json(200, {'ok': True, 'file': item})
except Exception as exc: # noqa: BLE001
self.send_json(400, {'ok': False, 'error': str(exc)})
return True
if pathname == '/api/pick-file' and method == 'POST':
picker = _hooks.get('pick_file')
if not callable(picker):
self.send_json(200, {'ok': False, 'error': '当前环境不支持原生选文件,请拖拽文件到窗口里',
'files': []})
return True
try:
picked = picker() or []
files = [uploads.register_local_file(p) for p in picked]
self.send_json(200, {'ok': True, 'files': files})
except Exception as exc: # noqa: BLE001
self.send_json(500, {'ok': False, 'error': str(exc), 'files': []})
return True
if pathname == '/api/uploads/pending' and method == 'GET':
self.send_json(200, {'files': uploads.take_pending()})
return True
if pathname == '/api/clipboard' and method == 'POST':
body = self.read_json_body()
writer = _hooks.get('clipboard')
if callable(writer):
writer(str(body.get('text') or ''))
self.send_json(200, {'ok': True, 'via': 'native'})
else:
self.send_json(200, {'ok': False, 'via': 'none'})
return True
# 流式对话(SSE 或轮询,由 body.transport 决定)
if pathname == '/api/chat' and method == 'POST':
_reap_runs()
self._handle_chat()
return True
# 轮询取增量:安卓端 Lynx 原生 fetch 没有流式 body,走这条
if pathname == '/api/chat/poll' and method == 'GET':
self._handle_chat_poll()
return True
# 前端用它判断"这条通道能不能边收边解析"
if pathname == '/api/chat/transport' and method == 'GET':
self.send_json(200, {'ok': True, 'sse': True, 'poll': True})
return True
return False
@staticmethod
def _match_id(pathname: str, prefix: str):
"""匹配 /api/xxx/<id>;id 里带斜杠的情况按 Node 的正则一样不支持。"""
if not pathname.startswith(prefix):
return None
rest = pathname[len(prefix):]
if not rest or '/' in rest:
return None
return unquote(rest)
# ------------------------------- 对话 ------------------------------- #
def _handle_chat(self) -> None:
body = self.read_json_body()
settings = store.read_settings()
conversation_id = body.get('conversationId') or 'c_main'
text = str(body.get('message') or '').strip()
attachments = body.get('attachments') if isinstance(body.get('attachments'), list) else []
if not text and not attachments:
self.send_json(400, {'error': '消息为空'})
return
# ★ 轮询模式:安卓上 Lynx 原生端的 fetch 没有 response.body,边收边解析做不到,
# 所以那条路走「先拿 runId,再每 200ms GET /api/chat/poll 取增量」。
# 两条路共用 _perform_chat,事件完全一致。
if body.get('transport') == 'poll':
run_id = 'r%d%s' % (int(time.time() * 1000), uuid.uuid4().hex[:5])
with _RUNS_LOCK:
_RUNS[run_id] = {'events': [], 'done': False, 'at': time.time()}
self.send_json(200, {'ok': True, 'runId': run_id, 'transport': 'poll'})
def sink_send(event):
with _RUNS_LOCK:
run = _RUNS.get(run_id)
if run is None:
return
run['events'].append(event)
if event.get('type') in ('done', 'error'):
run['done'] = True
def sink_end():
with _RUNS_LOCK:
run = _RUNS.get(run_id)
if run is not None:
run['done'] = True
# 后台线程跑,立刻把 HTTP 请求放掉
worker = threading.Thread(
target=self._perform_chat,
args=(sink_send, sink_end, settings, conversation_id, text, attachments, body),
name='chat-run',
daemon=True,
)
worker.start()
return
sse = SseChannel(self)
sse.start()
self._perform_chat(
sse.send, sse.end, settings, conversation_id, text, attachments, body,
should_stop=sse.should_stop,
)
def _perform_chat(self, emit, end, settings, conversation_id, text, attachments, body,
should_stop=None) -> None:
"""跑一轮对话。SSE 与轮询两条路共用,保证事件序列一致。"""
cancelled = should_stop or (lambda: False)
try:
existing = store.get_conversation(conversation_id) or {}
history_source = body.get('history') if isinstance(body.get('history'), list) else \
existing.get('messages') or []
history = [
{'role': m.get('role'), 'content': m.get('content')}
for m in history_source
if isinstance(m, dict) and m.get('role') in ('user', 'assistant')
]
# 附件 → 模型输入:图片走视觉格式,文本类内联正文
parts = []
if text:
parts.append({'type': 'text', 'text': text})
attachment_meta = []
for item in attachments:
payload = uploads.attachment_payload(item)
if payload.get('text'):
parts.append({'type': 'text', 'text': payload['text']})
for image in payload.get('images') or []:
parts.append({'type': 'image_url', 'image_url': {'url': image['url']}})
attachment_meta.append({
'id': item.get('id'),
'name': item.get('name'),
'size': item.get('size'),
'mime': item.get('mime'),
'url': item.get('url') or '',
})
has_image = any(p.get('type') == 'image_url' for p in parts)
user_content = parts if (has_image or len(parts) > 1) else text
agent = store.get_agent(body.get('agentId')) or store.get_agent(settings.get('activeAgentId'))
store.append_messages(conversation_id, [{
'role': 'user',
'content': text or f'(已发送 {len(attachment_meta)} 个附件)',
'attachments': attachment_meta,
'at': store.now_iso(),
}])
if text:
store.auto_title(conversation_id, text)
result = agent_loop.run_agent(
settings=settings,
agent=agent,
messages=[*history, {'role': 'user', 'content': user_content}],
emit=emit,
should_stop=cancelled,
)
store.append_messages(conversation_id, [{
'role': 'assistant',
'content': result.get('content', ''),
# 思维链也要落库,否则一刷新「思考过程」就没了
'reasoning': result.get('reasoning', '') or '',
'agentId': (agent or {}).get('id') or '',
'at': store.now_iso(),
}])
conv = store.get_conversation(conversation_id) or {}
emit({'type': 'saved', 'conversationId': conversation_id, 'title': conv.get('title')})
except Exception as exc: # noqa: BLE001 - 出错也要以 error 事件收尾,前端才知道停了
emit({'type': 'error', 'message': str(exc), 'hint': chat_error_hint(exc, settings)})
finally:
end()
def _handle_chat_poll(self) -> None:
"""GET /api/chat/poll?runId=xxx&cursor=N —— 取增量事件"""
parsed = urlsplit(self.path)
params = dict(
pair.split('=', 1) for pair in (parsed.query or '').split('&') if '=' in pair
)
run_id = unquote(params.get('runId') or '')
try:
cursor = max(0, int(params.get('cursor') or 0))
except ValueError:
cursor = 0
with _RUNS_LOCK:
run = _RUNS.get(run_id)
if run is None:
self.send_json(404, {'ok': False, 'error': '任务不存在或已过期'})
return
events = run['events'][cursor:]
total = len(run['events'])
done = run['done']
if done and total == cursor:
run['at'] = time.time() - 9 * 60 # 取完了,很快就能回收
self.send_json(200, {'ok': True, 'events': events, 'cursor': total, 'done': done})
# -------------------------------- 静态 -------------------------------- #
def handle_static(self, pathname: str) -> bool:
p = paths.get()
if pathname in ('/', '/index.html'):
index = os.path.join(p.web_dir, 'index.html')
if not os.path.isfile(index):
self.send_text(503, INDEX_MISSING_HINT)
return True
return self.serve_file(index)
if pathname.startswith('/lynx-web/'):
target = safe_join(p.web_core_dir, pathname[len('/lynx-web'):])
# 注意:Node 版这里漏了 404(serveFile 返回 false 被 `|| true` 吃掉,
# 请求会一直挂着)。Python 版改成正常 404,行为更好且不影响前端。
return bool(target and self.serve_file(target))
# 上传的附件(图片缩略图要用)
if pathname.startswith('/uploads/'):
target = safe_join(p.uploads_dir, pathname[len('/uploads'):])
if target and os.path.isfile(target):
return self.serve_file(target)
# @lynx-js/web-core 的运行时固定从 /static/ 拉 chunk 与 wasm,必须原样托管
if pathname.startswith('/static/'):
target = safe_join(p.web_core_dir, pathname[len('/static'):])
if target and os.path.isfile(target):
return self.serve_file(target)
if pathname in ('/main.web.bundle', '/main.lynx.bundle'):
return self.serve_file(os.path.join(p.dist_dir, os.path.basename(pathname)))
dist_file = safe_join(p.dist_dir, pathname)
if dist_file and os.path.isfile(dist_file):
return self.serve_file(dist_file)
return False
def serve_file(self, file_path: str) -> bool:
if not os.path.isfile(file_path):
return False
ext = os.path.splitext(file_path)[1].lower()
size = os.path.getsize(file_path)
cache = 'no-cache' if ext == '.bundle' else 'public, max-age=0, must-revalidate'
self._head(200, {
'Content-Type': MIME.get(ext, 'application/octet-stream'),
'Content-Length': str(size),
'Cache-Control': cache,
})
if self.command == 'HEAD':
return True
with open(file_path, 'rb') as fh:
while True:
chunk = fh.read(256 * 1024)
if not chunk:
break
self.wfile.write(chunk)
return True
def create_server(host: str, port: int) -> ThreadingHTTPServer:
"""建好但还没启动的 HTTP 服务(main.py / 安卓侧都用这个)。"""
server = ThreadingHTTPServer((host, port), KernelHandler)
server.daemon_threads = True
return server