Add Spotify playback, web search, and Mini 2 autostart

This commit is contained in:
2026-11-10 15:54:23 +03:00
parent 76a0eb86d0
commit 58d28c7683
31 changed files with 1282 additions and 64 deletions
+14 -2
View File
@@ -1,6 +1,7 @@
import { createHmac, timingSafeEqual } from 'node:crypto';
import { readFileSync } from 'node:fs';
import { validateSettings } from './store.mjs';
import { spotifyStatus, startSpotify, finishSpotify } from './spotify.mjs';
const assets = new Map([
['/', ['index.html', 'text/html; charset=utf-8']],
@@ -75,17 +76,28 @@ export async function handleAdmin(req, res, store) {
return true;
}
if (route !== '/api/admin' && route !== '/api/admin/settings' && route !== '/api/admin/history') return false;
if (route === '/api/spotify/callback' && req.method === 'GET') {
const params = new URL(req.url, 'http://localhost').searchParams;
let success = false;
try { await finishSpotify(params.get('state'), params.get('code')); success = true; } catch {}
res.writeHead(success ? 200 : 400, { ...securityHeaders, 'content-type': 'text/html; charset=utf-8' });
res.end(success ? '<!doctype html><html lang="ru"><meta charset="utf-8"><title>Spotify подключён</title><p>Spotify подключён. Вернитесь в пульт.</p></html>' : '<!doctype html><html lang="ru"><meta charset="utf-8"><title>Ошибка подключения</title><p>Не удалось подключить Spotify. Попробуйте снова из пульта.</p></html>');
return true;
}
if (route !== '/api/admin' && route !== '/api/admin/settings' && route !== '/api/admin/history' && route !== '/api/spotify/start') return false;
const auth = req.headers.authorization ?? '';
if (!auth.startsWith('tma ') || !verifyTelegram(auth.slice(4), process.env.TELEGRAM_BOT_TOKEN, process.env.TELEGRAM_OWNER_ID)) {
json(res, 401, { error: 'telegram_auth' });
return true;
}
if (route === '/api/admin' && req.method === 'GET') {
if (route === '/api/spotify/start' && req.method === 'POST') {
try { json(res, 200, { url: startSpotify() }); } catch { json(res, 503, { error: 'spotify_not_configured' }); }
} else if (route === '/api/admin' && req.method === 'GET') {
json(res, 200, {
settings: store.getSettings(),
history: store.getHistory().reverse(),
spotify: spotifyStatus(),
});
} else if (route === '/api/admin/settings' && req.method === 'PUT') {
const settings = await readSettings(req);
+58
View File
@@ -0,0 +1,58 @@
import { randomUUID } from 'node:crypto';
import WebSocket from 'ws';
import { searchSpotify } from './spotify.mjs';
const spotifyUri = /^spotify:(track|artist|album|playlist|episode):[A-Za-z0-9]{22}$/;
export function deviceTools(client, signal) {
const pending = new Map();
signal.addEventListener('abort', () => {
for (const { reject, timeout } of pending.values()) {
clearTimeout(timeout);
reject(new Error('device_disconnected'));
}
pending.clear();
}, { once: true });
function request(name, args) {
if (signal.aborted || client.readyState !== WebSocket.OPEN) throw new Error('device_disconnected');
const id = randomUUID();
return new Promise((resolve, reject) => {
const timeout = setTimeout(() => {
pending.delete(id);
reject(new Error('device_tool_timeout'));
}, 17000);
pending.set(id, { resolve, reject, timeout });
client.send(JSON.stringify({ type: 'device_tool', id, name, arguments: args }));
});
}
return {
accept(message) {
if (message?.type !== 'device_tool_result') return false;
const call = pending.get(message.id);
if (!call) return true;
clearTimeout(call.timeout);
pending.delete(message.id);
call.resolve(message.result ?? { error: 'empty_device_result' });
return true;
},
async execute(name, args) {
if (name !== 'spotify_play') 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];
} catch {
return { error: 'spotify_search_unavailable', hint: 'Подключи Spotify в пульте Telegram и повтори запрос.' };
}
}
if (!selected) return { error: 'spotify_not_found' };
const result = await request(name, { uri: selected.uri });
return { ...result, selection: selected };
},
};
}
+73 -24
View File
@@ -1,4 +1,5 @@
import WebSocket from 'ws';
import { tools, validateTool } from './tools.mjs';
const env = process.env;
const sttUrl = env.ELEVEN_STT_URL || 'wss://api.elevenlabs.io/v1/speech-to-text/realtime';
@@ -64,31 +65,79 @@ 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 })); } };
}
export async function streamAnswer(settings, history, userText, signal, onText) {
export async function streamAnswer(settings, history, userText, signal, onText, executeDeviceTool) {
if (env.LLM_MODE === 'echo') { onText(userText); return userText; }
if (!env.OPENROUTER_API_KEY) throw new Error('llm_config');
const messages = [{ role: 'system', content: settings.systemPrompt }, ...history.slice(-10).flatMap(t => [{ role: 'user', content: t.user }, { role: 'assistant', content: t.assistant }]), { role: 'user', content: userText }];
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, stream: true, max_tokens: 512 }) });
if (!response.ok || !response.body) throw new Error('llm_error');
let buffer = '', answer = '', finished = false;
const decoder = new TextDecoder();
const consume = event => {
const payload = event.split(/\r?\n/).filter(line => line.startsWith('data:')).map(line => line.slice(5).trimStart()).join('\n');
if (!payload) return;
if (payload === '[DONE]') { finished = true; return; }
const message = JSON.parse(payload);
if (message.error) throw new Error('llm_error');
const content = message.choices?.[0]?.delta?.content;
if (typeof content === 'string' && content) { answer += content; if (answer.length > 12000) throw new Error('llm_limit'); onText(content); }
};
for await (const chunk of response.body) {
buffer += decoder.decode(chunk, { stream: true });
if (buffer.length > 65536) throw new Error('llm_limit');
let match;
while ((match = /\r?\n\r?\n/.exec(buffer))) { consume(buffer.slice(0, match.index)); buffer = buffer.slice(match.index + match[0].length); }
const moscowDate = new Intl.DateTimeFormat('ru-RU', { timeZone: 'Europe/Moscow', dateStyle: 'long' }).format(new Date());
const systemPrompt = `${settings.systemPrompt}\nСегодня ${moscowDate} (Москва). Используй веб-поиск для актуальных сведений и когда требуется проверить сомнительные факты. Вызывай инструменты без вступительных фраз. Подтверждай воспроизведение музыки только после успешного результата инструмента. Отвечай для озвучивания без 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;
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' } } : {}) }) });
if (!response.ok || !response.body) throw new Error('llm_error');
let buffer = '', content = '', done = false, finishReason;
const calls = new Map();
const decoder = new TextDecoder();
const consume = event => {
const payload = event.split(/\r?\n/).filter(line => line.startsWith('data:')).map(line => line.slice(5).trimStart()).join('\n');
if (!payload) return;
if (payload === '[DONE]') { done = true; return; }
const message = JSON.parse(payload);
if (message.error) throw new Error('llm_error');
const choice = message.choices?.[0];
if (!choice) return;
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);
}
for (const part of delta.tool_calls || []) {
if (!Number.isInteger(part.index) || part.index < 0 || part.index >= 4) throw new Error('llm_limit');
const call = calls.get(part.index) || { id: '', type: 'function', function: { name: '', arguments: '' } };
if (part.id) call.id += part.id;
if (part.type && part.type !== 'function') throw new Error('llm_error');
if (part.function?.name) call.function.name += part.function.name;
if (part.function?.arguments) call.function.arguments += part.function.arguments;
if (call.id.length > 512 || call.function.name.length > 128 || call.function.arguments.length > 8192) throw new Error('llm_limit');
calls.set(part.index, call);
}
};
for await (const chunk of response.body) {
buffer += decoder.decode(chunk, { stream: true });
if (buffer.length > 65536) throw new Error('llm_limit');
let match;
while ((match = /\r?\n\r?\n/.exec(buffer))) { consume(buffer.slice(0, match.index)); buffer = buffer.slice(match.index + match[0].length); }
}
buffer += decoder.decode();
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');
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' });
}
messages.push({ role: 'tool', tool_call_id: call.id, content: result });
}
}
buffer += decoder.decode();
if (buffer.trim()) consume(buffer);
if (!finished || !answer.trim()) throw new Error('llm_incomplete');
return answer;
throw new Error('llm_limit');
}
+22 -1
View File
@@ -8,6 +8,8 @@ const showSettings = document.querySelector('#show-settings');
const clear = document.querySelector('#clear');
const form = document.querySelector('#form');
const turns = document.querySelector('#turns');
const spotifyStatus = document.querySelector('#spotify-status');
const spotifyConnect = document.querySelector('#spotify-connect');
const dateFormat = new Intl.DateTimeFormat('ru', { dateStyle: 'medium', timeStyle: 'short' });
@@ -61,7 +63,25 @@ showHistory.onclick = async () => {
status.textContent = error.message;
}
};
showSettings.onclick = () => selectTab(false);
function renderSpotify(spotify) {
spotifyStatus.textContent = !spotify.configured ? 'Spotify пока не настроен на сервере.' : spotify.connected ? 'Аккаунт подключён.' : 'Подключи аккаунт для управления музыкой.';
spotifyConnect.disabled = !spotify.configured;
spotifyConnect.textContent = spotify.connected ? 'Подключить другой аккаунт' : 'Подключить Spotify';
}
showSettings.onclick = async () => {
selectTab(false);
try { renderSpotify((await api()).spotify); } catch (error) { status.textContent = error.message; }
};
spotifyConnect.onclick = async () => {
spotifyConnect.disabled = true;
try {
const response = await fetch('/api/spotify/start', { method: 'POST', headers: { Authorization: 'tma ' + telegram.initData } });
if (!response.ok) throw new Error('Не удалось начать подключение Spotify.');
const { url } = await response.json();
telegram.openLink(url);
} catch (error) { status.textContent = error.message; }
finally { spotifyConnect.disabled = false; }
};
form.onsubmit = async (event) => {
event.preventDefault();
@@ -101,6 +121,7 @@ if (!telegram?.initData) {
const data = await api();
for (const [name, value] of Object.entries(data.settings)) form.elements.namedItem(name).value = value;
renderTurns(data.history);
renderSpotify(data.spotify);
status.textContent = '';
admin.hidden = false;
} catch (error) {
+1
View File
@@ -26,6 +26,7 @@
<div id="turns"></div>
</section>
<section id="settings" hidden>
<div class="spotify-card"><h2>Spotify</h2><p id="spotify-status">Проверяем подключение…</p><button id="spotify-connect" type="button" class="primary">Подключить Spotify</button></div>
<h2>Голосовой тракт</h2>
<form id="form">
<label>Распознавание<select name="sttModel"><option value="scribe_v2_realtime">Scribe v2 Realtime</option></select></label>
+3
View File
@@ -39,3 +39,6 @@ label { display: grid; gap: 5px; font-size: 13px; font-weight: 650; }
input, select, textarea { width: 100%; background: var(--surface); border: 1px solid transparent; border-radius: 11px; padding: 10px; font-size: 16px; font-weight: 400; }
textarea { resize: vertical; }
:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
.spotify-card { background: var(--surface); padding: 16px; border-radius: 15px; margin-bottom: 24px; }
.spotify-card p { color: var(--muted); margin: 5px 0 12px; }
+96
View File
@@ -0,0 +1,96 @@
import { createHash, randomBytes } from 'node:crypto';
import { chmodSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
const pending = new Map();
let refreshInFlight;
const clientId = () => process.env.SPOTIFY_CLIENT_ID || '';
const redirectUri = () => process.env.SPOTIFY_REDIRECT_URI || 'https://miniapp.pepega.systems/api/spotify/callback';
const tokenPath = () => join(process.env.DATA_DIR || './data', 'spotify.json');
const base64url = bytes => bytes.toString('base64url');
function loadToken() {
try {
const token = JSON.parse(readFileSync(tokenPath(), 'utf8'));
return typeof token.refresh_token === 'string' && token.refresh_token ? token : null;
} catch (error) {
if (error.code === 'ENOENT') return null;
throw error;
}
}
function saveToken(token) {
const path = tokenPath();
mkdirSync(process.env.DATA_DIR || './data', { recursive: true, mode: 0o700 });
const temp = `${path}.${randomBytes(8).toString('hex')}.tmp`;
try {
writeFileSync(temp, JSON.stringify(token), { mode: 0o600, flag: 'wx' });
renameSync(temp, path);
chmodSync(path, 0o600);
} catch (error) {
try { unlinkSync(temp); } catch {}
throw error;
}
}
export function spotifyStatus() {
return { configured: Boolean(clientId()), connected: Boolean(loadToken()) };
}
export function startSpotify() {
if (!clientId()) throw new Error('spotify_not_configured');
const now = Date.now();
for (const [key, entry] of pending) if (entry.expires <= now) pending.delete(key);
// One owner: a new attempt invalidates previous attempts.
pending.clear();
const state = base64url(randomBytes(32));
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' });
return url.toString();
}
async function tokenRequest(params, signal) {
const response = await fetch('https://accounts.spotify.com/api/token', { method: 'POST', headers: { 'content-type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams({ client_id: clientId(), ...params }), signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(10_000)]) : AbortSignal.timeout(10_000) });
if (!response.ok) throw new Error('spotify_token_error');
const data = await response.json();
if (typeof data.access_token !== 'string' || !Number.isFinite(data.expires_in) || data.expires_in <= 0) throw new Error('spotify_token_error');
return data;
}
export async function finishSpotify(state, code) {
if (typeof state !== 'string' || !state || typeof code !== 'string' || !code || code.length > 4096) throw new Error('spotify_callback_invalid');
const entry = pending.get(state);
if (!entry || entry.expires <= Date.now()) { pending.delete(state); throw new Error('spotify_callback_invalid'); }
pending.delete(state);
const data = await tokenRequest({ grant_type: 'authorization_code', code, redirect_uri: redirectUri(), code_verifier: entry.verifier });
if (typeof data.refresh_token !== 'string' || !data.refresh_token) throw new Error('spotify_token_error');
saveToken({ access_token: data.access_token, refresh_token: data.refresh_token, expires_at: Date.now() + data.expires_in * 1000 });
}
async function accessToken() {
const current = loadToken();
if (!current) throw new Error('spotify_not_connected');
if (current.access_token && current.expires_at > Date.now() + 60_000) return current.access_token;
if (!refreshInFlight) {
refreshInFlight = (async () => {
const data = await tokenRequest({ grant_type: 'refresh_token', refresh_token: current.refresh_token });
const next = { access_token: data.access_token, refresh_token: data.refresh_token || current.refresh_token, expires_at: Date.now() + data.expires_in * 1000 };
// A new authorization can complete while refresh is in flight.
const latest = loadToken();
if (!latest || latest.refresh_token !== current.refresh_token) return latest?.access_token || next.access_token;
saveToken(next);
return next.access_token;
})().finally(() => { refreshInFlight = undefined; });
}
return refreshInFlight;
}
export async function searchSpotify(query, signal) {
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' });
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, ' ');
const exactArtist = results.find(item => item.type === 'artist' && normalize(item.name) === normalize(query));
if (exactArtist) return [exactArtist, ...results.filter(item => item !== exactArtist)];
return results;
}
+17
View File
@@ -0,0 +1,17 @@
// OpenRouter executes web search itself; Spotify calls are handled by the device.
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 } } }
];
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');
} 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 throw new Error('unknown_tool');
return args;
}
+6 -2
View File
@@ -1,5 +1,6 @@
import WebSocket from 'ws';
import { openStt, openTts, streamAnswer } from './providers.mjs';
import { deviceTools } from './device.mjs';
const MAX_AUDIO = 60 * 16000 * 2;
const MAX_BUFFERED = 2 * 1024 * 1024;
@@ -7,6 +8,7 @@ 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;
const timeout = setTimeout(() => fail('timeout'), 120000);
const send = obj => { if (client.readyState === WebSocket.OPEN) client.send(JSON.stringify(obj)); };
@@ -27,6 +29,7 @@ export function handleTurn(client, store) {
}
async function respond(text, settings) {
if (state !== 'processing' || terminal) return;
state = 'responding';
text = text.trim();
if (!text) return fail('empty_transcript');
send({ type: 'transcript', text });
@@ -37,7 +40,7 @@ export function handleTurn(client, store) {
client.send(audio, { binary: true });
});
if (terminal) return;
const answer = await streamAnswer(settings, store.getHistory(), text, signal, part => tts.text(part));
const answer = await streamAnswer(settings, store.getHistory(), text, signal, part => tts.text(part), device.execute);
tts.finish();
await tts.done;
if (terminal) return;
@@ -49,7 +52,7 @@ export function handleTurn(client, store) {
let settings;
let chain = Promise.resolve();
client.on('message', (data, binary) => {
if (++messages > 10000 || (received += data.length) > MAX_AUDIO + 65536) return fail('input_limit');
if (++messages > 10000 || (received += data.length) > MAX_AUDIO + 131072) return fail('input_limit');
chain = chain.then(async () => {
if (terminal) return;
if (binary) {
@@ -62,6 +65,7 @@ export function handleTurn(client, store) {
}
let msg;
try { msg = JSON.parse(data.toString()); } catch { return fail('invalid_message'); }
if (device.accept(msg)) return;
if (msg?.type === 'start' && state === 'waiting') {
state = 'connecting'; settings = store.getSettings();
try {