豆包复刻:原生安卓(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:
12
server/.env.example
Normal file
12
server/.env.example
Normal file
@@ -0,0 +1,12 @@
|
||||
# 复制成 server/.env 后填写。代码里没填 apiKey 时会读这里。
|
||||
# 火山方舟(豆包):https://console.volcengine.com/ark
|
||||
ARK_API_KEY=
|
||||
|
||||
# OpenAI(或任何 OpenAI 兼容网关)
|
||||
OPENAI_API_KEY=
|
||||
|
||||
# 可选:指定 python 解释器(不填则自动探测 python / python3 / py -3)
|
||||
PYTHON=
|
||||
|
||||
# 可选:内核监听端口,默认 5199
|
||||
PORT=5199
|
||||
17
server/config/settings.example.json
Normal file
17
server/config/settings.example.json
Normal file
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"provider": "ark",
|
||||
"baseUrl": "https://ark.cn-beijing.volces.com/api/v3",
|
||||
"model": "doubao-seed-2-1-pro-260628",
|
||||
"apiKey": "",
|
||||
"temperature": 0.7,
|
||||
"maxRounds": 6,
|
||||
"thinking": "",
|
||||
"systemPrompt": "你是豆包,一个由字节跳动开发的 AI 助手,风格自然、亲切、简洁。\n\n回答要求:\n1. 用简体中文回答,除非用户要求其他语言。\n2. 先给结论,再给必要的解释,避免空话和过度铺垫。\n3. 需要计算、查时间、读写本地笔记或抓取网页时,主动调用可用工具,不要凭记忆编造。\n4. 工具返回的内容可能不完整,若失败要如实说明失败原因。\n5. 不确定的信息要明确标注不确定。",
|
||||
"tools": {
|
||||
"python": true,
|
||||
"mcp": true
|
||||
},
|
||||
"pythonBin": "",
|
||||
"nickname": "我",
|
||||
"doubaoId": "378269252"
|
||||
}
|
||||
1206
server/package-lock.json
generated
Normal file
1206
server/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
19
server/package.json
Normal file
19
server/package.json
Normal file
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"name": "doubao-kernel",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "豆包复刻的 AI 内核:火山方舟 / OpenAI 兼容 API + MCP + Python 工具",
|
||||
"main": "src/index.mjs",
|
||||
"scripts": {
|
||||
"start": "node src/index.mjs",
|
||||
"dev": "node --watch src/index.mjs"
|
||||
},
|
||||
"dependencies": {
|
||||
"@modelcontextprotocol/sdk": "^1.32.1",
|
||||
"zod": "^3.25.76"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
}
|
||||
}
|
||||
194
server/src/agent.mjs
Normal file
194
server/src/agent.mjs
Normal file
@@ -0,0 +1,194 @@
|
||||
/**
|
||||
* Agent 主循环:系统提示词 + 多轮工具调用 + 流式输出。
|
||||
* 支持两种安全模式:
|
||||
* open 所有工具都交给模型
|
||||
* restricted 只有白名单里的工具可用(连执行都会再拦一道)
|
||||
*/
|
||||
import { providerInfo } from './config.mjs';
|
||||
import { streamChat } from './providers.mjs';
|
||||
import { discoverPythonTools, runPythonTool, toOpenAITool } from './python-tools.mjs';
|
||||
import { callMcpTool, isMcpTool, mcpToolDefs } from './mcp.mjs';
|
||||
|
||||
/** 汇总当前可用的全部工具 */
|
||||
export async function listAllTools(settings) {
|
||||
const out = { python: [], mcp: [], errors: [], pythonInfo: null };
|
||||
if (settings.tools?.python !== false) {
|
||||
const res = await discoverPythonTools();
|
||||
out.python = res.tools;
|
||||
out.errors = res.errors;
|
||||
out.pythonInfo = res.python;
|
||||
}
|
||||
if (settings.tools?.mcp !== false) {
|
||||
out.mcp = mcpToolDefs();
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** 只读工具的名字特征,用来给"限制模式"生成一份保守的默认白名单 */
|
||||
const READONLY_NAME = /^(read|list|get|search|open|find|fetch|show|describe|query|inspect|calc|now|web_fetch)/i;
|
||||
|
||||
export function suggestAllowlist(toolNames) {
|
||||
return toolNames.filter((name) => READONLY_NAME.test(name.split('__').pop() || name));
|
||||
}
|
||||
|
||||
/** 按安全模式过滤工具 */
|
||||
export function applySecurity(defs, settings) {
|
||||
const mode = settings.security?.mode || 'open';
|
||||
if (mode !== 'restricted') return defs;
|
||||
const allow = new Set(settings.security?.allow || []);
|
||||
return defs.filter((def) => allow.has(def.function.name));
|
||||
}
|
||||
|
||||
export async function buildToolDefs(settings) {
|
||||
const all = await listAllTools(settings);
|
||||
const defs = [...all.python.map(toOpenAITool), ...all.mcp];
|
||||
return applySecurity(defs, settings);
|
||||
}
|
||||
|
||||
/** 执行任意工具(Python 或 MCP),返回可序列化结果 */
|
||||
export async function executeTool(name, args, settings) {
|
||||
// 限制模式下即使模型硬编出工具名也不能执行
|
||||
if ((settings?.security?.mode || 'open') === 'restricted') {
|
||||
const allow = settings.security?.allow || [];
|
||||
if (!allow.includes(name)) {
|
||||
return { ok: false, error: `限制模式:工具 ${name} 未授权` };
|
||||
}
|
||||
}
|
||||
if (isMcpTool(name)) {
|
||||
const res = await callMcpTool(name, args);
|
||||
const parts = [];
|
||||
for (const item of res.content || []) {
|
||||
if (item.type === 'text') parts.push(item.text);
|
||||
else parts.push(`[${item.type}]`);
|
||||
}
|
||||
return { ok: !res.isError, result: parts.join('\n') || '(空结果)' };
|
||||
}
|
||||
return runPythonTool(name, args);
|
||||
}
|
||||
|
||||
function truncate(text, max = 6000) {
|
||||
const s = typeof text === 'string' ? text : JSON.stringify(text);
|
||||
return s.length > max ? `${s.slice(0, max)}\n…(已截断)` : s;
|
||||
}
|
||||
|
||||
/**
|
||||
* 跑一轮完整对话。
|
||||
* @param {object} opts
|
||||
* @param {object} opts.settings 当前设置
|
||||
* @param {Array} opts.messages [{role, content}] 历史(不含 system)
|
||||
* @param {object} [opts.agent] 当前智能体(systemPrompt 覆盖全局的)
|
||||
* @param {(event:object)=>void} opts.emit 事件回调
|
||||
* @param {AbortSignal} [opts.signal]
|
||||
*/
|
||||
export async function runAgent({ settings, messages, agent, emit, signal }) {
|
||||
const provider = providerInfo(settings);
|
||||
const toolDefs = await buildToolDefs(settings);
|
||||
const maxRounds = Math.max(1, Math.min(12, Number(settings.maxRounds) || 6));
|
||||
const mode = settings.security?.mode || 'open';
|
||||
const systemPrompt = (agent?.systemPrompt || '').trim() || settings.systemPrompt;
|
||||
const thinkingLevel = settings.thinkingLevel || 'auto';
|
||||
|
||||
emit({
|
||||
type: 'start',
|
||||
provider: settings.provider,
|
||||
model: provider.model,
|
||||
tools: toolDefs.length,
|
||||
mode,
|
||||
thinkingLevel,
|
||||
agent: agent ? { id: agent.id, name: agent.name } : null,
|
||||
});
|
||||
|
||||
const convo = [];
|
||||
if (systemPrompt?.trim()) {
|
||||
convo.push({ role: 'system', content: systemPrompt });
|
||||
}
|
||||
convo.push(...messages);
|
||||
|
||||
let answer = '';
|
||||
let reasoningAll = '';
|
||||
let toolCallCount = 0;
|
||||
let usage = null;
|
||||
|
||||
for (let round = 0; round < maxRounds; round += 1) {
|
||||
let roundText = '';
|
||||
let toolCalls = [];
|
||||
|
||||
for await (const ev of streamChat({
|
||||
// 注意:这里的 provider 是"提供商名字"(ark/openai),
|
||||
// 和上面那个 providerInfo 出来的对象不是一回事,别搞混
|
||||
provider: settings.provider,
|
||||
baseUrl: provider.baseUrl,
|
||||
apiKey: settings.apiKey,
|
||||
model: provider.model,
|
||||
messages: convo,
|
||||
tools: toolDefs.length ? toolDefs : undefined,
|
||||
temperature: settings.temperature,
|
||||
thinkingLevel,
|
||||
signal,
|
||||
})) {
|
||||
if (ev.type === 'text') {
|
||||
roundText += ev.text;
|
||||
// 所有轮次的文本都要累积:只调用工具的那一轮通常没有正文,
|
||||
// 真正给用户的回答在最后一轮,漏掉会让保存下来的消息变空。
|
||||
answer += ev.text;
|
||||
emit({ type: 'delta', text: ev.text, round });
|
||||
} else if (ev.type === 'reasoning') {
|
||||
reasoningAll += ev.text;
|
||||
emit({ type: 'reasoning', text: ev.text, round });
|
||||
} else if (ev.type === 'tool_calls') {
|
||||
toolCalls = ev.toolCalls;
|
||||
} else if (ev.type === 'usage') {
|
||||
usage = ev.usage;
|
||||
}
|
||||
}
|
||||
|
||||
if (!toolCalls.length) {
|
||||
emit({
|
||||
type: 'done',
|
||||
content: answer,
|
||||
reasoning: reasoningAll,
|
||||
rounds: round + 1,
|
||||
toolCalls: toolCallCount,
|
||||
usage,
|
||||
});
|
||||
return { content: answer, reasoning: reasoningAll, rounds: round + 1, toolCalls: toolCallCount, usage };
|
||||
}
|
||||
|
||||
convo.push({
|
||||
role: 'assistant',
|
||||
content: roundText || '',
|
||||
tool_calls: toolCalls.map((tc) => ({
|
||||
id: tc.id,
|
||||
type: 'function',
|
||||
function: { name: tc.name, arguments: tc.argsRaw || JSON.stringify(tc.args || {}) },
|
||||
})),
|
||||
});
|
||||
|
||||
for (const tc of toolCalls) {
|
||||
toolCallCount += 1;
|
||||
emit({ type: 'tool_call', id: tc.id, name: tc.name, args: tc.args });
|
||||
let result;
|
||||
try {
|
||||
result = await executeTool(tc.name, tc.args, settings);
|
||||
} catch (err) {
|
||||
result = { ok: false, error: err?.message || String(err) };
|
||||
}
|
||||
const payload = result.ok
|
||||
? truncate(result.result ?? '(无输出)')
|
||||
: `调用失败:${result.error || '未知错误'}`;
|
||||
emit({ type: 'tool_result', id: tc.id, name: tc.name, ok: Boolean(result.ok), result: payload });
|
||||
convo.push({ role: 'tool', tool_call_id: tc.id, content: payload });
|
||||
}
|
||||
}
|
||||
|
||||
emit({
|
||||
type: 'done',
|
||||
content: answer,
|
||||
reasoning: reasoningAll,
|
||||
rounds: maxRounds,
|
||||
toolCalls: toolCallCount,
|
||||
usage,
|
||||
truncated: true,
|
||||
});
|
||||
return { content: answer, reasoning: reasoningAll, rounds: maxRounds, toolCalls: toolCallCount, usage };
|
||||
}
|
||||
130
server/src/agents.mjs
Normal file
130
server/src/agents.mjs
Normal file
@@ -0,0 +1,130 @@
|
||||
/**
|
||||
* 智能体(Agent):每个智能体有自己的头像和系统提示词。
|
||||
* 存在 <数据目录>/agents.json,首次运行写入几个内置智能体。
|
||||
*/
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { DATA_DIR } from './config.mjs';
|
||||
|
||||
const FILE = path.join(DATA_DIR, 'agents.json');
|
||||
|
||||
const DEFAULT_AGENTS = [
|
||||
{
|
||||
id: 'a_doubao',
|
||||
name: '豆包',
|
||||
avatar: 'doubao',
|
||||
tagline: '通用助手',
|
||||
systemPrompt: '',
|
||||
builtin: true,
|
||||
},
|
||||
{
|
||||
id: 'a_coder',
|
||||
name: '代码搭子',
|
||||
avatar: 'coder',
|
||||
tagline: '只聊代码,直接给能跑的',
|
||||
systemPrompt: [
|
||||
'你是一个资深工程师。',
|
||||
'1. 先给可以直接复制运行的代码,再解释关键点。',
|
||||
'2. 代码里不要有省略号,不要写"此处省略"。',
|
||||
'3. 指出你方案里的坑和替代做法。',
|
||||
'4. 涉及文件读写、执行命令时优先调用可用工具。',
|
||||
].join('\n'),
|
||||
builtin: true,
|
||||
},
|
||||
{
|
||||
id: 'a_writer',
|
||||
name: '文案师',
|
||||
avatar: 'writer',
|
||||
tagline: '写东西、改稿子',
|
||||
systemPrompt: [
|
||||
'你是中文文案编辑。',
|
||||
'1. 先问清楚用途、受众、字数要求,信息不全就按最常见的场景先给一版。',
|
||||
'2. 给成品,不要给"写作思路"。',
|
||||
'3. 口语化、短句、少用形容词堆砌,别用"赋能/闭环/抓手"这类词。',
|
||||
].join('\n'),
|
||||
builtin: true,
|
||||
},
|
||||
{
|
||||
id: 'a_analyst',
|
||||
name: '数据分析',
|
||||
avatar: 'analyst',
|
||||
tagline: '算数、看数据、讲结论',
|
||||
systemPrompt: [
|
||||
'你是数据分析师。',
|
||||
'1. 任何计算都必须调用 calc 工具,不要心算。',
|
||||
'2. 先给结论,再给口径和数据来源。',
|
||||
'3. 样本不足或数据可疑时直接说出来。',
|
||||
].join('\n'),
|
||||
builtin: true,
|
||||
},
|
||||
];
|
||||
|
||||
function rid() {
|
||||
return `a_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 6)}`;
|
||||
}
|
||||
|
||||
function write(state) {
|
||||
fs.writeFileSync(FILE, JSON.stringify(state, null, 2), 'utf8');
|
||||
}
|
||||
|
||||
export function listAgents() {
|
||||
if (!fs.existsSync(FILE)) {
|
||||
const state = { agents: DEFAULT_AGENTS };
|
||||
write(state);
|
||||
return state.agents;
|
||||
}
|
||||
try {
|
||||
const json = JSON.parse(fs.readFileSync(FILE, 'utf8'));
|
||||
if (!Array.isArray(json.agents) || json.agents.length === 0) throw new Error('空');
|
||||
return json.agents;
|
||||
} catch (err) {
|
||||
console.error('[agents] agents.json 损坏,重建内置智能体:', err.message);
|
||||
const state = { agents: DEFAULT_AGENTS };
|
||||
write(state);
|
||||
return state.agents;
|
||||
}
|
||||
}
|
||||
|
||||
export function getAgent(id) {
|
||||
if (!id) return null;
|
||||
return listAgents().find((a) => a.id === id) || null;
|
||||
}
|
||||
|
||||
export function createAgent({ name, avatar, tagline, systemPrompt }) {
|
||||
const state = { agents: listAgents() };
|
||||
const agent = {
|
||||
id: rid(),
|
||||
name: String(name || '新智能体').slice(0, 24),
|
||||
avatar: avatar || 'custom',
|
||||
tagline: String(tagline || '').slice(0, 40),
|
||||
systemPrompt: String(systemPrompt || ''),
|
||||
builtin: false,
|
||||
createdAt: new Date().toISOString(),
|
||||
};
|
||||
state.agents.push(agent);
|
||||
write(state);
|
||||
return agent;
|
||||
}
|
||||
|
||||
export function updateAgent(id, patch) {
|
||||
const state = { agents: listAgents() };
|
||||
const agent = state.agents.find((a) => a.id === id);
|
||||
if (!agent) return null;
|
||||
for (const key of ['name', 'avatar', 'tagline', 'systemPrompt']) {
|
||||
if (patch[key] !== undefined) agent[key] = patch[key];
|
||||
}
|
||||
write(state);
|
||||
return agent;
|
||||
}
|
||||
|
||||
export function deleteAgent(id) {
|
||||
const state = { agents: listAgents() };
|
||||
const index = state.agents.findIndex((a) => a.id === id);
|
||||
if (index < 0) return false;
|
||||
state.agents.splice(index, 1);
|
||||
write(state);
|
||||
return true;
|
||||
}
|
||||
|
||||
/** 可选头像(前端有同名 SVG,这里只做白名单校验) */
|
||||
export const AVATAR_KEYS = ['doubao', 'coder', 'writer', 'analyst', 'cat', 'robot', 'star', 'cloud', 'custom'];
|
||||
385
server/src/config.mjs
Normal file
385
server/src/config.mjs
Normal file
@@ -0,0 +1,385 @@
|
||||
/**
|
||||
* 配置与环境:项目路径、.env 解析、settings.json 读写、提供商预设。
|
||||
*/
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
export const SERVER_DIR = path.resolve(__dirname, '..');
|
||||
|
||||
/**
|
||||
* 资源根目录:
|
||||
* - 直接跑源码时 = 仓库根目录
|
||||
* - 打包成桌面程序后,Electron 主进程用 DOUBAO_RESOURCES 指向解包出来的资源目录
|
||||
*/
|
||||
export const ROOT = process.env.DOUBAO_RESOURCES
|
||||
? path.resolve(process.env.DOUBAO_RESOURCES)
|
||||
: path.resolve(SERVER_DIR, '..');
|
||||
|
||||
export const APP_DIR = path.join(ROOT, 'app');
|
||||
export const DIST_DIR = path.join(APP_DIR, 'dist');
|
||||
|
||||
export const TOOLS_DIR = process.env.DOUBAO_TOOLS
|
||||
? path.resolve(process.env.DOUBAO_TOOLS)
|
||||
: path.join(ROOT, 'tools');
|
||||
|
||||
/**
|
||||
* 可写数据目录:装到 Program Files 之后安装目录不可写,
|
||||
* 所以打包运行时主进程会把 DOUBAO_DATA 指到 %APPDATA%。
|
||||
*/
|
||||
export const DATA_DIR = process.env.DOUBAO_DATA
|
||||
? path.resolve(process.env.DOUBAO_DATA)
|
||||
: path.join(SERVER_DIR, 'data');
|
||||
export const TMP_DIR = path.join(DATA_DIR, 'tmp');
|
||||
|
||||
/** 设置文件:打包运行时放数据目录,开发时留在 server/config */
|
||||
export const CONFIG_FILE = process.env.DOUBAO_DATA
|
||||
? path.join(DATA_DIR, 'settings.json')
|
||||
: path.join(SERVER_DIR, 'config', 'settings.json');
|
||||
export const CONFIG_EXAMPLE = path.join(SERVER_DIR, 'config', 'settings.example.json');
|
||||
|
||||
/**
|
||||
* MCP 配置:打包运行时把它复制一份到数据目录,
|
||||
* 这样用户改的是自己可写的那份,升级程序不会覆盖。
|
||||
*/
|
||||
const bundledMcpFile = path.join(TOOLS_DIR, 'mcp.servers.json');
|
||||
const userMcpFile = path.join(DATA_DIR, 'mcp.servers.json');
|
||||
if (process.env.DOUBAO_DATA) {
|
||||
try {
|
||||
// 必须先保证数据目录存在,否则首次运行复制会 ENOENT
|
||||
fs.mkdirSync(DATA_DIR, { recursive: true });
|
||||
if (!fs.existsSync(userMcpFile) && fs.existsSync(bundledMcpFile)) {
|
||||
fs.copyFileSync(bundledMcpFile, userMcpFile);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(`[config] 初始化 mcp.servers.json 失败:${err.message}`);
|
||||
}
|
||||
}
|
||||
export const MCP_FILE = process.env.DOUBAO_DATA && fs.existsSync(userMcpFile) ? userMcpFile : bundledMcpFile;
|
||||
|
||||
export const WEB_INDEX = path.join(ROOT, 'web', 'index.html');
|
||||
|
||||
/**
|
||||
* @lynx-js/web-core 的预构建运行时:
|
||||
* 开发时在 app/node_modules,打包后被复制到 resources/web-core。
|
||||
*/
|
||||
export const WEB_CORE_STATIC = (() => {
|
||||
const candidates = [
|
||||
process.env.DOUBAO_WEB_CORE ? path.resolve(process.env.DOUBAO_WEB_CORE) : null,
|
||||
path.join(ROOT, 'web-core'),
|
||||
path.join(APP_DIR, 'node_modules', '@lynx-js', 'web-core', 'dist', 'client_prod', 'static'),
|
||||
].filter(Boolean);
|
||||
return candidates.find((dir) => fs.existsSync(dir)) || candidates[candidates.length - 1];
|
||||
})();
|
||||
|
||||
for (const dir of [DATA_DIR, TMP_DIR, path.dirname(CONFIG_FILE)]) {
|
||||
try {
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
} catch (err) {
|
||||
console.error(`[config] 无法创建目录 ${dir}:${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
/** 极简 .env 解析(server/.env) */
|
||||
function loadDotEnv() {
|
||||
const file = path.join(SERVER_DIR, '.env');
|
||||
if (!fs.existsSync(file)) return;
|
||||
for (const raw of fs.readFileSync(file, 'utf8').split(/\r?\n/)) {
|
||||
const line = raw.trim();
|
||||
if (!line || line.startsWith('#')) continue;
|
||||
const eq = line.indexOf('=');
|
||||
if (eq < 0) continue;
|
||||
const key = line.slice(0, eq).trim();
|
||||
let value = line.slice(eq + 1).trim();
|
||||
if (
|
||||
(value.startsWith('"') && value.endsWith('"')) ||
|
||||
(value.startsWith("'") && value.endsWith("'"))
|
||||
) {
|
||||
value = value.slice(1, -1);
|
||||
}
|
||||
if (!(key in process.env)) process.env[key] = value;
|
||||
}
|
||||
}
|
||||
loadDotEnv();
|
||||
|
||||
/**
|
||||
* 提供商预设。
|
||||
*
|
||||
* 全都是 **OpenAI 兼容协议**(`POST {baseUrl}/chat/completions`),区别只有
|
||||
* baseUrl、模型名、以及"思考强度怎么传"。
|
||||
*
|
||||
* `thinkingMode` 就是在说这件事,别写死成"非 ark 即 openai":
|
||||
* - 'ark' → 顶层 `thinking: {type: enabled|disabled}`(火山方舟、智谱 GLM 都是这个形状)
|
||||
* - 'effort' → `reasoning_effort: low|medium|high`(OpenAI 推理模型、OpenRouter 透传)
|
||||
* - 'none' → 什么都不发。★ 这是安全默认值:
|
||||
* 给不认识 reasoning_effort 的服务发这个字段,有些会直接 400。
|
||||
* DeepSeek / Kimi / 通义 / 硅基流动 的思考是模型自己决定的,不需要参数。
|
||||
*/
|
||||
export const PROVIDER_PRESETS = {
|
||||
ark: {
|
||||
label: '火山方舟(豆包)',
|
||||
baseUrl: 'https://ark.cn-beijing.volces.com/api/v3',
|
||||
apiKeyEnv: 'ARK_API_KEY',
|
||||
defaultModel: 'doubao-seed-2-1-pro-260628',
|
||||
modelHint: '填模型 ID(如 doubao-seed-2-1-pro-260628)或推理接入点 ID(ep-xxxxxxxx)',
|
||||
docs: 'https://www.volcengine.com/docs/82379/1298454',
|
||||
thinkingMode: 'ark',
|
||||
// 来源:volcengine/veadk-python 官方 SDK 常量与文档示例
|
||||
models: [
|
||||
'doubao-seed-2-1-pro-260628',
|
||||
'doubao-seed-1-8-251228',
|
||||
'deepseek-r1-250528',
|
||||
],
|
||||
},
|
||||
openai: {
|
||||
label: 'OpenAI 官方',
|
||||
baseUrl: 'https://api.openai.com/v1',
|
||||
apiKeyEnv: 'OPENAI_API_KEY',
|
||||
defaultModel: 'gpt-4o-mini',
|
||||
modelHint: '填 model 名称;推理模型(o 系 / gpt-5 系)会自动剥离 temperature 等参数',
|
||||
docs: 'https://platform.openai.com/docs/api-reference/chat',
|
||||
thinkingMode: 'effort',
|
||||
models: ['gpt-4o-mini', 'gpt-4o', 'gpt-4.1-mini', 'gpt-5-mini'],
|
||||
},
|
||||
deepseek: {
|
||||
label: 'DeepSeek',
|
||||
baseUrl: 'https://api.deepseek.com/v1',
|
||||
apiKeyEnv: 'DEEPSEEK_API_KEY',
|
||||
defaultModel: 'deepseek-chat',
|
||||
modelHint: 'deepseek-chat 是通用对话;deepseek-reasoner 会自动返回思维链',
|
||||
docs: 'https://api-docs.deepseek.com/zh-cn/',
|
||||
thinkingMode: 'none',
|
||||
models: ['deepseek-chat', 'deepseek-reasoner'],
|
||||
},
|
||||
kimi: {
|
||||
label: 'Kimi(月之暗面)',
|
||||
baseUrl: 'https://api.moonshot.cn/v1',
|
||||
apiKeyEnv: 'MOONSHOT_API_KEY',
|
||||
defaultModel: 'kimi-k2-0905-preview',
|
||||
modelHint: 'Kimi K2 支持工具调用;moonshot-v1-* 是上一代长文本模型',
|
||||
docs: 'https://platform.moonshot.cn/docs/api/chat',
|
||||
thinkingMode: 'none',
|
||||
models: ['kimi-k2-0905-preview', 'kimi-latest', 'moonshot-v1-128k'],
|
||||
},
|
||||
zhipu: {
|
||||
label: '智谱 GLM',
|
||||
baseUrl: 'https://open.bigmodel.cn/api/paas/v4',
|
||||
apiKeyEnv: 'ZHIPU_API_KEY',
|
||||
defaultModel: 'glm-4.6',
|
||||
modelHint: 'GLM 的思考开关和方舟同形状(顶层 thinking),已按这个发',
|
||||
docs: 'https://docs.bigmodel.cn/cn/guide/develop/openai/introduction',
|
||||
thinkingMode: 'ark',
|
||||
models: ['glm-4.6', 'glm-4.5', 'glm-4-flash'],
|
||||
},
|
||||
dashscope: {
|
||||
label: '通义千问(阿里云)',
|
||||
baseUrl: 'https://dashscope.aliyuncs.com/compatible-mode/v1',
|
||||
apiKeyEnv: 'DASHSCOPE_API_KEY',
|
||||
defaultModel: 'qwen-plus',
|
||||
modelHint: 'Qwen3 系列自己会思考,这里不发思考参数',
|
||||
docs: 'https://help.aliyun.com/zh/model-studio/compatibility-of-openai-with-dashscope',
|
||||
thinkingMode: 'none',
|
||||
models: ['qwen3-max', 'qwen-plus', 'qwen-turbo'],
|
||||
},
|
||||
siliconflow: {
|
||||
label: '硅基流动',
|
||||
baseUrl: 'https://api.siliconflow.cn/v1',
|
||||
apiKeyEnv: 'SILICONFLOW_API_KEY',
|
||||
defaultModel: 'deepseek-ai/DeepSeek-V3',
|
||||
modelHint: '模型名带斜杠(组织/模型),例如 deepseek-ai/DeepSeek-V3',
|
||||
docs: 'https://docs.siliconflow.cn/cn/api-reference/chat-completions/chat-completions',
|
||||
thinkingMode: 'none',
|
||||
models: ['deepseek-ai/DeepSeek-V3', 'Qwen/Qwen3-235B-A22B', 'THUDM/glm-4-9b-chat'],
|
||||
},
|
||||
openrouter: {
|
||||
label: 'OpenRouter(聚合)',
|
||||
baseUrl: 'https://openrouter.ai/api/v1',
|
||||
apiKeyEnv: 'OPENROUTER_API_KEY',
|
||||
defaultModel: 'openai/gpt-4o-mini',
|
||||
modelHint: '一个 Key 调各家模型,模型名是「厂商/模型」;会透传 reasoning_effort',
|
||||
docs: 'https://openrouter.ai/docs/api-reference/overview',
|
||||
thinkingMode: 'effort',
|
||||
models: ['openai/gpt-4o-mini', 'deepseek/deepseek-chat', 'anthropic/claude-3.5-sonnet'],
|
||||
},
|
||||
ollama: {
|
||||
label: '本地 Ollama',
|
||||
baseUrl: 'http://127.0.0.1:11434/v1',
|
||||
apiKeyEnv: 'OLLAMA_API_KEY',
|
||||
defaultModel: 'qwen2.5:7b',
|
||||
modelHint: '本地跑,Key 随便填(Ollama 不校验)。手机连电脑要填电脑的局域网 IP',
|
||||
docs: 'https://github.com/ollama/ollama/blob/main/docs/openai.md',
|
||||
thinkingMode: 'none',
|
||||
models: ['qwen2.5:7b', 'llama3.1:8b', 'deepseek-r1:7b'],
|
||||
},
|
||||
custom: {
|
||||
label: '自定义(任意兼容网关)',
|
||||
baseUrl: '',
|
||||
apiKeyEnv: 'CUSTOM_API_KEY',
|
||||
defaultModel: '',
|
||||
modelHint: '填完整的 /v1 地址和模型名,只要兼容 OpenAI 的 chat/completions 就能用',
|
||||
docs: '',
|
||||
thinkingMode: 'none',
|
||||
models: [],
|
||||
},
|
||||
};
|
||||
|
||||
export const DEFAULT_SYSTEM_PROMPT = [
|
||||
'你是豆包,一个由字节跳动开发的 AI 助手,风格自然、亲切、简洁。',
|
||||
'',
|
||||
'回答要求:',
|
||||
'1. 用简体中文回答,除非用户要求其他语言。',
|
||||
'2. 先给结论,再给必要的解释,避免空话和过度铺垫。',
|
||||
'3. 需要计算、查时间、读写本地笔记或抓取网页时,主动调用可用工具,不要凭记忆编造。',
|
||||
'4. 工具返回的内容可能不完整,若失败要如实说明失败原因。',
|
||||
'5. 不确定的信息要明确标注不确定。',
|
||||
].join('\n');
|
||||
|
||||
export const DEFAULT_SETTINGS = {
|
||||
provider: 'ark',
|
||||
baseUrl: PROVIDER_PRESETS.ark.baseUrl,
|
||||
model: PROVIDER_PRESETS.ark.defaultModel,
|
||||
apiKey: '',
|
||||
temperature: 0.7,
|
||||
maxRounds: 6,
|
||||
/**
|
||||
* 思考强度:off / low / medium / high / auto
|
||||
* - 方舟:映射到顶层 thinking 字段
|
||||
* - OpenAI:映射到 reasoning_effort(推理模型)
|
||||
*/
|
||||
thinkingLevel: 'auto',
|
||||
/** 额外工具目录(留空则用内置 tools/);安卓端可以指到手机上的目录 */
|
||||
toolsDir: '',
|
||||
systemPrompt: DEFAULT_SYSTEM_PROMPT,
|
||||
tools: { python: true, mcp: true },
|
||||
/**
|
||||
* 安全模式:
|
||||
* open 完全开放 —— 所有工具都交给模型自由调用
|
||||
* restricted 限制模式 —— 只有 allow 里授权的工具可用
|
||||
*/
|
||||
security: { mode: 'open', allow: [] },
|
||||
// 语音(朗读 / 语音输入)。引擎默认 'system' = 用设备自带的,不联网、不要 Key;
|
||||
// 想用云端音色(火山豆包音色 / OpenAI)就把 ttsEngine 改成 'volc' 或 'openai'。
|
||||
speech: {
|
||||
ttsEngine: 'system', // system | volc | openai
|
||||
ttsVoice: '', // volc: voice_type;openai: alloy/nova/...
|
||||
ttsSpeed: 1.0,
|
||||
autoRead: false, // 新回复自动念出来
|
||||
sttEngine: 'system', // system | openai
|
||||
sttModel: 'whisper-1',
|
||||
sttLanguage: '', // 留空 = 自动判断
|
||||
volcAppId: '',
|
||||
volcToken: '',
|
||||
volcCluster: 'volcano_tts',
|
||||
volcEncoding: 'mp3',
|
||||
openaiApiKey: '', // 留空则复用主对话的 Key
|
||||
openaiBaseUrl: '', // 留空则复用主对话的 Base URL
|
||||
ttsModel: 'tts-1',
|
||||
},
|
||||
pythonBin: '',
|
||||
nickname: '我',
|
||||
doubaoId: '378269252',
|
||||
activeAgentId: 'a_doubao',
|
||||
};
|
||||
|
||||
const SECRET_KEYS = new Set(['apiKey']);
|
||||
|
||||
export function maskSettings(settings) {
|
||||
const out = { ...settings, apiKey: settings.apiKey ? '••••••••' : '' };
|
||||
out.hasApiKey = Boolean(settings.apiKey);
|
||||
// 语音里的两个密钥同样只回掩码
|
||||
const speech = { ...(out.speech || {}) };
|
||||
speech.volcToken = speech.volcToken ? '••••••••' : '';
|
||||
speech.openaiApiKey = speech.openaiApiKey ? '••••••••' : '';
|
||||
out.speech = speech;
|
||||
return out;
|
||||
}
|
||||
|
||||
export function readSettings() {
|
||||
let stored = {};
|
||||
if (fs.existsSync(CONFIG_FILE)) {
|
||||
try {
|
||||
stored = JSON.parse(fs.readFileSync(CONFIG_FILE, 'utf8'));
|
||||
} catch (err) {
|
||||
console.error('[config] settings.json 解析失败,使用默认值:', err.message);
|
||||
}
|
||||
}
|
||||
const settings = { ...DEFAULT_SETTINGS, ...stored };
|
||||
// ★ 子对象必须是对象:曾经前端把嵌套 Map 序列化成了字符串存进来,
|
||||
// 之后每次读配置都会炸,/api/state 一直 500 —— 一个坏字段把整个 App 弄成空白。
|
||||
// 所以这里发现不是对象就回落默认值(自愈),而不是让整个接口挂掉。
|
||||
for (const key of ['tools', 'security', 'speech']) {
|
||||
const raw = stored[key];
|
||||
if (raw !== undefined && (typeof raw !== 'object' || raw === null || Array.isArray(raw))) {
|
||||
console.error(`[config] settings.json 里的 ${key} 不是对象,已回落默认值`);
|
||||
}
|
||||
settings[key] = {
|
||||
...(DEFAULT_SETTINGS[key] || {}),
|
||||
...(raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {}),
|
||||
};
|
||||
}
|
||||
if (!Array.isArray(settings.security.allow)) settings.security.allow = [];
|
||||
|
||||
// 环境变量兜底:没填 key 时用 .env 里的
|
||||
const preset = PROVIDER_PRESETS[settings.provider];
|
||||
if (!settings.apiKey && preset?.apiKeyEnv) {
|
||||
settings.apiKey = process.env[preset.apiKeyEnv] || '';
|
||||
}
|
||||
return settings;
|
||||
}
|
||||
|
||||
export function writeSettings(patch) {
|
||||
// ★ 保险:空的关键字段一律当"没填",不许用它覆盖已有配置。
|
||||
// 这些字段在正常使用中永远不该是空串(空 = 前端草稿没初始化好),
|
||||
// 前端曾经因为草稿没同步好就全量下发,一次保存把整份配置清空。
|
||||
// systemPrompt / toolsDir 故意不在此列:它们"留空"是合理需求,用户可能真想清掉。
|
||||
const clean = { ...patch };
|
||||
for (const key of ['baseUrl', 'model', 'apiKey', 'nickname', 'provider', 'thinkingLevel']) {
|
||||
if (typeof clean[key] === 'string' && clean[key].trim() === '') delete clean[key];
|
||||
}
|
||||
const current = readSettings();
|
||||
const next = { ...current, ...clean };
|
||||
// 子对象深合并:整体替换会把没提到的开关抹掉。
|
||||
// ★ 不是对象的直接丢掉:上游要是把嵌套对象发成了字符串(JSON 序列化踩坑),
|
||||
// 让它覆盖进去就会写出一个读不回来的配置 —— 宁可这次改动不生效。
|
||||
for (const key of ['tools', 'security', 'speech']) {
|
||||
if (!(key in clean)) continue;
|
||||
const v = clean[key];
|
||||
if (v && typeof v === 'object' && !Array.isArray(v)) {
|
||||
next[key] = { ...(current[key] || {}), ...v };
|
||||
} else {
|
||||
next[key] = current[key] || {};
|
||||
console.error(`[config] 补丁里的 ${key} 不是对象(${typeof v}),已忽略`);
|
||||
}
|
||||
}
|
||||
// 掩码值表示"不修改"
|
||||
if (clean.apiKey === '••••••••') next.apiKey = current.apiKey;
|
||||
// ★ 语音里的密钥同理:界面读到的是掩码,用户不改语音设置直接保存时掩码会跟着回来,
|
||||
// 不拦的话真 Token 就被这八个点覆盖了。
|
||||
if (next.speech) {
|
||||
for (const secret of ['volcToken', 'openaiApiKey']) {
|
||||
if (next.speech[secret] === '••••••••') next.speech[secret] = current.speech?.[secret] || '';
|
||||
}
|
||||
// ★ 语音里"空字符串就等于坏掉"的字段同样不许被空值覆盖:
|
||||
// 引擎名一空,界面上一张卡片都不高亮(看着就是"设置被清空了")。
|
||||
// ttsVoice / volcAppId / sttLanguage 不在此列 —— 它们留空是合理需求。
|
||||
for (const key of ['ttsEngine', 'sttEngine', 'sttModel', 'ttsModel', 'volcCluster', 'volcEncoding']) {
|
||||
const v = next.speech[key];
|
||||
if (typeof v === 'string' && v.trim() === '') {
|
||||
next.speech[key] = current.speech?.[key] || DEFAULT_SETTINGS.speech[key] || '';
|
||||
}
|
||||
}
|
||||
}
|
||||
const persisted = { ...next, hasApiKey: undefined };
|
||||
delete persisted.hasApiKey;
|
||||
fs.writeFileSync(CONFIG_FILE, JSON.stringify(persisted, null, 2), 'utf8');
|
||||
return next;
|
||||
}
|
||||
|
||||
export function providerInfo(settings) {
|
||||
const preset = PROVIDER_PRESETS[settings.provider] || PROVIDER_PRESETS.ark;
|
||||
return { ...preset, baseUrl: settings.baseUrl || preset.baseUrl, model: settings.model || preset.defaultModel };
|
||||
}
|
||||
|
||||
export { SECRET_KEYS };
|
||||
798
server/src/index.mjs
Normal file
798
server/src/index.mjs
Normal 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);
|
||||
});
|
||||
}
|
||||
260
server/src/mcp.mjs
Normal file
260
server/src/mcp.mjs
Normal file
@@ -0,0 +1,260 @@
|
||||
/**
|
||||
* MCP(Model Context Protocol)客户端管理。
|
||||
*
|
||||
* tools/mcp.servers.json 描述要连接的服务:
|
||||
* stdio: { "transport": "stdio", "command": "npx", "args": [...] }
|
||||
* http : { "transport": "http", "url": "https://.../mcp", "headers": {...} }
|
||||
* sse : { "transport": "sse", "url": "https://.../sse" }
|
||||
*
|
||||
* 对外暴露的工具名统一为 mcp__<server>__<tool>,避免和 Python 工具重名。
|
||||
*/
|
||||
import fs from 'node:fs';
|
||||
import { MCP_FILE } from './config.mjs';
|
||||
|
||||
const clients = new Map(); // serverName -> { client, transport, tools, error, spec }
|
||||
|
||||
export function readMcpConfig() {
|
||||
if (!fs.existsSync(MCP_FILE)) return { servers: [] };
|
||||
try {
|
||||
const json = JSON.parse(fs.readFileSync(MCP_FILE, 'utf8'));
|
||||
const servers = Array.isArray(json) ? json : json.servers || [];
|
||||
// 支持 ${VAR} 占位符:打包后路径随机器变,写死绝对路径不合适
|
||||
return { servers: servers.map(expandServer) };
|
||||
} catch (err) {
|
||||
console.error('[mcp] mcp.servers.json 解析失败:', err.message);
|
||||
return { servers: [], error: err.message };
|
||||
}
|
||||
}
|
||||
|
||||
function expand(value) {
|
||||
if (typeof value !== 'string') return value;
|
||||
return value.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g, (match, name) => process.env[name] ?? match);
|
||||
}
|
||||
|
||||
function expandServer(server) {
|
||||
return {
|
||||
...server,
|
||||
command: expand(server.command),
|
||||
args: (server.args || []).map(expand),
|
||||
url: expand(server.url),
|
||||
env: Object.fromEntries(Object.entries(server.env || {}).map(([k, v]) => [k, expand(v)])),
|
||||
headers: Object.fromEntries(Object.entries(server.headers || {}).map(([k, v]) => [k, expand(v)])),
|
||||
};
|
||||
}
|
||||
|
||||
export function writeMcpConfig(config) {
|
||||
fs.writeFileSync(MCP_FILE, JSON.stringify(config, null, 2), 'utf8');
|
||||
}
|
||||
|
||||
/** 配置文件路径(界面上要显示给用户看) */
|
||||
export function mcpConfigPath() {
|
||||
return MCP_FILE;
|
||||
}
|
||||
|
||||
/** 配置文件原文(供界面里直接编辑) */
|
||||
export function readMcpConfigText() {
|
||||
if (!fs.existsSync(MCP_FILE)) return '{\n "servers": []\n}\n';
|
||||
return fs.readFileSync(MCP_FILE, 'utf8');
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存界面里编辑的 JSON 文本。
|
||||
* 先校验再落盘,避免把坏 JSON 写进去导致下次起不来。
|
||||
*/
|
||||
export function writeMcpConfigText(text) {
|
||||
let parsed;
|
||||
try {
|
||||
parsed = JSON.parse(text);
|
||||
} catch (err) {
|
||||
throw new Error(`JSON 格式错误:${err.message}`);
|
||||
}
|
||||
const servers = Array.isArray(parsed) ? parsed : parsed.servers;
|
||||
if (!Array.isArray(servers)) throw new Error('顶层必须是 { "servers": [ ... ] } 或一个数组');
|
||||
for (const [i, server] of servers.entries()) {
|
||||
if (!server || typeof server !== 'object') throw new Error(`第 ${i + 1} 项不是对象`);
|
||||
if (!server.name) throw new Error(`第 ${i + 1} 项缺少 name`);
|
||||
const transport = server.transport || 'stdio';
|
||||
if (!['stdio', 'http', 'sse', 'inproc'].includes(transport)) {
|
||||
throw new Error(`${server.name}: transport 只能是 stdio / http / sse / inproc`);
|
||||
}
|
||||
// inproc:安卓端内核直接 import 这个 py 文件;桌面上等价于用 python 起子进程
|
||||
if (transport === 'inproc' && !server.path) throw new Error(`${server.name}: inproc 需要 path(py 文件路径)`);
|
||||
if (transport === 'stdio' && !server.command) throw new Error(`${server.name}: stdio 需要 command`);
|
||||
if ((transport === 'http' || transport === 'sse') && !server.url) throw new Error(`${server.name}: ${transport} 需要 url`);
|
||||
}
|
||||
writeMcpConfig(Array.isArray(parsed) ? { servers } : parsed);
|
||||
return servers.length;
|
||||
}
|
||||
|
||||
/** 断开全部连接(改完配置要重连) */
|
||||
export async function disconnectAll() {
|
||||
for (const name of [...clients.keys()]) {
|
||||
await disconnect(name);
|
||||
}
|
||||
}
|
||||
|
||||
async function loadSdk() {
|
||||
const [clientMod, stdioMod, httpMod, sseMod] = await Promise.all([
|
||||
import('@modelcontextprotocol/sdk/client/index.js'),
|
||||
import('@modelcontextprotocol/sdk/client/stdio.js'),
|
||||
import('@modelcontextprotocol/sdk/client/streamableHttp.js'),
|
||||
import('@modelcontextprotocol/sdk/client/sse.js'),
|
||||
]);
|
||||
return {
|
||||
Client: clientMod.Client,
|
||||
StdioClientTransport: stdioMod.StdioClientTransport,
|
||||
StreamableHTTPClientTransport: httpMod.StreamableHTTPClientTransport,
|
||||
SSEClientTransport: sseMod.SSEClientTransport,
|
||||
};
|
||||
}
|
||||
|
||||
export async function connect(serverName, { force = false } = {}) {
|
||||
const existing = clients.get(serverName);
|
||||
if (existing?.client && !force) return existing;
|
||||
if (existing?.client && force) await disconnect(serverName);
|
||||
|
||||
const spec = readMcpConfig().servers.find((s) => s.name === serverName);
|
||||
if (!spec) throw new Error(`mcp.servers.json 里没有服务器 ${serverName}`);
|
||||
if (spec.enabled === false) throw new Error(`服务器 ${serverName} 已被禁用`);
|
||||
|
||||
const record = { spec, client: null, transport: null, tools: [], error: null };
|
||||
clients.set(serverName, record);
|
||||
|
||||
try {
|
||||
const sdk = await loadSdk();
|
||||
let transport;
|
||||
// inproc 在桌面/服务器上退化成"用 python 起这个脚本",行为和 stdio 一样
|
||||
const isStdioLike = (spec.transport || 'stdio') === 'stdio' || spec.transport === 'inproc';
|
||||
if (isStdioLike) {
|
||||
const command = spec.transport === 'inproc' ? (spec.python || process.env.PYTHON || 'python') : spec.command;
|
||||
const rawArgs = spec.transport === 'inproc' ? [spec.path, ...(spec.args || [])] : spec.args || [];
|
||||
// Windows 下 npx / npm 是 .cmd,必须用 cmd /c 包一层(官方 README 明确要求)
|
||||
const isWin = process.platform === 'win32';
|
||||
const needsShellWrap = isWin && /^(npx|npm|node|pnpm|yarn)$/i.test(command || '');
|
||||
transport = new sdk.StdioClientTransport({
|
||||
command: needsShellWrap ? 'cmd' : command,
|
||||
args: needsShellWrap ? ['/c', command, ...rawArgs] : rawArgs,
|
||||
env: { ...process.env, ...(spec.env || {}) },
|
||||
// inherit:子进程日志进内核的 stderr,既能诊断又不会把管道塞满
|
||||
stderr: 'inherit',
|
||||
});
|
||||
} else if (spec.transport === 'sse') {
|
||||
transport = new sdk.SSEClientTransport(new URL(spec.url), {
|
||||
requestInit: { headers: spec.headers || {} },
|
||||
});
|
||||
} else {
|
||||
transport = new sdk.StreamableHTTPClientTransport(new URL(spec.url), {
|
||||
requestInit: { headers: spec.headers || {} },
|
||||
});
|
||||
}
|
||||
const client = new sdk.Client({ name: 'doubao-kernel', version: '0.1.0' }, { capabilities: {} });
|
||||
// 首次用 npx 拉起服务器时要下载包,可能远超 SDK 默认的 60s 超时
|
||||
await client.connect(transport, { timeout: 180000 });
|
||||
const listed = await client.listTools(undefined, { timeout: 60000 });
|
||||
record.client = client;
|
||||
record.transport = transport;
|
||||
record.tools = listed.tools || [];
|
||||
record.error = null;
|
||||
console.log(`[mcp] ${serverName} 已连接,${record.tools.length} 个工具`);
|
||||
} catch (err) {
|
||||
record.error = err?.message || String(err);
|
||||
console.error(`[mcp] ${serverName} 连接失败:${record.error}`);
|
||||
}
|
||||
return record;
|
||||
}
|
||||
|
||||
export async function disconnect(serverName) {
|
||||
const record = clients.get(serverName);
|
||||
if (!record) return;
|
||||
try {
|
||||
await record.client?.close();
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
clients.delete(serverName);
|
||||
}
|
||||
|
||||
export async function connectAllEnabled() {
|
||||
const { servers } = readMcpConfig();
|
||||
const results = [];
|
||||
for (const spec of servers) {
|
||||
if (spec.enabled === false) continue;
|
||||
try {
|
||||
const record = await connect(spec.name);
|
||||
results.push({ name: spec.name, ok: !record.error, error: record.error, toolCount: record.tools.length });
|
||||
} catch (err) {
|
||||
results.push({ name: spec.name, ok: false, error: err.message });
|
||||
}
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
export async function getMcpState() {
|
||||
const { servers } = readMcpConfig();
|
||||
return servers.map((spec) => {
|
||||
const record = clients.get(spec.name);
|
||||
return {
|
||||
name: spec.name,
|
||||
enabled: spec.enabled !== false,
|
||||
transport: spec.transport || 'stdio',
|
||||
target: spec.transport === 'stdio' ? `${spec.command} ${(spec.args || []).join(' ')}`.trim() : spec.url,
|
||||
connected: Boolean(record?.client),
|
||||
error: record?.error || null,
|
||||
tools: (record?.tools || []).map((t) => ({
|
||||
name: t.name,
|
||||
description: t.description || '',
|
||||
})),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* MCP 的 inputSchema 不能直接当 OpenAI 的 parameters 用:
|
||||
* 必须去掉 $schema、保证 type=object、补 properties/required,
|
||||
* 并且 outputSchema 绝不能混进来(OpenAI 会直接拒)。
|
||||
*/
|
||||
export function sanitizeSchema(schema) {
|
||||
const src = schema && typeof schema === 'object' ? schema : {};
|
||||
const out = { ...src };
|
||||
delete out.$schema;
|
||||
delete out.outputSchema;
|
||||
if (out.type !== 'object') out.type = 'object';
|
||||
if (!out.properties || typeof out.properties !== 'object') out.properties = {};
|
||||
if (!Array.isArray(out.required)) {
|
||||
out.required = Object.keys(out.properties).filter((k) => out.properties[k]?.required === true);
|
||||
}
|
||||
if (out.additionalProperties === undefined) out.additionalProperties = false;
|
||||
return out;
|
||||
}
|
||||
|
||||
/** 全部已连接 MCP 工具 → OpenAI tools 定义 */
|
||||
export function mcpToolDefs() {
|
||||
const defs = [];
|
||||
for (const [serverName, record] of clients.entries()) {
|
||||
if (!record.client) continue;
|
||||
for (const tool of record.tools) {
|
||||
defs.push({
|
||||
type: 'function',
|
||||
function: {
|
||||
name: `mcp__${serverName}__${tool.name}`,
|
||||
description: `[MCP:${serverName}] ${tool.description || tool.name}`,
|
||||
parameters: sanitizeSchema(tool.inputSchema),
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
return defs;
|
||||
}
|
||||
|
||||
export async function callMcpTool(fullName, args) {
|
||||
const [, serverName, ...rest] = fullName.split('__');
|
||||
const toolName = rest.join('__');
|
||||
const record = clients.get(serverName);
|
||||
if (!record?.client) throw new Error(`MCP 服务器 ${serverName} 未连接`);
|
||||
const res = await record.client.callTool({ name: toolName, arguments: args || {} });
|
||||
return res;
|
||||
}
|
||||
|
||||
export function isMcpTool(name) {
|
||||
return typeof name === 'string' && name.startsWith('mcp__');
|
||||
}
|
||||
236
server/src/providers.mjs
Normal file
236
server/src/providers.mjs
Normal file
@@ -0,0 +1,236 @@
|
||||
/**
|
||||
* 提供商调用层:火山方舟 / OpenAI / DeepSeek / Kimi / 智谱 / 通义 / 硅基流动 / OpenRouter …
|
||||
* 全都是 OpenAI 兼容协议,所以这里只有一份实现。
|
||||
* 统一暴露:
|
||||
* chatOnce() - 非流式
|
||||
* streamChat() - 流式(async generator,吐 text / tool_calls / usage)
|
||||
* listModels() - 拉取模型列表(可选能力,失败不致命)
|
||||
*/
|
||||
|
||||
import { PROVIDER_PRESETS } from './config.mjs';
|
||||
|
||||
function joinUrl(baseUrl, suffix) {
|
||||
return `${String(baseUrl || '').replace(/\/+$/, '')}${suffix}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 思考强度怎么传给服务端 —— 由预设里的 thinkingMode 决定。
|
||||
*
|
||||
* 别写死成"是 ark 就发 thinking、是 openai 就发 reasoning_effort":
|
||||
* 现在支持的兼容厂商有十来家,各自认的字段不一样,
|
||||
* 而**给不认这个字段的服务发过去,有些会直接 400**。所以认不出来的一律 'none'。
|
||||
*
|
||||
* 'ark' → 顶层 thinking: {type: enabled|disabled}
|
||||
* 'effort' → reasoning_effort: low|medium|high
|
||||
* 'none' → 什么都不发(DeepSeek / Kimi / 通义 / 硅基流动 等自己决定要不要思考)
|
||||
*/
|
||||
export function thinkingModeOf(provider) {
|
||||
return PROVIDER_PRESETS[provider]?.thinkingMode || 'none';
|
||||
}
|
||||
|
||||
function applyThinking({ provider, level, body }) {
|
||||
const value = level || 'auto';
|
||||
if (value === 'auto') return body;
|
||||
|
||||
const mode = thinkingModeOf(provider);
|
||||
if (mode === 'ark') {
|
||||
body.thinking = { type: value === 'off' ? 'disabled' : 'enabled' };
|
||||
return body;
|
||||
}
|
||||
if (mode === 'effort') {
|
||||
if (value === 'off') {
|
||||
delete body.reasoning_effort;
|
||||
} else {
|
||||
body.reasoning_effort = value === 'high' ? 'high' : value === 'low' ? 'low' : 'medium';
|
||||
}
|
||||
}
|
||||
return body;
|
||||
}
|
||||
|
||||
/**
|
||||
* 推理模型(o 系列 / gpt-5 系)不接受 temperature 等采样参数,
|
||||
* 而且"传默认值"也算传了,所以这里直接 delete,不是改回默认值。
|
||||
*/
|
||||
const REASONING_MODEL_RE = /^(o1|o3|o4|gpt-5|gpt-6)/i;
|
||||
|
||||
export function normalizeBody({ provider, model, thinkingLevel, body }) {
|
||||
if (thinkingModeOf(provider) === 'effort' && REASONING_MODEL_RE.test(String(model || ''))) {
|
||||
delete body.temperature;
|
||||
delete body.top_p;
|
||||
delete body.presence_penalty;
|
||||
delete body.frequency_penalty;
|
||||
delete body.logprobs;
|
||||
if (body.max_tokens != null) {
|
||||
body.max_completion_tokens = body.max_tokens;
|
||||
delete body.max_tokens;
|
||||
}
|
||||
// 推理模型默认就带思考,off 时明确要求最小
|
||||
if (thinkingLevel === 'off') body.reasoning_effort = 'minimal';
|
||||
}
|
||||
return applyThinking({ provider, level: thinkingLevel, body });
|
||||
}
|
||||
|
||||
function buildBody({ provider, model, messages, tools, temperature, stream, thinkingLevel }) {
|
||||
const body = {
|
||||
model,
|
||||
messages,
|
||||
stream: Boolean(stream),
|
||||
};
|
||||
if (typeof temperature === 'number' && Number.isFinite(temperature)) {
|
||||
body.temperature = temperature;
|
||||
}
|
||||
if (Array.isArray(tools) && tools.length > 0) {
|
||||
body.tools = tools;
|
||||
body.tool_choice = 'auto';
|
||||
}
|
||||
return normalizeBody({ provider, model, thinkingLevel, body });
|
||||
}
|
||||
|
||||
async function post({ baseUrl, apiKey, body, signal, timeoutMs = 180000 }) {
|
||||
if (!apiKey) {
|
||||
throw new Error('缺少 API Key:请在「设置 → AI 内核」里填写,或在 server/.env 里配置');
|
||||
}
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(() => controller.abort(new Error('上游请求超时')), timeoutMs);
|
||||
const onAbort = () => controller.abort(signal?.reason);
|
||||
signal?.addEventListener('abort', onAbort, { once: true });
|
||||
try {
|
||||
return await fetch(joinUrl(baseUrl, '/chat/completions'), {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${apiKey}`,
|
||||
},
|
||||
body: JSON.stringify(body),
|
||||
signal: controller.signal,
|
||||
});
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
signal?.removeEventListener('abort', onAbort);
|
||||
}
|
||||
}
|
||||
|
||||
export async function chatOnce(opts) {
|
||||
const res = await post({ ...opts, body: buildBody({ ...opts, stream: false }) });
|
||||
const text = await res.text();
|
||||
if (!res.ok) throw new Error(`上游 ${res.status}:${text.slice(0, 600)}`);
|
||||
let json;
|
||||
try {
|
||||
json = JSON.parse(text);
|
||||
} catch {
|
||||
throw new Error(`上游返回非 JSON:${text.slice(0, 300)}`);
|
||||
}
|
||||
const message = json.choices?.[0]?.message || {};
|
||||
return {
|
||||
content: message.content || '',
|
||||
reasoning: message.reasoning_content || '',
|
||||
toolCalls: (message.tool_calls || []).map((tc) => ({
|
||||
id: tc.id,
|
||||
name: tc.function?.name,
|
||||
argsRaw: tc.function?.arguments || '{}',
|
||||
args: safeParse(tc.function?.arguments),
|
||||
})),
|
||||
usage: json.usage,
|
||||
raw: json,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 流式调用。yield 出的事件:
|
||||
* {type:'text', text}
|
||||
* {type:'reasoning', text}
|
||||
* {type:'tool_calls', toolCalls}
|
||||
* {type:'usage', usage}
|
||||
* {type:'finish', reason}
|
||||
*/
|
||||
export async function* streamChat(opts) {
|
||||
const res = await post({ ...opts, body: buildBody({ ...opts, stream: true }) });
|
||||
if (!res.ok || !res.body) {
|
||||
const detail = await res.text().catch(() => '');
|
||||
throw new Error(`上游 ${res.status}:${detail.slice(0, 600)}`);
|
||||
}
|
||||
|
||||
const reader = res.body.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
const toolAcc = new Map();
|
||||
let buffer = '';
|
||||
let finishReason = null;
|
||||
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
buffer += decoder.decode(value, { stream: true });
|
||||
|
||||
let nl;
|
||||
while ((nl = buffer.indexOf('\n')) >= 0) {
|
||||
const line = buffer.slice(0, nl).trim();
|
||||
buffer = buffer.slice(nl + 1);
|
||||
if (!line || line.startsWith(':')) continue;
|
||||
if (!line.startsWith('data:')) continue;
|
||||
const payload = line.slice(5).trim();
|
||||
if (payload === '[DONE]') continue;
|
||||
let json;
|
||||
try {
|
||||
json = JSON.parse(payload);
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
const choice = json.choices?.[0];
|
||||
if (!choice) {
|
||||
if (json.usage) yield { type: 'usage', usage: json.usage };
|
||||
continue;
|
||||
}
|
||||
if (choice.finish_reason) finishReason = choice.finish_reason;
|
||||
const delta = choice.delta || {};
|
||||
if (typeof delta.reasoning_content === 'string' && delta.reasoning_content) {
|
||||
yield { type: 'reasoning', text: delta.reasoning_content };
|
||||
}
|
||||
if (typeof delta.content === 'string' && delta.content) {
|
||||
yield { type: 'text', text: delta.content };
|
||||
}
|
||||
for (const tc of delta.tool_calls || []) {
|
||||
const idx = tc.index ?? 0;
|
||||
const acc = toolAcc.get(idx) || { id: '', name: '', argsRaw: '' };
|
||||
if (tc.id) acc.id = tc.id;
|
||||
if (tc.function?.name) acc.name = tc.function.name;
|
||||
if (tc.function?.arguments) acc.argsRaw += tc.function.arguments;
|
||||
toolAcc.set(idx, acc);
|
||||
}
|
||||
if (json.usage) yield { type: 'usage', usage: json.usage };
|
||||
}
|
||||
}
|
||||
|
||||
const toolCalls = [...toolAcc.entries()]
|
||||
.sort((a, b) => a[0] - b[0])
|
||||
.map(([, v], i) => ({
|
||||
id: v.id || `call_${i}`,
|
||||
name: v.name,
|
||||
argsRaw: v.argsRaw || '{}',
|
||||
args: safeParse(v.argsRaw),
|
||||
}))
|
||||
.filter((tc) => tc.name);
|
||||
|
||||
if (toolCalls.length) yield { type: 'tool_calls', toolCalls };
|
||||
yield { type: 'finish', reason: finishReason };
|
||||
}
|
||||
|
||||
export async function listModels({ baseUrl, apiKey, signal }) {
|
||||
if (!apiKey) throw new Error('缺少 API Key');
|
||||
const res = await fetch(joinUrl(baseUrl, '/models'), {
|
||||
headers: { Authorization: `Bearer ${apiKey}` },
|
||||
signal,
|
||||
});
|
||||
if (!res.ok) throw new Error(`上游 ${res.status}`);
|
||||
const json = await res.json();
|
||||
return (json.data || []).map((m) => m.id).filter(Boolean);
|
||||
}
|
||||
|
||||
export function safeParse(raw) {
|
||||
if (raw == null) return {};
|
||||
if (typeof raw === 'object') return raw;
|
||||
try {
|
||||
return JSON.parse(raw);
|
||||
} catch {
|
||||
return { __raw: String(raw) };
|
||||
}
|
||||
}
|
||||
250
server/src/python-tools.mjs
Normal file
250
server/src/python-tools.mjs
Normal file
@@ -0,0 +1,250 @@
|
||||
/**
|
||||
* Python 工具运行时。
|
||||
*
|
||||
* 工具即 tools/*.py,每个文件用 `_protocol.serve(TOOL, run)` 暴露能力:
|
||||
* TOOL = {"name":..., "description":..., "parameters": {JSON Schema}}
|
||||
* def run(args: dict) -> dict
|
||||
*
|
||||
* 发现:python tool.py --spec → 打印 TOOL 的 JSON
|
||||
* 执行:python tool.py --input <json文件> → stdout 打印 {"ok":true,"result":...}
|
||||
*
|
||||
* 注意:这里**刻意用文件重定向**而不是管道(stdio: ['ignore', fd, fd]),
|
||||
* 这样在受限沙箱里也能用(某些沙箱禁止子进程使用命名管道)。
|
||||
*/
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { spawn } from 'node:child_process';
|
||||
import { TMP_DIR, TOOLS_DIR, readSettings } from './config.mjs';
|
||||
|
||||
const specCache = new Map(); // file -> { mtimeMs, spec, error }
|
||||
|
||||
let cachedPython = null;
|
||||
|
||||
function candidates() {
|
||||
const settings = readSettings();
|
||||
const list = [];
|
||||
if (settings.pythonBin) list.push({ bin: settings.pythonBin, prefix: [] });
|
||||
if (process.env.PYTHON) list.push({ bin: process.env.PYTHON, prefix: [] });
|
||||
list.push({ bin: 'python', prefix: [] });
|
||||
list.push({ bin: 'python3', prefix: [] });
|
||||
list.push({ bin: 'py', prefix: ['-3'] });
|
||||
return list;
|
||||
}
|
||||
|
||||
async function runFile({ bin, args, input, timeoutMs = 60000, cwd }) {
|
||||
const id = `${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`;
|
||||
const inPath = path.join(TMP_DIR, `${id}.in.json`);
|
||||
const outPath = path.join(TMP_DIR, `${id}.out.txt`);
|
||||
const errPath = path.join(TMP_DIR, `${id}.err.txt`);
|
||||
fs.writeFileSync(inPath, input ?? '', 'utf8');
|
||||
const outFd = fs.openSync(outPath, 'w');
|
||||
const errFd = fs.openSync(errPath, 'w');
|
||||
|
||||
let child;
|
||||
try {
|
||||
child = spawn(bin, args, {
|
||||
stdio: ['ignore', outFd, errFd],
|
||||
cwd,
|
||||
windowsHide: true,
|
||||
env: { ...process.env, PYTHONIOENCODING: 'utf-8', PYTHONUTF8: '1' },
|
||||
});
|
||||
} catch (err) {
|
||||
fs.closeSync(outFd);
|
||||
fs.closeSync(errFd);
|
||||
throw err;
|
||||
}
|
||||
fs.closeSync(outFd);
|
||||
fs.closeSync(errFd);
|
||||
|
||||
const started = Date.now();
|
||||
const result = await new Promise((resolve) => {
|
||||
let settled = false;
|
||||
const finish = (value) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
resolve(value);
|
||||
};
|
||||
const timer = setTimeout(() => {
|
||||
try {
|
||||
child.kill();
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
finish({ code: null, timedOut: true, ms: Date.now() - started });
|
||||
}, timeoutMs);
|
||||
child.on('error', (err) => {
|
||||
clearTimeout(timer);
|
||||
finish({ code: null, error: err, ms: Date.now() - started });
|
||||
});
|
||||
child.on('close', (code) => {
|
||||
clearTimeout(timer);
|
||||
finish({ code, timedOut: false, ms: Date.now() - started });
|
||||
});
|
||||
});
|
||||
|
||||
const read = (p) => {
|
||||
try {
|
||||
return fs.readFileSync(p, 'utf8');
|
||||
} catch {
|
||||
return '';
|
||||
}
|
||||
};
|
||||
const stdout = read(outPath);
|
||||
const stderr = read(errPath);
|
||||
for (const p of [inPath, outPath, errPath]) {
|
||||
try {
|
||||
fs.unlinkSync(p);
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
return { ...result, stdout, stderr };
|
||||
}
|
||||
|
||||
function parseSpec(stdout) {
|
||||
const lines = stdout.split(/\r?\n/).filter((l) => l.trim());
|
||||
for (let i = lines.length - 1; i >= 0; i -= 1) {
|
||||
try {
|
||||
const json = JSON.parse(lines[i]);
|
||||
if (json && json.name) return json;
|
||||
} catch {
|
||||
/* try previous line */
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
async function resolvePython() {
|
||||
if (cachedPython) return cachedPython;
|
||||
for (const { bin, prefix } of candidates()) {
|
||||
const probe = await runFile({
|
||||
bin,
|
||||
args: [...prefix, '-c', 'print("ok")'],
|
||||
input: '',
|
||||
timeoutMs: 15000,
|
||||
}).catch((err) => ({ error: err }));
|
||||
if (!probe.error && probe.code === 0 && String(probe.stdout).includes('ok')) {
|
||||
cachedPython = { bin, prefix };
|
||||
return cachedPython;
|
||||
}
|
||||
}
|
||||
cachedPython = null;
|
||||
throw new Error('找不到可用的 python 解释器,请在设置里指定 pythonBin');
|
||||
}
|
||||
|
||||
/** 工具目录:设置里可以指到别处(安卓端指到手机上的目录) */
|
||||
export function toolsDir() {
|
||||
const custom = readSettings().toolsDir;
|
||||
if (custom && fs.existsSync(custom)) return custom;
|
||||
return TOOLS_DIR;
|
||||
}
|
||||
|
||||
export function pythonFiles() {
|
||||
const dir = toolsDir();
|
||||
if (!fs.existsSync(dir)) return [];
|
||||
return fs
|
||||
.readdirSync(dir)
|
||||
.filter((f) => f.endsWith('.py') && !f.startsWith('_'))
|
||||
.map((f) => path.join(dir, f));
|
||||
}
|
||||
|
||||
/** 扫描全部 Python 工具(带 mtime 缓存) */
|
||||
export async function discoverPythonTools({ force = false } = {}) {
|
||||
const files = pythonFiles();
|
||||
const tools = [];
|
||||
const errors = [];
|
||||
let py = null;
|
||||
try {
|
||||
py = await resolvePython();
|
||||
} catch (err) {
|
||||
return { tools: [], errors: [{ file: '*', error: err.message }], python: null };
|
||||
}
|
||||
|
||||
for (const file of files) {
|
||||
const stat = fs.statSync(file);
|
||||
const cached = specCache.get(file);
|
||||
if (!force && cached && cached.mtimeMs === stat.mtimeMs) {
|
||||
if (cached.spec) tools.push({ ...cached.spec, __file: file, __python: py });
|
||||
else if (cached.error) errors.push({ file: path.basename(file), error: cached.error });
|
||||
continue;
|
||||
}
|
||||
const res = await runFile({
|
||||
bin: py.bin,
|
||||
args: [...py.prefix, file, '--spec'],
|
||||
input: '',
|
||||
timeoutMs: 20000,
|
||||
cwd: toolsDir(),
|
||||
});
|
||||
const spec = parseSpec(res.stdout);
|
||||
if (spec) {
|
||||
specCache.set(file, { mtimeMs: stat.mtimeMs, spec });
|
||||
tools.push({ ...spec, __file: file, __python: py });
|
||||
} else {
|
||||
const error = (res.stderr || res.stdout || `退出码 ${res.code}`).slice(0, 400);
|
||||
specCache.set(file, { mtimeMs: stat.mtimeMs, error });
|
||||
errors.push({ file: path.basename(file), error });
|
||||
}
|
||||
}
|
||||
return { tools, errors, python: py };
|
||||
}
|
||||
|
||||
/** 执行一个 Python 工具 */
|
||||
export async function runPythonTool(name, args) {
|
||||
const { tools } = await discoverPythonTools();
|
||||
const tool = tools.find((t) => t.name === name);
|
||||
if (!tool) throw new Error(`没有名为 ${name} 的 Python 工具`);
|
||||
const py = tool.__python || (await resolvePython());
|
||||
return runPythonToolWithFile(tool, py, args);
|
||||
}
|
||||
|
||||
async function runPythonToolWithFile(tool, py, args) {
|
||||
const id = `${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`;
|
||||
const inPath = path.join(TMP_DIR, `${id}.args.json`);
|
||||
fs.writeFileSync(inPath, JSON.stringify(args ?? {}), 'utf8');
|
||||
const res = await runFile({
|
||||
bin: py.bin,
|
||||
args: [...py.prefix, tool.__file, '--input', inPath],
|
||||
input: '',
|
||||
timeoutMs: 60000,
|
||||
cwd: toolsDir(),
|
||||
});
|
||||
try {
|
||||
fs.unlinkSync(inPath);
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
const lines = res.stdout.split(/\r?\n/).filter((l) => l.trim());
|
||||
let parsed = null;
|
||||
for (let i = lines.length - 1; i >= 0; i -= 1) {
|
||||
try {
|
||||
parsed = JSON.parse(lines[i]);
|
||||
break;
|
||||
} catch {
|
||||
/* keep looking */
|
||||
}
|
||||
}
|
||||
if (res.error) {
|
||||
return { ok: false, error: `无法启动 python:${res.error.message}` };
|
||||
}
|
||||
if (parsed) {
|
||||
return { ok: Boolean(parsed.ok), result: parsed.result, error: parsed.error, stderr: res.stderr || undefined };
|
||||
}
|
||||
return {
|
||||
ok: res.code === 0,
|
||||
error: res.timedOut ? '工具执行超时(60s)' : `未解析到 JSON 输出(退出码 ${res.code})`,
|
||||
stdout: res.stdout.slice(0, 2000),
|
||||
stderr: res.stderr.slice(0, 2000),
|
||||
};
|
||||
}
|
||||
|
||||
/** 转成 OpenAI tools 定义 */
|
||||
export function toOpenAITool(spec) {
|
||||
return {
|
||||
type: 'function',
|
||||
function: {
|
||||
name: spec.name,
|
||||
description: spec.description || spec.name,
|
||||
parameters: spec.parameters || { type: 'object', properties: {} },
|
||||
},
|
||||
};
|
||||
}
|
||||
284
server/src/speech.mjs
Normal file
284
server/src/speech.mjs
Normal file
@@ -0,0 +1,284 @@
|
||||
/**
|
||||
* 语音:朗读(TTS)和语音识别(STT)。
|
||||
*
|
||||
* 对应 Python 版 android/kernel/speech.py —— 两份实现的请求体、返回字段、错误文案
|
||||
* 都要逐字段一致(手机和电脑的用户体验不能有差别)。
|
||||
*
|
||||
* 为什么放在内核里而不是各端自己调:
|
||||
* 1. API Key 只存一份(跟对话的 Key 放一起);
|
||||
* 2. 浏览器 / 安卓 / exe 三端白捡同一个能力;
|
||||
* 3. 厂商鉴权差异全在这一个文件里。
|
||||
*
|
||||
* 引擎:
|
||||
* TTS 'volc'(火山,豆包同款音色)/ 'openai'(兼容 /audio/speech)/ 'system'(交给设备)
|
||||
* STT 'openai'(兼容 /audio/transcriptions)/ 'system'(交给设备)
|
||||
*/
|
||||
|
||||
export const VOLC_TTS_URL = process.env.DOUBAO_VOLC_TTS_URL || 'https://openspeech.bytedance.com/api/v1/tts';
|
||||
|
||||
const TIMEOUT_TTS = 60000;
|
||||
const TIMEOUT_STT = 120000;
|
||||
|
||||
const VOLC_MIME = {
|
||||
mp3: 'audio/mpeg',
|
||||
wav: 'audio/wav',
|
||||
ogg_opus: 'audio/ogg',
|
||||
pcm: 'audio/L16',
|
||||
};
|
||||
|
||||
/** 带用户可读原因的失败:界面直接显示这个 message,不用再猜 */
|
||||
export class SpeechError extends Error {}
|
||||
|
||||
const speechOf = (settings) => (settings?.speech && typeof settings.speech === 'object' ? settings.speech : {});
|
||||
|
||||
async function fetchWithTimeout(url, options, ms) {
|
||||
const ctrl = new AbortController();
|
||||
const timer = setTimeout(() => ctrl.abort(), ms);
|
||||
try {
|
||||
return await fetch(url, { ...options, signal: ctrl.signal });
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
}
|
||||
|
||||
async function readError(res) {
|
||||
try {
|
||||
const t = await res.text();
|
||||
return t.slice(0, 400);
|
||||
} catch {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
/* 朗读 */
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
||||
export async function synthesize(text, settings) {
|
||||
const content = String(text || '').trim();
|
||||
if (!content) throw new SpeechError('没有要朗读的内容');
|
||||
|
||||
const speech = speechOf(settings);
|
||||
const engine = String(speech.ttsEngine || 'system').toLowerCase();
|
||||
const speed = Math.min(Math.max(Number(speech.ttsSpeed) || 1.0, 0.2), 3.0);
|
||||
|
||||
if (engine === 'volc') return synthesizeVolc(content, speech, speed);
|
||||
if (engine === 'openai') return synthesizeOpenai(content, settings, speech, speed);
|
||||
return { engine: 'system' };
|
||||
}
|
||||
|
||||
/**
|
||||
* 火山语音合成。
|
||||
*
|
||||
* 两个容易踩的点(对着官方文档和第三方实现核对过):
|
||||
* 1. 鉴权头是 `Bearer;{token}` —— **分号,不是空格**,写成空格会判鉴权失败;
|
||||
* 2. 成功判定看 body 里的 `code === 3000`,HTTP 200 也可能带错误码。
|
||||
* 返回的 `data` 是**纯 base64**,解出来就是音频字节。
|
||||
*/
|
||||
async function synthesizeVolc(text, speech, speed) {
|
||||
const appId = String(speech.volcAppId || '').trim();
|
||||
const token = String(speech.volcToken || '').trim();
|
||||
const cluster = String(speech.volcCluster || '').trim() || 'volcano_tts';
|
||||
const voice = String(speech.ttsVoice || '').trim() || 'BV700_streaming';
|
||||
const encoding = String(speech.volcEncoding || '').trim() || 'mp3';
|
||||
|
||||
if (!appId || !token) {
|
||||
throw new SpeechError('火山语音需要 App ID 和 Access Token(在火山控制台「语音技术」里创建应用后拿到)');
|
||||
}
|
||||
|
||||
const body = {
|
||||
app: { appid: appId, token, cluster },
|
||||
user: { uid: 'doubao' },
|
||||
audio: {
|
||||
voice_type: voice,
|
||||
encoding,
|
||||
speed_ratio: speed,
|
||||
volume_ratio: 1.0,
|
||||
pitch_ratio: 1.0,
|
||||
},
|
||||
request: {
|
||||
reqid: crypto.randomUUID(),
|
||||
text,
|
||||
text_type: 'plain',
|
||||
operation: 'query',
|
||||
},
|
||||
};
|
||||
|
||||
let res;
|
||||
try {
|
||||
res = await fetchWithTimeout(VOLC_TTS_URL, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: `Bearer;${token}` },
|
||||
body: JSON.stringify(body),
|
||||
}, TIMEOUT_TTS);
|
||||
} catch (err) {
|
||||
throw new SpeechError(`连不上:${err.message}`);
|
||||
}
|
||||
|
||||
const raw = await res.text();
|
||||
let result;
|
||||
try {
|
||||
result = JSON.parse(raw);
|
||||
} catch {
|
||||
throw new SpeechError(`返回不是 JSON(HTTP ${res.status}):${raw.slice(0, 200)}`);
|
||||
}
|
||||
|
||||
if (result.code !== 3000) {
|
||||
throw new SpeechError(`火山返回 code=${result.code} message=${result.message || result.Message || '?'}`);
|
||||
}
|
||||
if (!result.data) throw new SpeechError('火山没返回音频数据');
|
||||
|
||||
return { engine: 'volc', mime: VOLC_MIME[encoding] || 'audio/mpeg', audio: result.data };
|
||||
}
|
||||
|
||||
/** OpenAI 兼容的 /audio/speech:POST 进去,直接吐音频字节(不是 JSON) */
|
||||
async function synthesizeOpenai(text, settings, speech, speed) {
|
||||
const { apiKey, baseUrl } = resolveOpenai(settings, speech);
|
||||
const voice = String(speech.ttsVoice || '').trim() || 'alloy';
|
||||
const model = String(speech.ttsModel || '').trim() || 'tts-1';
|
||||
const format = String(speech.openaiFormat || '').trim() || 'mp3';
|
||||
|
||||
let res;
|
||||
try {
|
||||
res = await fetchWithTimeout(`${baseUrl}/audio/speech`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${apiKey}` },
|
||||
body: JSON.stringify({ model, input: text, voice, response_format: format, speed }),
|
||||
}, TIMEOUT_TTS);
|
||||
} catch (err) {
|
||||
throw new SpeechError(`连不上:${err.message}`);
|
||||
}
|
||||
|
||||
if (!res.ok) throw new SpeechError(`HTTP ${res.status} ${await readError(res)}`);
|
||||
|
||||
const buf = Buffer.from(await res.arrayBuffer());
|
||||
if (!buf.length) throw new SpeechError('返回了空音频');
|
||||
const ctype = (res.headers.get('content-type') || 'audio/mpeg').split(';')[0].trim();
|
||||
return { engine: 'openai', mime: ctype || 'audio/mpeg', audio: buf.toString('base64') };
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
/* 语音识别 */
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
||||
export async function transcribe(audio, filename, contentType, settings) {
|
||||
if (!audio || !audio.length) throw new SpeechError('没有录到音频');
|
||||
|
||||
const speech = speechOf(settings);
|
||||
const engine = String(speech.sttEngine || 'system').toLowerCase();
|
||||
if (engine !== 'openai') return { engine: 'system' };
|
||||
|
||||
const { apiKey, baseUrl } = resolveOpenai(settings, speech);
|
||||
const model = String(speech.sttModel || '').trim() || 'whisper-1';
|
||||
const lang = String(speech.sttLanguage || '').trim();
|
||||
|
||||
const form = new FormData();
|
||||
form.append('model', model);
|
||||
if (lang) form.append('language', lang);
|
||||
form.append('file', new Blob([audio], { type: contentType || 'audio/wav' }), filename || 'audio.wav');
|
||||
|
||||
let res;
|
||||
try {
|
||||
res = await fetchWithTimeout(`${baseUrl}/audio/transcriptions`, {
|
||||
method: 'POST',
|
||||
headers: { Authorization: `Bearer ${apiKey}` },
|
||||
body: form,
|
||||
}, TIMEOUT_STT);
|
||||
} catch (err) {
|
||||
throw new SpeechError(`连不上:${err.message}`);
|
||||
}
|
||||
|
||||
if (!res.ok) throw new SpeechError(`HTTP ${res.status} ${await readError(res)}`);
|
||||
|
||||
const raw = await res.text();
|
||||
let result;
|
||||
try {
|
||||
result = JSON.parse(raw);
|
||||
} catch {
|
||||
throw new SpeechError(`返回不是 JSON:${raw.slice(0, 200)}`);
|
||||
}
|
||||
|
||||
const text = String(result.text || '').trim();
|
||||
if (!text) throw new SpeechError('识别结果为空(可能是没人说话,或音频格式不对)');
|
||||
return { engine: 'openai', text };
|
||||
}
|
||||
|
||||
/**
|
||||
* 取 OpenAI 兼容那套的 Key 和地址。
|
||||
* 默认复用主对话的设置(同一个 Key 通常也能用语音接口);
|
||||
* 也可以在 speech 里单独填,方便"对话用方舟、语音用 OpenAI"这种组合。
|
||||
*/
|
||||
function resolveOpenai(settings, speech) {
|
||||
const apiKey = String(speech.openaiApiKey || '').trim() || settings?.apiKey || '';
|
||||
let baseUrl = String(speech.openaiBaseUrl || '').trim() || settings?.baseUrl || '';
|
||||
baseUrl = baseUrl.replace(/\/+$/, '');
|
||||
if (!apiKey) throw new SpeechError('没有 API Key(在设置里填,或在「语音」里单独指定)');
|
||||
if (!baseUrl) throw new SpeechError('没有 Base URL');
|
||||
return { apiKey, baseUrl };
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
/* 给界面看的 */
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
||||
export function speechState(settings) {
|
||||
const speech = speechOf(settings);
|
||||
return {
|
||||
ttsEngine: speech.ttsEngine || 'system',
|
||||
ttsVoice: speech.ttsVoice || '',
|
||||
ttsSpeed: speech.ttsSpeed || 1.0,
|
||||
autoRead: Boolean(speech.autoRead),
|
||||
sttEngine: speech.sttEngine || 'system',
|
||||
sttModel: speech.sttModel || 'whisper-1',
|
||||
sttLanguage: speech.sttLanguage || '',
|
||||
volcAppId: speech.volcAppId || '',
|
||||
volcCluster: speech.volcCluster || 'volcano_tts',
|
||||
volcEncoding: speech.volcEncoding || 'mp3',
|
||||
hasVolcToken: Boolean(speech.volcToken),
|
||||
hasOpenaiKey: Boolean(speech.openaiApiKey || settings?.apiKey),
|
||||
openaiBaseUrl: speech.openaiBaseUrl || '',
|
||||
ttsModel: speech.ttsModel || 'tts-1',
|
||||
};
|
||||
}
|
||||
|
||||
/** 掩码值:写设置时看到它表示"不改"(跟 apiKey 一个套路) */
|
||||
export const MASK = '••••••••';
|
||||
|
||||
export const DEFAULT_SPEECH = {
|
||||
ttsEngine: 'system',
|
||||
ttsVoice: '',
|
||||
ttsSpeed: 1.0,
|
||||
autoRead: false,
|
||||
sttEngine: 'system',
|
||||
sttModel: 'whisper-1',
|
||||
sttLanguage: '',
|
||||
volcAppId: '',
|
||||
volcToken: '',
|
||||
volcCluster: 'volcano_tts',
|
||||
volcEncoding: 'mp3',
|
||||
openaiApiKey: '',
|
||||
openaiBaseUrl: '',
|
||||
ttsModel: 'tts-1',
|
||||
};
|
||||
|
||||
export const VOLC_VOICES = [
|
||||
{ value: 'BV700_streaming', label: '通用女声(BV700)' },
|
||||
{ value: 'BV001_streaming', label: '通用女声 2(BV001)' },
|
||||
{ value: 'BV002_streaming', label: '通用男声(BV002)' },
|
||||
{ value: 'BV701_streaming', label: '通用男声 2(BV701)' },
|
||||
{ value: 'BV064_streaming', label: '甜美女声(BV064)' },
|
||||
{ value: 'BV138_streaming', label: '沉稳男声(BV138)' },
|
||||
];
|
||||
|
||||
export const OPENAI_VOICES = [
|
||||
{ value: 'alloy', label: 'alloy(中性)' },
|
||||
{ value: 'nova', label: 'nova(女声,推荐)' },
|
||||
{ value: 'shimmer', label: 'shimmer(女声,柔和)' },
|
||||
{ value: 'echo', label: 'echo(男声)' },
|
||||
{ value: 'onyx', label: 'onyx(男声,低沉)' },
|
||||
{ value: 'fable', label: 'fable(叙述)' },
|
||||
{ value: 'coral', label: 'coral(女声,明快)' },
|
||||
{ value: 'sage', label: 'sage(女声,沉稳)' },
|
||||
];
|
||||
|
||||
export const VOICE_OPTIONS = { volc: VOLC_VOICES, openai: OPENAI_VOICES, system: [] };
|
||||
144
server/src/store.mjs
Normal file
144
server/src/store.mjs
Normal file
@@ -0,0 +1,144 @@
|
||||
/**
|
||||
* 会话持久化:<数据目录>/conversations.json
|
||||
* 结构:{ conversations: [{ id, title, agentId, createdAt, updatedAt, pinned, messages: [...] }] }
|
||||
*
|
||||
* 这里不放假数据:列表里的每一条都是真聊出来的,
|
||||
* 列表上显示的就是最后一条消息的预览。
|
||||
*/
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { DATA_DIR } from './config.mjs';
|
||||
|
||||
const FILE = path.join(DATA_DIR, 'conversations.json');
|
||||
|
||||
function nowIso() {
|
||||
return new Date().toISOString();
|
||||
}
|
||||
|
||||
function rid() {
|
||||
return `c_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 7)}`;
|
||||
}
|
||||
|
||||
function freshState() {
|
||||
return {
|
||||
conversations: [
|
||||
{
|
||||
id: 'c_main',
|
||||
title: '主对话',
|
||||
agentId: 'a_doubao',
|
||||
pinned: true,
|
||||
createdAt: nowIso(),
|
||||
updatedAt: nowIso(),
|
||||
messages: [],
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
let state = null;
|
||||
|
||||
function load() {
|
||||
if (state) return state;
|
||||
if (fs.existsSync(FILE)) {
|
||||
try {
|
||||
state = JSON.parse(fs.readFileSync(FILE, 'utf8'));
|
||||
} catch (err) {
|
||||
console.error('[store] conversations.json 解析失败,重建:', err.message);
|
||||
state = freshState();
|
||||
}
|
||||
} else {
|
||||
state = freshState();
|
||||
}
|
||||
if (!Array.isArray(state.conversations) || state.conversations.length === 0) state = freshState();
|
||||
return state;
|
||||
}
|
||||
|
||||
function persist() {
|
||||
fs.writeFileSync(FILE, JSON.stringify(load(), null, 2), 'utf8');
|
||||
}
|
||||
|
||||
function previewOf(messages) {
|
||||
for (let i = messages.length - 1; i >= 0; i -= 1) {
|
||||
const msg = messages[i];
|
||||
if (!msg.content) continue;
|
||||
const text = String(msg.content).replace(/\s+/g, ' ').trim();
|
||||
if (!text) continue;
|
||||
const tag = msg.role === 'user' ? '我:' : '';
|
||||
return `${tag}${text.length > 30 ? `${text.slice(0, 30)}…` : text}`;
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
/** 列表:带最后一条消息预览,按置顶 + 更新时间排 */
|
||||
export function listConversations() {
|
||||
return load().conversations
|
||||
.slice()
|
||||
.sort((a, b) => {
|
||||
if (Boolean(b.pinned) !== Boolean(a.pinned)) return Number(b.pinned) - Number(a.pinned);
|
||||
return String(b.updatedAt).localeCompare(String(a.updatedAt));
|
||||
})
|
||||
.map(({ messages, ...meta }) => ({
|
||||
...meta,
|
||||
messageCount: messages?.length || 0,
|
||||
preview: previewOf(messages || []),
|
||||
}));
|
||||
}
|
||||
|
||||
export function getConversation(id) {
|
||||
return load().conversations.find((c) => c.id === id) || null;
|
||||
}
|
||||
|
||||
export function createConversation(title = '新对话', agentId) {
|
||||
const item = {
|
||||
id: rid(),
|
||||
title,
|
||||
agentId: agentId || '',
|
||||
pinned: false,
|
||||
createdAt: nowIso(),
|
||||
updatedAt: nowIso(),
|
||||
messages: [],
|
||||
};
|
||||
load().conversations.unshift(item);
|
||||
persist();
|
||||
return item;
|
||||
}
|
||||
|
||||
export function updateConversation(id, patch) {
|
||||
const item = getConversation(id);
|
||||
if (!item) return null;
|
||||
Object.assign(item, patch, { updatedAt: nowIso() });
|
||||
persist();
|
||||
return item;
|
||||
}
|
||||
|
||||
export function deleteConversation(id) {
|
||||
const s = load();
|
||||
const i = s.conversations.findIndex((c) => c.id === id);
|
||||
if (i < 0) return false;
|
||||
s.conversations.splice(i, 1);
|
||||
if (s.conversations.length === 0) s.conversations.push(...freshState().conversations);
|
||||
persist();
|
||||
return true;
|
||||
}
|
||||
|
||||
export function appendMessages(id, messages) {
|
||||
const item = getConversation(id);
|
||||
if (!item) return null;
|
||||
item.messages.push(...messages);
|
||||
item.updatedAt = nowIso();
|
||||
persist();
|
||||
return item;
|
||||
}
|
||||
|
||||
/** 用首条用户消息自动起标题 */
|
||||
export function autoTitle(id, text) {
|
||||
const item = getConversation(id);
|
||||
if (!item || (item.title !== '新对话' && item.title !== '主对话')) return;
|
||||
const title = String(text).replace(/\s+/g, ' ').trim().slice(0, 18);
|
||||
if (title) updateConversation(id, { title });
|
||||
}
|
||||
|
||||
/** 会话数据文件位置(界面上显示用) */
|
||||
export function storeFilePath() {
|
||||
return FILE;
|
||||
}
|
||||
141
server/src/uploads.mjs
Normal file
141
server/src/uploads.mjs
Normal file
@@ -0,0 +1,141 @@
|
||||
/**
|
||||
* 附件:上传、Electron 原生选文件、以及"宿主页拖拽进来的文件"待取队列。
|
||||
* 图片会以 data URL 形式喂给支持视觉的模型;文本类文件直接内联正文。
|
||||
*/
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { DATA_DIR } from './config.mjs';
|
||||
|
||||
export const UPLOADS_DIR = path.join(DATA_DIR, 'uploads');
|
||||
fs.mkdirSync(UPLOADS_DIR, { recursive: true });
|
||||
|
||||
const IMAGE_EXT = new Set(['.png', '.jpg', '.jpeg', '.webp', '.gif', '.bmp']);
|
||||
const TEXT_EXT = new Set([
|
||||
'.txt', '.md', '.markdown', '.json', '.csv', '.tsv', '.log', '.ini', '.toml', '.yml', '.yaml',
|
||||
'.py', '.js', '.mjs', '.cjs', '.ts', '.tsx', '.jsx', '.html', '.htm', '.css', '.scss',
|
||||
'.xml', '.sql', '.sh', '.bat', '.ps1', '.java', '.c', '.h', '.cpp', '.cs', '.go', '.rs',
|
||||
'.rb', '.php', '.swift', '.kt', '.lua', '.r', '.vue', '.svelte',
|
||||
]);
|
||||
|
||||
/** 复制进 uploads 的上限;再大就只登记路径,不复制 */
|
||||
const COPY_LIMIT = 25 * 1024 * 1024;
|
||||
/** 喂给模型的单张图片上限 */
|
||||
const VISION_LIMIT = 6 * 1024 * 1024;
|
||||
|
||||
let pending = [];
|
||||
|
||||
function rid() {
|
||||
return `f_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 6)}`;
|
||||
}
|
||||
|
||||
function safeName(name) {
|
||||
return String(name || 'file').replace(/[\\/:*?"<>|]/g, '_').slice(-60);
|
||||
}
|
||||
|
||||
export function isImage(name) {
|
||||
return IMAGE_EXT.has(path.extname(String(name || '')).toLowerCase());
|
||||
}
|
||||
|
||||
export function isText(name) {
|
||||
return TEXT_EXT.has(path.extname(String(name || '')).toLowerCase());
|
||||
}
|
||||
|
||||
function mimeOf(name) {
|
||||
const ext = path.extname(String(name || '')).toLowerCase();
|
||||
const map = {
|
||||
'.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.webp': 'image/webp',
|
||||
'.gif': 'image/gif', '.bmp': 'image/bmp', '.pdf': 'application/pdf',
|
||||
'.json': 'application/json', '.md': 'text/markdown',
|
||||
};
|
||||
return map[ext] || (isText(name) ? 'text/plain' : 'application/octet-stream');
|
||||
}
|
||||
|
||||
function meta(filePath, name, { copy = true } = {}) {
|
||||
const stat = fs.statSync(filePath);
|
||||
let storedPath = filePath;
|
||||
let url = '';
|
||||
if (copy && stat.size <= COPY_LIMIT) {
|
||||
const target = path.join(UPLOADS_DIR, `${Date.now().toString(36)}_${safeName(name)}`);
|
||||
fs.copyFileSync(filePath, target);
|
||||
storedPath = target;
|
||||
url = `/uploads/${path.basename(target)}`;
|
||||
}
|
||||
return {
|
||||
id: rid(),
|
||||
name: String(name),
|
||||
size: stat.size,
|
||||
mime: mimeOf(name),
|
||||
path: storedPath,
|
||||
url,
|
||||
at: new Date().toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
/** 浏览器上传:base64 → 落盘 */
|
||||
export function saveUpload({ name, base64 }) {
|
||||
if (!name || !base64) throw new Error('缺少 name 或 base64');
|
||||
const buffer = Buffer.from(String(base64).replace(/^data:[^,]+,/, ''), 'base64');
|
||||
if (buffer.length > COPY_LIMIT) throw new Error(`文件超过 ${COPY_LIMIT / 1024 / 1024}MB`);
|
||||
const target = path.join(UPLOADS_DIR, `${Date.now().toString(36)}_${safeName(name)}`);
|
||||
fs.writeFileSync(target, buffer);
|
||||
return {
|
||||
id: rid(),
|
||||
name: String(name),
|
||||
size: buffer.length,
|
||||
mime: mimeOf(name),
|
||||
path: target,
|
||||
url: `/uploads/${path.basename(target)}`,
|
||||
at: new Date().toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
/** 桌面版原生选文件:登记(必要时复制) */
|
||||
export function registerLocalFile(filePath) {
|
||||
if (!fs.existsSync(filePath)) throw new Error(`文件不存在:${filePath}`);
|
||||
return meta(filePath, path.basename(filePath));
|
||||
}
|
||||
|
||||
/** 宿主页拖拽进来的文件先放这里,等界面来取 */
|
||||
export function addPending(items) {
|
||||
pending.push(...items);
|
||||
}
|
||||
|
||||
export function takePending() {
|
||||
const items = pending;
|
||||
pending = [];
|
||||
return items;
|
||||
}
|
||||
|
||||
/**
|
||||
* 把附件转成模型能吃的形式。
|
||||
* @returns {{text: string, images: {url: string}[]}}
|
||||
*/
|
||||
export function attachmentPayload(attachment) {
|
||||
const out = { text: '', images: [] };
|
||||
if (!attachment || !fs.existsSync(attachment.path)) {
|
||||
out.text = `【附件 ${attachment?.name || '未知'} 已丢失】`;
|
||||
return out;
|
||||
}
|
||||
const size = fs.statSync(attachment.path).size;
|
||||
if (isImage(attachment.name) && size <= VISION_LIMIT) {
|
||||
const b64 = fs.readFileSync(attachment.path).toString('base64');
|
||||
out.images.push({ url: `data:${attachment.mime};base64,${b64}` });
|
||||
out.text = `【图片 ${attachment.name}】`;
|
||||
return out;
|
||||
}
|
||||
if (isText(attachment.name) || size < 64 * 1024) {
|
||||
let body = '';
|
||||
try {
|
||||
body = fs.readFileSync(attachment.path, 'utf8');
|
||||
} catch {
|
||||
body = '';
|
||||
}
|
||||
if (body) {
|
||||
const clipped = body.length > 20000 ? `${body.slice(0, 20000)}\n…(已截断,共 ${body.length} 字符)` : body;
|
||||
out.text = `【文件 ${attachment.name}(${size} 字节)】\n\`\`\`\n${clipped}\n\`\`\``;
|
||||
return out;
|
||||
}
|
||||
}
|
||||
out.text = `【附件 ${attachment.name}(${size} 字节,二进制)本地路径:${attachment.path}】`;
|
||||
return out;
|
||||
}
|
||||
Reference in New Issue
Block a user