用户:"运算为啥不给数字类型连?端点颜色根据类型定白色exec 绿色str 蓝色 num
红色bool。运算可以根据运算的类型从而改变输入端点的类型。加个分支节点,
输入bool,输入为1走a exec 否则走 b exec。运算加上大于等于,小于等于,
或,与,异或,左移右移" + "还有值节点如何设置值"
【1. 数字连不上运算 —— 界面的读变量出口写死了 str】
"readvar" -> listOf(PinSpec("str", "", "值")) ← 就是这行
读变量的出口类型**必须按变量登记表**。写死 str 的后果:
数字变量 → 读变量 → 运算 的线**接不上**(运算的 num 入口只收 num,
而读变量声称自己给 str)。引擎那边 `_data_out_type` 本来就查登记表,
界面这份漏了 —— **又一次"引擎有、界面没有"**。
修:outputPins 加 varTypes 参数(MeetingEditorScreen 里 remember 算一次),
readvar 的出口类型从登记表查。
【2. 端点按类型上色】
新增 pinColor(kind):白 exec / 绿 str / 蓝 num / 红 bool / 橙 list。
引脚圆点和**连线**用同一个颜色 —— 顺着颜色就能看出这根线接得对不对。
★ 判断/while/分支的 exec 出口保留绿(真)/红(假):
那表达的是"走哪条"不是"什么类型",和按类型上色不冲突。
(列表给橙色:它是后加的类型,得和前面三个一眼区分开。)
【3. 分支节点】
新节点类型 `branch`:收一个真假,走真/假两条 exec。
· 和判断节点的区别:判断按**规则**算真假(包含关键词/字数多于…),
分支**直接收**一个真假 —— 真假从哪来由用户自己接
(运算的比较结果、变量、读变量、自定义节点)。
· 规则和判断**完全一致**(同一套坑不能两样):判成的分支没连线 →
停在原地 + 报警告,不顺走另一条。
· 条件入口收得宽(bool/str/num):变量和上游多半给的是 "true"/"1" 这类
文本,用 truthy() 统一判断。
实测:true→A false→B 1→A 0→B 是→A 空→B
【4. 七个新算子】
gte 大于等于 ≥ lte 小于等于 ≤
and 与 or 或 xor 异或
shl 左移 << shr 右移 >>
算子总数 14 → 21。
★ 逻辑运算不要求两边"是严格的 bool":硬卡类型的话用户得先接一堆转换节点。
用 truthy() 统一判断(认 0/空/false/no/off),输出统一 true/false。
★ 位运算先转**整数**(Python 的 << 对浮点会报错),
位移量限 0~64(不让用户一不小心写出 1 << 9999999 算到天荒地老),
负数位移量和超限都报错而不是崩。
【5. 值节点的配置面板(用户:"值节点如何设置值")】
配置面板有 agent/judge/var/py/cast/op/readvar **七个分支,没有 value** ——
值节点打开是空的,根本没法设值。**还是同一个毛病。**
补上:类型选择器 + 值输入框 + 按类型的提示
(数字能接运算、真假能接分支、列表写成 JSON 数组…)。
【端到端实测】
数字变量 n=7 → 读变量(num) → 运算 gte(5) → 分支 → 走「够大」
读变量出口类型: num ✓ 运算入口类型: ('num',) ✓ 边保留 6/6 ✓
【验证】
- 会议引擎 40/40,Node 与 Python 16/16 逐用例一致
- APK 构建通过、装机通过
- 截图确认:bool 引脚红、list 引脚橙、str 引脚绿、exec 白
1117 lines
40 KiB
JavaScript
1117 lines
40 KiB
JavaScript
/**
|
||
* 豆包复刻 · 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,
|
||
listRuns,
|
||
clearRuns,
|
||
appendRun,
|
||
variablesPrompt,
|
||
} 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, variables) => {
|
||
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}`);
|
||
// 变量说明拼在最后:它和"输出要求"一样是这一轮的约束,
|
||
// 但放在更后面,模型对"最后看到的东西"注意力更高
|
||
const varText = variablesPrompt(variables || {}, node.readVars, node.writeVars);
|
||
if (varText) parts.push(varText);
|
||
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,
|
||
// 界面上按节点分组显示。
|
||
//
|
||
// ★ 流式正文的事件名是 **delta**,不是 text —— agent.mjs 发的是
|
||
// {type:'delta', text:…}。按 'text' 判断的话 node_delta 一个都发不出去,
|
||
// 节点上的正文只在最后 node_done 时"啪"地出现,完全没有流式效果。
|
||
if (event.type === 'delta') {
|
||
emit({ type: 'node_delta', nodeId, text: event.text || '' });
|
||
} else if (event.type === 'reasoning') {
|
||
emit({ type: 'node_reasoning', nodeId, text: event.text || '' });
|
||
} else if (event.type !== 'done' && event.type !== 'start') {
|
||
// done / start 是"整个 agent 轮次"的开始和结束,和会议节点的语义重复,
|
||
// 转出去只会让界面多两个没用的状态
|
||
emit({ ...event, nodeId });
|
||
}
|
||
},
|
||
});
|
||
// ★ 这里**不**处理 [[SET]]:那是节点语义,归引擎管(见 meeting.runMeeting)。
|
||
// 放在这一层的话,引擎自己的测试压根覆盖不到,换个调用方也会忘。
|
||
return result?.content || '';
|
||
};
|
||
|
||
try {
|
||
// ★ 一边转发一边攒一份运行记录:结果界面要能按"哪个节点、第几轮"回看,
|
||
// 而不是只有一个最终答案。循环跑很多轮时这份记录尤其有用。
|
||
const steps = [];
|
||
const final = { output: '', aborted: false, error: '' };
|
||
|
||
const record = (event) => {
|
||
send(event);
|
||
if (event.type === 'node_done') {
|
||
steps.push({
|
||
nodeId: event.nodeId,
|
||
nodeType: event.nodeType,
|
||
title: event.title,
|
||
run: event.run || 1,
|
||
output: event.output || '',
|
||
note: event.note || '',
|
||
});
|
||
} else if (event.type === 'node_error') {
|
||
steps.push({
|
||
nodeId: event.nodeId,
|
||
nodeType: event.nodeType,
|
||
title: event.title,
|
||
run: event.run || 1,
|
||
output: '',
|
||
error: event.error || '',
|
||
});
|
||
} else if (event.type === 'meeting_done') {
|
||
final.output = event.output || '';
|
||
final.aborted = !!event.aborted;
|
||
final.error = event.error || '';
|
||
}
|
||
};
|
||
|
||
await runMeeting({
|
||
meeting: item,
|
||
settings,
|
||
userInput,
|
||
emit: record,
|
||
runAgentFn,
|
||
});
|
||
|
||
// 存历史。节点标题在事件里可能没有(引擎只在 node_start 里给),
|
||
// 这里从会议定义里补齐,免得历史界面上全是"未命名"。
|
||
const titles = {};
|
||
for (const n of item.nodes || []) titles[n.id] = n.title;
|
||
for (const step of steps) {
|
||
if (!step.title) step.title = titles[step.nodeId] || '';
|
||
}
|
||
appendRun(meetingId, {
|
||
at: new Date().toISOString(),
|
||
input: userInput,
|
||
steps,
|
||
output: final.output,
|
||
aborted: final.aborted,
|
||
error: final.error,
|
||
});
|
||
} 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: '整张图从这里开始(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: JUDGE_KINDS.map(([key, label]) => ({ key, label })),
|
||
agents: listAgents().map((a) => ({ id: a.id, name: a.name, avatar: a.avatar })),
|
||
});
|
||
return true;
|
||
}
|
||
// 运行历史:结果界面要能回看前几次跑了什么
|
||
if (pathname.startsWith('/api/meetings/') && pathname.endsWith('/runs')) {
|
||
const id = pathname.slice('/api/meetings/'.length, -'/runs'.length);
|
||
if (method === 'GET') {
|
||
sendJson(res, 200, { runs: listRuns(id) });
|
||
return true;
|
||
}
|
||
if (method === 'DELETE') {
|
||
sendJson(res, 200, { ok: clearRuns(id) });
|
||
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);
|
||
});
|
||
}
|