Improve voice turns, local commands and Spotify controls

This commit is contained in:
2026-11-11 13:34:30 +03:00
parent 095bc51521
commit 0e921617dd
28 changed files with 906 additions and 126 deletions
+1 -1
View File
@@ -97,7 +97,7 @@ export async function handleAdmin(req, res, store) {
json(res, 200, {
settings: store.getSettings(),
history: store.getHistory().reverse(),
spotify: spotifyStatus(),
spotify: { ...spotifyStatus(), playback: store.getDevice() },
});
} else if (route === '/api/admin/settings' && req.method === 'PUT') {
const settings = await readSettings(req);
+6 -4
View File
@@ -1,6 +1,6 @@
import { randomUUID } from 'node:crypto';
import WebSocket from 'ws';
import { searchSpotify } from './spotify.mjs';
import { searchSpotify, playlistTool } from './spotify.mjs';
const spotifyUri = /^spotify:(track|artist|album|playlist|episode):[A-Za-z0-9]{22}$/;
@@ -38,20 +38,22 @@ export function deviceTools(client, signal) {
return true;
},
async execute(name, args) {
if (name !== 'spotify_play') return request(name, args);
if (name === 'spotify_playlist') return playlistTool(args, signal);
const enqueue = name === 'spotify_control' && args.action === 'enqueue';
if (name !== 'spotify_play' && !enqueue) return request(name, args);
let selected;
if (args.uri) {
if (!spotifyUri.test(args.uri)) return { error: 'invalid_spotify_uri' };
selected = { uri: args.uri };
} else {
try {
selected = (await searchSpotify(args.query, signal))[0];
selected = (await searchSpotify(args.query, signal, enqueue ? 'track' : args.type))[0];
} catch {
return { error: 'spotify_search_unavailable', hint: 'Подключи Spotify в пульте Telegram и повтори запрос.' };
}
}
if (!selected) return { error: 'spotify_not_found' };
const result = await request(name, { uri: selected.uri });
const result = await request(name, enqueue ? { action: 'enqueue', uri: selected.uri } : { uri: selected.uri });
return { ...result, selection: selected };
},
};
+17 -2
View File
@@ -13,16 +13,31 @@ const store = openStore();
const server = http.createServer(async (req, res) => {
try {
if (req.method === 'GET' && req.url === '/healthz') { res.writeHead(200, { 'content-type': 'application/json', 'cache-control': 'no-store' }); res.end('{"ok":true}'); return; }
if (req.url === '/v1/device/status' && req.method === 'POST') {
if (!authorizedDevice(req)) { res.writeHead(401); res.end(); return; }
let body = '';
for await (const chunk of req) {
body += chunk;
if (body.length > 14000) { res.writeHead(413); res.end(); return; }
}
const data = JSON.parse(body);
if (!data || typeof data !== 'object' || Array.isArray(data)) { res.writeHead(400); res.end(); return; }
store.recordDevice(data);
res.writeHead(204); res.end(); return;
}
if (await handleAdmin(req, res, store)) return;
res.writeHead(404); res.end();
} catch { if (!res.headersSent) res.writeHead(500); res.end(); }
});
const sockets = new WebSocketServer({ noServer: true, maxPayload: 128 * 1024, perMessageDeflate: false });
let active = false;
server.on('upgrade', (req, socket, head) => {
function authorizedDevice(req) {
const token = req.headers.authorization?.startsWith('Bearer ') ? req.headers.authorization.slice(7) : '';
const a = Buffer.from(token), b = Buffer.from(DEVICE_TOKEN);
if (req.url !== '/v1/voice' || a.length !== b.length || !timingSafeEqual(a, b)) { socket.end('HTTP/1.1 401 Unauthorized\r\nConnection: close\r\n\r\n'); return; }
return a.length === b.length && timingSafeEqual(a, b);
}
server.on('upgrade', (req, socket, head) => {
if (req.url !== '/v1/voice' || !authorizedDevice(req)) { socket.end('HTTP/1.1 401 Unauthorized\r\nConnection: close\r\n\r\n'); return; }
if (active) { socket.end('HTTP/1.1 503 Service Unavailable\r\nConnection: close\r\n\r\n'); return; }
sockets.handleUpgrade(req, socket, head, ws => {
active = true;
+56 -22
View File
@@ -68,15 +68,32 @@ export async function openTts(settings, signal, onAudio) {
return { ws, done, text(text) { if (ws.readyState !== WebSocket.OPEN) throw new Error('tts_closed'); ws.send(JSON.stringify(flash ? { text } : { inputs: [{ text, voice_id: settings.voiceId }] })); }, finish() { if (ws.readyState !== WebSocket.OPEN) throw new Error('tts_closed'); ws.send(JSON.stringify(flash ? { text: '' } : { close_socket: true })); } };
}
const sentenceSegments = new Intl.Segmenter('ru', { granularity: 'sentence' });
function shortReply(text) {
const compact = Array.from(sentenceSegments.segment(text.trim()), part => part.segment).slice(0, 2).join('').trim();
if (compact.length <= 300) return compact;
const end = compact.lastIndexOf(' ', 297);
return compact.slice(0, end > 170 ? end : 297).trimEnd() + '…';
}
export async function streamAnswer(settings, history, userText, signal, onText, executeDeviceTool) {
if (env.LLM_MODE === 'echo') { onText(userText); return userText; }
const question = userText.toLowerCase().replace(/[?!.…]+$/u, '').trim();
if (/^(?:какая (?:это|у тебя) модель|на какой модели ты работаешь|какая у тебя языковая модель)$/u.test(question)) {
const model = settings.llmModel === 'anthropic/claude-haiku-5.5' ? 'Claude Haiku 5.5' : settings.llmModel;
const answer = `Я работаю на ${model}.`;
onText(answer);
return answer;
}
if (!env.OPENROUTER_API_KEY) throw new Error('llm_config');
const moscowDate = new Intl.DateTimeFormat('ru-RU', { timeZone: 'Europe/Moscow', dateStyle: 'long' }).format(new Date());
const systemPrompt = `${settings.systemPrompt}\nСегодня ${moscowDate} (Москва). Используй веб-поиск для актуальных сведений и когда требуется проверить сомнительные факты. Вызывай инструменты без вступительных фраз. Подтверждай воспроизведение музыки только после успешного результата инструмента. Отвечай для озвучивания без Markdown и ссылок, если их не попросили.`;
const systemPrompt = `${settings.systemPrompt}\nСегодня ${moscowDate} (Москва). Используй веб-поиск для актуальных сведений и когда требуется проверить сомнительные факты. Твоя языковая модель: ${settings.llmModel}. Обычно отвечай одной короткой фразой, максимум двумя предложениями. Подробности давай по просьбе. На простой вопрос отвечай сразу, без служебных оговорок, и не возвращайся к предыдущим темам без просьбы. При неясности задай один короткий уточняющий вопрос. Вызывай инструменты без вступительных фраз. Сообщай результат команды один раз. Упоминай громкость, только если её спросили или попросили изменить. Подтверждай трек, только если инструмент вернул актуальный трек. Отвечай для озвучивания без Markdown и ссылок, если их не попросили.`;
const messages = [{ role: 'system', content: systemPrompt }, ...history.slice(-10).flatMap(t => [{ role: 'user', content: t.user }, { role: 'assistant', content: t.assistant }]), { role: 'user', content: userText }];
let answer = '', totalCalls = 0;
const detailed = /подробн|развернут|пошагов|детальн/iu.test(userText);
let totalCalls = 0;
for (let round = 0; round < 4; round++) {
const response = await fetch(llmUrl, { method: 'POST', signal, headers: { Authorization: `Bearer ${env.OPENROUTER_API_KEY}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ model: settings.llmModel, messages, tools, stream: true, max_tokens: 1200, ...(settings.llmModel === 'anthropic/claude-haiku-5.5' ? { reasoning: { enabled: false, effort: 'low' } } : {}) }) });
const response = await fetch(llmUrl, { method: 'POST', signal, headers: { Authorization: `Bearer ${env.OPENROUTER_API_KEY}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ model: settings.llmModel, messages, tools, stream: true, max_tokens: detailed ? 800 : 220, ...(settings.llmModel === 'anthropic/claude-haiku-5.5' ? { reasoning: { enabled: false, effort: 'low' } } : {}) }) });
if (!response.ok || !response.body) throw new Error('llm_error');
let buffer = '', content = '', done = false, finishReason;
const calls = new Map();
@@ -92,10 +109,8 @@ export async function streamAnswer(settings, history, userText, signal, onText,
if (choice.finish_reason) finishReason = choice.finish_reason;
const delta = choice.delta || {};
if (typeof delta.content === 'string' && delta.content) {
const prefix = !content && answer && !/\s$/.test(answer) && !/^\s/.test(delta.content) ? ' ' : '';
content += delta.content; answer += prefix + delta.content;
if (answer.length > 12000) throw new Error('llm_limit');
onText(prefix + delta.content);
content += delta.content;
if (content.length > 12000) throw new Error('llm_limit');
}
for (const part of delta.tool_calls || []) {
if (!Number.isInteger(part.index) || part.index < 0 || part.index >= 4) throw new Error('llm_limit');
@@ -118,28 +133,47 @@ export async function streamAnswer(settings, history, userText, signal, onText,
if (buffer.trim()) consume(buffer);
if (!done || !finishReason) throw new Error('llm_incomplete');
if (!calls.size) {
if (finishReason !== 'stop' || !answer.trim()) throw new Error('llm_incomplete');
if (!['stop', 'length'].includes(finishReason) || !content.trim()) throw new Error('llm_incomplete');
const answer = detailed ? content.trim() : shortReply(content);
onText(answer);
return answer;
}
if (finishReason !== 'tool_calls') throw new Error('llm_incomplete');
const ordered = [...calls.entries()].sort((a, b) => a[0] - b[0]).map(([, call]) => call);
if ((totalCalls += ordered.length) > 4 || round === 3 || ordered.some(c => !c.id || !c.function.name)) throw new Error('llm_limit');
messages.push({ role: 'assistant', content: content || null, tool_calls: ordered });
for (const call of ordered) {
if (signal.aborted) throw new Error('aborted');
let result;
try {
const args = validateTool(call.function.name, JSON.parse(call.function.arguments));
if (typeof executeDeviceTool !== 'function') throw new Error('device_unavailable');
result = await executeDeviceTool(call.function.name, args);
if (signal.aborted) throw new Error('aborted');
result = JSON.stringify(result ?? { ok: true });
if (result.length > 8192) result = JSON.stringify({ error: 'result_too_large' });
} catch (error) {
if (signal.aborted) throw error;
result = JSON.stringify({ error: 'tool_failed' });
const results = new Map();
const groups = [
ordered.filter(call => call.function.name === 'station_volume'),
ordered.filter(call => call.function.name !== 'station_volume'),
];
await Promise.all(groups.map(async group => {
for (const call of group) {
signal.throwIfAborted();
let result;
try {
const args = validateTool(call.function.name, JSON.parse(call.function.arguments));
if (typeof executeDeviceTool !== 'function') throw new Error('device_unavailable');
result = await executeDeviceTool(call.function.name, args);
signal.throwIfAborted();
if (JSON.stringify(result ?? {}).length > 8192) result = { error: 'result_too_large' };
} catch (error) {
if (signal.aborted) throw error;
result = { error: 'tool_failed' };
}
results.set(call.id, result ?? { ok: true });
}
messages.push({ role: 'tool', tool_call_id: call.id, content: result });
}));
if (ordered.length === 1 && ordered[0].function.name === 'spotify_play') {
const result = results.get(ordered[0].id);
const title = result.selection?.name?.trim().slice(0, 110);
let answer;
if (result.accepted === true) answer = title ? `Включаю «${title}».` : 'Включаю музыку.';
if (result.error === 'spotify_not_found') answer = 'В Spotify ничего не нашла.';
if (answer) { onText(answer); return answer; }
}
for (const call of ordered) {
messages.push({ role: 'tool', tool_call_id: call.id, content: JSON.stringify(results.get(call.id)) });
}
}
throw new Error('llm_limit');
+21 -3
View File
@@ -65,8 +65,14 @@ showHistory.onclick = async () => {
};
function renderSpotify(spotify) {
spotifyStatus.textContent = !spotify.configured ? 'Spotify пока не настроен на сервере.' : spotify.connected ? 'Аккаунт подключён.' : 'Подключи аккаунт для управления музыкой.';
const playback = spotify.playback;
if (playback) {
spotifyStatus.textContent += playback.online
? ` Колонка онлайн${playback.active ? ', активна' : ', неактивна'}. ${playback.item?.name || ''}${playback.status === 'paused' ? ' — пауза' : ''}`
: ` Колонка офлайн.${playback.lastPlayback?.item?.name ? ' Последний трек — ' + playback.lastPlayback.item.name + '.' : ''}`;
}
spotifyConnect.disabled = !spotify.configured;
spotifyConnect.textContent = spotify.connected ? 'Подключить другой аккаунт' : 'Подключить Spotify';
spotifyConnect.textContent = spotify.connected ? 'Переподключить Spotify' : 'Подключить Spotify';
}
showSettings.onclick = async () => {
selectTab(false);
@@ -88,7 +94,8 @@ form.onsubmit = async (event) => {
const button = form.querySelector('button');
button.disabled = true;
try {
const body = JSON.stringify(Object.fromEntries(new FormData(form)));
const values = Object.fromEntries(new FormData(form));
const body = JSON.stringify({ ...values, followUpMs: Number(values.followUpMs), activationSound: form.elements.activationSound.checked });
await api('/settings', { method: 'PUT', body });
status.textContent = 'Сохранено. Настройки вступят в силу со следующего запроса.';
} catch (error) {
@@ -119,7 +126,12 @@ if (!telegram?.initData) {
} else {
try {
const data = await api();
for (const [name, value] of Object.entries(data.settings)) form.elements.namedItem(name).value = value;
for (const [name, value] of Object.entries(data.settings)) {
const input = form.elements.namedItem(name);
if (!input) continue;
if (input.type === 'checkbox') input.checked = value === true;
else input.value = value;
}
renderTurns(data.history);
renderSpotify(data.spotify);
status.textContent = '';
@@ -128,3 +140,9 @@ if (!telegram?.initData) {
status.textContent = error.message;
}
}
setInterval(async () => {
if (settings.hidden || !telegram?.initData) return;
try { renderSpotify((await api()).spotify); } catch {}
}, 15000);
+2
View File
@@ -38,6 +38,8 @@
</select></label>
<label>ID голоса ElevenLabs<input name="voiceId" required minlength="20" maxlength="20" spellcheck="false" autocomplete="off"></label>
<label>Системный промпт<textarea name="systemPrompt" required maxlength="4000" rows="6"></textarea></label>
<label>Окно продолжения, мс (0 отключает)<input name="followUpMs" type="number" required min="0" max="10000" step="500"></label>
<label><input name="activationSound" type="checkbox"> Звук активации</label>
<button class="primary">Сохранить</button>
</form>
</section>
+2
View File
@@ -42,3 +42,5 @@ textarea { resize: vertical; }
.spotify-card { background: var(--surface); padding: 16px; border-radius: 15px; margin-bottom: 24px; }
.spotify-card p { color: var(--muted); margin: 5px 0 12px; }
#form input[type="checkbox"] { width: auto; vertical-align: middle; }
+9
View File
@@ -25,6 +25,15 @@ export function quickAction(transcript) {
success: result => result?.accepted === true && ['paused', 'stopped'].includes(result.status),
};
}
if (text === 'громче' || text === 'тише') return {
name: 'station_volume', args: { delta: text === 'громче' ? 10 : -10 }, done: 'Готово.',
failure: 'Не удалось изменить громкость.', success: result => result?.ok === true,
};
const playback = { 'продолжи': 'resume', 'продолжай': 'resume', 'играй': 'resume', 'дальше':'next', 'следующий трек':'next', 'назад':'previous', 'предыдущий трек':'previous' }[text];
if (playback) return {
name: 'spotify_control', args: { action: playback }, done: 'Готово.',
failure: 'Не удалось выполнить команду Spotify.', success: result => result?.accepted === true,
};
const match = text.match(/^(?:(?:поставь|установи|сделай) )?громкость(?: на| до)? (.+?)(?: ?%| процент(?:а|ов)?)?$/);
if (!match) return null;
const level = volumeLevel(match[1]);
+45 -3
View File
@@ -43,7 +43,7 @@ export function startSpotify() {
const verifier = base64url(randomBytes(64));
pending.set(state, { verifier, expires: now + 600_000 });
const url = new URL('https://accounts.spotify.com/authorize');
url.search = new URLSearchParams({ client_id: clientId(), response_type: 'code', redirect_uri: redirectUri(), state, code_challenge_method: 'S256', code_challenge: base64url(createHash('sha256').update(verifier).digest()), scope: 'user-read-playback-state user-modify-playback-state' });
url.search = new URLSearchParams({ client_id: clientId(), response_type: 'code', redirect_uri: redirectUri(), state, code_challenge_method: 'S256', code_challenge: base64url(createHash('sha256').update(verifier).digest()), scope: 'user-read-playback-state user-modify-playback-state playlist-read-private playlist-read-collaborative playlist-modify-private playlist-modify-public' });
return url.toString();
}
async function tokenRequest(params, signal) {
@@ -79,18 +79,60 @@ async function accessToken() {
}
return refreshInFlight;
}
export async function searchSpotify(query, signal) {
export async function searchSpotify(query, signal, type) {
if (typeof query !== 'string' || !query.trim() || query.length > 500) throw new Error('spotify_invalid_query');
const token = await accessToken();
if (signal?.aborted) throw new Error('aborted');
const url = new URL('https://api.spotify.com/v1/search');
url.search = new URLSearchParams({ q: query.trim(), type: 'track,artist,album,playlist', limit: '5' });
url.search = new URLSearchParams({ q: query.trim(), type: type || 'track,artist,album,playlist', limit: '5' });
const response = await fetch(url, { headers: { Authorization: `Bearer ${token}` }, signal });
if (!response.ok) throw new Error('spotify_search_error');
const data = await response.json();
const results = ['tracks', 'artists', 'albums', 'playlists'].flatMap(key => (data[key]?.items || []).filter(item => item?.uri && item?.name).map(item => ({ uri: item.uri, name: item.name, type: item.type, artists: (item.artists || []).map(artist => artist.name), album: item.album?.name || null })));
const normalize = value => value.normalize('NFKC').trim().toLocaleLowerCase().replace(/\s+/g, ' ');
if (type) {
const words = normalize(query).match(/[\p{L}\p{N}]+/gu) || [];
return results.filter(item => item.type === type && words.every(word => normalize([item.name, ...item.artists].join(' ')).includes(word)));
}
const exactArtist = results.find(item => item.type === 'artist' && normalize(item.name) === normalize(query));
if (exactArtist) return [exactArtist, ...results.filter(item => item !== exactArtist)];
return results;
}
export async function spotifyApi(path, { method = 'GET', body, signal } = {}) {
const token = await accessToken();
const response = await fetch('https://api.spotify.com/v1/' + path, {
method, signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(7000)]) : AbortSignal.timeout(7000),
headers: { Authorization: `Bearer ${token}`, ...(body ? { 'Content-Type': 'application/json' } : {}) },
...(body ? { body: JSON.stringify(body) } : {}),
});
if (response.status === 403) return { error: 'spotify_permission_required', hint: 'Переподключи Spotify в пульте, чтобы разрешить работу с плейлистами.' };
if (!response.ok) return { error: 'spotify_request_failed' };
return response.status === 204 ? { ok: true } : response.json();
}
export async function playlistTool(args, signal) {
if (args.action === 'list') {
const data = await spotifyApi('me/playlists?limit=30', { signal });
return data.error ? data : { playlists: (data.items || []).map(p => ({ name: p.name, uri: p.uri })) };
}
if (args.action === 'create') {
const data = await spotifyApi('me/playlists', { method: 'POST', signal, body: { name: args.name, public: false } });
return data.error ? data : { ok: true, name: data.name, uri: data.uri };
}
const id = args.playlistUri.split(':').at(-1);
if (args.action === 'read') {
const data = await spotifyApi(`playlists/${id}/items?limit=15`, { signal });
return data.error ? data : { tracks: (data.items || []).map(entry => {
const item = entry.item || entry.track;
return { name: item?.name, uri: item?.uri, artists: item?.artists?.map(a => a.name) };
}) };
}
let uri = args.trackUri;
if (!uri) uri = (await searchSpotify(args.trackQuery, signal, 'track'))[0]?.uri;
if (!uri) return { error: 'spotify_not_found' };
return spotifyApi(`playlists/${id}/items`, {
method: args.action === 'add' ? 'POST' : 'DELETE', signal,
body: args.action === 'add' ? { uris: [uri] } : { items: [{ uri }] },
});
}
+17 -3
View File
@@ -4,6 +4,8 @@ import { join } from 'node:path';
export const defaults = Object.freeze({
llmModel: 'anthropic/claude-haiku-5.5',
sttModel: 'scribe_v3_live',
followUpMs: 3000,
activationSound: false,
ttsModel: 'eleven_v4_turbo',
voiceId: '21m00Tcm4TlvDq8ikWAM',
systemPrompt: 'Ты голосовой помощник Алиса. Отвечай по-русски, коротко и по делу. Пиши так, чтобы ответ хорошо звучал вслух: обычный текст, без Markdown. Если не знаешь ответа, скажи об этом прямо.',
@@ -14,12 +16,13 @@ export const ttsModels = ['eleven_v4_turbo', 'eleven_v3_conversational', 'eleven
export function validateSettings(input) {
if (typeof input !== 'object' || input === null) return null;
const { llmModel, sttModel, ttsModel, voiceId, systemPrompt } = input;
const { llmModel, sttModel, ttsModel, voiceId, systemPrompt, followUpMs = defaults.followUpMs, activationSound = defaults.activationSound } = input;
if (typeof llmModel !== 'string' || !/^[\w.~:-]+\/[\w.:~-]+$/.test(llmModel) || llmModel.length > 120) return null;
if (!sttModels.includes(sttModel) || !ttsModels.includes(ttsModel)) return null;
if (typeof voiceId !== 'string' || !/^[a-zA-Z0-9]{20}$/.test(voiceId)) return null;
if (typeof systemPrompt !== 'string' || !systemPrompt.trim() || systemPrompt.length > 4000) return null;
return { llmModel, sttModel, ttsModel, voiceId, systemPrompt: systemPrompt.trim() };
if (!Number.isInteger(followUpMs) || followUpMs < 0 || followUpMs > 10000 || typeof activationSound !== 'boolean') return null;
return { llmModel, sttModel, ttsModel, voiceId, systemPrompt: systemPrompt.trim(), followUpMs, activationSound };
}
export function openStore(directory = process.env.DATA_DIR ?? './data') {
@@ -30,7 +33,7 @@ export function openStore(directory = process.env.DATA_DIR ?? './data') {
const saved = JSON.parse(readFileSync(path, 'utf8'));
const settings = validateSettings({ ...defaults, ...saved.settings });
if (!settings || !Array.isArray(saved.history)) throw new Error('Invalid assistant state');
state = { settings, history: saved.history };
state = { settings, history: saved.history, device: saved.device };
} catch (error) {
if (error.code !== 'ENOENT') throw error;
}
@@ -43,6 +46,17 @@ export function openStore(directory = process.env.DATA_DIR ?? './data') {
}
return {
getDevice: () => {
if (!state.device) return null;
return { ...state.device, online: Date.now() - state.device.updatedAt < 45000 };
},
recordDevice(device) {
const updatedAt = Date.now();
const lastPlayback = device.item?.uri && device.active
? { item: device.item, context: device.context, position: device.position, status: device.status, updatedAt }
: state.device?.lastPlayback;
commit({ ...state, device: { ...device, updatedAt, lastPlayback } });
},
getSettings: () => ({ ...state.settings }),
getHistory: () => state.history.map(turn => ({ ...turn })),
updateSettings(settings) {
+37 -6
View File
@@ -1,20 +1,51 @@
// OpenRouter executes web search itself; Spotify calls are handled by the device.
const spotifyTypes = ['track', 'artist', 'album', 'playlist'];
const actions = {
pause: {}, resume: {}, next: {}, previous: {}, status: {}, queue: {},
volume: { volume: { type: 'integer', minimum: 0, maximum: 100 } },
seek: { positionMs: { type: 'integer', minimum: 0, maximum: 86400000 } },
shuffle: { enabled: { type: 'boolean' } },
repeat: { mode: { enum: ['off', 'track', 'context'] } },
enqueue: { query: { type: 'string', maxLength: 500 } },
};
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 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 } } },
{ type: 'function', function: { name: 'spotify_play', description: 'Play a track, artist, album or playlist on Spotify. Pass type when the user names a kind of content. Normalize known transliterations.', parameters: { type: 'object', properties: { query: { type: 'string', maxLength: 500 }, uri: { type: 'string', maxLength: 500 }, type: { type: 'string', enum: spotifyTypes } }, additionalProperties: false } } },
{ type: 'function', function: { name: 'spotify_control', description: 'Control Spotify on the station. Use status for what is playing, queue to read upcoming tracks, enqueue to add a track by name, seek with an absolute position in milliseconds, and repeat with track, context (album or playlist), or off.', parameters: { type: 'object', properties: { action: { type: 'string', enum: Object.keys(actions) }, ...Object.assign({}, ...Object.values(actions)) }, required: ['action'], additionalProperties: false } } },
{ type: 'function', function: { name: 'spotify_playlist', description: 'List own playlists, read tracks, create a private playlist, or add/remove a track. Use playlistUri for an existing playlist, trackUri or trackQuery for a track, and name when creating.', parameters: { type: 'object', properties: {
action: { enum: ['list', 'read', 'create', 'add', 'remove'] }, name: { type: 'string', maxLength: 100 },
playlistUri: { type: 'string' }, trackUri: { type: 'string' }, trackQuery: { type: 'string', maxLength: 500 },
}, 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 }, delta: { type: 'integer', enum: [-10, 10] } }, additionalProperties: false } } },
];
function validValue(value, schema) {
if (schema.enum) return schema.enum.includes(value);
if (schema.type === 'integer') return Number.isInteger(value) && value >= schema.minimum && value <= schema.maximum;
if (schema.type === 'boolean') return typeof value === 'boolean';
return typeof value === 'string' && !!value.trim() && value.length <= schema.maxLength;
}
export function validateTool(name, args) {
if (!args || typeof args !== 'object' || Array.isArray(args)) throw new Error('invalid_arguments');
const keys = Object.keys(args);
if (name === 'spotify_play') {
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');
if (keys.some(k => !['query', 'uri', 'type'].includes(k)) || (!args.query && !args.uri) ||
keys.some(k => k === 'type' ? !spotifyTypes.includes(args[k]) : !validValue(args[k], { maxLength: 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');
if (!Object.hasOwn(actions, args.action)) throw new Error('invalid_arguments');
const fields = Object.entries(actions[args.action]);
if (keys.length !== fields.length + 1 || fields.some(([key, schema]) => !validValue(args[key], schema))) throw new Error('invalid_arguments');
} else if (name === 'spotify_playlist') {
const required = { list: [], read: ['playlistUri'], create: ['name'], add: ['playlistUri'], remove: ['playlistUri'] }[args.action];
if (!required || keys.some(k => !['action', 'name', 'playlistUri', 'trackUri', 'trackQuery'].includes(k)) ||
required.some(k => !args[k]) || keys.some(k => typeof args[k] !== 'string' || args[k].length > 500)) throw new Error('invalid_arguments');
if (args.playlistUri && !/^spotify:playlist:[A-Za-z0-9]{22}$/.test(args.playlistUri)) throw new Error('invalid_arguments');
if (args.trackUri && !/^spotify:track:[A-Za-z0-9]{22}$/.test(args.trackUri)) throw new Error('invalid_arguments');
if (['add', 'remove'].includes(args.action) && !args.trackUri && !args.trackQuery) 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');
if (keys.length !== 1 || ('delta' in args ? ![-10, 10].includes(args.delta) : !Number.isInteger(args.level) || args.level < 0 || args.level > 100)) throw new Error('invalid_arguments');
} else throw new Error('unknown_tool');
return args;
}
+6 -3
View File
@@ -14,7 +14,7 @@ export function handleTurn(client, store) {
let state = 'waiting', stt, tts, bytes = 0, received = 0, messages = 0, ended = false, terminal = false, wake = false;
let pending = [];
let pendingBytes = 0;
const timeout = setTimeout(() => fail('timeout'), 120000);
let timeout = setTimeout(() => fail('timeout'), 120000);
const send = obj => { if (client.readyState === WebSocket.OPEN) client.send(JSON.stringify(obj)); };
function cleanup() {
clearTimeout(timeout);
@@ -47,7 +47,7 @@ export function handleTurn(client, store) {
text = text.replace(/^[«"“]?алиса(?:[»"”.,!?…:;\s–—-]+|$)/iu, '');
if (!text) return complete('', '');
}
if (!text) return fail('empty_transcript');
if (!text || /^(?:стоп|хватит)[.!?…]*$/iu.test(text)) return complete('', '');
send({ type: 'transcript', text });
try {
const action = quickAction(text);
@@ -103,6 +103,8 @@ export function handleTurn(client, store) {
if (!pendingBytes) return fail('empty_audio');
ended = true;
state = 'processing';
clearTimeout(timeout);
timeout = setTimeout(() => fail('response_timeout'), 45000);
sendChunk(Buffer.concat(pending, pendingBytes), true);
pending = [];
pendingBytes = 0;
@@ -111,5 +113,6 @@ export function handleTurn(client, store) {
});
client.on('error', () => { if (!terminal) { terminal = true; cleanup(); } });
client.on('close', () => { if (!terminal) { terminal = true; cleanup(); } });
send({ type: 'ready' });
const { followUpMs, activationSound } = store.getSettings();
send({ type: 'ready', followUpMs, activationSound });
}