""" 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/ 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/ 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 datetime import datetime, timezone from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from urllib.parse import unquote, urlsplit import agent_loop import mcp_client import meeting 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 def _custom_defs(): """ 加载用户的自定义节点。 ★ 用 try 包住:加载器自己出问题(比如数据目录不可写)也不能让 meta 挂掉 —— meta 挂了整个会议界面就是白屏,用户连"哪里出错了"都看不到。 坏掉的节点以 error 字段返回,界面上照样列出来、显示原因。 """ try: import custom_nodes return custom_nodes.list_defs() except Exception as exc: # noqa: BLE001 return [{'key': '', 'label': '(自定义节点加载失败)', 'error': f'{type(exc).__name__}: {exc}'}] def _custom_dir(): try: import custom_nodes return custom_nodes.nodes_dir() except Exception: # noqa: BLE001 return '' 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/meetings' and method == 'GET': self.send_json(200, {'meetings': meeting.list_meetings()}) return True if pathname == '/api/meetings' and method == 'POST': body = self.read_json_body() self.send_json(200, {'meeting': meeting.create_meeting(body)}) return True if pathname == '/api/meeting/meta' and method == 'GET': # 编辑器要用:节点类型、判断条件、可用智能体 self.send_json(200, { # ★ 用户用 Python 拓展出来的节点也在这里列出来。 # 界面拿到 inputs / outputs 就能**自动画出引脚** —— # 不用在 Kotlin 里再写一份,也就不会再出现 # "引擎有了、界面没有"那种事。 'customNodes': [ { 'key': d.get('key'), 'label': d.get('label'), 'desc': d.get('desc') or '', 'file': os.path.basename(d.get('file') or ''), 'inputs': d.get('inputs') or [], 'outputs': d.get('outputs') or [], 'hasExecIn': bool(d.get('hasExecIn')), 'error': d.get('error') or '', } for d in _custom_defs() ], 'customDir': _custom_dir(), 'nodeTypes': [ {'key': 'start', 'label': '开始事件', 'desc': '整张图从这里开始(exec 起点)'}, {'key': 'agent', 'label': '智能体', 'desc': '一个智能体处理一轮'}, {'key': 'judge', 'label': '判断', 'desc': '按条件分 true / false 两条路'}, {'key': 'end', 'label': '最终输出', 'desc': '汇总结果'}, {'key': 'var', 'label': '写变量', 'desc': '把内容存进一个变量,后面任何节点都能读'}, {'key': 'readvar', 'label': '读变量', 'desc': '纯节点:取变量当前值(只出数据,没有 exec)'}, {'key': 'value', 'label': '值', 'desc': '纯节点:一个写死的值,接到智能体的数据输入'}, {'key': 'while', 'label': 'while 循环', 'desc': '条件为真就跑循环体,像 C 的 while'}, {'key': 'cast', 'label': '转换', 'desc': '纯节点:str / bool / num 互转'}, {'key': 'op', 'label': '运算', 'desc': '纯节点:+ − × ÷ % 拼接 取反 比较'}, {'key': 'py', 'label': 'Python', 'desc': '写一段 Python(run(ctx)),也可以给智能体当工具调'}, ], 'judgeKinds': [{'key': k, 'label': v} for k, v in meeting.JUDGE_KINDS], 'agents': [ {'id': a.get('id'), 'name': a.get('name'), 'avatar': a.get('avatar')} for a in store.list_agents() ], }) return True # 运行历史:结果界面要能回看前几次跑了什么 if pathname.startswith('/api/meetings/') and pathname.endswith('/runs'): mid = pathname[len('/api/meetings/'):-len('/runs')] if method == 'GET': self.send_json(200, {'runs': meeting.list_runs(mid)}) return True if method == 'DELETE': self.send_json(200, {'ok': meeting.clear_runs(mid)}) return True # /api/meetings//run —— 走 SSE 跑整张图。 # ★ 必须在 _match_id 之前处理:那个函数明确拒绝带斜杠的 id, # 而这里路径里就有一个 /run,交给它会永远匹配不上。 if pathname.startswith('/api/meetings/') and pathname.endswith('/run') and method == 'POST': self._handle_meeting_run(pathname[len('/api/meetings/'):-len('/run')]) return True meeting_id = self._match_id(pathname, '/api/meetings/') if meeting_id is not None: if method == 'GET': item = meeting.get_meeting(meeting_id) if item: self.send_json(200, {'meeting': item}) else: self.send_json(404, {'error': '会议不存在'}) return True if method in ('PUT', 'PATCH'): body = self.read_json_body() item = meeting.save_meeting(meeting_id, body) if item: self.send_json(200, {'meeting': item}) else: self.send_json(404, {'error': '会议不存在'}) return True if method == 'DELETE': ok = meeting.delete_meeting(meeting_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 里带斜杠的情况按 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_meeting_run(self, meeting_id: str) -> None: """跑一整张会议图,事件走 SSE。""" body = self.read_json_body() settings = store.read_settings() item = meeting.get_meeting(meeting_id) if not item: self.send_json(404, {'error': '会议不存在'}) return user_input = str(body.get('input') or '').strip() sse = SseChannel(self) sse.start() def run_agent_fn(node: dict, incoming: str, cfg: dict, emit, node_id: str, variables: dict) -> str: """ 跑一个 agent 节点 / AI 判断节点。 ★ 节点的附加提示词和输出控制都是**拼在系统提示词后面**,而不是替换它 —— 智能体本身的人设("你是毒舌评论员")不能被节点的输出要求顶掉, 两者是"人设 + 这一轮的额外要求"的关系。 variables 是整场会议共享的变量表。节点上勾了可读/可写变量时, 可读的把当前值拼进提示词,可写的告诉它怎么用 [[SET 名字=值]] 写回来。 """ # ★ 节点上勾了「可用工具」时,会议里那些 Python 节点会**变成这个智能体 # 能调用的工具**(用户要的"智能体可以调用节点工具")。 # 工具定义走 cfg 里的 nodeTools,由 tools_runtime 统一组装和派发 —— # 不在这里自己拼,免得和内置工具那套分家。 tool_ids = node.get('toolNodes') or [] if tool_ids: id_set = set(tool_ids) node_tools = [] for pn in (item.get('nodes') or []): if pn.get('type') != 'py' or pn.get('id') not in id_set: continue # 工具名必须是合法标识符:拿节点标题清洗一下,不行就用 id;重名加序号 raw = str(pn.get('title') or '').strip() name = ''.join(ch if (ch.isalnum() or ch == '_') else '_' for ch in raw) if not name or not (name[0].isalpha() or name[0] == '_'): name = 'py_' + str(pn.get('id')) base = name k = 2 while any(t['name'] == name for t in node_tools): name = f'{base}_{k}' k += 1 node_tools.append({ 'name': name, 'description': str(pn.get('desc') or pn.get('title') or '') or '会议里的自定义 Python 工具', 'code': pn.get('code') or '', 'node': pn, 'variables': variables, }) if node_tools: cfg = {**(cfg or {}), 'nodeTools': node_tools} agent = store.agent_or_empty(node.get('agentId') or '') or None extra = (node.get('extraPrompt') or '').strip() control = (node.get('outputControl') or '').strip() if node.get('_judgeOnly'): # AI 判断:只要一个是/否,别的都不要 sys_prompt = ( '你是一个判断器。根据下面给出的内容回答 YES 或 NO,' '不要解释、不要加别的字。\n\n判断标准:' + (extra or '内容是否合格') ) merged_agent = {'systemPrompt': sys_prompt, 'id': '', 'name': '判断器'} else: base = (agent or {}).get('systemPrompt') or cfg.get('systemPrompt') or '' parts = [base] if base.strip() else [] if extra: parts.append('【本次任务的额外要求】\n' + extra) if control: parts.append('【输出要求】\n' + control) # 变量说明拼在最后:它和"输出要求"一样是这一轮的约束, # 但放在更后面,模型对"最后看到的东西"注意力更高 # 变量登记表里的**类型和描述**也一起给模型: # 光有变量名,模型只能猜"这个 isRun 是次数还是个开关"。 var_meta = { v.get('name'): {'type': v.get('type'), 'note': v.get('note')} for v in ((item or {}).get('vars') or []) } var_text = meeting.variables_prompt( variables, node.get('readVars'), node.get('writeVars'), var_meta) if var_text: parts.append(var_text) merged_agent = {**(agent or {}), 'systemPrompt': '\n\n'.join(parts)} # 上游内容作为这一轮的用户消息;没有上游就给个占位,免得空消息报错 message = incoming.strip() or '(上游没有内容,请根据你的角色直接开始)' def relay(event): # 只把正文增量转成 node_delta,其它事件(工具调用、思维链)原样转发, # 界面上按节点分组显示。 # # ★ 流式正文的事件名是 **delta**,不是 text —— agent_loop 发的是 # {'type':'delta','text':…}。我之前按 'text' 判断,结果 node_delta # 一个都没发出去,节点上的正文只在最后 node_done 时"啪"地出现, # 完全没有流式效果。事件统计日志(delta=103 / node_delta=0)抓到的。 kind = event.get('type') if kind == 'delta': emit({'type': 'node_delta', 'nodeId': node_id, 'text': event.get('text') or ''}) elif kind in ('done', 'start'): # 这两个是"整个 agent 轮次"的开始和结束,和会议节点的语义重复, # 转出去只会让界面多两个没用的状态 pass elif kind == 'reasoning': emit({'type': 'node_reasoning', 'nodeId': node_id, 'text': event.get('text') or ''}) else: emit({**event, 'nodeId': node_id}) result = agent_loop.run_agent( settings=cfg, messages=[{'role': 'user', 'content': message}], agent=merged_agent, emit=relay, should_stop=sse.should_stop, ) raw = (result or {}).get('content') or '' # ★ 这里**不**处理 [[SET]]:那是节点语义,归引擎管(见 meeting.run_meeting)。 # 放在这一层的话,引擎自己的测试压根覆盖不到,换个调用方也会忘 —— # 真发生过:引擎测试全绿,一上 HTTP 就漏出 [[SET]] 那行。 return raw try: # ★ 一边转发一边攒一份运行记录:结果界面要能按"哪个节点、第几轮" # 回看,而不是只有一个最终答案。循环跑很多轮时这份记录尤其有用。 steps = [] final = {'output': '', 'aborted': False, 'error': ''} def record(event): sse.send(event) kind = event.get('type') if kind == 'node_done': steps.append({ 'nodeId': event.get('nodeId'), 'nodeType': event.get('nodeType'), 'title': event.get('title'), 'run': event.get('run') or 1, 'output': event.get('output') or '', 'note': event.get('note') or '', # ★ 判断 / while 的结论必须留下来:结果界面要写明 # "这个判断走的是真还是假"。只留 output 的话, # 回看时只看到一段文本,根本不知道当时判成了什么。 'verdict': event.get('verdict'), 'branch': event.get('branch') or '', }) elif kind == 'node_error': steps.append({ 'nodeId': event.get('nodeId'), 'nodeType': event.get('nodeType'), 'title': event.get('title'), 'run': event.get('run') or 1, 'output': '', 'error': event.get('error') or '', }) elif kind == 'meeting_done': final['output'] = event.get('output') or '' final['aborted'] = bool(event.get('aborted')) final['error'] = event.get('error') or '' # 多个最终输出(结果界面按标签页展示) final['results'] = event.get('results') or [] meeting.run_meeting( meeting=item, settings=settings, user_input=user_input, emit=record, run_agent_fn=run_agent_fn, should_stop=sse.should_stop, ) # 存历史。节点标题在事件里可能没有(引擎只在 node_start 里给), # 这里从会议定义里补齐,免得历史界面上全是"未命名"。 titles = {n['id']: n.get('title') for n in (item.get('nodes') or [])} for step in steps: if not step.get('title'): step['title'] = titles.get(step.get('nodeId')) or '' meeting.append_run(meeting_id, { 'at': datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z'), 'input': user_input, 'steps': steps, 'results': final.get('results') or [], 'output': final['output'], 'aborted': final['aborted'], 'error': final['error'], }) except Exception as exc: # noqa: BLE001 # 引擎自己炸了也要让界面知道,不能一声不响地断掉 sse.send({'type': 'meeting_done', 'output': '', 'error': f'{type(exc).__name__}: {exc}'}) finally: sse.end() 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