Files
doubao-clone/scripts/mock-llm.mjs
l f056bcf45a 豆包复刻:原生安卓(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。
2026-10-09 14:09:36 +08:00

195 lines
7.7 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

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

/**
* 假的 OpenAI 兼容服务 + 假的火山语音服务,用来端到端验证内核(不消耗任何真实额度)。
*
* 对话:第一轮返回 tool_call(calc),第二轮根据工具结果流式回答。
* 语音:/v1/audio/speech 回一段真 WAV;/v1/audio/transcriptions 回固定文字;
* 还顺手把收到的请求形状打出来,用来核对"我们到底发了什么头/字段"。
*/
import http from 'node:http';
const PORT = Number(process.env.MOCK_PORT || 5299);
function sse(res, obj) {
res.write(`data: ${JSON.stringify(obj)}\n\n`);
}
/** 造一段 0.3 秒的正弦波 WAV(16000Hz 单声道 16bit),用来验证播放链路 */
function makeWav(seconds = 0.3, freq = 440) {
const rate = 16000;
const n = Math.floor(rate * seconds);
const data = Buffer.alloc(n * 2);
for (let i = 0; i < n; i += 1) {
data.writeInt16LE(Math.round(Math.sin((2 * Math.PI * freq * i) / rate) * 8000), i * 2);
}
const header = Buffer.alloc(44);
header.write('RIFF', 0);
header.writeUInt32LE(36 + data.length, 4);
header.write('WAVE', 8);
header.write('fmt ', 12);
header.writeUInt32LE(16, 16);
header.writeUInt16LE(1, 20);
header.writeUInt16LE(1, 22);
header.writeUInt32LE(rate, 24);
header.writeUInt32LE(rate * 2, 28);
header.writeUInt16LE(2, 32);
header.writeUInt16LE(16, 34);
header.write('data', 36);
header.writeUInt32LE(data.length, 40);
return Buffer.concat([header, data]);
}
const server = http.createServer(async (req, res) => {
const url = req.url || '';
/* ---------------- 语音合成(OpenAI 兼容 /audio/speech)---------------- */
if (url.startsWith('/v1/audio/speech')) {
const chunks = [];
for await (const c of req) chunks.push(c);
let body = {};
try {
body = JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}');
} catch { /* 下面照常回音频 */ }
console.log(
`[mock][tts] auth=${req.headers.authorization ? '有' : '无'} model=${body.model} ` +
`voice=${body.voice} speed=${body.speed} fmt=${body.response_format} ` +
`文本=${JSON.stringify(String(body.input || '').slice(0, 30))}`,
);
const wav = makeWav(0.3, 520);
res.writeHead(200, { 'Content-Type': 'audio/wav', 'Content-Length': wav.length }).end(wav);
return;
}
/* ---------------- 语音合成(火山 v1 /api/v1/tts)---------------- */
if (url.startsWith('/api/v1/tts')) {
const chunks = [];
for await (const c of req) chunks.push(c);
let body = {};
try {
body = JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}');
} catch { /* 忽略 */ }
const auth = req.headers.authorization || '';
console.log(
`[mock][volc-tts] Authorization=${JSON.stringify(auth)} ` +
`app.appid=${body.app?.appid} app.token=${body.app?.token ? '有' : '无'} app.cluster=${body.app?.cluster} ` +
`audio.voice_type=${body.audio?.voice_type} audio.encoding=${body.audio?.encoding} ` +
`audio.speed_ratio=${body.audio?.speed_ratio} ` +
`request.text_type=${body.request?.text_type} request.operation=${body.request?.operation} ` +
`request.reqid=${body.request?.reqid ? '有' : '无'} text=${JSON.stringify(String(body.request?.text || '').slice(0, 20))}`,
);
// 校验鉴权头是不是文档要求的分号形式 —— 这正是最容易写错的地方
const semicolonOk = auth.startsWith('Bearer;');
if (!semicolonOk) {
res.writeHead(200, { 'Content-Type': 'application/json' }).end(
JSON.stringify({ code: 3001, message: '鉴权头格式不对:必须是 Bearer;<token>(分号)' }),
);
return;
}
const wav = makeWav(0.3, 660);
res.writeHead(200, { 'Content-Type': 'application/json' }).end(
JSON.stringify({ code: 3000, message: 'Success', reqid: body.request?.reqid, data: wav.toString('base64') }),
);
return;
}
/* ---------------- 语音识别(OpenAI 兼容 /audio/transcriptions)---------------- */
if (url.startsWith('/v1/audio/transcriptions')) {
const chunks = [];
for await (const c of req) chunks.push(c);
const raw = Buffer.concat(chunks);
const ctype = req.headers['content-type'] || '';
const boundary = (ctype.match(/boundary=(.+)$/) || [])[1] || '';
const text = raw.toString('latin1');
const model = (text.match(/name="model"\r\n\r\n([^\r]*)/) || [])[1] || '?';
const hasFile = text.includes('name="file"') && text.includes('filename=');
console.log(
`[mock][stt] auth=${req.headers.authorization ? '有' : '无'} boundary=${boundary ? '有' : '无'} ` +
`model=${model} 带文件=${hasFile} 体积=${raw.length}`,
);
res.writeHead(200, { 'Content-Type': 'application/json' }).end(
JSON.stringify({ text: '这是语音识别的模拟结果' }),
);
return;
}
if (!url.startsWith('/v1/chat/completions')) {
res.writeHead(404).end('nope');
return;
}
const chunks = [];
for await (const c of req) chunks.push(c);
// 别让一条坏请求把整个 mock 打死:壳脚本/手敲 curl 很容易发出不合法 JSON,
// 之前没防这一下,mock 直接退出,界面那边只看到 "Remote end closed connection"。
let body;
try {
body = JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}');
} catch (e) {
console.log('[mock] 请求体不是合法 JSON,已忽略:', e.message);
res.writeHead(400, { 'Content-Type': 'application/json' }).end('{"error":"bad json"}');
return;
}
const messages = body.messages || [];
const toolMsg = messages.findLast?.((m) => m.role === 'tool');
const hasTools = Array.isArray(body.tools) && body.tools.length > 0;
console.log(
`[mock] model=${body.model} tools=${body.tools?.length || 0} msgs=${messages.length} ` +
`temperature=${body.temperature} thinking=${JSON.stringify(body.thinking)} ` +
`reasoning_effort=${body.reasoning_effort}`,
);
res.writeHead(200, {
'Content-Type': 'text/event-stream; charset=utf-8',
'Cache-Control': 'no-cache, no-transform',
Connection: 'keep-alive',
});
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
if (!toolMsg && hasTools) {
// 第一轮:要求调用 calc 工具
const args = JSON.stringify({ expression: '(1+2)*3' });
sse(res, {
choices: [{
delta: {
tool_calls: [{
index: 0,
id: 'call_mock_1',
type: 'function',
function: { name: 'calc', arguments: args },
}],
},
}],
});
await sleep(120);
sse(res, { choices: [{ delta: {}, finish_reason: 'tool_calls' }] });
res.write('data: [DONE]\n\n');
res.end();
return;
}
// 第二轮:先吐一段思维链(reasoning_content),再给最终回答
const thinking = [
'用户要算 (1+2)*3。',
'我需要先调用计算工具,避免自己算错。',
'工具返回的表达式是 (1+2)*3,结果是 9。',
'把结果解释给用户,并说明这条链路是端到端跑通的。',
].join('');
for (const ch of thinking) {
sse(res, { choices: [{ delta: { reasoning_content: ch } }] });
await sleep(8);
}
const toolText = toolMsg ? String(toolMsg.content) : '(没拿到工具结果)';
const answer = `我用 calc 工具算了一下:${toolText}\n\n所以 (1+2)*3 = 9。这条回答是端到端跑通的:界面 → 内核 → 工具调用 → 流式返回。`;
for (const ch of answer) {
sse(res, { choices: [{ delta: { content: ch } }] });
await sleep(12);
}
sse(res, { choices: [{ delta: {}, finish_reason: 'stop' }] });
sse(res, { usage: { prompt_tokens: 100, completion_tokens: 60, total_tokens: 160 }, choices: [] });
res.write('data: [DONE]\n\n');
res.end();
});
server.listen(PORT, '127.0.0.1', () => console.log(`[mock] listening on http://127.0.0.1:${PORT}/v1`));