131 lines
12 KiB
JavaScript
131 lines
12 KiB
JavaScript
// HEL-903 isolated contract mock: the HEL-878 voice session (fake LiveKit via tests/fake-livekit.js) and the HEL-900
|
|
// custom-voice endpoints in one process, answering as src/cybergril/voice/router.py does at b09a907 — the session
|
|
// answer carries `voice` (selection if still listed, else "default"), /api/voice/status carries configured/tts_ok.
|
|
// Adds the failures this card handles: a registration the panel filed while the answer was lost (500 / dropped).
|
|
// Synthetic data only: no voice panel, ASR, TTS, LiveKit or network beyond 127.0.0.1.
|
|
// Usage: node tests/hel903_mock.mjs <port>. Control GETs: /__status?mode=ok|down|off|none|500|net,
|
|
// /__session-voice?v=<id>|omit|(empty: as the server), /__fail?register=503|500|net|commit500|commitnet,
|
|
// /__select?voice=<id> (another device applies a voice), /__reset, /__log (drains), /__uploads, /__state, /__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)), fake = fileURLToPath(new URL('./fake-livekit.js', import.meta.url));
|
|
const port = Number(process.argv[2] || 8903);
|
|
const T0 = Date.UTC(2026, 9, 27, 12, 0);
|
|
const identity = { id: '1', name: '栖', birth: '2000-03-14', hour: '子', relation: '朋友', nickname: '', boundary: '', color: { pillars: { year: '庚辰', month: '己卯', day: '丙午', hour: '戊子' }, traits: '合成测试档案' } };
|
|
const BUILTIN = ['bailu', 'default', 'female_soft', 'male_warm', 'rain', 'xiaoyun'];
|
|
const log = [], uploads = [], sessions = new Map();
|
|
let statusMode = 'ok', sessionVoice = '', fail = {}, custom = new Map(), orphans = new Set(), previewed = new Set(), selection = { voice: null, label: '', updated_at: null }, made = 0, rooms = 0;
|
|
const reset = () => { statusMode = 'ok'; sessionVoice = ''; fail = {}; custom = new Map(); orphans = new Set(); previewed = new Set(); selection = { voice: null, label: '', updated_at: null }; made = 0; log.splice(0); uploads.splice(0); sessions.clear(); };
|
|
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 listed = () => [...BUILTIN, ...custom.keys(), ...orphans];
|
|
const known = id => listed().includes(id);
|
|
// An orphan is in the shared panel only: no CyberGril metadata, so the router lists it with label = 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 ? r.prompt_wav : null }; };
|
|
const take = kind => { const f = fail[kind]; delete fail[kind]; return f; };
|
|
const newId = () => `cg-${(0x5e7a0000 + ++made).toString(16)}`;
|
|
|
|
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: 'hel903' });
|
|
if (p === '/__log') return send(res, 200, log.splice(0));
|
|
if (p === '/__uploads') return send(res, 200, uploads);
|
|
if (p === '/__reset') { reset(); return send(res, 200, { ok: true }); }
|
|
if (p === '/__status') { statusMode = url.searchParams.get('mode') || 'ok'; return send(res, 200, { statusMode }); }
|
|
if (p === '/__session-voice') { sessionVoice = url.searchParams.get('v') || ''; return send(res, 200, { sessionVoice }); }
|
|
if (p === '/__fail') { fail = Object.fromEntries(url.searchParams); return send(res, 200, fail); }
|
|
if (p === '/__select') { const v = url.searchParams.get('voice'); selection = { voice: v, label: custom.get(v)?.label || v, updated_at: Date.now() }; return send(res, 200, selection); }
|
|
if (p === '/__state') return send(res, 200, { selection, custom: [...custom.keys()], orphans: [...orphans], open: [...sessions.keys()], rooms });
|
|
if (p.startsWith('/vendor/livekit-client')) return send(res, 200, await readFile(fake), 'text/javascript');
|
|
|
|
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: false, memory: true } });
|
|
if (p === '/api/companion') return send(res, 200, identity);
|
|
if (p === '/api/messages') return send(res, 200, { messages: [{ id: 1, ts: T0, role: 'user', text: '今天下雨了吗?', turn_id: 't1', status: 'sent', lifeIds: [] }, { id: 2, ts: T0 + 6e4, role: 'companion', text: '下了一点,窗台上还湿着。', turn_id: 't1', status: 'sent', lifeIds: [] }], 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') {
|
|
if (statusMode === 'none') return send(res, 404, { detail: 'Not Found' });
|
|
if (statusMode === '500') return send(res, 500, 'Internal Server Error', 'text/plain');
|
|
if (statusMode === 'net') { res.destroy(); return; }
|
|
if (statusMode === 'off') return send(res, 200, { configured: false, tts_ok: false, agent_name: null, voice: false });
|
|
return send(res, 200, { configured: true, tts_ok: statusMode === 'ok', agent_name: 'cybergril-voice-agent', voice: false, livekit_url: 'wss://lk.invalid' });
|
|
}
|
|
if (p === '/api/voice/session' && req.method === 'POST') {
|
|
if (statusMode !== 'ok') return send(res, 503, { detail: '她的声音服务这会儿不在,稍后再试试。' });
|
|
await sleep(120);
|
|
// As _capture_voice: a still-listed selection, else "default"; captured once, at opening.
|
|
const captured = selection.voice && known(selection.voice) ? selection.voice : 'default';
|
|
const id = `sess-${++rooms}`; sessions.set(id, captured);
|
|
const grant = { url: 'wss://lk.invalid', token: `token-${id}`, room: `cg-voice-${rooms}`, session_id: id, agent_name: 'cybergril-voice-agent', epoch: 3, expires_at: Date.now() + 2 * 3600e3, voice: sessionVoice && sessionVoice !== 'omit' ? sessionVoice : captured };
|
|
if (sessionVoice === 'omit') delete grant.voice;
|
|
return send(res, 201, grant);
|
|
}
|
|
if (p.startsWith('/api/voice/session/') && req.method === 'DELETE') { const id = decodeURIComponent(p.slice(19)); return sessions.delete(id) ? send(res, 200, { ended: true }) : send(res, 404, { detail: '这次通话已经不在了。' }); }
|
|
|
|
if (p === '/api/voice/voices' && req.method === 'GET') return send(res, 200, { configured: true, voices: listed().map(item), selection: { ...selection } });
|
|
if (p === '/api/voice/voices' && req.method === 'POST') {
|
|
const data = await body(req), q = url.searchParams, info = wavInfo(data), f = take('register');
|
|
uploads.push({ type: req.headers['content-type'], bytes: data.length, info, label: q.get('label'), prompt_text: q.get('prompt_text'), allow_asr: q.get('allow_asr'), fail: f || '' });
|
|
// The panel took it, then the local metadata write failed (HEL-902 §4: OSError → 500) or the answer was lost.
|
|
// `commitnet` cuts the answer mid-body (a reset before any byte would let Chromium silently resend the POST on a
|
|
// reused socket, which is not the case this card covers).
|
|
if (f === 'commit500' || f === 'commitnet') { const lost = newId(); orphans.add(lost); if (f === 'commitnet') { res.writeHead(201, { 'Content-Type': 'application/json; charset=utf-8', 'Content-Length': '400' }); res.write(`{"id":"${lost}","la`); setTimeout(() => res.destroy(), 50); return; } return send(res, 500, 'Internal Server Error', 'text/plain'); }
|
|
if (f === 'net') { res.destroy(); return; }
|
|
if (f === '503') return send(res, 503, { detail: '音色登记服务这会儿不在,稍后再试试。' });
|
|
if (f === '500') return send(res, 500, 'Internal Server Error', 'text/plain');
|
|
if (!info) return send(res, 422, { detail: '只支持 WAV 格式的参考音频。' });
|
|
const text = (q.get('prompt_text') || '').trim(), asr = q.get('allow_asr') === 'true';
|
|
if (!text && !asr) return send(res, 422, { detail: '请填写这段音频的参考文字,或明确选择让系统转写(会用到语音识别)。' });
|
|
const id = newId(), 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 } = JSON.parse((await body(req)).toString() || '{}');
|
|
if (!known(voice)) return send(res, 404, { detail: '这个声音现在不在列表里。' });
|
|
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() || '{}');
|
|
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 => { console.log(`client gave up: ${req.method} ${req.url} (${e.code || e.message})`); try { res.destroy(); } catch { /* gone */ } }); })
|
|
.on('error', e => { console.error(`hel903 mock could not listen on ${port}: ${e.code || e.message}`); process.exit(2); })
|
|
.listen(port, '127.0.0.1', () => console.log(`hel903 mock on ${port} pid ${process.pid}`));
|