Files
doubao-clone/server/src/index.mjs
l 376a143a37 会议模式:内核数据模型 + 执行引擎 + SSE 路由
用户需求 C 的第一部分(引擎侧)。界面编辑器下一轮。

【数据模型】
meeting = { id, name, nodes[], edges[] }
节点四类:
  start  初始输入(文本可写死,留空则用用户发的那句)
  agent  智能体:agentId + **本节点专属**的附加提示词 + 输出控制
  judge  判断:按条件分 true / false 两条出边
  end    最终输出

★ 新增会议时给的是"输入 → 一个智能体 → 输出"的**最小可跑闭环**,
  不是空白画布 —— 对着空白画布干瞪眼是最差的新手体验,
  而且有个能跑的例子,节点和连线怎么连一眼就懂。

【安全决定:判断节点的规则不用 eval】
判断节点要支持"包含某词""字数多于 N"这类条件。最省事是让用户写表达式然后
eval —— **绝对不行**:配置能被任意改写(界面上可编辑、文件可手改),
eval 就等于把任意代码执行权交出去。
改用**结构化规则**(7 种 kind + value):能表达的就那几种,
多一种就多一个分支,而不是多一分风险。AI 判断也支持(让模型回 YES/NO)。

【执行引擎】
- 拓扑序 + 访问集合 + 步数上限,而不是递归:
  用户画错画出环时递归会直接爆栈,这样最多"少跑几个节点"
- 一个节点的输入 = 所有上游输出拼接(多条入边不用额外的合并节点)
- 单个节点出错**不让整场会议停摆**:上报 node_error,继续跑下游
- 边和节点在保存时做消毒:丢掉类型不认识的节点、指向不存在节点的悬空连线

【测试抓到的一个真设计缺陷】
判断节点原先把输出**覆盖成了字符串 "true"/"false"**,
于是下游智能体收到的输入就是 "true",完全没法用 ——
验证脚本报出来的是"真 收到[true]"。
修成**透传上游内容**,判断结论单独走 verdict 字段。

这个错误要是等界面做完再发现,会以为是"连线没连对",白查半天。

【验证】
- scripts/verify-meeting.mjs:引擎逻辑,7 张图(直链 / true 分支 / false 分支 /
  多入边拼接 / 环 / 节点报错 / 无入口),用**假智能体**不打真实模型。
  Node 与 Python 逐用例对拍一致;判断规则 6/6。20/20。
- scripts/verify-meeting-http.mjs:HTTP 端到端(起内核 + mock LLM),
  验路由、SSE 事件流、真调模型、判断分支、透传。两份内核各 12/12。

回归:语音 41/41 ×2、Markdown 19/19。

【还剩】会议模式的可视化编辑器(Compose 画布:拖节点、拉连线、点节点配参数)。
2026-10-10 11:29:56 +08:00

1031 lines
36 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* 豆包复刻 · AI 内核 + 静态托管服务(零框架依赖,Node 原生 http)
*
* 一个端口同时提供:
* / Lynx for Web 宿主页(<lynx-view> 加载 main.web.bundle)
* /main.web.bundle 由 app/ 构建出来的 Lynx Web 产物
* /lynx-web/* @lynx-js/web-core 运行时(本地托管,不依赖公网 CDN)
* /api/* AI 内核:会话、设置、工具、MCP、流式对话
*/
import http from 'node:http';
import fs from 'node:fs';
import path from 'node:path';
import { URL, pathToFileURL } from 'node:url';
import {
DIST_DIR,
PROVIDER_PRESETS,
WEB_CORE_STATIC,
WEB_INDEX,
maskSettings,
providerInfo,
readSettings,
writeSettings,
} from './config.mjs';
import * as store from './store.mjs';
import { listAllTools, runAgent, executeTool, suggestAllowlist } from './agent.mjs';
import {
createAgent,
deleteAgent,
getAgent,
listAgents,
updateAgent,
} from './agents.mjs';
import {
UPLOADS_DIR,
addPending,
attachmentPayload,
registerLocalFile,
saveUpload,
takePending,
} from './uploads.mjs';
import {
connect,
connectAllEnabled,
disconnect,
disconnectAll,
getMcpState,
mcpConfigPath,
readMcpConfig,
readMcpConfigText,
writeMcpConfigText,
} from './mcp.mjs';
import { listModels } from './providers.mjs';
import {
listMeetings,
getMeeting,
createMeeting,
saveMeeting,
deleteMeeting,
runMeeting,
JUDGE_KINDS,
} from './meeting.mjs';
import {
synthesize,
synthesizeStream,
transcribe,
speechState,
voiceFor,
VOICE_OPTIONS,
VOICE_OPTIONS_ALL,
} from './speech.mjs';
const DEFAULT_PORT = Number(process.env.PORT || 5199);
const DEFAULT_HOST = process.env.HOST || '127.0.0.1';
const 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',
};
function sendJson(res, status, payload) {
const body = JSON.stringify(payload, null, 2);
res.writeHead(status, {
'Content-Type': 'application/json; charset=utf-8',
'Content-Length': Buffer.byteLength(body),
});
res.end(body);
}
function sendText(res, status, text) {
res.writeHead(status, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end(text);
}
function cors(res) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE, OPTIONS');
}
/**
* 跑一整张会议图,事件走 SSE。
*
* ★ 节点的附加提示词和输出控制都是**拼在系统提示词后面**,而不是替换它 ——
* 智能体本身的人设不能被节点的输出要求顶掉,两者是
* "人设 + 这一轮的额外要求"的关系。
*/
async function streamMeetingRun(req, res, meetingId) {
const body = await readBody(req).catch(() => ({}));
const settings = readSettings();
const item = getMeeting(meetingId);
if (!item) {
sendJson(res, 404, { error: '会议不存在' });
return;
}
const userInput = String(body.input || '').trim();
cors(res);
res.writeHead(200, {
'Content-Type': 'text/event-stream; charset=utf-8',
'Cache-Control': 'no-cache, no-transform',
Connection: 'keep-alive',
'X-Accel-Buffering': 'no',
});
const send = (event) => {
try {
res.write(`data: ${JSON.stringify(event)}\n\n`);
} catch { /* 客户端断了就算了 */ }
};
const runAgentFn = async (node, incoming, cfg, emit, nodeId) => {
const agent = node.agentId ? getAgent(node.agentId) : null;
const extra = String(node.extraPrompt || '').trim();
const control = String(node.outputControl || '').trim();
let mergedAgent;
if (node._judgeOnly) {
// AI 判断:只要一个是/否,别的都不要
mergedAgent = {
id: '',
name: '判断器',
systemPrompt: '你是一个判断器。根据下面给出的内容回答 YES 或 NO,'
+ '不要解释、不要加别的字。\n\n判断标准:' + (extra || '内容是否合格'),
};
} else {
const base = agent?.systemPrompt || cfg.systemPrompt || '';
const parts = base.trim() ? [base] : [];
if (extra) parts.push(`【本次任务的额外要求】\n${extra}`);
if (control) parts.push(`【输出要求】\n${control}`);
mergedAgent = { ...(agent || {}), systemPrompt: parts.join('\n\n') };
}
// 上游内容作为这一轮的用户消息;没有上游就给个占位,免得空消息报错
const message = incoming.trim() || '(上游没有内容,请根据你的角色直接开始)';
const result = await runAgent({
settings: cfg,
messages: [{ role: 'user', content: message }],
agent: mergedAgent,
emit: (event) => {
// 只把正文增量转成 node_delta,其它事件原样转发但带上 nodeId,
// 界面上按节点分组显示
if (event.type === 'text') {
emit({ type: 'node_delta', nodeId, text: event.text || '' });
} else if (event.type !== 'done') {
emit({ ...event, nodeId });
}
},
});
return result?.content || '';
};
try {
await runMeeting({
meeting: item,
settings,
userInput,
emit: send,
runAgentFn,
});
} catch (err) {
// 引擎自己炸了也要让界面知道,不能一声不响地断掉
send({ type: 'meeting_done', output: '', error: `${err.name}: ${err.message}` });
} finally {
res.end();
}
}
/**
* 边合成边下发音频。
*
* ★ 关键设计:**先把第一块取出来,再发响应头**。
* 合成失败(Key 不对、音色不存在……)基本都发生在第一块之前,
* 这时候还没发头,就能照常返回 JSON 错误,客户端拿得到具体原因并退回系统 TTS。
* 要是先把头发出去,就只能截断连接,客户端看到的是"啥也没说就断了"。
*
* 中途失败就只能截断 —— 头都发出去了,改不了状态码。
* 客户端会把已收到的部分播完,不会崩。
*/
async function streamTts(req, res, text, settings, agent = null) {
// 引擎是"设备自带"时不走流式:那种情况内核根本不参与合成,
// 直接告诉客户端"这轮该用系统 TTS",别让它收到一个莫名其妙的空音频错误。
//
// ★ 判断引擎要用**智能体覆盖后**的那套:某个智能体单独配了云端音色、
// 而全局是"设备自带"时,不能因为全局是 system 就把它的流式挡掉。
if ((voiceFor(settings, agent).ttsEngine || 'system') === 'system') {
sendJson(res, 200, { ok: false, engine: 'system', error: '当前是系统朗读,不用云端合成' });
return;
}
const gen = synthesizeStream(text, settings, agent);
let first;
try {
first = await gen.next();
} catch (err) {
sendJson(res, 200, { ok: false, error: err.message });
return;
}
if (first.done) {
sendJson(res, 200, { ok: false, error: '没有要朗读的内容' });
return;
}
cors(res);
res.writeHead(200, {
'Content-Type': first.value.mime || 'audio/L16',
'Cache-Control': 'no-store',
'X-Audio-Stream': '1',
// 不设 Content-Length,Node 会自动用 chunked
});
res.write(Buffer.from(first.value.data));
try {
for (;;) {
const next = await gen.next();
if (next.done) break;
if (!res.write(Buffer.from(next.value.data))) {
// 背压:等 drain 再继续,否则慢客户端会把内存撑爆
await new Promise((resolve) => res.once('drain', resolve));
}
}
} catch {
// 已经出了几块,头改不了,只能截断(见上面注释)
} finally {
res.end();
}
}
async function readBody(req, limit = 4 * 1024 * 1024) {
const chunks = [];
let size = 0;
for await (const chunk of req) {
size += chunk.length;
if (size > limit) throw new Error('请求体过大');
chunks.push(chunk);
}
const raw = Buffer.concat(chunks).toString('utf8');
if (!raw) return {};
try {
return JSON.parse(raw);
} catch {
throw new Error('请求体不是合法 JSON');
}
}
/** 原样读字节(音频上传用:不套 JSON,省一次 base64 编解码) */
async function readRaw(req, limit = 25 * 1024 * 1024) {
const chunks = [];
let size = 0;
for await (const chunk of req) {
size += chunk.length;
if (size > limit) throw new Error(`音频太大(超过 ${Math.round(limit / 1024 / 1024)} MB)`);
chunks.push(chunk);
}
return Buffer.concat(chunks);
}
function safeJoin(root, urlPath) {
const decoded = decodeURIComponent(urlPath.split('?')[0]);
const target = path.join(root, path.normalize(decoded).replace(/^([/\\])+/, ''));
const resolved = path.resolve(target);
if (!resolved.startsWith(path.resolve(root))) return null;
return resolved;
}
function serveFile(res, filePath, { fallback404 = true } = {}) {
if (!fs.existsSync(filePath) || !fs.statSync(filePath).isFile()) {
if (fallback404) sendText(res, 404, '404 Not Found');
return false;
}
const ext = path.extname(filePath).toLowerCase();
const stat = fs.statSync(filePath);
res.writeHead(200, {
'Content-Type': MIME[ext] || 'application/octet-stream',
'Content-Length': stat.size,
'Cache-Control': ext === '.bundle' ? 'no-cache' : 'public, max-age=0, must-revalidate',
});
fs.createReadStream(filePath).pipe(res);
return true;
}
/* ------------------------------- SSE 工具 ------------------------------- */
function sseStart(res, req) {
res.writeHead(200, {
'Content-Type': 'text/event-stream; charset=utf-8',
'Cache-Control': 'no-cache, no-transform',
Connection: 'keep-alive',
'X-Accel-Buffering': 'no',
});
res.write(': connected\n\n');
const heartbeat = setInterval(() => {
try {
res.write(': ping\n\n');
} catch {
/* ignore */
}
}, 15000);
const controller = new AbortController();
req.on('close', () => {
clearInterval(heartbeat);
if (!res.writableEnded) controller.abort(new Error('客户端断开'));
});
return {
signal: controller.signal,
send(event) {
if (res.writableEnded) return;
res.write(`data: ${JSON.stringify(event)}\n\n`);
},
end() {
clearInterval(heartbeat);
if (!res.writableEnded) res.end();
},
};
}
/* -------------------- 轮询式对话任务(原生端没有流式 body 时用) -------------------- */
/**
* runId -> { events: [], done: bool, at: number }
*
* 为什么需要它:Lynx 原生端(安卓)的 fetch 不提供 response.body,
* 没法边收边解析,只能等服务端全部写完 —— 表现出来就是"等很久然后一次性吐出来"。
* 轮询通道把同样的 SSE 事件攒在内存里,客户端每 200ms 取一次增量,
* 观感和真流式基本一致,而且三个平台(web / exe / 安卓)都能用。
*/
const chatRuns = new Map();
const RUN_TTL_MS = 10 * 60 * 1000;
setInterval(() => {
const now = Date.now();
for (const [id, run] of chatRuns) {
if (now - run.at > RUN_TTL_MS) chatRuns.delete(id);
}
}, 60_000).unref?.();
/**
* 真正跑一轮对话。SSE 和轮询两条路共用它,保证行为一致。
* sink: { send(event), end(), signal }
*/
async function performChat({ sink, settings, conversationId, text, attachments, body }) {
try {
const history = (body.history || store.getConversation(conversationId)?.messages || [])
.filter((m) => m.role === 'user' || m.role === 'assistant')
.map((m) => ({ role: m.role, content: m.content }));
// 附件 → 模型输入:图片走视觉格式,文本类内联正文
const parts = [];
if (text) parts.push({ type: 'text', text });
const attachmentMeta = [];
for (const item of attachments) {
const payload = attachmentPayload(item);
if (payload.text) parts.push({ type: 'text', text: payload.text });
for (const image of payload.images) {
parts.push({ type: 'image_url', image_url: { url: image.url } });
}
attachmentMeta.push({
id: item.id,
name: item.name,
size: item.size,
mime: item.mime,
url: item.url || '',
});
}
const userContent = parts.some((p) => p.type === 'image_url') || parts.length > 1 ? parts : text;
const agent = getAgent(body.agentId) || getAgent(settings.activeAgentId);
store.appendMessages(conversationId, [
{
role: 'user',
content: text || `(已发送 ${attachmentMeta.length} 个附件)`,
attachments: attachmentMeta,
at: new Date().toISOString(),
},
]);
if (text) store.autoTitle(conversationId, text);
const result = await runAgent({
settings,
agent,
messages: [...history, { role: 'user', content: userContent }],
emit: (event) => sink.send(event),
signal: sink.signal,
});
store.appendMessages(conversationId, [
{
role: 'assistant',
content: result.content,
// 思维链也落库,否则刷新后「思考过程」就空了
reasoning: result.reasoning || '',
agentId: agent?.id || '',
at: new Date().toISOString(),
},
]);
sink.send({ type: 'saved', conversationId, title: store.getConversation(conversationId)?.title });
} catch (err) {
// 错误一定要带上下文,前端才能给出有用的提示(缺 Key / 模型名错 / 网络)
sink.send({
type: 'error',
message: err?.message || String(err),
hint: chatErrorHint(err, settings),
});
} finally {
sink.end();
}
}
/** 把常见报错翻译成一句人话,前端直接展示 */
function chatErrorHint(err, settings) {
const msg = String(err?.message || err || '');
if (/401|Unauthorized|invalid.*api.*key|AuthenticationError/i.test(msg)) {
return 'API Key 不对或没填:右上角 ✎ → AI 内核设置 → 粘贴 Key 后保存';
}
if (/404|model.*not.*found|does not exist|InvalidEndpoint/i.test(msg)) {
return `模型或接入点不存在:当前是 ${settings?.model},去「模型」那一栏换一个,或填方舟的 ep- 接入点 ID`;
}
if (/429|rate.?limit|quota|insufficient/i.test(msg)) {
return '被限流或余额不足,等一会儿或去控制台看额度';
}
if (/timeout|ETIMEDOUT|ECONNREFUSED|ENOTFOUND|fetch failed|getaddrinfo/i.test(msg)) {
return '网络不通:检查手机网络,或(远程内核模式)内网地址是否可达';
}
if (/400/.test(msg)) {
return '请求被拒:多半是模型名/参数不匹配,试试把思考强度调成「自动」';
}
return '';
}
/* ------------------------------- 路由 ------------------------------- */
async function handleApi(req, res, url) {
const { pathname } = url;
const method = req.method;
if (method === 'OPTIONS') {
res.writeHead(204);
res.end();
return true;
}
if (pathname === '/api/health') {
sendJson(res, 200, { ok: true, pid: process.pid, cwd: process.cwd() });
return true;
}
// 探活:前端用它判断"这条通道能不能边收边解析"。
// 注意:Lynx 原生端的 fetch 不支持 response.body,所以轮询才是那边的正路。
if (pathname === '/api/chat/transport' && method === 'GET') {
sendJson(res, 200, { ok: true, sse: true, poll: true });
return true;
}
// 当前状态:设置(脱敏)+ 工具 + MCP + 会话列表 + 智能体
if (pathname === '/api/state' && method === 'GET') {
const settings = readSettings();
const tools = await listAllTools(settings);
const toolNames = [...tools.python.map((t) => t.name), ...tools.mcp.map((d) => d.function.name)];
sendJson(res, 200, {
settings: maskSettings(settings),
provider: providerInfo(settings),
providers: PROVIDER_PRESETS,
speech: speechState(settings),
speechVoices: VOICE_OPTIONS,
// 全量音色:界面的"全部音色"用这个(V1 73 / V3 90),
// speechVoices 只是快捷胶囊用的常用项
speechVoicesAll: VOICE_OPTIONS_ALL,
python: {
tools: tools.python.map(({ __file, __python, ...t }) => ({ ...t, file: path.basename(__file) })),
errors: tools.errors,
interpreter: tools.pythonInfo ? tools.pythonInfo.bin : null,
},
mcp: await getMcpState(),
mcpConfig: readMcpConfig(),
conversations: store.listConversations(),
agents: listAgents(),
toolNames,
suggestedAllow: suggestAllowlist(toolNames),
// 前端用它挑终端里的预设命令(Windows 的 dir / 安卓的 getprop 不通用)
platform: process.platform,
shellKind: process.platform === 'win32' ? 'cmd' : 'sh',
});
return true;
}
if (pathname === '/api/settings' && (method === 'PUT' || method === 'POST')) {
const patch = await readBody(req);
const next = writeSettings(patch);
sendJson(res, 200, { ok: true, settings: maskSettings(next) });
return true;
}
if (pathname === '/api/models' && method === 'GET') {
const settings = readSettings();
try {
const models = await listModels({ baseUrl: settings.baseUrl, apiKey: settings.apiKey });
sendJson(res, 200, { ok: true, models });
} catch (err) {
sendJson(res, 200, { ok: false, error: err.message, fallback: PROVIDER_PRESETS[settings.provider]?.models || [] });
}
return true;
}
/* ------------------------------------------------------------------ *
* 语音
*
* 两个接口都刻意**失败也返回 HTTP 200 + ok:false**:缺 Key、厂商报错
* 都是预期内的失败,界面要的是把原因显示出来,而不是让 fetch 抛一个
* 网络异常(那样错误信息就丢了)。
* ------------------------------------------------------------------ */
if (pathname === '/api/tts' && method === 'POST') {
let body = {};
try {
body = await readBody(req);
} catch { /* 空 body 也在下面统一报错 */ }
try {
// 带上 agentId 就用那个智能体的音色(多人会议里不同智能体不同声音,
// 否则四个人一个嗓子根本听不出谁在说)。不传就沿用全局。
const agent = body.agentId ? getAgent(body.agentId) : null;
const result = await synthesize(body.text, readSettings(), agent);
sendJson(res, 200, { ok: true, ...result });
} catch (err) {
sendJson(res, 200, { ok: false, error: err.message });
}
return true;
}
if (pathname === '/api/tts/stream' && method === 'POST') {
// 边合成边下发:音频块一到就 write,客户端能立刻开始播,
// 不用等整段合成完(实测长句首块 ~0.9s 到、末块 ~2.7s 到)。
let body = {};
try {
body = await readBody(req);
} catch { /* 空 body 由 synthesizeStream 自己报错 */ }
const agent = body.agentId ? getAgent(body.agentId) : null;
await streamTts(req, res, body.text, readSettings(), agent);
return true;
}
if (pathname === '/api/stt' && method === 'POST') {
// 音频是原始字节(不套 JSON/base64):省一次编解码,客户端录完直接发
let audio;
try {
audio = await readRaw(req, 25 * 1024 * 1024);
} catch (err) {
sendJson(res, 200, { ok: false, error: err.message });
return true;
}
try {
const result = await transcribe(
audio,
req.headers['x-audio-filename'] || 'audio.wav',
req.headers['x-audio-type'] || 'audio/wav',
readSettings(),
);
sendJson(res, 200, { ok: true, ...result });
} catch (err) {
sendJson(res, 200, { ok: false, error: err.message });
}
return true;
}
if (pathname === '/api/speech' && method === 'GET') {
const settings = readSettings();
sendJson(res, 200, { ok: true, speech: speechState(settings), voices: VOICE_OPTIONS });
return true;
}
// 会话
if (pathname === '/api/conversations' && method === 'GET') {
sendJson(res, 200, { conversations: store.listConversations() });
return true;
}
if (pathname === '/api/conversations' && method === 'POST') {
const body = await readBody(req).catch(() => ({}));
sendJson(res, 200, { conversation: store.createConversation(body.title || '新对话') });
return true;
}
const convMatch = pathname.match(/^\/api\/conversations\/([^/]+)$/);
if (convMatch) {
const id = convMatch[1];
if (method === 'GET') {
const conv = store.getConversation(id);
return conv ? (sendJson(res, 200, { conversation: conv }), true) : (sendJson(res, 404, { error: '会话不存在' }), true);
}
if (method === 'PATCH' || method === 'PUT') {
const body = await readBody(req);
const conv = store.updateConversation(id, body);
sendJson(res, conv ? 200 : 404, conv ? { conversation: conv } : { error: '会话不存在' });
return true;
}
if (method === 'DELETE') {
const ok = store.deleteConversation(id);
sendJson(res, ok ? 200 : 404, { ok });
return true;
}
}
// 会议模式
if (pathname === '/api/meetings' && method === 'GET') {
sendJson(res, 200, { meetings: listMeetings() });
return true;
}
if (pathname === '/api/meetings' && method === 'POST') {
const body = await readBody(req).catch(() => ({}));
sendJson(res, 200, { meeting: createMeeting(body) });
return true;
}
if (pathname === '/api/meeting/meta' && method === 'GET') {
// 编辑器要用:节点类型、判断条件、可用智能体
sendJson(res, 200, {
nodeTypes: [
{ key: 'start', label: '初始输入', desc: '整张图的入口' },
{ key: 'agent', label: '智能体', desc: '一个智能体处理一轮' },
{ key: 'judge', label: '判断', desc: '按条件分 true / false 两条路' },
{ key: 'end', label: '最终输出', desc: '汇总结果' },
],
judgeKinds: JUDGE_KINDS.map(([key, label]) => ({ key, label })),
agents: listAgents().map((a) => ({ id: a.id, name: a.name, avatar: a.avatar })),
});
return true;
}
// /api/meetings/<id>/run 走 SSE;必须在通用 id 匹配之前判掉(那条正则不接受斜杠)
if (pathname.startsWith('/api/meetings/') && pathname.endsWith('/run') && method === 'POST') {
const id = pathname.slice('/api/meetings/'.length, -'/run'.length);
await streamMeetingRun(req, res, id);
return true;
}
const meetMatch = pathname.match(/^\/api\/meetings\/([^/]+)$/);
if (meetMatch) {
const id = meetMatch[1];
if (method === 'GET') {
const item = getMeeting(id);
sendJson(res, item ? 200 : 404, item ? { meeting: item } : { error: '会议不存在' });
return true;
}
if (method === 'PUT' || method === 'PATCH') {
const body = await readBody(req).catch(() => ({}));
const item = saveMeeting(id, body);
sendJson(res, item ? 200 : 404, item ? { meeting: item } : { error: '会议不存在' });
return true;
}
if (method === 'DELETE') {
const ok = deleteMeeting(id);
sendJson(res, ok ? 200 : 404, { ok });
return true;
}
}
// 工具
if (pathname === '/api/tools' && method === 'GET') {
const settings = readSettings();
const tools = await listAllTools(settings);
const toolNames = [...tools.python.map((t) => t.name), ...tools.mcp.map((d) => d.function.name)];
sendJson(res, 200, {
python: tools.python.map(({ __file, __python, ...t }) => ({ ...t, file: path.basename(__file) })),
errors: tools.errors,
mcp: await getMcpState(),
toolNames,
suggestedAllow: suggestAllowlist(toolNames),
});
return true;
}
if (pathname === '/api/tools/run' && method === 'POST') {
const body = await readBody(req);
if (!body.name) {
sendJson(res, 400, { error: '缺少 name' });
return true;
}
try {
// 手动试运行不受安全模式限制(是用户自己点的),但仍要能报错
const result = await executeTool(body.name, body.args || {}, { security: { mode: 'open' } });
sendJson(res, 200, result);
} catch (err) {
sendJson(res, 500, { ok: false, error: err.message });
}
return true;
}
// MCP
if (pathname === '/api/mcp' && method === 'GET') {
const configPath = mcpConfigPath();
sendJson(res, 200, {
servers: await getMcpState(),
config: readMcpConfig(),
path: configPath,
dir: path.dirname(configPath),
text: readMcpConfigText(),
// Electron 主进程会挂上这个钩子,用来在资源管理器里定位配置文件
canReveal: typeof globalThis.__doubaoReveal === 'function',
placeholders: {
DOUBAO_DATA: process.env.DOUBAO_DATA || '',
APPDATA: process.env.APPDATA || '',
USERPROFILE: process.env.USERPROFILE || '',
},
});
return true;
}
if (pathname === '/api/mcp/config' && (method === 'PUT' || method === 'POST')) {
const body = await readBody(req);
try {
const count = writeMcpConfigText(String(body.text ?? ''));
await disconnectAll();
const results = await connectAllEnabled();
sendJson(res, 200, {
ok: true,
count,
results,
servers: await getMcpState(),
});
} catch (err) {
sendJson(res, 400, { ok: false, error: err.message });
}
return true;
}
if (pathname === '/api/mcp/reveal' && method === 'POST') {
const target = mcpConfigPath();
const reveal = globalThis.__doubaoReveal;
if (typeof reveal === 'function') {
const err = await reveal(target);
sendJson(res, 200, { ok: !err, error: err || null, path: target });
} else {
sendJson(res, 200, { ok: false, error: '当前运行方式不支持打开文件夹', path: target });
}
return true;
}
if (pathname === '/api/mcp/connect' && method === 'POST') {
const body = await readBody(req);
if (body.name) {
const record = await connect(body.name, { force: true });
sendJson(res, 200, { ok: !record.error, error: record.error, toolCount: record.tools.length });
} else {
const results = await connectAllEnabled();
sendJson(res, 200, { ok: results.every((r) => r.ok), results });
}
return true;
}
if (pathname === '/api/mcp/disconnect' && method === 'POST') {
const body = await readBody(req);
await disconnect(body.name);
sendJson(res, 200, { ok: true });
return true;
}
// 智能体
if (pathname === '/api/agents' && method === 'GET') {
sendJson(res, 200, { agents: listAgents() });
return true;
}
if (pathname === '/api/agents' && method === 'POST') {
const body = await readBody(req);
sendJson(res, 200, { agent: createAgent(body) });
return true;
}
const agentMatch = pathname.match(/^\/api\/agents\/([^/]+)$/);
if (agentMatch) {
const id = agentMatch[1];
if (method === 'PATCH' || method === 'PUT') {
const body = await readBody(req);
const agent = updateAgent(id, body);
sendJson(res, agent ? 200 : 404, agent ? { agent } : { error: '智能体不存在' });
return true;
}
if (method === 'DELETE') {
sendJson(res, deleteAgent(id) ? 200 : 404, { ok: true });
return true;
}
}
// 附件
if (pathname === '/api/upload' && method === 'POST') {
// 150MB:100MB 上限的文件 base64 之后约 133MB,再套 JSON
const body = await readBody(req, 150 * 1024 * 1024);
try {
// 三个字段名都收:dataUrl 是约定名,base64 是历史名,
// data 是安卓客户端曾经错发过的名字 —— 收下它,免得旧版本一直传不上来
const item = saveUpload({ name: body.name, base64: body.dataUrl || body.base64 || body.data });
if (body.pending) addPending([item]);
sendJson(res, 200, { ok: true, file: item });
} catch (err) {
sendJson(res, 400, { ok: false, error: err.message });
}
return true;
}
if (pathname === '/api/pick-file' && method === 'POST') {
const picker = globalThis.__doubaoPickFile;
if (typeof picker !== 'function') {
sendJson(res, 200, { ok: false, error: '当前环境不支持原生选文件,请拖拽文件到窗口里', files: [] });
return true;
}
try {
const paths = (await picker()) || [];
const files = paths.map((p) => registerLocalFile(p));
sendJson(res, 200, { ok: true, files });
} catch (err) {
sendJson(res, 500, { ok: false, error: err.message, files: [] });
}
return true;
}
if (pathname === '/api/uploads/pending' && method === 'GET') {
sendJson(res, 200, { files: takePending() });
return true;
}
if (pathname === '/api/clipboard' && method === 'POST') {
const body = await readBody(req);
const writer = globalThis.__doubaoClipboard;
if (typeof writer === 'function') {
writer(String(body.text ?? ''));
sendJson(res, 200, { ok: true, via: 'native' });
} else {
sendJson(res, 200, { ok: false, via: 'none' });
}
return true;
}
// 流式对话
if (pathname === '/api/chat' && method === 'POST') {
const body = await readBody(req);
const settings = readSettings();
const conversationId = body.conversationId || 'c_main';
const text = String(body.message || '').trim();
const attachments = Array.isArray(body.attachments) ? body.attachments : [];
if (!text && attachments.length === 0) {
sendJson(res, 400, { error: '消息为空' });
return true;
}
// ★ 轮询模式:Lynx 原生端的 fetch 拿不到 response.body(没法边收边解析),
// 所以那条路走「先返回 runId,再不断 GET /api/chat/poll」。
// 两条路共用同一个 performChat,行为完全一致。
if (body.transport === 'poll') {
const runId = `r${Date.now().toString(36)}${Math.random().toString(36).slice(2, 7)}`;
chatRuns.set(runId, { events: [], done: false, at: Date.now() });
sendJson(res, 200, { ok: true, runId, transport: 'poll' });
const sink = {
send: (event) => {
const run = chatRuns.get(runId);
if (!run) return;
run.events.push(event);
if (event.type === 'done' || event.type === 'error') run.done = true;
},
end: () => {
const run = chatRuns.get(runId);
if (run) run.done = true;
},
// 轮询模式感知不到客户端断开,用 abort 控制器占位(超时/关闭由内核自己兜底)
signal: new AbortController().signal,
};
// 故意不 await:让 HTTP 立刻返回,任务在后台跑
void performChat({ sink, settings, conversationId, text, attachments, body });
return true;
}
const sse = sseStart(res, req);
await performChat({ sink: sse, settings, conversationId, text, attachments, body });
return true;
}
// 轮询取增量:GET /api/chat/poll?runId=xxx&cursor=N
if (pathname === '/api/chat/poll' && method === 'GET') {
const url = new URL(req.url, 'http://localhost');
const runId = url.searchParams.get('runId') || '';
const cursor = Number(url.searchParams.get('cursor') || 0) || 0;
const run = chatRuns.get(runId);
if (!run) {
sendJson(res, 404, { ok: false, error: '任务不存在或已过期' });
return true;
}
const events = run.events.slice(cursor);
sendJson(res, 200, { ok: true, events, cursor: run.events.length, done: run.done });
// 已经取完的任务过一会儿就清掉,别一直占内存
if (run.done && run.events.length === cursor) run.at = Date.now() - 9 * 60 * 1000;
return true;
}
return false;
}
function handleStatic(req, res, url) {
const { pathname } = url;
if (pathname === '/' || pathname === '/index.html') {
if (!fs.existsSync(WEB_INDEX)) {
sendText(
res,
503,
'宿主页不存在。请先运行 npm run build(app/),或在 app/ 里跑 npm run dev 用 Rspeedy 开发服务器预览。',
);
return true;
}
return serveFile(res, WEB_INDEX);
}
if (pathname.startsWith('/lynx-web/')) {
const file = safeJoin(WEB_CORE_STATIC, pathname.slice('/lynx-web'.length));
return file ? serveFile(res, file, { fallback404: false }) || true : true;
}
// 上传的附件(图片缩略图要用)
if (pathname.startsWith('/uploads/')) {
const file = safeJoin(UPLOADS_DIR, pathname.slice('/uploads'.length));
if (file && fs.existsSync(file) && fs.statSync(file).isFile()) return serveFile(res, file);
}
// @lynx-js/web-core 的运行时固定从 /static/ 拉 chunk 与 wasm,必须原样托管
if (pathname.startsWith('/static/')) {
const coreFile = safeJoin(WEB_CORE_STATIC, pathname.slice('/static'.length));
if (coreFile && fs.existsSync(coreFile) && fs.statSync(coreFile).isFile()) {
return serveFile(res, coreFile);
}
}
if (pathname === '/main.web.bundle' || pathname === '/main.lynx.bundle') {
return serveFile(res, path.join(DIST_DIR, path.basename(pathname)));
}
const distFile = safeJoin(DIST_DIR, pathname);
if (distFile && fs.existsSync(distFile) && fs.statSync(distFile).isFile()) {
return serveFile(res, distFile);
}
return false;
}
/** 创建(但不启动)内核 HTTP 服务,方便被 Electron 主进程内嵌 */
export function createKernelServer() {
return http.createServer(async (req, res) => {
const url = new URL(req.url, `http://${req.headers.host || 'localhost'}`);
cors(res);
try {
if (url.pathname.startsWith('/api/')) {
const handled = await handleApi(req, res, url);
if (!handled) sendJson(res, 404, { error: `未知接口 ${url.pathname}` });
return;
}
const handled = handleStatic(req, res, url);
if (!handled) sendText(res, 404, '404 Not Found');
} catch (err) {
console.error('[http] 处理失败:', err);
if (!res.headersSent) sendJson(res, 500, { error: err?.message || String(err) });
else res.end();
}
});
}
/**
* 启动内核。
* @param {{port?:number, host?:string, quiet?:boolean}} [options]
* @returns {Promise<{port:number, host:string, url:string, close:()=>Promise<void>}>}
*/
export function startKernel(options = {}) {
const host = options.host || DEFAULT_HOST;
const port = options.port ?? DEFAULT_PORT;
const server = createKernelServer();
return new Promise((resolve, reject) => {
server.once('error', reject);
server.listen(port, host, () => {
const actualPort = server.address().port;
const url = `http://${host}:${actualPort}/`;
if (!options.quiet) {
const settings = readSettings();
console.log('');
console.log(' Doubao Clone · AI kernel started');
console.log(` ├─ UI ${url}`);
console.log(` ├─ provider ${settings.provider} · ${providerInfo(settings).model}`);
console.log(` ├─ api key ${settings.apiKey ? 'configured' : 'missing (set it in Settings, or server/.env)'}`);
console.log(` └─ tools python=${settings.tools.python} mcp=${settings.tools.mcp}`);
console.log(` web-core ${WEB_CORE_STATIC}`);
console.log('');
}
connectAllEnabled().catch((err) => console.error('[mcp] 启动连接失败:', err.message));
resolve({
port: actualPort,
host,
url,
close: () =>
new Promise((done) => {
server.close(() => done());
server.closeAllConnections?.();
}),
});
});
});
}
/** 直接 `node src/index.mjs` 时按命令行方式启动 */
const isCli = process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href;
if (isCli) {
startKernel().catch((err) => {
console.error('启动失败:', err.message);
process.exit(1);
});
}