Files
doubao-clone/android/kernel/app.py
l 24cc34d79b 智能体支持独立模型与语音(留空继承全局)
用户需求 A。规则是**智能体 > 全局**:智能体自己配了 provider / model /
baseUrl / ttsEngine / ttsVoice / ttsSpeed 就用它的,留空(空串 / null / 0)
就沿用全局设置。

这样"代码搭子走 DeepSeek、文案师换个音色"只改那一个智能体,
而全局设置仍然是没配过的智能体的默认值。

【内核】
- store.provider_info(settings, agent):provider/model/baseUrl 三层解析
  (智能体 > 全局 > 预设)
- speech.voice_for(settings, agent):音色解析,只有这一份实现 ——
  别在别处再抄一遍规则,两处不一致最难查
- agent_loop 用解析后的 provider 发请求(以前永远走全局)
- /api/tts 和 /api/tts/stream 接受 agentId;流式的"是不是系统引擎"
  判断也要用**智能体覆盖后**的那套 —— 某个智能体单独配了云端音色、
  全局是"设备自带"时,不能因为全局是 system 就把它的流式挡掉

【关键设计:多人会议靠它区分谁在说话】
四个智能体一个嗓子的话,会议模式根本没法听。所以音色必须能按智能体覆盖 ——
这是会议模式的前置依赖,先做掉。

【测试抓到的两个真 bug】
1. store.create_agent / update_agent 用的是**硬编码字段白名单**,
   ttsVoice 这些新字段直接被丢掉 —— 表现就是"界面上填了、保存后又变空"。
   两份内核都有这个问题。现在字段表提成常量(AGENT_FIELDS),
   create / update 共用,加字段不会再漏改一处。
2. Node 的 /api/tts/stream 忘了给 synthesizeStream 传 agent。

这两条都是新加的回归断言抓到的 —— 不是我看代码看出来的。

【顺带】
- store.py 少了 PROVIDER_PRESETS 的 import(一跑内核就 NameError)
- 排查时手滑把 VOLC_TTS_URL 的定义删了(node --check 查不出运行时错误,
  是导入模块才暴露的)

回归:语音验收 36 → 41 项(新增 5 条智能体音色断言:
带 agentId 用自己的、不传回落全局、智能体没配则继承全局),
两份内核各 41/41;Markdown 对拍 19/19。

【这一轮之后还剩】
- B 的界面部分:可搜索的全量音色选择器(内核数据已就位)
- A 的界面部分:智能体编辑页的模型/语音选择
- C 会议模式(节点+连线编排)—— 最大的一块,下一轮开始
2026-10-10 11:10:29 +08:00

1072 lines
46 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
def _trace_tts(text: str, outcome: str, total_bytes: int, chunks: int, seconds: float) -> None:
"""
把每次流式朗读的结果写一行到 kernel-data/tts-trace.log。
为什么不用 print/log:这台 ROM 把应用日志全吞了(logcat 里一条 app 记录都没有),
排查"读一半就不读了"时最要紧的问题是**音频是我们没发完,还是客户端提前断开**,
没有这个就只能在两边瞎猜。
outcome 的取值:
completed 正常发完
client_aborted(...) 客户端提前断开 —— 音频是它不要了
upstream_error(...) 厂商那边断了
kernel_error(...) 内核自己出错
按 48000 字节/秒能算出这段音频本该有多长,和实际耗时一比就知道断在哪。
"""
try:
path = os.path.join(paths.get().data_dir, 'tts-trace.log')
line = json.dumps({
'at': time.strftime('%m-%d %H:%M:%S'),
'textChars': len(text),
'outcome': outcome,
'bytes': total_bytes,
'audioSec': round(total_bytes / 48000.0, 1), # PCM 24k 单声道 16bit
'chunks': chunks,
'elapsedSec': round(seconds, 1),
}, ensure_ascii=False)
with open(path, 'a', encoding='utf-8') as fh:
fh.write(line + '\n')
# 只留最后 200 行,别让它无限长
with open(path, encoding='utf-8') as fh:
rows = fh.readlines()
if len(rows) > 200:
with open(path, 'w', encoding='utf-8') as fh:
fh.writelines(rows[-200:])
except Exception: # noqa: BLE001
# 追踪本身绝不能影响朗读
pass
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, agent_id: str = '') -> None:
"""
边合成边下发音频。
★ 关键设计:**先把第一块取出来,再发响应头**。
合成失败(Key 不对、音色不存在……)基本都发生在第一块之前,
这时候还没发头,就能照常返回一个 JSON 错误,客户端能拿到具体原因并
退回系统 TTS。要是先把头发出去了,就只能截断连接,
客户端看到的是"啥也没说就断了",没法告诉用户为什么。
中途失败(已经出了几块)就只能截断了 —— 头都发出去了,改不了状态码。
这种半截音频客户端会自然播完已收到的部分,不会崩。
"""
# 引擎是"设备自带"时不走流式:那种情况内核根本不参与合成,
# 直接告诉客户端"这轮该用系统 TTS",别让它收到一个莫名其妙的空音频错误。
#
# ★ 判断引擎要用**智能体覆盖后**的那套:某个智能体单独配了云端音色、
# 而全局是"设备自带"时,不能因为全局是 system 就把它的流式挡掉。
agent = store.agent_or_empty(agent_id)
state = speech.voice_for(settings, agent)
if (state.get('ttsEngine') or 'system') == 'system':
self.send_json(200, {'ok': False, 'engine': 'system', 'error': '当前是系统朗读,不用云端合成'})
return
# ★ 追踪写文件而不是打日志:这台 ROM 会把应用日志吞掉,排查时
# "到底是我们没发完还是客户端提前断开"根本无从判断。
total_bytes = 0
t0 = time.time()
gen = speech.synthesize_stream(text, settings, agent)
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)
total_bytes += len(first)
chunks = 1
for _mime, chunk in gen:
self._write_chunk(chunk)
total_bytes += len(chunk)
chunks += 1
outcome = 'completed'
n_chunks = chunks
except (BrokenPipeError, ConnectionResetError) as exc:
# ★ 客户端提前断开 —— 这是判断"谁断的"的关键信号。
# 如果是这种,说明音频是客户端那边不要了(用户点了停止、或者播放端
# 自己退出了循环),不是我们没发完。
outcome = f'client_aborted({type(exc).__name__})'
n_chunks = 0
self.close_connection = True
except speech.SpeechError as exc:
# 已经出了几块,头改不了,只能截断(见方法注释)
outcome = f'upstream_error({exc})'
n_chunks = 0
except Exception as exc: # noqa: BLE001
# 兜底:别让流式这条路的任何意外把请求线程带走
outcome = f'kernel_error({type(exc).__name__}: {exc})'
n_chunks = 0
finally:
try:
self.wfile.write(b'0\r\n\r\n')
self.wfile.flush()
except (OSError, ValueError):
self.close_connection = True
_trace_tts(text, outcome, total_bytes, locals().get('n_chunks', 0), time.time() - t0)
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:
# 上限按**最大的那个接口**给:/api/upload 收 100MB 文件时,
# base64 之后是约 133MB,再套一层 JSON,150MB 才够用。
# 其它接口各自在 read_body/read_json_body 里卡自己的小上限。
self._raw_body = self._read_body_raw(150 * 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': [],
},
# 全量音色:界面上的"全部音色"用这个(V1 73 个 / V3 90 个),
# 上面的 speechVoices 只是快捷胶囊用的常用项
'speechVoicesAll': {
'volc': speech.VOLC_VOICES_ALL,
'volcv3': speech.VOLC_V3_SPEAKERS_ALL,
'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()
# 带上 agentId 就用那个智能体的音色(多人会议里不同智能体不同声音,
# 否则四个人一个嗓子根本听不出谁在说)。不传就沿用全局。
agent = store.agent_or_empty(body.get('agentId') or '')
try:
result = speech.synthesize(body.get('text') or '', settings, agent)
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, body.get('agentId') or '')
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':
# 150MB:100MB 上限的文件 base64 之后约 133MB,再套 JSON。
# 这个值和 uploads.COPY_LIMIT 是联动的,改一个要改另一个。
body = self.read_json_body(150 * 1024 * 1024)
try:
# 三个字段名都收:dataUrl 是约定名,base64 是历史名,
# data 是安卓客户端曾经错发过的名字 —— 收下它,
# 免得已经装在手机上的旧版本一直传不上来。
item = uploads.save_upload(
body.get('name'),
body.get('dataUrl') or body.get('base64') or body.get('data'),
)
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