规则引擎的**执行层**接完了。仍不发版 —— 还差"规则包导入导出", 没有它用户根本建不出规则包,功能实际用不上。 ## 两个工具(附录 B 的最后两个) `change_stat(name, delta)` —— 只能申请**增量**。 ★ 被裁决过必须**明说**:返回里带一句 「你申请的是 +70,规则裁决后实际生效 +100」。 不说的话,模型会以为自己算错了,下一轮按错误的心智继续演。 ★ 返回值里带回 `now`(命中区间的文案)—— 它得知道"现在到「亲近」这一档了"。 `grant_status(target, status_name, turns?)` —— 按**名字**找目标。 ★ 为什么按名字:模型在提示词里看到的伙伴就是名字 (`<peer_emotions>` 给的是"仙辰-哀"),它拿不到 id。 ★ **被抵抗时抛错**而不是返回 `ok:false` —— 需求说"A 必须知道结果", 而工具抛错是模型**一定会看到**的那条路(返回里的字段它可能忽略)。 ★ 不能给自己施加状态:直接拒绝。不拒的话模型会以为"自残"是个正常操作。 ## 每轮递减:放在**生成之后** 需求 §3.11 说"每参与一轮后减 1"。放在生成**之后**而不是之前 —— 被额度拦下、被死亡拦下的那些轮次不该扣,因为它根本没说话。 过期时发一个 `status` 事件让界面播报("中毒已经消退了")—— 那是个用户能感知的变化。 ## 验证 `probe-rule-engine.py` 扩到 15 节:工具层 11 项 + 附录 B 的清单核对 (8 个必须有的都在、`invite_agent`/`pass_turn` 明确留到阶段 4)。 ★ 探针又踩了三次**自己挖的坑**(都是断言没考虑前面的状态): · 第 10 节给这个包配了"正向翻倍"脚本,所以 +70 实际是 +100(被 clamp) · 这个包没配区间表,所以不该期待 `now` · 前面已经建过一个"仙辰",重名时 `_find_agent` 取第一个 —— 断言打在了别人身上 三次都是**代码对、断言错**。但这也说明一件事:探针的断言必须**自足**, 不能依赖"前面某节留下的状态"——那正是让测试变脆的原因。 七个探针全绿;构建通过(含内核语法自检)。 ## 阶段 3 还剩 规则包 zip 导入导出(含「包含可执行 Python 脚本」警告确认)+ 资源页第四个 Tab + [规则包编辑] / [状态数值] 两个界面。
1956 lines
92 KiB
Python
1956 lines
92 KiB
Python
"""
|
||
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 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 timeouts
|
||
import agentdb
|
||
import agent_api
|
||
import agent_context
|
||
import context_window
|
||
import rule_engine
|
||
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()
|
||
# `send_message` 触发的回复里最多再套几层(防无限套娃,见 /api/session-message)
|
||
SESSION_MSG_MAX_DEPTH = 2
|
||
_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:
|
||
# ★ 心跳间隔可调(设置 → 超时 → 心跳间隔)。
|
||
# 它必须**明显小于**客户端的读超时(sseRead),否则客户端会先
|
||
# 判定"连接死了"再断开 —— 等用户回答的那种场景会因此白等。
|
||
try:
|
||
gap = float(timeouts.get('heartbeat'))
|
||
except Exception: # noqa: BLE001
|
||
gap = 15.0
|
||
# 用 Event.wait 代替 sleep,结束时会立刻退出,不用等满
|
||
if self._stop_event.wait(gap):
|
||
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(),
|
||
# ★ 给每个智能体算好"当前该显示哪张立绘"(需求 2.6 的回退链:
|
||
# 当前 preset 档 → 平常档 → 旧单一 front → 空 = 内置默认人物)。
|
||
#
|
||
# 界面(选择界面、对话界面、编辑界面的预览)直接用这个字段,
|
||
# 不用各自实现一遍回退链 —— 那种"同一逻辑抄三份"的写法,
|
||
# 改一处必漏两处,而这个仓库里已经反复出现过。
|
||
'agents': [
|
||
{**a, 'portrait': agent_api.portrait_of(
|
||
a.get('image') or {},
|
||
(agentdb.emotion_state(a.get('id') or '').get('preset') or '平常'),
|
||
)}
|
||
for a in store.list_agents()
|
||
],
|
||
# 每个智能体当前的情绪(v1.2 双字段)。
|
||
# ★ 情绪原来只在提示词里生效 —— AI 用 emotion_set 改了情绪,
|
||
# 用户完全无感知,这个功能就成了一个看不见的字段。
|
||
# `preset` 驱动界面(立绘、死亡禁言、成员标签),
|
||
# `text` 是扮演质感。
|
||
# **有情绪才带上**:没记过的(默认「平常」+ 空文本)不占位。
|
||
'emotions': {
|
||
a.get('id'): st for a in store.list_agents()
|
||
if (st := agentdb.emotion_state(a.get('id') or ''))
|
||
and (st.get('text') or st.get('preset') != agentdb.PRESET_DEFAULT)
|
||
},
|
||
# ---- 智能体系统的另外三种资源(需求 v1.1)----
|
||
# 都不大(几个到几十个),一次带给界面省得进页面再拉一次
|
||
'worldviews': store.list_resource('worldviews'),
|
||
'modelEntries': store.list_resource('models'),
|
||
'skills': store.list_resource('skills'),
|
||
# AI 提的"该整理记忆了"(按智能体存),界面据此显示按钮
|
||
'memorySuggestions': {
|
||
a.get('id'): store.peek_summary_suggestion(a.get('id') or '')
|
||
for a in store.list_agents()
|
||
if store.peek_summary_suggestion(a.get('id') or '')
|
||
},
|
||
'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
|
||
|
||
# ---------------------------------------------------------------- #
|
||
# 超时(设置 → 超时)
|
||
#
|
||
# ★ 清单由内核给,**界面不硬编码这些项目** —— 加一项超时只改 timeouts.py,
|
||
# 界面自动多出一行(连说明文字都是这里带过去的)。
|
||
# ★ 写的时候是**整体替换**而不是深合并:默认值在 timeouts.py 里,
|
||
# "改回默认"等于"从设置文件里删掉这一项",深合并会让它删不掉。
|
||
# ---------------------------------------------------------------- #
|
||
if pathname == '/api/timeouts' and method == 'GET':
|
||
self.send_json(200, {
|
||
'ok': True,
|
||
'items': timeouts.catalog(),
|
||
'values': timeouts.resolved(),
|
||
})
|
||
return True
|
||
|
||
if pathname == '/api/timeouts' and method in ('PUT', 'POST'):
|
||
body = self.read_json_body()
|
||
if body.get('reset'):
|
||
next_values = timeouts.reset()
|
||
else:
|
||
next_values = timeouts.patch(body.get('values') or body)
|
||
store.write_settings({'timeouts': next_values})
|
||
self.send_json(200, {
|
||
'ok': True,
|
||
'items': timeouts.catalog(),
|
||
'values': timeouts.resolved(),
|
||
})
|
||
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
|
||
|
||
# ---- AI 主动往会话里发一条消息(send_message 工具)----
|
||
#
|
||
# ★★★ 这里最危险的是**死循环**:模型发消息 → 顺手跑回复 →
|
||
# 回复里又发消息 → ……。所以深度和条数两道闸都在 [SESSION_MSG_*]
|
||
# 常量那边守着,任何一道超了就直接拒绝并说明原因。
|
||
if pathname == '/api/session-message' and method == 'POST':
|
||
try:
|
||
body = self.read_json_body()
|
||
except ValueError:
|
||
body = {}
|
||
conv = str(body.get('conversationId') or '')
|
||
text = str(body.get('text') or '').strip()
|
||
role = str(body.get('role') or 'user')
|
||
want_reply = bool(body.get('reply'))
|
||
try:
|
||
depth = int(body.get('depth') or 1)
|
||
except (TypeError, ValueError):
|
||
depth = 1
|
||
|
||
if not text:
|
||
self.send_json(400, {'error': 'text 不能为空'})
|
||
return True
|
||
if not conv:
|
||
self.send_json(400, {'error': '缺少 conversationId'})
|
||
return True
|
||
|
||
# 闸①:嵌套太深
|
||
if depth > SESSION_MSG_MAX_DEPTH:
|
||
self.send_json(200, {
|
||
'error': (
|
||
f'嵌套太深(第 {depth} 层)—— send_message 触发的回复里'
|
||
f'不能再发消息,最多 {SESSION_MSG_MAX_DEPTH} 层。'
|
||
'这是防止无限套娃把额度烧光。'
|
||
),
|
||
})
|
||
return True
|
||
# 闸②:这个会话发得太多了
|
||
used = store.session_message_count(conv)
|
||
if used >= store.SESSION_MSG_MAX:
|
||
self.send_json(200, {
|
||
'error': (
|
||
f'这次会话你已经主动发了 {used} 条消息(上限 '
|
||
f'{store.SESSION_MSG_MAX} 条)。'
|
||
'别再发了,直接在你这一轮的回答里说。'
|
||
),
|
||
})
|
||
return True
|
||
|
||
try:
|
||
store.append_message(conv, role, text)
|
||
except KeyError as exc:
|
||
self.send_json(404, {'error': str(exc)})
|
||
return True
|
||
|
||
if not want_reply:
|
||
self.send_json(200, {'ok': True, 'sent': True, 'replied': False})
|
||
return True
|
||
|
||
# ★ 要顺手回一轮:**必须放在后台线程**。
|
||
# 当前这个线程正被 `send_message` 工具占着(模型还在等它的返回值),
|
||
# 在这里同步跑一轮回复会**死锁**(等自己)。
|
||
# 而且用 poll 那条路(和安卓端一样),事件进 _RUNS,界面能收到。
|
||
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()}
|
||
|
||
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
|
||
|
||
worker = threading.Thread(
|
||
target=self._perform_chat,
|
||
args=(sink_send, sink_end, store.read_settings(), conv, text, [], {}),
|
||
kwargs={
|
||
'should_stop': lambda: False,
|
||
# ★ 关键:把深度传下去。这一轮回复里模型再调 send_message 时
|
||
# 拿到的就是 depth+1;超过上限直接被拒。
|
||
# 不传的话是无限套娃(见 /api/session-message 上面的注释)。
|
||
'send_depth': depth,
|
||
},
|
||
name='self-message-reply',
|
||
daemon=True,
|
||
)
|
||
worker.start()
|
||
self.send_json(200, {
|
||
'ok': True, 'sent': True, 'replyStarted': True, 'runId': run_id,
|
||
})
|
||
return True
|
||
|
||
# ---- 笔记(用户要能查看)----
|
||
#
|
||
# ★ 用户的原话:"notes 用户要能查看"。
|
||
# 以前笔记只有 AI 能读写(走 notes 工具),用户看不到 ——
|
||
# 而且路径算错落到了 App 外部私有目录,卸载还会被清掉。
|
||
# 现在存 `<数据目录>/notes`,这几个接口让 App 列出来看。
|
||
if pathname == '/api/notes' and method == 'GET':
|
||
self.send_json(200, {'notes': store.list_notes()})
|
||
return True
|
||
|
||
note_name = self._match_id(pathname, '/api/notes/')
|
||
if note_name is not None:
|
||
if method == 'GET':
|
||
note = store.read_note(note_name)
|
||
if note is None:
|
||
self.send_json(404, {'error': '笔记不存在'})
|
||
else:
|
||
self.send_json(200, note)
|
||
return True
|
||
if method == 'DELETE':
|
||
ok = store.delete_note(note_name)
|
||
self.send_json(200 if ok else 404, {'ok': ok})
|
||
return True
|
||
|
||
# ---- AI 弹过的界面(关掉之后还能再打开)----
|
||
#
|
||
# ★ 用户要求:"AI 写的界面可以再点开"。
|
||
# 每次 show_ui 都把 HTML 存一份到 <data>/screens/,这几个接口
|
||
# 让 App 列出 / 读取 / 删除它们。
|
||
if pathname == '/api/screens' and method == 'GET':
|
||
parsed = urlsplit(self.path)
|
||
params = dict(
|
||
pair.split('=', 1) for pair in (parsed.query or '').split('&') if '=' in pair
|
||
)
|
||
conv = unquote(params.get('conversationId') or '')
|
||
self.send_json(200, {'screens': store.list_screens(conv)})
|
||
return True
|
||
|
||
screen_id = self._match_id(pathname, '/api/screens/')
|
||
if screen_id is not None:
|
||
if method == 'GET':
|
||
html = store.read_screen(screen_id)
|
||
if html is None:
|
||
self.send_json(404, {'error': '界面不存在或已清理'})
|
||
else:
|
||
self.send_json(200, {'id': screen_id, 'html': html})
|
||
return True
|
||
if method == 'DELETE':
|
||
ok = store.delete_screen(screen_id)
|
||
self.send_json(200 if ok else 404, {'ok': ok})
|
||
return True
|
||
|
||
# ---- AI 界面的数据回流 ----
|
||
#
|
||
# ★★★ 这是"AI 自己写进网页里的接口"的落点。
|
||
#
|
||
# AI 用 show_ui 弹一个 HTML 界面,界面里可以写:
|
||
# Doubao.sendToAi("用户选的是方案 B")
|
||
# 那个值经安卓桥打到这里,**排队等下一次对话**。
|
||
# 下一轮 run_agent 会把队里的东西作为上下文交给模型 ——
|
||
# 于是"用户在 AI 自己写的界面里选了什么"真的回到了模型手里。
|
||
#
|
||
# ★ 为什么用"排队"而不是"直接起一轮对话":
|
||
# 用户可能连点几下、或者在界面里选好几项再确认。
|
||
# 每点一下就跑一轮模型既慢又费 token,而且用户还没说完。
|
||
# 排队 → 用户下一次说话(或点界面上的提交按钮)时一起带上,
|
||
# 语义上也更对:**界面是提问的一部分,不是提问本身**。
|
||
if pathname == '/api/ui-result' and method == 'POST':
|
||
try:
|
||
body = self.read_json_body()
|
||
except ValueError:
|
||
body = {}
|
||
conv = str(body.get('conversationId') or '')
|
||
value = str(body.get('value') or '').strip()
|
||
if not value:
|
||
self.send_json(400, {'error': 'value 不能为空'})
|
||
return True
|
||
if not conv:
|
||
self.send_json(400, {'error': '缺少 conversationId'})
|
||
return True
|
||
n = store.add_pending_ui(conv, value)
|
||
self.send_json(200, {'ok': True, 'queued': n})
|
||
return True
|
||
|
||
if pathname == '/api/ui-result' and method == 'GET':
|
||
parsed = urlsplit(self.path)
|
||
params = dict(
|
||
pair.split('=', 1) for pair in (parsed.query or '').split('&') if '=' in pair
|
||
)
|
||
conv = unquote(params.get('conversationId') or '')
|
||
if not conv:
|
||
self.send_json(400, {'error': '缺少 conversationId'})
|
||
return True
|
||
self.send_json(200, {'pending': store.peek_pending_ui(conv)})
|
||
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 '新对话',
|
||
# ★ 新会话要**记住它属于谁** —— 会话隔离的依据就是它。
|
||
# 不传的话所有会话的主人都是空,切换智能体时就没法判断
|
||
# "这是不是同一个人的对话",只能一直串着(用户报的 bug)。
|
||
agent_id=(body.get('agentId') or '').strip(),
|
||
)})
|
||
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
|
||
|
||
# ---------------- 自定义节点(用户用 Python 拓展的) ---------------- #
|
||
if pathname == '/api/meeting/nodes' and method == 'GET':
|
||
import custom_nodes as _cn
|
||
folder = _cn.nodes_dir()
|
||
items = []
|
||
if os.path.isdir(folder):
|
||
for fn in sorted(os.listdir(folder)):
|
||
if not fn.endswith('.py'):
|
||
continue
|
||
d = _cn.load_file(os.path.join(folder, fn))
|
||
items.append({
|
||
'file': fn,
|
||
'ok': not d.get('error'),
|
||
'error': d.get('error') or '',
|
||
'label': d.get('label') or '',
|
||
'desc': d.get('desc') or '',
|
||
'inputs': d.get('inputs') or [],
|
||
'outputs': d.get('outputs') or [],
|
||
})
|
||
self.send_json(200, {'dir': folder, 'nodes': items})
|
||
return True
|
||
|
||
if pathname.startswith('/api/meeting/nodes/') and method == 'GET':
|
||
# 读一个节点文件的**源码** —— 现场编辑要用
|
||
import custom_nodes as _cn
|
||
import urllib.parse as _up
|
||
fname = os.path.basename(
|
||
_up.unquote(pathname[len('/api/meeting/nodes/'):]).replace('\\', '/'))
|
||
target = os.path.join(_cn.nodes_dir(), fname)
|
||
if not fname.endswith('.py') or not os.path.isfile(target):
|
||
self.send_json(404, {'error': '没有这个节点文件'})
|
||
return True
|
||
try:
|
||
with open(target, 'r', encoding='utf-8') as fh:
|
||
code = fh.read()
|
||
except OSError as exc:
|
||
self.send_json(400, {'error': f'读不了:{exc}'})
|
||
return True
|
||
d = _cn.load_file(target)
|
||
self.send_json(200, {
|
||
'file': fname,
|
||
'code': code,
|
||
'ok': not d.get('error'),
|
||
'error': d.get('error') or '',
|
||
'label': d.get('label') or '',
|
||
'inputs': d.get('inputs') or [],
|
||
'outputs': d.get('outputs') or [],
|
||
})
|
||
return True
|
||
|
||
if pathname == '/api/meeting/nodes' and method == 'POST':
|
||
# 导入一个节点文件。
|
||
#
|
||
# 为什么要有这个接口:应用沙箱里**没有别的办法**把文件放进数据目录 ——
|
||
# 界面用系统的文件选择器读进来,再 POST 到这里落盘。
|
||
# 不给的话用户只能用 adb push,那不叫能用。
|
||
import custom_nodes as _cn
|
||
body = self.read_json_body()
|
||
fname = str(body.get('file') or '').strip()
|
||
code = str(body.get('code') or '')
|
||
if not fname.lower().endswith('.py'):
|
||
fname += '.py'
|
||
# 只留文件名:用户选的路径里可能带 / 或 ..,不能让它写到别处
|
||
fname = os.path.basename(fname.replace('\\', '/'))
|
||
if not fname or fname == '.py':
|
||
self.send_json(400, {'error': '文件名不对'})
|
||
return True
|
||
if not code.strip():
|
||
self.send_json(400, {'error': '这个文件是空的'})
|
||
return True
|
||
|
||
# ★ 先**试加载一遍**再落盘。
|
||
# 直接写进去的话,用户导入一个写错的文件,节点列表里就多一个坏节点,
|
||
# 每次打开会议都看到它。先跑一遍能把错误**当场**告诉他,
|
||
# 而且原始报错不吞 —— 用户要照着那句报错去改代码。
|
||
folder = _cn.nodes_dir()
|
||
try:
|
||
os.makedirs(folder, exist_ok=True)
|
||
except OSError as exc:
|
||
self.send_json(400, {'error': f'节点目录建不出来:{exc}'})
|
||
return True
|
||
tmp = os.path.join(folder, '_import_check_.py')
|
||
try:
|
||
with open(tmp, 'w', encoding='utf-8') as fh:
|
||
fh.write(code)
|
||
chk = _cn.load_file(tmp)
|
||
finally:
|
||
try:
|
||
os.remove(tmp)
|
||
except OSError:
|
||
pass
|
||
if chk.get('error'):
|
||
self.send_json(400, {'error': chk['error']})
|
||
return True
|
||
|
||
target = os.path.join(folder, fname)
|
||
try:
|
||
with open(target, 'w', encoding='utf-8') as fh:
|
||
fh.write(code)
|
||
except OSError as exc:
|
||
self.send_json(400, {'error': f'写不进去:{exc}'})
|
||
return True
|
||
self.send_json(200, {
|
||
'ok': True,
|
||
'file': fname,
|
||
'label': chk.get('label') or fname,
|
||
'key': chk.get('key') or '',
|
||
})
|
||
return True
|
||
|
||
if pathname.startswith('/api/meeting/nodes/') and method == 'DELETE':
|
||
import custom_nodes as _cn
|
||
import urllib.parse as _up
|
||
fname = os.path.basename(
|
||
_up.unquote(pathname[len('/api/meeting/nodes/'):]).replace('\\', '/'))
|
||
target = os.path.join(_cn.nodes_dir(), fname)
|
||
if not fname.endswith('.py') or not os.path.isfile(target):
|
||
self.send_json(404, {'error': '没有这个节点文件'})
|
||
return True
|
||
try:
|
||
os.remove(target)
|
||
except OSError as exc:
|
||
self.send_json(400, {'error': f'删不掉:{exc}'})
|
||
return True
|
||
self.send_json(200, {'ok': True})
|
||
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)),也可以给智能体当工具调'},
|
||
{'key': 'branch', 'label': '分支', 'desc': '收一个真假,走真/假两条 exec(和判断的区别:判断按规则算,分支直接收)'},
|
||
],
|
||
'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/<id>/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:
|
||
# ★ 手动试运行**不受安全模式限制**(是用户自己在「技能」页点的),
|
||
# 但仍要能报错。所以 mode 强制 open。
|
||
#
|
||
# ★★ 但**不能**只传一个空壳 settings(以前就是 {'security':...}):
|
||
# 界面工具(show_ui/ask_user/end_conversation)的开关也在 settings 里,
|
||
# 空壳会让它们**永远被第二道拦截挡住** —— 用户在技能页点"试运行",
|
||
# 明明开关是开的,却收到"已关闭"。这个错会让人以为是开关没生效。
|
||
# 所以拿真实设置、只覆盖 security。
|
||
live = store.read_settings() or {}
|
||
settings = {**live, 'security': {'mode': 'open', 'allow': []}}
|
||
tools_runtime.push_context(
|
||
conversationId=str(body.get('conversationId') or ''),
|
||
toolName=name,
|
||
)
|
||
try:
|
||
result = tools_runtime.execute_tool(name, body.get('args') or {}, settings)
|
||
finally:
|
||
tools_runtime.clear_context()
|
||
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
|
||
|
||
# 智能体系统的接口(记忆 / 情绪 / Token / 世界观 / 模型列表 / Skill / 导入导出)
|
||
#
|
||
# ★ 全部集中在 agent_api.py 里 —— app.py 已经 1800 行,二十多个新接口
|
||
# 塞进来会让这个文件彻底没法看。
|
||
# ★ 老的 /api/agents 那三个路由**删掉了**(原来在下面),由这里统一处理:
|
||
# 留着就是两份实现,而新那份多了"内置智能体不能删"的保护 ——
|
||
# 两份并存的话,哪份生效取决于顺序,这种 bug 最难查。
|
||
if agent_api.handle(self, pathname, method):
|
||
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_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:
|
||
# ★ 会议节点也走**同一套** system prompt 拼装(需求附录 C)。
|
||
#
|
||
# 以前这里是自己拼的(`agent.systemPrompt or cfg.systemPrompt`),
|
||
# 于是同一个智能体在聊天里有记忆/情绪/世界观、在会议节点里没有 ——
|
||
# "引擎改了另一端必须跟上"这条在这个仓库里踩过好几次,
|
||
# 所以这次直接复用 agent_context,别再抄一份。
|
||
#
|
||
# ★ 节点的额外要求 / 输出要求 / 变量说明仍然**追加在后面**:
|
||
# 它们是"这一轮的任务约束",比人设更具体,放最后模型才看得重。
|
||
if agent:
|
||
base = agent_context.build_system_prompt(store.read_settings(), agent)
|
||
else:
|
||
base = 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, send_depth: int = 0) -> 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 []
|
||
# ★ 先只做**过滤**,真正的窗口裁剪放到下面(`agent` 解析之后)——
|
||
# 因为窗口大小是**按智能体配**的(需求 4.3),这里还不知道是谁。
|
||
raw_history = [
|
||
m 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'))
|
||
agent_id = (agent or {}).get('id') or ''
|
||
|
||
# ★★ 对话上下文窗口(需求 v1.2 §4.3)。
|
||
#
|
||
# 只把"最近 N 轮 + 用户标了重要的那几条"送进模型。
|
||
# 超出的**直接丢弃、不做摘要**(需求原话)—— 沉淀走记忆系统,
|
||
# 不搞第二套摘要管线(摘要自己也要花一次调用,还会丢信息且不可追溯)。
|
||
#
|
||
# ★ 命名:这里叫「上下文窗口」,和记忆侧的「记忆注入窗口」不是一回事。
|
||
# 后者管"塞多少条记忆",超出部分**还能 memory_search 搜到**;
|
||
# 这里管"送几轮对话",超出就真的不送了。
|
||
#
|
||
# ★ `strip_for_model` 是**新建** dict,不原地改历史 ——
|
||
# 改一个字,从那儿往后的前缀缓存全废(需求 4.3 的"字节冻结")。
|
||
win_rounds, win_batch = context_window.resolve(settings, agent)
|
||
window = context_window.trim(raw_history, win_rounds, win_batch)
|
||
history = [context_window.strip_for_model(m) for m in window['messages']]
|
||
if window.get('reason'):
|
||
print(f'[context] {context_window.describe(window)}', file=sys.stderr)
|
||
|
||
# ★★ 会话隔离:**一个会话属于一个智能体**(豆包也是这个模型)。
|
||
#
|
||
# 以前这里完全不看会话的主人是谁,于是用户中途换了智能体之后
|
||
# 还在同一个会话里接着聊 —— 历史消息是上一个角色说的,
|
||
# 而 system prompt 已经换成新角色的了。新角色**会把别人的话
|
||
# 当成自己说的**(用户的原话:"智能体怎么串味了")。
|
||
#
|
||
# 处理:主人不一致就**另起一个会话**,并通知界面换 id。
|
||
# · 老会话(本次改动之前建的)没有 agentId —— 那种**认领**它,
|
||
# 而不是也另起一个,否则所有历史会话第一次聊天都会跳走。
|
||
owner = (existing.get('agentId') or '').strip()
|
||
if existing and agent_id:
|
||
if not owner:
|
||
store.set_conversation_agent(conversation_id, agent_id)
|
||
elif owner != agent_id:
|
||
conversation_id = store.create_conversation(agent_id=agent_id)['id']
|
||
existing = store.get_conversation(conversation_id) or {}
|
||
# 界面据此把当前会话切过去(不然它会往老 id 上继续追加)
|
||
emit({'type': 'rebased', 'conversationId': conversation_id,
|
||
'reason': 'agent_changed'})
|
||
|
||
# ★★ 死亡的智能体**不能对话**(需求 3.5)。
|
||
#
|
||
# 判定放在**发起前**,和 Token 限额同一层:不是在生成时才拦
|
||
# (那时候已经花了钱),而是根本不让这一轮开始。
|
||
#
|
||
# 复活只有两条通道,都不在这里:
|
||
# · 用户手动改(界面上的情绪区,兜底主权)
|
||
# · 状态脚本改(定时复活/解药剧情,走沙箱)
|
||
if agent_id and agentdb.is_dead(agent_id):
|
||
emit({
|
||
'type': 'error',
|
||
'code': 'agent_dead',
|
||
'message': f'「{(agent or {}).get("name") or "这个智能体"}」已经死亡,无法对话。',
|
||
'hint': '在「记忆 → 情绪」里把它改回其他状态就能复活。',
|
||
})
|
||
return
|
||
|
||
# ★★ Token 限额:**发起前**拦(需求 3.1)。
|
||
#
|
||
# 判定时机是"返回后结算 + 下一轮发起前检查"—— 所以这里查的是
|
||
# **已经攒下来的**用量,超了就根本不发这一轮。
|
||
#
|
||
# ★ 拦在"写用户消息之前":拦住了还把用户那句话落库的话,
|
||
# 他会看到自己发的消息挂在那儿、AI 永远不回,以为卡住了。
|
||
#
|
||
# ★ 豁免:记忆整理、导出这些**非对话生成**的操作不走这里
|
||
# (它们有自己的接口),所以不会被限额挡住。
|
||
try:
|
||
limit = int(float((agent or {}).get('tokenLimit') or 0))
|
||
except (TypeError, ValueError):
|
||
limit = 0
|
||
if limit > 0 and agent_id:
|
||
used = sum(agentdb.token_usage(agent_id)['total'].values())
|
||
if used >= limit:
|
||
farewell = (settings.get('tokenLimitFarewell') or '我没力气再说话了……').strip()
|
||
store.append_messages(conversation_id, [{
|
||
'role': 'assistant',
|
||
'content': farewell,
|
||
'agentId': agent_id,
|
||
# ★ 标一下"这不是模型生成的":界面据此把它显示成提示样式,
|
||
# 而且重新生成时不会被当成一条正常的 AI 回复
|
||
'limitNotice': True,
|
||
'at': store.now_iso(),
|
||
}])
|
||
emit({
|
||
'type': 'error',
|
||
'code': 'token_limit',
|
||
'message': f'{(agent or {}).get("name") or "这个智能体"}的 Token 额度用完了',
|
||
'used': used,
|
||
'limit': limit,
|
||
'farewell': farewell,
|
||
'hint': '可以清零重新开始,或者把限额调大 / 改成无限制。',
|
||
})
|
||
return
|
||
|
||
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,
|
||
# ★ 界面工具要靠它知道"结束哪次对话"。不传的话
|
||
# end_conversation 会明确报错(而不是假装成功)。
|
||
conversation_id=conversation_id,
|
||
# ★ 防无限套娃:这一轮的深度传进去,send_message 据此判断能不能再发
|
||
send_depth=send_depth,
|
||
)
|
||
|
||
# ★ 这一轮的 Token 用量(需求 4.1:对话界面显示"本次对话"的用量)。
|
||
# 按轮记在消息上,会话级用量是**加起来**算的 —— 这样"重新生成"
|
||
# 把上一条替换掉时,它的消耗也跟着消失,不会虚高。
|
||
in_tok, out_tok = agent_loop.usage_pair(result.get('usage'))
|
||
model_name = (store.provider_info(settings, agent) or {}).get('model') or ''
|
||
|
||
store.append_messages(conversation_id, [{
|
||
'role': 'assistant',
|
||
'content': result.get('content', ''),
|
||
# 思维链也要落库,否则一刷新「思考过程」就没了
|
||
'reasoning': result.get('reasoning', '') or '',
|
||
'agentId': agent_id,
|
||
'usage': {'input': in_tok, 'output': out_tok},
|
||
# ★ 幻觉调用检测(需求 3.7):嘴上说记住了、实际没调工具。
|
||
# 界面据此显示一个 ⚠ 标记 —— 用户当场看不出来,
|
||
# 但下次发现它"完全不记得"时就晚了。
|
||
'hallucination': agent_loop.check_hallucinated_memory(
|
||
result.get('content') or '',
|
||
int(result.get('toolCalls') or 0),
|
||
bool((settings.get('tools') or {}).get('python', True)),
|
||
),
|
||
'at': store.now_iso(),
|
||
}])
|
||
# ★ 智能体级累计(需求 3.1):**按模型分桶、输入输出分开**。
|
||
# 记失败不影响这一轮对话 —— 统计是附加价值,不能让它把回复搞崩。
|
||
if agent_id and (in_tok or out_tok):
|
||
try:
|
||
# ★ v1.2:缓存命中 / 未命中一起落库。
|
||
# `cache_pair` 已经把三家的字段名归一化过
|
||
# (DeepSeek 两个都给、Claude/OpenAI 只给命中要自己推);
|
||
# 两家都没给就是 0/0,界面据此**不显示**那一列。
|
||
hit, miss = agent_loop.cache_pair(result.get('usage'))
|
||
agentdb.token_add(agent_id, model_name, in_tok, out_tok, hit, miss)
|
||
except Exception as exc: # noqa: BLE001
|
||
print(f'[usage] 记 Token 用量失败:{exc}', file=sys.stderr)
|
||
|
||
# ★ 状态每参与一轮减 1(需求 §3.11)。
|
||
#
|
||
# 放在**生成之后**:这一轮它确实开口了,才该扣。
|
||
# 放在之前的话,被额度拦下、被死亡拦下的那些轮次也会扣 ——
|
||
# 而它根本没说话。
|
||
#
|
||
# 过期要播报("中毒已经消退了")—— 那是个用户能感知的变化。
|
||
if agent_id:
|
||
try:
|
||
for ev in rule_engine.tick_statuses(agent_id):
|
||
emit({
|
||
'type': 'status',
|
||
'name': ev.get('name'),
|
||
'expired': bool(ev.get('expired')),
|
||
'remaining': ev.get('remaining', 0),
|
||
})
|
||
except Exception as exc: # noqa: BLE001 - 状态系统坏了不该让回复发不出去
|
||
print(f'[rule] 状态递减失败:{exc}', file=sys.stderr)
|
||
|
||
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
|