豆包复刻:原生安卓(Compose + 内嵌 Termux)+ Web / Windows

一个界面照着豆包抠的 AI 助手。主力是安卓端,完全离线自主:不依赖电脑、
不需要另外装 Termux。

安卓端
- 原生 Jetpack Compose,7 个页面,配色/圆角/间距对着真机截图量出来的
- 完整动效:抽屉滑入、页面切换、气泡淡入上移、面板底部升起、typing 三点、按钮回弹
- 内置 Termux:bash/apt/pkg 388 个命令、真 pty 终端;
  pty 不可用的 ROM 上自动降级成命令控制台
- APK 内嵌 CPython 3.13(Chaquopy),AI 内核跑在手机上
- 设备能力:定位 / 陀螺仪 / 加速度计 / 光线 / 电量 / 剪贴板
- 语音:朗读 + 语音输入,火山豆包音色 / OpenAI 兼容 / 设备自带三级引擎

AI 能力
- 10 家 OpenAI 兼容提供商:方舟 / OpenAI / DeepSeek / Kimi / 智谱 /
  通义 / 硅基流动 / OpenRouter / 本地 Ollama / 自定义
- 思考强度按各家支持情况发不同字段(thinking / reasoning_effort / 不发),
  认不出来的一律不发,避免给不支持的厂商发字段直接 400
- MCP 三种传输(http / stdio / inproc)、工具热加载、文件上传、权限模式

跨端
- 安卓走原生 Compose,Web / Windows 走 Lynx
- Node 与 Python 两份内核接口逐字段一致,关键路径都有对拍脚本

自检脚本(都不需要真 Key)
- verify-phone.mjs          设备端 24 项验收
- verify-speech.mjs         语音链路 31 项,两份内核各跑一遍
- parity-thinking.mjs       思考强度映射对拍
- probe-settings-wipe.mjs   设置防清空攻击测试
- mock-llm.mjs              假的 OpenAI + 火山语音服务

许可 MIT;第三方组件(Termux Apache-2.0、Chaquopy、Compose、LynxJS、Electron)
的授权见 LICENSE。
This commit is contained in:
l
2026-10-09 14:09:36 +08:00
commit f056bcf45a
308 changed files with 46874 additions and 0 deletions

798
server/src/index.mjs Normal file
View File

@@ -0,0 +1,798 @@
/**
* 豆包复刻 · 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 {
synthesize,
transcribe,
speechState,
VOICE_OPTIONS,
} 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');
}
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,
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 {
const result = await synthesize(body.text, readSettings());
sendJson(res, 200, { ok: true, ...result });
} catch (err) {
sendJson(res, 200, { ok: false, error: err.message });
}
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/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') {
const body = await readBody(req, 40 * 1024 * 1024);
try {
const item = saveUpload({ name: body.name, base64: body.dataUrl || body.base64 });
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);
});
}