Tighten wake detection and keep short commands quiet

This commit is contained in:
2026-11-10 22:35:13 +03:00
parent 6b483c9c08
commit a27589447e
20 changed files with 833 additions and 92 deletions
+1 -1
View File
@@ -25,7 +25,7 @@ function connect(url, signal) {
}
export async function openStt(settings, signal, onPartial, onFinal, onFailure) {
const ws = await connect(endpoint(sttUrl, { model_id: settings.sttModel, audio_format: 'pcm_16000', language_code: 'ru', commit_strategy: 'manual' }), signal);
const ws = await connect(endpoint(sttUrl, { model_id: settings.sttModel, audio_format: 'pcm_16000', language_code: 'ru', commit_strategy: 'manual', filter_background_audio: 'true' }), signal);
let final = false;
ws.on('message', data => {
try {
+39
View File
@@ -0,0 +1,39 @@
const units = 'ноль один два три четыре пять шесть семь восемь девять десять одиннадцать двенадцать тринадцать четырнадцать пятнадцать шестнадцать семнадцать восемнадцать девятнадцать'.split(' ');
const tens = 'двадцать тридцать сорок пятьдесят шестьдесят семьдесят восемьдесят девяносто'.split(' ');
function volumeLevel(text) {
if (/^\d{1,3}$/.test(text)) return Number(text);
if (text === 'сто') return 100;
const words = text.split(' ');
if (words.length === 1 && units.includes(words[0])) return units.indexOf(words[0]);
const decade = tens.indexOf(words[0]);
if (decade === -1) return -1;
if (words.length === 1) return (decade + 2) * 10;
const unit = units.indexOf(words[1]);
return words.length === 2 && unit >= 1 && unit <= 9 ? (decade + 2) * 10 + unit : -1;
}
export function quickAction(transcript) {
const text = transcript.toLowerCase().replace(/[.,!?;:…\s]+/gu, ' ').trim()
.replace(/^алиса\s+/, '').replace(/^пожалуйста\s+|\s+пожалуйста$/g, '');
if (/^(?:пауза|на паузу|(?:поставь|поставить)(?: музыку| воспроизведение)? на паузу|(?:приостанови|выключи|останови) (?:музыку|воспроизведение))$/.test(text)) {
return {
name: 'spotify_control',
args: { action: 'pause' },
done: 'Музыка на паузе.',
failure: 'Не удалось поставить музыку на паузу.',
success: result => result?.accepted === true && ['paused', 'stopped'].includes(result.status),
};
}
const match = text.match(/^(?:(?:поставь|установи|сделай) )?громкость(?: на| до)? (.+?)(?: ?%| процент(?:а|ов)?)?$/);
if (!match) return null;
const level = volumeLevel(match[1]);
if (level < 0 || level > 100) return null;
return {
name: 'station_volume',
args: { level },
done: `Громкость ${level}%.`,
failure: 'Не удалось изменить громкость колонки.',
success: result => result?.ok === true && result.level === level,
};
}
+4 -1
View File
@@ -2,7 +2,8 @@
export const tools = [
{ type: 'openrouter:web_search' },
{ type: 'function', function: { name: 'spotify_play', description: 'Play a track, artist, album or playlist on Spotify by search query or Spotify URI. Normalize Russian transliterations of artist names to their canonical spelling when known.', parameters: { type: 'object', properties: { query: { type: 'string', maxLength: 500 }, uri: { type: 'string', maxLength: 500 } }, additionalProperties: false } } },
{ type: 'function', function: { name: 'spotify_control', description: 'Control Spotify playback or set volume.', parameters: { type: 'object', properties: { action: { type: 'string', enum: ['pause', 'resume', 'next', 'previous', 'volume'] }, volume: { type: 'integer', minimum: 0, maximum: 100 } }, required: ['action'], additionalProperties: false } } }
{ type: 'function', function: { name: 'spotify_control', description: 'Control Spotify playback or set the Spotify stream volume.', parameters: { type: 'object', properties: { action: { type: 'string', enum: ['pause', 'resume', 'next', 'previous', 'volume'] }, volume: { type: 'integer', minimum: 0, maximum: 100 } }, required: ['action'], additionalProperties: false } } },
{ type: 'function', function: { name: 'station_volume', description: 'Set the overall speaker volume for both speech and music. Use this for a general volume request.', parameters: { type: 'object', properties: { level: { type: 'integer', minimum: 0, maximum: 100 } }, required: ['level'], additionalProperties: false } } },
];
export function validateTool(name, args) {
@@ -12,6 +13,8 @@ export function validateTool(name, args) {
if (keys.some(k => !['query', 'uri'].includes(k)) || !keys.length || keys.some(k => typeof args[k] !== 'string' || !args[k].trim() || args[k].length > 500)) throw new Error('invalid_arguments');
} else if (name === 'spotify_control') {
if (keys.some(k => !['action', 'volume'].includes(k)) || !['pause', 'resume', 'next', 'previous', 'volume'].includes(args.action) || (args.action === 'volume' ? !Number.isInteger(args.volume) || args.volume < 0 || args.volume > 100 : 'volume' in args)) throw new Error('invalid_arguments');
} else if (name === 'station_volume') {
if (keys.length !== 1 || !Number.isInteger(args.level) || args.level < 0 || args.level > 100) throw new Error('invalid_arguments');
} else throw new Error('unknown_tool');
return args;
}
+35 -9
View File
@@ -1,15 +1,19 @@
import WebSocket from 'ws';
import { openStt, openTts, streamAnswer } from './providers.mjs';
import { deviceTools } from './device.mjs';
import { quickAction } from './quick-actions.mjs';
const MAX_AUDIO = 60 * 16000 * 2;
const STT_CHUNK_BYTES = 3200; // 100 ms of mono PCM16 at 16 kHz.
const MAX_BUFFERED = 2 * 1024 * 1024;
export function handleTurn(client, store) {
const controller = new AbortController();
const { signal } = controller;
const device = deviceTools(client, signal);
let state = 'waiting', stt, tts, pending, bytes = 0, received = 0, messages = 0, ended = false, terminal = false;
let state = 'waiting', stt, tts, bytes = 0, received = 0, messages = 0, ended = false, terminal = false;
let pending = [];
let pendingBytes = 0;
const timeout = setTimeout(() => fail('timeout'), 120000);
const send = obj => { if (client.readyState === WebSocket.OPEN) client.send(JSON.stringify(obj)); };
function cleanup() {
@@ -27,6 +31,14 @@ export function handleTurn(client, store) {
if (!stt || stt.readyState !== WebSocket.OPEN || stt.bufferedAmount > MAX_BUFFERED) return fail('stt_unavailable');
stt.send(JSON.stringify({ message_type: 'input_audio_chunk', audio_base_64: chunk.toString('base64'), ...(commit ? { commit: true } : {}) }));
}
function complete(text, answer) {
store.recordTurn(text, answer);
terminal = true;
send({ type: 'done' });
cleanup();
if (client.readyState === WebSocket.OPEN) client.close(1000);
}
async function respond(text, settings) {
if (state !== 'processing' || terminal) return;
state = 'responding';
@@ -34,19 +46,24 @@ export function handleTurn(client, store) {
if (!text) return fail('empty_transcript');
send({ type: 'transcript', text });
try {
const action = quickAction(text);
if (action) {
const result = await device.execute(action.name, action.args).catch(() => null);
if (terminal) return;
if (action.success(result)) return complete(text, action.done);
}
tts = await openTts(settings, signal, audio => {
if (terminal || client.readyState !== WebSocket.OPEN) return;
if (client.bufferedAmount > MAX_BUFFERED) return fail('client_too_slow');
client.send(audio, { binary: true });
});
if (terminal) return;
const answer = await streamAnswer(settings, store.getHistory(), text, signal, part => tts.text(part), device.execute);
const answer = action?.failure ?? await streamAnswer(settings, store.getHistory(), text, signal, part => tts.text(part), device.execute);
if (action) tts.text(answer);
tts.finish();
await tts.done;
if (terminal) return;
store.recordTurn(text, answer);
terminal = true; send({ type: 'done' }); cleanup();
if (client.readyState === WebSocket.OPEN) client.close(1000);
complete(text, answer);
} catch { fail('upstream_error'); }
}
let settings;
@@ -59,8 +76,13 @@ export function handleTurn(client, store) {
if (state !== 'recording') return fail('invalid_state');
const audio = Buffer.from(data);
if (!audio.length || audio.length % 2 || (bytes += audio.length) > MAX_AUDIO) return fail('invalid_audio');
if (pending) sendChunk(pending);
pending = audio;
if (pendingBytes >= STT_CHUNK_BYTES) {
sendChunk(Buffer.concat(pending, pendingBytes));
pending = [];
pendingBytes = 0;
}
pending.push(audio);
pendingBytes += audio.length;
return;
}
let msg;
@@ -74,8 +96,12 @@ export function handleTurn(client, store) {
state = 'recording';
} catch { fail('stt_error'); }
} else if (msg?.type === 'end' && state === 'recording') {
if (!pending) return fail('empty_audio');
ended = true; state = 'processing'; sendChunk(pending, true); pending = null;
if (!pendingBytes) return fail('empty_audio');
ended = true;
state = 'processing';
sendChunk(Buffer.concat(pending, pendingBytes), true);
pending = [];
pendingBytes = 0;
} else fail('invalid_state');
}).catch(() => fail('internal_error'));
});