tz-voice-chat 1.0.2 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/README.md +616 -127
  2. package/bin/tz-voice-chat.js +46 -0
  3. package/dist/assets/llmWorker-CVEGn6yI.js +1 -0
  4. package/dist/assets/whisperWorker-D69IwlqW.js +1 -0
  5. package/dist/index.cjs +2 -1
  6. package/dist/index.js +1429 -437
  7. package/dist/style.css +1 -1
  8. package/dist-app/assets/index-BDMCgrF_.css +1 -0
  9. package/dist-app/assets/index-CFWv17S2.js +41 -0
  10. package/dist-app/assets/llmWorker-CVEGn6yI.js +1 -0
  11. package/dist-app/assets/whisperWorker-D69IwlqW.js +1 -0
  12. package/dist-app/index.html +27 -0
  13. package/package.json +58 -10
  14. package/server/chat.js +91 -0
  15. package/server/elevenlabs.js +40 -0
  16. package/server/index.js +344 -0
  17. package/server/openai-stt.js +21 -0
  18. package/server/run.js +42 -0
  19. package/server/settings.js +102 -0
  20. package/server/tts.js +139 -0
  21. package/server/vendor.js +57 -0
  22. package/shared/settingsSchema.js +212 -0
  23. package/vendor/kokoro/kokoro.web.js +1 -0
  24. package/vendor/ort/ort-wasm-simd-threaded.jsep.mjs +125 -0
  25. package/vendor/ort/ort-wasm-simd-threaded.jsep.wasm +0 -0
  26. package/vendor/ort/ort-wasm-simd-threaded.mjs +70 -0
  27. package/vendor/ort/ort-wasm-simd-threaded.wasm +0 -0
  28. package/vendor/ort/ort.wasm.min.js +8 -0
  29. package/vendor/transformers/ort-wasm-simd-threaded.jsep.mjs +125 -0
  30. package/vendor/transformers/ort-wasm-simd-threaded.jsep.wasm +0 -0
  31. package/vendor/transformers/transformers.min.js +2 -0
  32. package/vendor/transformers/transformers.node.min.mjs +2 -0
  33. package/vendor/transformers/transformers.node.mjs +36472 -0
  34. package/vendor/vad/bundle.min.js +2 -0
  35. package/vendor/vad/silero_vad_legacy.onnx +0 -0
  36. package/vendor/vad/vad.worklet.bundle.min.js +1 -0
  37. package/dist/assets/whisperWorker-BJuP9cl9.js +0 -1
@@ -0,0 +1,102 @@
1
+ /**
2
+ * Settings store: defaults < environment variables < constructor options < saved settings file.
3
+ * The saved file (JSON, mode 0600) holds only the keys the user set through the Settings page.
4
+ */
5
+ import fs from 'node:fs';
6
+ import os from 'node:os';
7
+ import path from 'node:path';
8
+ import { ALL_FIELDS, FIELD_BY_KEY, SECRET_KEYS, coerce, computeMissing } from '../shared/settingsSchema.js';
9
+
10
+ export function defaultSettingsFile(env = process.env) {
11
+ return env.TZ_VOICE_CHAT_SETTINGS || path.join(os.homedir(), '.tz-voice-chat', 'settings.json');
12
+ }
13
+
14
+ function fromEnv(env) {
15
+ const out = {};
16
+ for (const f of ALL_FIELDS) {
17
+ if (f.env && env[f.env] !== undefined && env[f.env] !== '') {
18
+ const v = coerce(f, env[f.env]);
19
+ if (v !== undefined) out[f.key] = v;
20
+ }
21
+ }
22
+ // Back-compat: infer the chat provider from whichever key is present.
23
+ if (out.chatProvider === undefined) {
24
+ if (env.OPENROUTER_API_KEY) out.chatProvider = 'openrouter';
25
+ else if (env.HUGGINGFACE_API_KEY) out.chatProvider = 'huggingface';
26
+ }
27
+ return out;
28
+ }
29
+
30
+ /** Keep only known keys with valid values. `null` means "remove the saved value". */
31
+ function sanitize(input) {
32
+ const clean = {};
33
+ const ignored = [];
34
+ for (const [k, raw] of Object.entries(input || {})) {
35
+ const f = FIELD_BY_KEY[k];
36
+ if (!f) { ignored.push(k); continue; }
37
+ if (raw === null) { clean[k] = null; continue; }
38
+ const v = coerce(f, raw);
39
+ if (v === undefined) { ignored.push(k); continue; }
40
+ clean[k] = v;
41
+ }
42
+ return { clean, ignored };
43
+ }
44
+
45
+ export function createSettingsStore({ file = defaultSettingsFile(), options = {}, env = process.env } = {}) {
46
+ const defaults = Object.fromEntries(ALL_FIELDS.map(f => [f.key, f.default ?? '']));
47
+ const envValues = fromEnv(env);
48
+ const optionValues = sanitize(options).clean;
49
+ let saved = {};
50
+ let current = null;
51
+ const listeners = [];
52
+
53
+ function load() {
54
+ try {
55
+ saved = sanitize(JSON.parse(fs.readFileSync(file, 'utf8'))).clean;
56
+ } catch (err) {
57
+ if (err.code !== 'ENOENT') console.warn(`[tz-voice-chat] could not read settings file ${file}: ${err.message}`);
58
+ saved = {};
59
+ }
60
+ for (const k of Object.keys(saved)) if (saved[k] === null) delete saved[k];
61
+ recompute();
62
+ }
63
+
64
+ function recompute() {
65
+ current = { ...defaults, ...envValues, ...optionValues, ...saved };
66
+ }
67
+
68
+ function persist() {
69
+ fs.mkdirSync(path.dirname(file), { recursive: true });
70
+ fs.writeFileSync(file, JSON.stringify(saved, null, 2), { mode: 0o600 });
71
+ }
72
+
73
+ load();
74
+
75
+ return {
76
+ file,
77
+ /** Effective settings, including secrets. Server-side use only. */
78
+ get: () => current,
79
+ /** Effective settings with secrets removed, plus which secrets are set. */
80
+ getPublic() {
81
+ const values = { ...current };
82
+ const secretsSet = {};
83
+ for (const k of SECRET_KEYS) { secretsSet[k] = Boolean(current[k]); delete values[k]; }
84
+ return { values, secretsSet, missing: computeMissing(current, secretsSet) };
85
+ },
86
+ /** Effective values including secrets (for export). */
87
+ exportAll: () => ({ ...current }),
88
+ /** Merge a partial update, persist it, and notify listeners. Returns the keys that were ignored. */
89
+ update(patch) {
90
+ const before = current;
91
+ const { clean, ignored } = sanitize(patch);
92
+ for (const [k, v] of Object.entries(clean)) {
93
+ if (v === null) delete saved[k]; else saved[k] = v;
94
+ }
95
+ persist();
96
+ recompute();
97
+ listeners.forEach(fn => fn(current, before));
98
+ return { ignored };
99
+ },
100
+ onChange(fn) { listeners.push(fn); },
101
+ };
102
+ }
package/server/tts.js ADDED
@@ -0,0 +1,139 @@
1
+ /**
2
+ * server/tts.js — Kokoro TTS running in Node.js via kokoro-js.
3
+ *
4
+ * The model is loaded once and kept in memory for the life of the process.
5
+ * Call loadKokoro() at startup for eager pre-loading; generateWav() lazy-loads
6
+ * on demand if the startup call was skipped.
7
+ *
8
+ * Adding a new provider in the future:
9
+ * Just add another export or another branch in server/index.js — this module
10
+ * stays Kokoro-only and the server routes to whichever backend it needs.
11
+ */
12
+
13
+
14
+ let DTYPE = process.env.KOKORO_DTYPE || 'q8';
15
+ let DEVICE = process.env.KOKORO_DEVICE || 'cpu'; // Node onnxruntime: cpu
16
+ let DEFAULT_VOICE = process.env.KOKORO_VOICE || 'af_bella';
17
+
18
+ /** Override the env-derived defaults (call before the model is first loaded). */
19
+ export function configureKokoro({ dtype, device, voice } = {}) {
20
+ if (dtype) DTYPE = dtype;
21
+ if (device) DEVICE = device;
22
+ if (voice) DEFAULT_VOICE = voice;
23
+ }
24
+
25
+ let _model = null;
26
+ let _loadPromise = null;
27
+
28
+ /**
29
+ * kokoro-js is an OPTIONAL extra, needed only for server-side Kokoro. It is not installed with
30
+ * tz-voice-chat because its dependency chain (onnxruntime-node) runs an install script that downloads
31
+ * binaries at install time. Install it yourself if you want this provider.
32
+ */
33
+ async function importKokoro() {
34
+ try {
35
+ return await import('kokoro-js');
36
+ } catch (err) {
37
+ if (err.code === 'ERR_MODULE_NOT_FOUND' || /Cannot find (package|module)/.test(err.message)) {
38
+ throw new Error('Server-side Kokoro needs the optional "kokoro-js" package: run "npm install kokoro-js" ' +
39
+ '(on Linux x64 use "ONNXRUNTIME_NODE_INSTALL_CUDA=skip npm install kokoro-js"). ' +
40
+ 'Or pick Kokoro in the browser, OpenAI, ElevenLabs or Web Speech in Settings.');
41
+ }
42
+ throw err;
43
+ }
44
+ }
45
+
46
+ /** Drop the loaded model so the next load picks up new dtype/device settings. */
47
+ export function resetKokoro() {
48
+ _model = null;
49
+ _loadPromise = null;
50
+ }
51
+
52
+ /**
53
+ * Start loading (or return the already-loaded) Kokoro model.
54
+ * Safe to call multiple times — returns the same Promise until the model is
55
+ * ready, then resolves immediately on every subsequent call.
56
+ * @returns {Promise<KokoroTTS>}
57
+ */
58
+ export function loadKokoro() {
59
+ if (_model) return Promise.resolve(_model);
60
+ if (_loadPromise) return _loadPromise;
61
+
62
+ console.log(`[Kokoro] Loading model (dtype=${DTYPE}) …`);
63
+
64
+ _loadPromise = importKokoro().then(({ KokoroTTS }) => KokoroTTS.from_pretrained('onnx-community/Kokoro-82M-ONNX', {
65
+ dtype: DTYPE,
66
+ device: DEVICE,
67
+ })).then(model => {
68
+ _model = model;
69
+ _loadPromise = null;
70
+ console.log('[Kokoro] Model ready.');
71
+ return _model;
72
+ }).catch(err => {
73
+ _loadPromise = null;
74
+ throw err;
75
+ });
76
+
77
+ return _loadPromise;
78
+ }
79
+
80
+ /**
81
+ * Generate speech and return a complete WAV file as a Node.js Buffer.
82
+ * @param {string} text
83
+ * @param {string} [voice]
84
+ * @param {number} [speed] speech-rate multiplier (default 1)
85
+ * @returns {Promise<Buffer>}
86
+ */
87
+ export async function generateWav(text, voice = DEFAULT_VOICE, speed = 1) {
88
+ const tts = await loadKokoro();
89
+ const result = await tts.generate(text, { voice, speed });
90
+
91
+ // kokoro-js returns { audio: Float32Array, sampling_rate: number }
92
+ const samples = result?.audio ?? result;
93
+ const sampleRate = result?.sampling_rate ?? result?.samplingRate ?? 24000;
94
+
95
+ return encodePcmWav(samples, sampleRate);
96
+ }
97
+
98
+ /**
99
+ * Encode a mono Float32Array as a standard 16-bit PCM WAV file.
100
+ * @param {Float32Array} samples
101
+ * @param {number} sampleRate
102
+ * @returns {Buffer}
103
+ */
104
+ function encodePcmWav(samples, sampleRate) {
105
+ const numSamples = samples.length;
106
+ const blockAlign = 2; // 1 channel × 2 bytes (16-bit)
107
+ const byteRate = sampleRate * blockAlign;
108
+ const dataSize = numSamples * blockAlign;
109
+ const buf = Buffer.allocUnsafe(44 + dataSize);
110
+
111
+ // RIFF chunk descriptor
112
+ buf.write('RIFF', 0, 'ascii');
113
+ buf.writeUInt32LE(36 + dataSize, 4);
114
+ buf.write('WAVE', 8, 'ascii');
115
+
116
+ // fmt sub-chunk
117
+ buf.write('fmt ', 12, 'ascii');
118
+ buf.writeUInt32LE(16, 16); // chunk size (PCM = 16)
119
+ buf.writeUInt16LE(1, 20); // audio format: PCM
120
+ buf.writeUInt16LE(1, 22); // num channels: mono
121
+ buf.writeUInt32LE(sampleRate, 24);
122
+ buf.writeUInt32LE(byteRate, 28);
123
+ buf.writeUInt16LE(blockAlign, 32);
124
+ buf.writeUInt16LE(16, 34); // bits per sample
125
+
126
+ // data sub-chunk
127
+ buf.write('data', 36, 'ascii');
128
+ buf.writeUInt32LE(dataSize, 40);
129
+
130
+ // Convert float32 → int16 PCM
131
+ let offset = 44;
132
+ for (let i = 0; i < numSamples; i++) {
133
+ const s = Math.max(-1, Math.min(1, samples[i]));
134
+ buf.writeInt16LE(s < 0 ? Math.round(s * 0x8000) : Math.round(s * 0x7FFF), offset);
135
+ offset += 2;
136
+ }
137
+
138
+ return buf;
139
+ }
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Serves the browser runtime assets at /vendor/ort, /vendor/vad, /vendor/transformers and
3
+ * /vendor/kokoro: onnxruntime-web (used by the VAD), the VAD, the transformers.js bundle and
4
+ * the browser build of Kokoro. They are same-origin runtime URLs, never loaded from a CDN.
5
+ *
6
+ * Installed copies ship them inside the package (vendor/, created by scripts/bundle-vendor.mjs).
7
+ * In this repository (no vendor/ yet) they fall back to the packages in node_modules.
8
+ */
9
+ import express from 'express';
10
+ import fs from 'node:fs';
11
+ import path from 'node:path';
12
+ import { fileURLToPath } from 'node:url';
13
+
14
+ const here = path.dirname(fileURLToPath(import.meta.url));
15
+ const bundled = path.resolve(here, '../vendor');
16
+
17
+ /** Find an installed package's directory by walking up node_modules from this file. */
18
+ function findPackageDir(name) {
19
+ let dir = here;
20
+ for (;;) {
21
+ const candidate = path.join(dir, 'node_modules', name);
22
+ if (fs.existsSync(path.join(candidate, 'package.json'))) return candidate;
23
+ const parent = path.dirname(dir);
24
+ if (parent === dir) return null;
25
+ dir = parent;
26
+ }
27
+ }
28
+
29
+ const SOURCES = [
30
+ { mount: 'ort', pkg: 'onnxruntime-web', allow: f => f === 'ort.wasm.min.js' || f.startsWith('ort-wasm') },
31
+ { mount: 'vad', pkg: '@ricky0123/vad-web',
32
+ allow: f => ['bundle.min.js', 'vad.worklet.bundle.min.js', 'silero_vad_legacy.onnx'].includes(f) },
33
+ { mount: 'transformers', pkg: '@huggingface/transformers',
34
+ allow: f => f === 'transformers.min.js' || f.endsWith('.wasm') || f.endsWith('.mjs') },
35
+ { mount: 'kokoro', pkg: 'kokoro-js', allow: f => f === 'kokoro.web.js' },
36
+ ];
37
+
38
+ /** @returns {import('express').Router} */
39
+ export function createVendorRouter() {
40
+ const router = express.Router();
41
+ for (const { mount, pkg, allow } of SOURCES) {
42
+ const pkgDir = findPackageDir(pkg);
43
+ const dirs = [path.join(bundled, mount), pkgDir && path.join(pkgDir, 'dist')].filter(d => d && fs.existsSync(d));
44
+ if (!dirs.length) {
45
+ console.warn(`[tz-voice-chat] no browser files found for /vendor/${mount}/* — it will 404 (run "npm run build" in the package)`);
46
+ continue;
47
+ }
48
+ router.use(`/${mount}`, (req, res, next) => {
49
+ const name = decodeURIComponent(req.path.slice(1));
50
+ if (!name || name.includes('/') || name.includes('..') || !allow(name)) return next();
51
+ const dir = dirs.find(d => fs.existsSync(path.join(d, name)));
52
+ if (!dir) return next();
53
+ res.sendFile(path.join(dir, name), { maxAge: '1d' }, (err) => { if (err) next(); });
54
+ });
55
+ }
56
+ return router;
57
+ }
@@ -0,0 +1,212 @@
1
+ /**
2
+ * Single source of truth for every configurable parameter. Used by the server
3
+ * (defaults, env mapping, validation, "missing" detection) and by the client
4
+ * Settings page (form generation). Plain ESM with no dependencies.
5
+ *
6
+ * Field: { key, label, type, env?, default?, secret?, options?, hint?, showWhen? }
7
+ * type: 'select' | 'text' | 'password' | 'number' | 'textarea'
8
+ * options (select): [value, label, group?] — items sharing a group are shown under one heading
9
+ * (the Settings page uses "Local · free" and "Cloud").
10
+ * showWhen: { otherKey: value | [values] } — field is relevant only then (all keys must match).
11
+ * showWhenAny: [showWhen, …] — relevant when any of the conditions matches.
12
+ */
13
+
14
+ const kokoroDtypes = ['q8', 'q4', 'q4f16', 'fp16', 'fp32'];
15
+
16
+ // Option groups used by the provider dropdowns.
17
+ const LOCAL = 'Local · free';
18
+ const CLOUD = 'Cloud';
19
+
20
+ export const SETTINGS_SCHEMA = [
21
+ {
22
+ group: 'Chat model',
23
+ fields: [
24
+ {
25
+ key: 'chatProvider', label: 'Provider', type: 'select', env: 'OPENAI_PROVIDER', default: 'local',
26
+ options: [
27
+ ['', 'Not configured'],
28
+ ['local', 'In-browser model (SmolLM2, no key, ~200 MB) — slow and simple', LOCAL],
29
+ ['openai-compatible', 'OpenAI-compatible server (Ollama, LM Studio, vLLM, on-premise…)', LOCAL],
30
+ ['openrouter', 'OpenRouter', CLOUD],
31
+ ['openai', 'OpenAI', CLOUD],
32
+ ['anthropic', 'Anthropic (Claude)', CLOUD],
33
+ ['huggingface', 'Hugging Face', CLOUD],
34
+ ],
35
+ },
36
+ { key: 'openrouterApiKey', label: 'OpenRouter API key', type: 'password', secret: true, env: 'OPENROUTER_API_KEY',
37
+ showWhen: { chatProvider: 'openrouter' }, hint: 'Get one at https://openrouter.ai/keys' },
38
+ { key: 'openrouterModel', label: 'OpenRouter model', type: 'text', env: 'OPENROUTER_MODEL', default: 'gpt-4o-mini',
39
+ showWhen: { chatProvider: 'openrouter' }, hint: 'e.g. openai/gpt-4o-mini, or a ":free" model' },
40
+ { key: 'openaiApiKey', label: 'OpenAI API key', type: 'password', secret: true, env: 'OPENAI_API_KEY',
41
+ showWhenAny: [{ chatProvider: 'openai' }, { sttProvider: 'openai' }, { ttsProvider: 'openai' }],
42
+ hint: 'Used for OpenAI chat, transcription and/or TTS. Get one at https://platform.openai.com/api-keys' },
43
+ { key: 'openaiChatModel', label: 'OpenAI model', type: 'text', env: 'OPENAI_CHAT_MODEL', default: 'gpt-4o-mini',
44
+ showWhen: { chatProvider: 'openai' }, suggestions: ['gpt-4o-mini', 'gpt-4o', 'gpt-4.1-mini', 'gpt-4.1'] },
45
+ { key: 'anthropicApiKey', label: 'Anthropic API key', type: 'password', secret: true, env: 'ANTHROPIC_API_KEY',
46
+ showWhen: { chatProvider: 'anthropic' }, hint: 'Get one at https://console.anthropic.com/settings/keys' },
47
+ { key: 'anthropicModel', label: 'Anthropic model', type: 'text', env: 'ANTHROPIC_MODEL', default: 'claude-haiku-5-5',
48
+ showWhen: { chatProvider: 'anthropic' }, suggestions: ['claude-haiku-5-5', 'claude-sonnet-5-5', 'claude-opus-5-5', 'claude-fable-5-2'],
49
+ hint: 'Haiku is the fastest — best for voice' },
50
+ { key: 'huggingfaceApiKey', label: 'Hugging Face token', type: 'password', secret: true, env: 'HUGGINGFACE_API_KEY',
51
+ showWhen: { chatProvider: 'huggingface' }, hint: 'A token with read scope' },
52
+ { key: 'compatBaseUrl', label: 'Server base URL', type: 'text', env: 'OPENAI_COMPAT_BASE_URL', default: 'http://localhost:11434/v1',
53
+ showWhen: { chatProvider: 'openai-compatible' }, suggestions: ['http://localhost:11434/v1', 'http://localhost:1234/v1', 'http://localhost:8000/v1'],
54
+ hint: 'Must serve /chat/completions. Ollama :11434, LM Studio :1234, vLLM :8000. From inside Docker use host.docker.internal instead of localhost.' },
55
+ { key: 'compatModel', label: 'Model name', type: 'text', env: 'OPENAI_COMPAT_MODEL', default: '',
56
+ showWhen: { chatProvider: 'openai-compatible' }, hint: 'Exactly as the server names it, e.g. llama3.2 or qwen2.5:7b-instruct' },
57
+ { key: 'compatApiKey', label: 'API key (optional)', type: 'password', secret: true, env: 'OPENAI_COMPAT_API_KEY',
58
+ showWhen: { chatProvider: 'openai-compatible' }, hint: 'Leave empty if the server needs no key (most local servers).' },
59
+ { key: 'systemPrompt', label: 'System prompt', type: 'textarea', default: '',
60
+ hint: 'Leave blank for the built-in short, spoken-style prompt.' },
61
+ ],
62
+ },
63
+ {
64
+ group: 'Speech-to-text',
65
+ fields: [
66
+ {
67
+ key: 'sttProvider', label: 'Provider', type: 'select', env: 'STT_PROVIDER', default: 'whisper',
68
+ options: [
69
+ ['whisper', 'Whisper in the browser', LOCAL],
70
+ ['openai', 'OpenAI transcription', CLOUD],
71
+ ['elevenlabs', 'ElevenLabs Scribe', CLOUD],
72
+ ],
73
+ },
74
+ { key: 'openaiSttModel', label: 'OpenAI model', type: 'text', env: 'OPENAI_STT_MODEL', default: 'whisper-1',
75
+ showWhen: { sttProvider: 'openai' }, suggestions: ['whisper-1', 'gpt-4o-mini-transcribe', 'gpt-4o-transcribe'],
76
+ hint: 'Uses the OpenAI API key below' },
77
+ { key: 'openaiSttLanguage', label: 'OpenAI language', type: 'text', env: 'OPENAI_STT_LANGUAGE', default: '',
78
+ showWhen: { sttProvider: 'openai' }, hint: 'ISO-639-1 code such as en; blank = detect automatically' },
79
+ { key: 'elevenlabsApiKey', label: 'ElevenLabs API key', type: 'password', secret: true, env: 'ELEVENLABS_API_KEY',
80
+ showWhenAny: [{ sttProvider: 'elevenlabs' }, { ttsProvider: 'elevenlabs' }],
81
+ hint: 'Used for ElevenLabs speech-to-text and/or text-to-speech. Get one at https://elevenlabs.io/app/settings/api-keys' },
82
+ { key: 'elevenlabsSttModel', label: 'ElevenLabs model', type: 'text', env: 'ELEVENLABS_STT_MODEL', default: 'scribe_v2',
83
+ showWhen: { sttProvider: 'elevenlabs' }, suggestions: ['scribe_v2', 'scribe_v3', 'scribe_v2_medical'] },
84
+ { key: 'elevenlabsLanguage', label: 'ElevenLabs language', type: 'text', env: 'ELEVENLABS_STT_LANGUAGE', default: '',
85
+ showWhen: { sttProvider: 'elevenlabs' }, hint: 'ISO code such as en or de; blank = detect automatically' },
86
+ { key: 'whisperModel', label: 'Model', type: 'select', env: 'WHISPER_MODEL', default: 'onnx-community/whisper-small.en',
87
+ showWhen: { sttProvider: 'whisper' }, allowCustom: true, // any other Hugging Face model id from an env var / imported file is kept
88
+ options: [
89
+ ['onnx-community/whisper-tiny.en', 'whisper-tiny.en — fastest, ~40 MB, more errors'],
90
+ ['onnx-community/whisper-base.en', 'whisper-base.en — better, ~74 MB, recommended'],
91
+ ['onnx-community/whisper-small.en', 'whisper-small.en — good, ~244 MB, significantly more accurate'],
92
+ ] },
93
+ { key: 'whisperDtype', label: 'Precision', type: 'select', env: 'WHISPER_DTYPE', default: 'fp32', showWhen: { sttProvider: 'whisper' },
94
+ options: [['q8', 'q8'], ['q4', 'q4'], ['fp16', 'fp16 (WebGPU)'], ['fp32', 'fp32']] },
95
+ { key: 'whisperDevice', label: 'Device', type: 'select', env: 'WHISPER_DEVICE', default: 'webgpu',
96
+ showWhen: { sttProvider: 'whisper' }, aliases: { cpu: 'wasm' }, options: [['wasm', 'wasm (CPU)'], ['webgpu', 'webgpu']] },
97
+ ],
98
+ },
99
+ {
100
+ group: 'Text-to-speech',
101
+ fields: [
102
+ {
103
+ key: 'ttsProvider', label: 'Provider', type: 'select', env: 'TTS_PROVIDER', default: 'kokoro',
104
+ options: [
105
+ ['kokoro', 'Kokoro in the browser', LOCAL],
106
+ ['server-kokoro', 'Kokoro on the server (needs: npm install kokoro-js)', LOCAL],
107
+ ['webspeech', 'Browser Web Speech API (built-in voices)', LOCAL],
108
+ ['openai', 'OpenAI TTS', CLOUD],
109
+ ['elevenlabs', 'ElevenLabs', CLOUD],
110
+ ],
111
+ },
112
+ { key: 'kokoroVoice', label: 'Kokoro voice', type: 'text', env: 'KOKORO_VOICE', default: 'af_bella',
113
+ showWhen: { ttsProvider: ['kokoro', 'server-kokoro'] }, hint: 'e.g. af_bella, af_sarah, am_adam' },
114
+ { key: 'kokoroSpeed', label: 'Kokoro speed', type: 'number', env: 'KOKORO_SPEED', default: 1,
115
+ showWhen: { ttsProvider: ['kokoro', 'server-kokoro'] }, hint: '1 = normal; 1.1–1.2 often sounds more natural' },
116
+ { key: 'kokoroDtype', label: 'Kokoro precision', type: 'select', env: 'KOKORO_DTYPE', default: 'fp32',
117
+ showWhen: { ttsProvider: ['kokoro', 'server-kokoro'] }, options: kokoroDtypes.map(v => [v, v]),
118
+ hint: 'q4/q8 are promoted to fp32 on WebGPU' },
119
+ { key: 'kokoroBrowserDevice', label: 'Kokoro device (browser)', type: 'select', env: 'KOKORO_BROWSER_DEVICE', default: 'webgpu',
120
+ showWhen: { ttsProvider: 'kokoro' }, options: [['wasm', 'wasm'], ['webgpu', 'webgpu']] },
121
+ { key: 'kokoroDevice', label: 'Kokoro device (server)', type: 'select', env: 'KOKORO_DEVICE', default: 'cpu',
122
+ showWhen: { ttsProvider: 'server-kokoro' }, options: [['cpu', 'cpu']] },
123
+ { key: 'openaiTtsModel', label: 'OpenAI TTS model', type: 'text', env: 'OPENAI_TTS_MODEL', default: 'tts-1',
124
+ showWhen: { ttsProvider: 'openai' }, suggestions: ['tts-1', 'tts-1-hd', 'gpt-4o-mini-tts'] },
125
+ { key: 'openaiTtsVoice', label: 'OpenAI voice', type: 'text', env: 'OPENAI_TTS_VOICE', default: 'alloy',
126
+ showWhen: { ttsProvider: 'openai' }, suggestions: ['alloy', 'echo', 'fable', 'onyx', 'nova', 'shimmer'] },
127
+ { key: 'elevenlabsVoiceId', label: 'ElevenLabs voice ID', type: 'text', env: 'ELEVENLABS_VOICE_ID', default: '21m00Tcm4TlvDq8ikWAM',
128
+ showWhen: { ttsProvider: 'elevenlabs' }, hint: 'Default is the premade "Rachel" voice. Copy another voice\'s ID from your ElevenLabs voice library.' },
129
+ { key: 'elevenlabsTtsModel', label: 'ElevenLabs model', type: 'text', env: 'ELEVENLABS_TTS_MODEL', default: 'eleven_flash_v2_5',
130
+ showWhen: { ttsProvider: 'elevenlabs' }, suggestions: ['eleven_flash_v2_5', 'eleven_turbo_v2_5', 'eleven_multilingual_v2'],
131
+ hint: 'Flash is the lowest latency — best for voice chat' },
132
+ { key: 'webSpeechVoice', label: 'Web Speech voice', type: 'text', env: 'WEBSPEECH_VOICE', default: '',
133
+ showWhen: { ttsProvider: 'webspeech' }, hint: 'Exact voice name; blank = browser default' },
134
+ { key: 'webSpeechRate', label: 'Web Speech rate', type: 'number', env: 'WEBSPEECH_RATE', default: 1,
135
+ showWhen: { ttsProvider: 'webspeech' }, hint: '0.1 – 10' },
136
+ { key: 'webSpeechPitch', label: 'Web Speech pitch', type: 'number', env: 'WEBSPEECH_PITCH', default: 1,
137
+ showWhen: { ttsProvider: 'webspeech' }, hint: '0 – 2' },
138
+ ],
139
+ },
140
+ ];
141
+
142
+ export const ALL_FIELDS = SETTINGS_SCHEMA.flatMap(g => g.fields);
143
+ export const FIELD_BY_KEY = Object.fromEntries(ALL_FIELDS.map(f => [f.key, f]));
144
+ export const SECRET_KEYS = ALL_FIELDS.filter(f => f.secret).map(f => f.key);
145
+
146
+ /** Is the field relevant given the current values? */
147
+ export function isVisible(field, values) {
148
+ const matches = (cond) => Object.entries(cond).every(([k, v]) =>
149
+ (Array.isArray(v) ? v : [v]).includes(values[k]));
150
+ if (field.showWhenAny) return field.showWhenAny.some(matches);
151
+ if (field.showWhen) return matches(field.showWhen);
152
+ return true;
153
+ }
154
+
155
+ /** Coerce a raw value (string from env/form/import) to the field's type. Returns undefined if invalid. */
156
+ export function coerce(field, raw) {
157
+ if (raw === undefined || raw === null) return undefined;
158
+ if (field.type === 'number') {
159
+ const n = typeof raw === 'number' ? raw : parseFloat(raw);
160
+ return Number.isFinite(n) ? n : undefined;
161
+ }
162
+ let s = String(raw);
163
+ if (field.aliases && s in field.aliases) s = field.aliases[s];
164
+ if (field.type === 'select' && !field.allowCustom && !field.options.some(([v]) => v === s)) return undefined;
165
+ return s;
166
+ }
167
+
168
+ /**
169
+ * Which required parameters are still missing? `secretsSet` says which secret
170
+ * keys have a value (the server never sends the secrets themselves to the page).
171
+ * `scope` says what is affected: 'chat' blocks the chat model, 'stt' speech input, 'tts' speech output.
172
+ * @returns {Array<{key: string, message: string, scope: 'chat'|'stt'|'tts'}>}
173
+ */
174
+ export function computeMissing(values, secretsSet = {}) {
175
+ const missing = [];
176
+ const has = (k) => Boolean(secretsSet[k]);
177
+ const p = values.chatProvider;
178
+ if (!p) {
179
+ missing.push({ key: 'chatProvider', message: 'No chat model provider is configured.', scope: 'chat' });
180
+ }
181
+
182
+ // Keys that several features can share are reported once, listing every feature that needs them.
183
+ if (p === 'openai-compatible') {
184
+ if (!values.compatBaseUrl) missing.push({ key: 'compatBaseUrl', message: 'The OpenAI-compatible server URL is missing.', scope: 'chat' });
185
+ if (!values.compatModel) missing.push({ key: 'compatModel', message: 'The model name for the OpenAI-compatible server is missing.', scope: 'chat' });
186
+ }
187
+
188
+ const needs = [
189
+ { key: 'openrouterApiKey', name: 'OpenRouter API key', uses: [p === 'openrouter' && ['chat', 'chat']] },
190
+ { key: 'anthropicApiKey', name: 'Anthropic API key', uses: [p === 'anthropic' && ['chat', 'chat']] },
191
+ { key: 'huggingfaceApiKey', name: 'Hugging Face token', uses: [p === 'huggingface' && ['chat', 'chat']] },
192
+ { key: 'openaiApiKey', name: 'OpenAI API key', uses: [
193
+ p === 'openai' && ['chat', 'chat'],
194
+ values.sttProvider === 'openai' && ['speech-to-text', 'stt'],
195
+ values.ttsProvider === 'openai' && ['text-to-speech', 'tts'],
196
+ ] },
197
+ { key: 'elevenlabsApiKey', name: 'ElevenLabs API key', uses: [
198
+ values.sttProvider === 'elevenlabs' && ['speech-to-text', 'stt'],
199
+ values.ttsProvider === 'elevenlabs' && ['text-to-speech', 'tts'],
200
+ ] },
201
+ ];
202
+ for (const { key, name, uses } of needs) {
203
+ const used = uses.filter(Boolean);
204
+ if (!used.length || has(key)) continue;
205
+ const scope = used.some(u => u[1] === 'chat') ? 'chat' : used[0][1];
206
+ const message = used.length === 1 && used[0][0] === 'chat'
207
+ ? `${name} is missing.`
208
+ : `${name} (for ${used.map(u => u[0]).join(', ').replace(/, ([^,]*)$/, ' and $1')}) is missing.`;
209
+ missing.push({ key, message, scope });
210
+ }
211
+ return missing;
212
+ }