121 lines
11 KiB
JavaScript
121 lines
11 KiB
JavaScript
// HEL-900 isolated contract mock for her own voice (docs/voice-custom-contract-HEL899.md §2). Serves web/dist plus the
|
||
// minimum real-app API (companion, messages, health) and the five custom-voice endpoints, answering exactly as the
|
||
// HEL-899 router does. Synthetic data only: no voice panel, no ASR, no TTS, no network beyond 127.0.0.1. The preview is
|
||
// a generated tone wrapped as 24 kHz mono WAV, not a voice. Usage: node tests/hel900_mock.mjs <port>.
|
||
// Control GETs: /__mode?list=ok|off|none|down, /__fail?register=&preview=&apply= (status code, `net`, `bad`, `slow`),
|
||
// /__reset, /__log (drains), /__uploads, /__pid.
|
||
import { createServer } from 'node:http';
|
||
import { readFile } from 'node:fs/promises';
|
||
import { extname, join, normalize } from 'node:path';
|
||
import { fileURLToPath } from 'node:url';
|
||
|
||
const dist = fileURLToPath(new URL('../dist/', import.meta.url));
|
||
const port = Number(process.argv[2] || 8900);
|
||
const identity = { id: '1', name: '栖', birth: '2000-03-14', hour: '子', relation: '朋友', nickname: '', boundary: '', color: { pillars: { year: '庚辰', month: '己卯', day: '丙午', hour: '戊子' }, traits: '合成测试档案' } };
|
||
const BUILTIN = ['bailu', 'bajie', 'default', 'female_soft', 'haimianbaobao', 'jiaojiao', 'male_warm', 'nezha', 'rain', 'sunwukong', 'xiaoyun'];
|
||
const log = [], uploads = [], gaveUp = [];
|
||
let mode = 'ok', fail = {}, custom = new Map(), previewed = new Set(), selection = { voice: null, label: '', updated_at: null }, made = 0;
|
||
const reset = () => { mode = 'ok'; fail = {}; custom = new Map(); previewed = new Set(); selection = { voice: null, label: '', updated_at: null }; made = 0; log.splice(0); uploads.splice(0); };
|
||
const send = (res, status, body, type = 'application/json; charset=utf-8') => { res.writeHead(status, { 'Content-Type': type, 'Cache-Control': 'no-store' }); res.end(typeof body === 'string' || Buffer.isBuffer(body) ? body : JSON.stringify(body)); };
|
||
const sleep = ms => new Promise(r => setTimeout(r, ms));
|
||
const body = async req => { const parts = []; for await (const c of req) parts.push(c); return Buffer.concat(parts); };
|
||
function wavInfo(b) {
|
||
if (b.length < 44 || b.toString('ascii', 0, 4) !== 'RIFF' || b.toString('ascii', 8, 12) !== 'WAVE') return null;
|
||
let at = 12, fmt = null;
|
||
while (at + 8 <= b.length) {
|
||
const id = b.toString('ascii', at, at + 4), size = b.readUInt32LE(at + 4);
|
||
if (id === 'fmt ') fmt = { channels: b.readUInt16LE(at + 10), rate: b.readUInt32LE(at + 12), bits: b.readUInt16LE(at + 22) };
|
||
if (id === 'data') return fmt && { ...fmt, seconds: Math.min(size, b.length - at - 8) / (fmt.rate * fmt.channels * fmt.bits / 8) };
|
||
at += 8 + size + (size & 1);
|
||
}
|
||
return null;
|
||
}
|
||
function tone(seconds = 1.6, rate = 24000) {
|
||
const n = Math.round(seconds * rate), b = Buffer.alloc(44 + n * 2);
|
||
b.write('RIFF', 0); b.writeUInt32LE(36 + n * 2, 4); b.write('WAVE', 8); b.write('fmt ', 12); b.writeUInt32LE(16, 16); b.writeUInt16LE(1, 20); b.writeUInt16LE(1, 22);
|
||
b.writeUInt32LE(rate, 24); b.writeUInt32LE(rate * 2, 28); b.writeUInt16LE(2, 32); b.writeUInt16LE(16, 34); b.write('data', 36); b.writeUInt32LE(n * 2, 40);
|
||
for (let i = 0; i < n; i++) b.writeInt16LE(Math.round(Math.sin(i / 9) * 6000 * Math.min(1, i / 2000, (n - i) / 2000)), 44 + i * 2);
|
||
return b;
|
||
}
|
||
const known = id => BUILTIN.includes(id) || custom.has(id);
|
||
const item = id => { const r = custom.get(id); return { id, label: r ? r.label : id, source: id.startsWith('cg-') ? 'custom' : 'builtin', selected: selection.voice === id, previewed: previewed.has(id), registered_at: r ? r.registered_at : null, prompt_text: r ? r.prompt_text : null, prompt_wav: r ? `/opt/voice-agent/cosyvoice/voice_samples/${id}.wav` : null }; };
|
||
// A failure set with /__fail applies once, then the endpoint behaves again (a retry can succeed).
|
||
const take = kind => { const f = fail[kind]; delete fail[kind]; return f; };
|
||
const failed = async (res, f, detail) => {
|
||
if (f === 'net') { res.destroy(); return true; }
|
||
if (/^\d+$/.test(String(f))) { send(res, Number(f), { detail }); return true; }
|
||
return false;
|
||
};
|
||
|
||
// A request the page aborts (leaving, switching voice) must not take the mock down with it.
|
||
const handle = async (req, res) => {
|
||
const url = new URL(req.url, 'http://x'), p = url.pathname;
|
||
if (p.startsWith('/api/')) log.push(`${req.method} ${p}${url.search}`);
|
||
if (p === '/__pid') return send(res, 200, { pid: process.pid, mock: 'hel900' });
|
||
if (p === '/__log') return send(res, 200, log.splice(0));
|
||
if (p === '/__uploads') return send(res, 200, uploads);
|
||
if (p === '/__gaveup') return send(res, 200, gaveUp);
|
||
if (p === '/__reset') { reset(); return send(res, 200, { ok: true }); }
|
||
if (p === '/__mode') { mode = url.searchParams.get('list') || 'ok'; return send(res, 200, { mode }); }
|
||
if (p === '/__fail') { fail = Object.fromEntries(url.searchParams); return send(res, 200, fail); }
|
||
if (p === '/__state') return send(res, 200, { selection, previewed: [...previewed], custom: [...custom.keys()] });
|
||
if (p === '/api/health') return send(res, 200, { ok: true, epoch: 3, llm: { ok: true, model: 'mock' }, backend: { life: true, persona: true, receipt: true, web_connected: true }, life_runtime: { state: 'running', timezone: 'Asia/Shanghai', budget_warning: false, budget_stopped: false, last: null }, capabilities: { text: true, proactive: true, voice: true, memory: true } });
|
||
if (p === '/api/companion') return send(res, 200, identity);
|
||
if (p === '/api/messages') return send(res, 200, { messages: [], next_before: null, epoch: 3 });
|
||
if (p === '/api/persona') return send(res, 200, { state: 'ready', interpretation: null, seeds: [], growth: [] });
|
||
if (p === '/api/life' || p === '/api/memories') return send(res, 200, { events: [], memories: [], next_before: null, epoch: 3 });
|
||
if (p === '/api/voice/status') return send(res, 200, { configured: true, tts_ok: true, agent_name: 'cybergril-voice-agent', voice: true });
|
||
|
||
if (p === '/api/voice/voices' && req.method === 'GET') {
|
||
if (mode === 'none') return send(res, 404, { detail: 'Not Found' });
|
||
if (mode === 'off') return send(res, 200, { configured: false, voices: [], selection: null });
|
||
if (mode === 'down') return send(res, 503, { detail: '音色登记服务这会儿不在,稍后再试试。' });
|
||
return send(res, 200, { configured: true, voices: [...BUILTIN, ...custom.keys()].map(item), selection: { ...selection } });
|
||
}
|
||
if (p === '/api/voice/voices' && req.method === 'POST') {
|
||
const data = await body(req), q = url.searchParams, info = wavInfo(data);
|
||
uploads.push({ type: req.headers['content-type'], bytes: data.length, magic: data.toString('ascii', 0, 4), wave: data.toString('ascii', 8, 12), info, label: q.get('label'), prompt_text: q.get('prompt_text'), allow_asr: q.get('allow_asr') });
|
||
const f = take('register');
|
||
if (f === 'slow') await sleep(2500);
|
||
else if (await failed(res, f, f === '503' || f === 503 ? '音色登记服务这会儿不在,稍后再试。' : '登记没有成功。')) return;
|
||
if (!info) return send(res, 422, { detail: '只支持 WAV 格式的参考音频。' });
|
||
if (data.length > 15 * 1024 * 1024) return send(res, 422, { detail: '文件过大(>15MB),请录 5–20 秒的一段。' });
|
||
if (info.seconds < 2) return send(res, 422, { detail: '参考音频太短(至少 2 秒),请录 5–20 秒。' });
|
||
const text = (q.get('prompt_text') || '').trim(), asr = q.get('allow_asr') === 'true';
|
||
if (!text && !asr) return send(res, 422, { detail: '请填写这段音频的参考文字,或明确选择让系统转写(会用到语音识别)。' });
|
||
const id = `cg-${(0x9f2c1a70 + ++made).toString(16)}`, label = (q.get('label') || '').trim() || id;
|
||
const record = { id, label, prompt_text: text || '(模拟转写)今天天气很好,我们出去走走吧。', prompt_text_source: text ? 'user' : 'asr', prompt_wav: `/opt/voice-agent/cosyvoice/voice_samples/${id}.wav`, registered_at: Date.now() };
|
||
custom.set(id, record);
|
||
return send(res, 201, record);
|
||
}
|
||
if (p === '/api/voice/preview' && req.method === 'POST') {
|
||
const { voice, text } = JSON.parse((await body(req)).toString() || '{}');
|
||
log.push(` preview ${voice} ${text ? `"${text}"` : '(default)'}`);
|
||
const f = take('preview');
|
||
if (!voice) return send(res, 422, { detail: '请指定要试听的声音。' });
|
||
if (!known(voice)) return send(res, 404, { detail: '这个声音现在不在列表里。' });
|
||
if (f === 'slow') await sleep(2500);
|
||
else if (f === 'bad') return send(res, 200, '<html>not audio</html>', 'text/html');
|
||
else if (await failed(res, f, '她的声音服务这会儿不在,稍后再试试。')) return;
|
||
previewed.add(voice);
|
||
return send(res, 200, tone(), 'audio/wav');
|
||
}
|
||
if (p === '/api/voice/selection' && req.method === 'GET') return send(res, 200, { ...selection });
|
||
if (p === '/api/voice/selection' && req.method === 'POST') {
|
||
const { voice } = JSON.parse((await body(req)).toString() || '{}');
|
||
const f = take('apply');
|
||
if (await failed(res, f, f === '409' ? '这个声音还没有试听过,先试听再给她用。' : '她的音色状态这会儿写不进,这次没有换成功。')) return;
|
||
if (!known(voice)) return send(res, 404, { detail: '这个声音现在不在列表里。' });
|
||
if (voice.startsWith('cg-') && !previewed.has(voice)) return send(res, 409, { detail: '这个声音还没有试听过,先试听再给她用。' });
|
||
selection = { voice, label: custom.get(voice)?.label || voice, updated_at: Date.now() };
|
||
return send(res, 200, { ...selection });
|
||
}
|
||
if (p.startsWith('/api/')) return send(res, 404, { detail: 'Not Found' });
|
||
const file = normalize(join(dist, p === '/' ? 'index.html' : p));
|
||
if (!file.startsWith(normalize(dist))) return send(res, 403, 'no', 'text/plain');
|
||
try { send(res, 200, await readFile(file), { '.js': 'text/javascript', '.css': 'text/css', '.html': 'text/html; charset=utf-8', '.svg': 'image/svg+xml', '.png': 'image/png', '.jpg': 'image/jpeg', '.webp': 'image/webp' }[extname(file)] || 'application/octet-stream'); }
|
||
catch { send(res, 200, await readFile(join(dist, 'index.html')), 'text/html; charset=utf-8'); }
|
||
};
|
||
createServer((req, res) => { handle(req, res).catch(e => { gaveUp.push(`${req.method} ${req.url}`); console.log(`client gave up: ${req.method} ${req.url} (${e.code || e.message})`); try { res.destroy(); } catch { /* gone */ } }); }).on('error', e => { console.error(`hel900 mock could not listen on ${port}: ${e.code || e.message}`); process.exit(2); })
|
||
.listen(port, '127.0.0.1', () => console.log(`hel900 mock on ${port} pid ${process.pid}`));
|