@hyperwindmill/caretaker-cli 0.16.0 → 0.18.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.
@@ -1,26 +1,59 @@
1
- // Detect / start / stop the managed local Speaches container backing voice
2
- // mode. The configured endpoint is the source of truth (see the design doc);
3
- // this module never rewrites `voice.endpoint` and never invents a port — it
4
- // only parses the one the user already configured and makes a container match
5
- // it. `lib/docker.ts` is deliberately task-agnostic, so we reuse its
6
- // `containerState` primitive but build our own run argv here (Speaches needs a
7
- // published port + a named cache volume, not a worktree bind-mount + a
8
- // `sleep infinity` keep-alive).
1
+ // Detect / start / stop the managed local voice containers. Voice mode uses
2
+ // one OpenAI-compatible endpoint by default (Speaches does both STT and TTS);
3
+ // an optional `ttsEndpoint` splits synthesis to a separate host — today that
4
+ // is openai-edge-tts, a TTS-only container with Microsoft Neural voices.
5
+ //
6
+ // The configured endpoint is the source of truth (see the design doc): this
7
+ // module never rewrites `voice.endpoint` / `voice.ttsEndpoint` and never
8
+ // invents a port — it only parses the one the user already configured and
9
+ // makes a container match it. `lib/docker.ts` is deliberately task-agnostic,
10
+ // so we reuse its `containerState` primitive but build our own run argv here
11
+ // (Speaches needs a published port + a named cache volume, not a worktree
12
+ // bind-mount + a `sleep infinity` keep-alive; edge-tts needs neither a volume
13
+ // nor a model-install step).
9
14
  import { execFile, spawn } from 'node:child_process';
10
15
  import { promisify } from 'node:util';
11
16
  import { stream } from 'hono/streaming';
12
17
  import { commandEnv, probeShellEnv } from '../../harness/tools/builtin/shell-env.js';
13
18
  import { containerState } from '../../lib/docker.js';
14
19
  import { loadConfig } from '../../store/json.js';
15
- import { resolveVoice, voiceAuthHeaders } from './voice_proxy.js';
20
+ import { resolveVoice, ttsTarget, authHeaders } from './voice_proxy.js';
16
21
  const exec = promisify(execFile);
17
- const CONTAINER_NAME = 'caretaker-speaches';
18
- const IMAGE = 'ghcr.io/speaches-ai/speaches:latest-cpu';
19
- // A named volume, deliberately not the `caretaker-cli_hf-hub-cache` that
20
- // docker-compose.voice.yml creates — a container already running under that
21
- // name (compose-started or hand-started) is adopted as-is and keeps its own
22
- // volume; only a fresh create uses ours.
23
- const VOLUME = 'caretaker-hf-hub-cache:/home/ubuntu/.cache/huggingface/hub';
22
+ // ponytail: the TTS target's backend is inferred, not configured — there is
23
+ // exactly one alternative synthesis backend, so `ttsEndpoint` being set is the
24
+ // same fact as "run edge-tts there". Persist a kind on VoiceConfig when a
25
+ // second alternative appears and the inference is no longer unambiguous.
26
+ const SPECS = {
27
+ stt: {
28
+ container: 'caretaker-speaches',
29
+ image: 'ghcr.io/speaches-ai/speaches:latest-cpu',
30
+ internalPort: 8000,
31
+ // A named volume, deliberately not the `caretaker-cli_hf-hub-cache` that
32
+ // docker-compose.voice.yml creates — a container already running under
33
+ // that name (compose-started or hand-started) is adopted as-is and keeps
34
+ // its own volume; only a fresh create uses ours.
35
+ extraRunArgs: ['-v', 'caretaker-hf-hub-cache:/home/ubuntu/.cache/huggingface/hub'],
36
+ readyPath: '/models',
37
+ installsModels: true,
38
+ pullNote: 'first run downloads about 2 GB',
39
+ },
40
+ tts: {
41
+ container: 'caretaker-edge-tts',
42
+ image: 'travisvn/openai-edge-tts:latest',
43
+ internalPort: 5050,
44
+ // edge-tts fetches voices from Microsoft's online service at runtime — no
45
+ // model cache, no volume. REQUIRE_API_KEY=False disables the default
46
+ // auth requirement so the readiness probe and the proxy both work with no
47
+ // key; the user can set one and configure ttsApiKey if they want auth.
48
+ extraRunArgs: ['-e', 'REQUIRE_API_KEY=False'],
49
+ // /v1/models has no @require_api_key guard, so it answers 200 without a
50
+ // key — the correct readiness path. /v1/voices has @require_api_key and
51
+ // would 401 without a key, failing the probe.
52
+ readyPath: '/models',
53
+ installsModels: false,
54
+ pullNote: 'a small image, a few hundred MB',
55
+ },
56
+ };
24
57
  const READY_TIMEOUT_MS = 60_000;
25
58
  const READY_POLL_INTERVAL_MS = 500;
26
59
  const PROBE_TIMEOUT_MS = 2_000;
@@ -123,7 +156,7 @@ export function setVoiceBackendDepsForTest(overrides) {
123
156
  // --- Port / endpoint parsing --------------------------------------------
124
157
  // Node's WHATWG URL keeps the brackets in `.hostname` for a bracketed IPv6
125
158
  // authority (verified: `new URL('http://[::1]:1/').hostname === '[::1]'`,
126
- // not `'::1'`), so the literal bracketed form is what we must match here.
159
+ // not `'::1]'`), so the literal bracketed form is what we must match here.
127
160
  const LOOPBACK_HOSTS = new Set(['127.0.0.1', 'localhost', '[::1]']);
128
161
  /** Port when the endpoint is loopback, else null. Exported for tests. */
129
162
  export function loopbackPort(endpoint) {
@@ -143,13 +176,29 @@ export function loopbackPort(endpoint) {
143
176
  function joinUrl(endpoint, suffix) {
144
177
  return `${endpoint.replace(/\/+$/, '')}${suffix}`;
145
178
  }
179
+ /** The endpoint for a given target: `voice.endpoint` for STT, `ttsTarget` for
180
+ * TTS. Returns '' when the target's endpoint is not configured. */
181
+ function targetEndpoint(voice, target) {
182
+ if (target === 'stt')
183
+ return voice.endpoint;
184
+ return ttsTarget(voice).endpoint;
185
+ }
186
+ /** The auth headers for a given target. STT uses `voice.apiKey`; TTS uses its
187
+ * own `ttsApiKey` or none — the STT key never leaks to the TTS host. */
188
+ function targetAuth(voice, target) {
189
+ if (target === 'stt') {
190
+ const key = voice.apiKey;
191
+ return key ? authHeaders(key) : {};
192
+ }
193
+ return authHeaders(ttsTarget(voice).apiKey);
194
+ }
146
195
  /** Short-timeout GET, independent of Docker — a remote or hand-run backend
147
196
  * still reports `responding: true`. */
148
- async function probeResponding(endpoint, headers = {}) {
197
+ async function probeResponding(endpoint, readyPath, headers = {}) {
149
198
  const ctrl = new AbortController();
150
199
  const timer = setTimeout(() => ctrl.abort(), PROBE_TIMEOUT_MS);
151
200
  try {
152
- const res = await fetch(joinUrl(endpoint, '/models'), { headers, signal: ctrl.signal });
201
+ const res = await fetch(joinUrl(endpoint, readyPath), { headers, signal: ctrl.signal });
153
202
  return res.ok;
154
203
  }
155
204
  catch {
@@ -169,37 +218,77 @@ async function classifyDocker() {
169
218
  return 'denied';
170
219
  return 'down';
171
220
  }
172
- export async function probeBackend(endpoint) {
221
+ export async function probeBackend(voiceOrEndpoint, target) {
222
+ // Overload 1: the legacy (endpoint-only) call, used by existing tests that
223
+ // don't know about targets. Defaults to the STT spec.
224
+ if (typeof voiceOrEndpoint === 'string') {
225
+ const endpoint = voiceOrEndpoint;
226
+ const spec = SPECS[target ?? 'stt'];
227
+ const port = loopbackPort(endpoint);
228
+ const docker = await classifyDocker();
229
+ const container = docker === 'ok' ? await deps.containerState(spec.container) : 'absent';
230
+ const imagePresent = docker === 'ok' ? await deps.imagePresent(spec.image) : false;
231
+ const responding = await probeResponding(endpoint, spec.readyPath);
232
+ return { docker, container, imagePresent, port, responding };
233
+ }
234
+ // Overload 2: the (voice, target) call — resolves the endpoint and auth
235
+ // from the config, so TTS probes the TTS endpoint with the TTS key.
236
+ const voice = voiceOrEndpoint;
237
+ const t = target ?? 'stt';
238
+ const spec = SPECS[t];
239
+ const endpoint = targetEndpoint(voice, t);
173
240
  const port = loopbackPort(endpoint);
174
241
  const docker = await classifyDocker();
175
- // Coherent status without throwing: don't even ask Docker for container /
176
- // image state when it isn't there to ask.
177
- const container = docker === 'ok' ? await deps.containerState(CONTAINER_NAME) : 'absent';
178
- const imagePresent = docker === 'ok' ? await deps.imagePresent(IMAGE) : false;
179
- const responding = await probeResponding(endpoint);
242
+ const container = docker === 'ok' ? await deps.containerState(spec.container) : 'absent';
243
+ const imagePresent = docker === 'ok' ? await deps.imagePresent(spec.image) : false;
244
+ const responding = await probeResponding(endpoint, spec.readyPath, targetAuth(voice, t));
180
245
  return { docker, container, imagePresent, port, responding };
181
246
  }
182
- function runArgs(port) {
247
+ /** Probe both configured targets. `tts` is null when no separate
248
+ * `ttsEndpoint` is set (the single-endpoint Speaches case). Docker is
249
+ * classified once and shared across both targets — `docker info` + `image
250
+ * inspect` are the expensive part of a probe, and running them twice per
251
+ * 10 s poll when a `ttsEndpoint` is set is wasteful. */
252
+ export async function probeBackends(voice) {
253
+ const docker = await classifyDocker();
254
+ const stt = await probeBackendWithDocker(voice, 'stt', docker);
255
+ const ttsEndpoint = voice.ttsEndpoint?.trim();
256
+ const tts = ttsEndpoint ? await probeBackendWithDocker(voice, 'tts', docker) : null;
257
+ return { stt, tts };
258
+ }
259
+ /** Internal: probe a target with a pre-classified docker status, so
260
+ * `probeBackends` can classify once and reuse. */
261
+ async function probeBackendWithDocker(voice, target, docker) {
262
+ const spec = SPECS[target];
263
+ const endpoint = targetEndpoint(voice, target);
264
+ const port = loopbackPort(endpoint);
265
+ const container = docker === 'ok' ? await deps.containerState(spec.container) : 'absent';
266
+ const imagePresent = docker === 'ok' ? await deps.imagePresent(spec.image) : false;
267
+ const responding = await probeResponding(endpoint, spec.readyPath, targetAuth(voice, target));
268
+ return { docker, container, imagePresent, port, responding };
269
+ }
270
+ function runArgs(port, spec) {
183
271
  return [
184
272
  'run',
185
273
  '-d',
186
274
  '--name',
187
- CONTAINER_NAME,
275
+ spec.container,
188
276
  '-p',
189
- `127.0.0.1:${port}:8000`,
190
- '-v',
191
- VOLUME,
192
- IMAGE,
277
+ `127.0.0.1:${port}:${spec.internalPort}`,
278
+ ...spec.extraRunArgs,
279
+ spec.image,
193
280
  ];
194
281
  }
195
282
  function errMsg(err) {
196
283
  return err instanceof Error ? err.message : String(err);
197
284
  }
198
- async function pollReady(voice) {
285
+ async function pollReady(voice, target) {
286
+ const spec = SPECS[target];
287
+ const endpoint = targetEndpoint(voice, target);
199
288
  const deadline = Date.now() + READY_TIMEOUT_MS;
200
- const headers = voiceAuthHeaders(voice);
289
+ const headers = targetAuth(voice, target);
201
290
  for (;;) {
202
- if (await probeResponding(voice.endpoint, headers))
291
+ if (await probeResponding(endpoint, spec.readyPath, headers))
203
292
  return true;
204
293
  if (Date.now() >= deadline)
205
294
  return false;
@@ -215,184 +304,223 @@ async function pollReady(voice) {
215
304
  * and Speaches' route captures the id verbatim including the slash — so the
216
305
  * id goes in the path unencoded, not through encodeURIComponent (which would
217
306
  * turn it into `%2F` and very likely 404 against a path-style route match). */
218
- async function installModel(voice, modelId) {
219
- const res = await fetch(joinUrl(voice.endpoint, `/models/${modelId}`), {
307
+ async function installModel(voice, target, modelId) {
308
+ const endpoint = targetEndpoint(voice, target);
309
+ const res = await fetch(joinUrl(endpoint, `/models/${modelId}`), {
220
310
  method: 'POST',
221
- headers: voiceAuthHeaders(voice),
311
+ headers: targetAuth(voice, target),
222
312
  });
223
313
  if (res.ok || res.status === 409)
224
314
  return;
225
315
  const body = await res.text().catch(() => '');
226
316
  throw new Error(`${res.status} ${res.statusText}: ${body.slice(0, 300)}`);
227
317
  }
228
- export async function* startBackend(voice) {
229
- const endpoint = voice.endpoint;
318
+ export async function* startBackend(voice, target = 'stt') {
319
+ const spec = SPECS[target];
320
+ const endpoint = targetEndpoint(voice, target);
230
321
  const port = loopbackPort(endpoint);
231
322
  if (port == null) {
232
323
  yield {
233
324
  step: 'error',
234
325
  message: `Cannot manage a local backend for a non-loopback endpoint (${endpoint}).`,
235
- status: await probeBackend(endpoint),
326
+ status: await probeBackend(voice, target),
236
327
  };
237
328
  return;
238
329
  }
239
330
  // 1. Image
240
331
  try {
241
- if (await deps.imagePresent(IMAGE)) {
242
- yield { step: 'image', message: `Image ${IMAGE} already present.` };
332
+ if (await deps.imagePresent(spec.image)) {
333
+ yield { step: 'image', message: `Image ${spec.image} already present.` };
243
334
  }
244
335
  else {
245
- yield { step: 'image', message: `Pulling ${IMAGE} — first run downloads about 2 GB.` };
246
- for await (const line of deps.pullImage(IMAGE)) {
336
+ yield { step: 'image', message: `Pulling ${spec.image} — ${spec.pullNote}.` };
337
+ for await (const line of deps.pullImage(spec.image)) {
247
338
  yield { step: 'image', message: line };
248
339
  }
249
340
  }
250
341
  }
251
342
  catch (err) {
252
- yield { step: 'error', message: errMsg(err), status: await probeBackend(endpoint) };
343
+ yield { step: 'error', message: errMsg(err), status: await probeBackend(voice, target) };
253
344
  return;
254
345
  }
255
346
  // 2. Run — idempotent, so two caretaker instances or a hand/compose-started
256
347
  // container are all fine.
257
348
  try {
258
- const state = await deps.containerState(CONTAINER_NAME);
349
+ const state = await deps.containerState(spec.container);
259
350
  if (state === 'running') {
260
351
  yield { step: 'run', message: 'Container already running.' };
261
352
  }
262
353
  else if (state === 'stopped') {
263
354
  yield { step: 'run', message: 'Starting the existing container.' };
264
- await deps.startContainer(CONTAINER_NAME);
355
+ await deps.startContainer(spec.container);
265
356
  }
266
357
  else {
267
358
  yield { step: 'run', message: `Creating the container on port ${port}.` };
268
- await deps.runContainer(runArgs(port));
359
+ await deps.runContainer(runArgs(port, spec));
269
360
  }
270
361
  }
271
362
  catch (err) {
272
- yield { step: 'error', message: errMsg(err), status: await probeBackend(endpoint) };
363
+ yield { step: 'error', message: errMsg(err), status: await probeBackend(voice, target) };
273
364
  return;
274
365
  }
275
366
  // 3. Readiness — running is not the same as ready.
276
367
  yield { step: 'ready', message: 'Waiting for the backend to respond…' };
277
- if (!(await pollReady(voice))) {
368
+ if (!(await pollReady(voice, target))) {
278
369
  yield {
279
370
  step: 'error',
280
- message: `Timed out after ${READY_TIMEOUT_MS / 1000}s waiting for ${endpoint}/models to respond.`,
281
- status: await probeBackend(endpoint),
371
+ message: `Timed out after ${READY_TIMEOUT_MS / 1000}s waiting for ${endpoint}${spec.readyPath} to respond.`,
372
+ status: await probeBackend(voice, target),
282
373
  };
283
374
  return;
284
375
  }
285
376
  yield { step: 'ready', message: 'Backend is responding.' };
286
- // 4. Models — required, see installModel's comment.
287
- const modelIds = [voice.sttModel, voice.ttsModel].filter((id) => typeof id === 'string' && id.trim().length > 0);
288
- for (const id of modelIds) {
289
- try {
290
- await installModel(voice, id);
291
- yield { step: 'models', message: `Model ${id} ready.` };
292
- }
293
- catch (err) {
294
- yield {
295
- step: 'error',
296
- message: `Failed to install model ${id}: ${errMsg(err)}`,
297
- status: await probeBackend(endpoint),
298
- };
299
- return;
377
+ // 4. Models — required for Speaches, skipped for edge-tts (ships its voices).
378
+ // Only Speaches (the STT target) reaches here because `installsModels` is
379
+ // false for edge-tts. When a separate `ttsEndpoint` is configured, the
380
+ // `ttsModel` belongs to the other host — installing it on Speaches would 404
381
+ // and report a hard failure on the feature's own happy path, so it is
382
+ // excluded. Without a separate endpoint, synthesis also uses this server, so
383
+ // the TTS model is installed alongside the STT one.
384
+ if (spec.installsModels) {
385
+ const hasSeparateTts = !!voice.ttsEndpoint?.trim();
386
+ const modelIds = [voice.sttModel, ...(hasSeparateTts ? [] : [voice.ttsModel])].filter((id) => typeof id === 'string' && id.trim().length > 0);
387
+ for (const id of modelIds) {
388
+ try {
389
+ await installModel(voice, target, id);
390
+ yield { step: 'models', message: `Model ${id} ready.` };
391
+ }
392
+ catch (err) {
393
+ yield {
394
+ step: 'error',
395
+ message: `Failed to install model ${id}: ${errMsg(err)}`,
396
+ status: await probeBackend(voice, target),
397
+ };
398
+ return;
399
+ }
300
400
  }
301
401
  }
302
- yield { step: 'done', message: 'Backend started.', status: await probeBackend(endpoint) };
402
+ yield { step: 'done', message: 'Backend started.', status: await probeBackend(voice, target) };
303
403
  }
304
404
  /** `docker stop` only — never `rm`, never touches the volume. Stopping must
305
405
  * not cost a multi-gigabyte re-download. Removing the container (and only
306
406
  * the container — the model-cache volume and the image survive) is its own
307
407
  * affordance, `deleteBackend`, so a container that froze stale state at
308
408
  * creation (e.g. the network's DNS) can be recreated by the next Start. */
309
- export async function stopBackend() {
310
- await deps.stopContainer(CONTAINER_NAME);
409
+ export async function stopBackend(target = 'stt') {
410
+ await deps.stopContainer(SPECS[target].container);
311
411
  }
312
412
  /** `docker rm -f` on the managed container. Handles running and stopped
313
413
  * alike; never touches the `caretaker-hf-hub-cache` volume or the image. */
314
- export async function deleteBackend() {
315
- await deps.removeContainer(CONTAINER_NAME);
414
+ export async function deleteBackend(target = 'stt') {
415
+ await deps.removeContainer(SPECS[target].container);
316
416
  }
317
417
  // --- HTTP surface + auto-start -------------------------------------------
318
418
  // The realistic collision here is auto-start-at-boot racing the user
319
419
  // pressing Start; there is never more than one caretaker web-server process
320
- // per CARETAKER_HOME in the ordinary case, so a plain module-level boolean
321
- // is enough — no job queue, no lock file. The check and the set below are
322
- // both synchronous (no `await` between them), so two overlapping calls in
323
- // the same process can never both pass the check: Node runs one at a time,
420
+ // per CARETAKER_HOME in the ordinary case. A per-target guard (Set<Target>)
421
+ // means starting edge-tts is not refused because a 2 GB Speaches pull is
422
+ // running — the two are independent containers. The check and the set below
423
+ // are both synchronous (no `await` between them), so two overlapping calls
424
+ // in the same process can never both pass the check: Node runs one at a time,
324
425
  // and nothing yields control between the read and the write.
325
- let backendStarting = false;
426
+ const starting = new Set();
326
427
  /** @internal Test-only seam: observe the in-flight guard without inferring it
327
428
  * from side effects (call counts, timing) — deterministic instead of racy. */
328
- export function isBackendStartInFlightForTest() {
329
- return backendStarting;
429
+ export function isBackendStartInFlightForTest(target = 'stt') {
430
+ return starting.has(target);
330
431
  }
331
- /** Same generator contract as `startBackend`, plus the one-at-a-time rule.
332
- * A caller that loses the race gets a single terminal line carrying the
432
+ /** Same generator contract as `startBackend`, plus the one-at-a-time-per-target
433
+ * rule. A caller that loses the race gets a single terminal line carrying the
333
434
  * current status rather than a second concurrent `docker pull`. */
334
- async function* startBackendGuarded(voice) {
335
- if (backendStarting) {
435
+ async function* startBackendGuarded(voice, target = 'stt') {
436
+ if (starting.has(target)) {
336
437
  yield {
337
438
  step: 'done',
338
439
  message: 'A start is already in progress; showing the current status.',
339
- status: await probeBackend(voice.endpoint),
440
+ status: await probeBackend(voice, target),
340
441
  };
341
442
  return;
342
443
  }
343
- backendStarting = true;
444
+ starting.add(target);
344
445
  try {
345
- yield* startBackend(voice);
446
+ yield* startBackend(voice, target);
346
447
  }
347
448
  finally {
348
- backendStarting = false;
449
+ starting.delete(target);
349
450
  }
350
451
  }
452
+ function reqTarget(c) {
453
+ return c.req.query('target') === 'tts' ? 'tts' : 'stt';
454
+ }
351
455
  export function registerVoiceBackend(app) {
352
456
  app.get('/api/voice/backend', async (c) => {
353
457
  const config = await loadConfig();
354
- const status = await probeBackend(config.voice?.endpoint ?? '');
355
- return c.json(status);
458
+ const voice = config.voice;
459
+ if (!voice) {
460
+ // No voice configured: return the STT status with an empty endpoint,
461
+ // matching the legacy contract (a coherent status, not an error).
462
+ const status = await probeBackend('');
463
+ return c.json({ stt: status, tts: null });
464
+ }
465
+ const statuses = await probeBackends(voice);
466
+ return c.json(statuses);
356
467
  });
357
468
  app.post('/api/voice/backend/start', async (c) => {
358
469
  const resolved = await resolveVoice();
359
470
  if ('error' in resolved)
360
471
  return c.text(resolved.error, 400);
361
472
  const { voice } = resolved;
473
+ const target = reqTarget(c);
474
+ // For the TTS target, refuse when ttsEndpoint is unset or non-loopback —
475
+ // there is no container to manage. The wording matches the STT path so
476
+ // the user sees a consistent message.
477
+ if (target === 'tts') {
478
+ const ttsEndpoint = voice.ttsEndpoint?.trim();
479
+ if (!ttsEndpoint) {
480
+ return c.text('No separate TTS endpoint configured. Set one in Settings → Voice.', 400);
481
+ }
482
+ if (loopbackPort(ttsEndpoint) == null) {
483
+ return c.text(`Cannot manage a local backend for a non-loopback endpoint (${ttsEndpoint}).`, 400);
484
+ }
485
+ }
362
486
  c.header('Content-Type', 'application/x-ndjson');
363
487
  return stream(c, async (s) => {
364
- for await (const progress of startBackendGuarded(voice)) {
488
+ for await (const progress of startBackendGuarded(voice, target)) {
365
489
  await s.writeln(JSON.stringify(progress));
366
490
  }
367
491
  });
368
492
  });
369
493
  app.post('/api/voice/backend/stop', async (c) => {
494
+ const target = reqTarget(c);
370
495
  const config = await loadConfig();
371
496
  try {
372
- await stopBackend();
497
+ await stopBackend(target);
373
498
  }
374
499
  catch {
375
500
  // No such container, daemon unreachable, etc. — the truth is in the
376
501
  // re-probe below, not in a 500 for an action that is already done.
377
502
  }
378
- const status = await probeBackend(config.voice?.endpoint ?? '');
503
+ const voice = config.voice;
504
+ const status = voice ? await probeBackend(voice, target) : await probeBackend('');
379
505
  return c.json(status);
380
506
  });
381
507
  app.post('/api/voice/backend/delete', async (c) => {
508
+ const target = reqTarget(c);
382
509
  // Never tear the container down mid-pull/mid-install: the start flow
383
510
  // assumes the container it just created is still there.
384
- if (backendStarting) {
511
+ if (starting.has(target)) {
385
512
  return c.text('A start is in progress; wait for it to finish before deleting.', 409);
386
513
  }
387
514
  const config = await loadConfig();
388
515
  try {
389
- await deleteBackend();
516
+ await deleteBackend(target);
390
517
  }
391
518
  catch {
392
519
  // No such container, daemon unreachable, etc. — the truth is in the
393
520
  // re-probe below, not in a 500 for an action that is already done.
394
521
  }
395
- const status = await probeBackend(config.voice?.endpoint ?? '');
522
+ const voice = config.voice;
523
+ const status = voice ? await probeBackend(voice, target) : await probeBackend('');
396
524
  return c.json(status);
397
525
  });
398
526
  }
@@ -420,26 +548,37 @@ async function runAutoStart() {
420
548
  }
421
549
  if (!voice || voice.enabled !== true || voice.autoStartBackend !== true)
422
550
  return;
423
- if (loopbackPort(voice.endpoint) == null)
424
- return;
425
- console.log('[voice] auto-starting the managed local speech backend…');
426
- // A 2 GB pull emits one line per layer, all under step 'image': log the first
427
- // and drop the rest. Every other step emits a handful of distinct messages
428
- // that each say something a server log wants — which model was installed,
429
- // whether the readiness wait ever ended — so those are not collapsed.
430
- let loggedImageLine = false;
431
- try {
432
- for await (const progress of startBackendGuarded(voice)) {
433
- if (progress.step === 'image' && loggedImageLine)
434
- continue;
435
- loggedImageLine = progress.step === 'image';
436
- const log = progress.step === 'error' ? console.error : console.log;
437
- log(`[voice] ${progress.message}`);
551
+ // Iterate both targets, skipping any whose endpoint is missing or
552
+ // non-loopback. The two containers are independent: a 2 GB Speaches pull
553
+ // does not block the edge-tts start (per-target in-flight guard). The TTS
554
+ // target is only auto-started when a *separate* ttsEndpoint is configured —
555
+ // without one, synthesis goes to `endpoint` (the single-server Speaches case)
556
+ // and there is no second container to manage.
557
+ for (const target of ['stt', 'tts']) {
558
+ if (target === 'tts' && !voice.ttsEndpoint?.trim())
559
+ continue;
560
+ const endpoint = targetEndpoint(voice, target);
561
+ if (loopbackPort(endpoint) == null)
562
+ continue;
563
+ console.log(`[voice:${target}] auto-starting the managed local ${target === 'stt' ? 'speech' : 'synthesis'} backend…`);
564
+ // A 2 GB pull emits one line per layer, all under step 'image': log the first
565
+ // and drop the rest. Every other step emits a handful of distinct messages
566
+ // that each say something a server log wants — which model was installed,
567
+ // whether the readiness wait ever ended — so those are not collapsed.
568
+ let loggedImageLine = false;
569
+ try {
570
+ for await (const progress of startBackendGuarded(voice, target)) {
571
+ if (progress.step === 'image' && loggedImageLine)
572
+ continue;
573
+ loggedImageLine = progress.step === 'image';
574
+ const log = progress.step === 'error' ? console.error : console.log;
575
+ log(`[voice:${target}] ${progress.message}`);
576
+ }
577
+ }
578
+ catch (err) {
579
+ // startBackend/startBackendGuarded report failures as an 'error' progress
580
+ // line rather than throwing; this only guards a genuinely unexpected throw.
581
+ console.error(`[voice:${target}] auto-start failed: ${errMsg(err)}`);
438
582
  }
439
- }
440
- catch (err) {
441
- // startBackend/startBackendGuarded report failures as an 'error' progress
442
- // line rather than throwing; this only guards a genuinely unexpected throw.
443
- console.error(`[voice] auto-start failed: ${errMsg(err)}`);
444
583
  }
445
584
  }
@@ -11,6 +11,16 @@ export declare function resolveVoice(): Promise<{
11
11
  error: string;
12
12
  }>;
13
13
  export declare function voiceAuthHeaders(voice: VoiceConfig): Record<string, string>;
14
+ /** Build auth headers from an explicit key (which may be stored encrypted).
15
+ * Used so the synthesis leg can send its own key — or none at all. */
16
+ export declare function authHeaders(apiKey: string | undefined | null): Record<string, string>;
17
+ /** Where synthesis goes. A configured `ttsEndpoint` takes its own key — or
18
+ * none at all: the transcription key belongs to a different host and must
19
+ * not leak to a third-party TTS service. */
20
+ export declare function ttsTarget(voice: VoiceConfig): {
21
+ endpoint: string;
22
+ apiKey?: string;
23
+ };
14
24
  export declare function registerVoiceProxy(app: Hono): void;
15
25
  /**
16
26
  * Read a speech endpoint's installed models so the settings form can offer real
@@ -20,6 +30,12 @@ export declare function registerVoiceProxy(app: Hono): void;
20
30
  * those are correctly scoped, unlike the global /v1/audio/voices catalogue, which
21
31
  * ignores its model_id parameter. A plain OpenAI-compatible endpoint reports
22
32
  * neither, so every id is offered for both tasks and the voice stays free text.
33
+ *
34
+ * openai-edge-tts reports models under `{"models": [...]}` (not `{"data": [...]}`),
35
+ * with no task metadata, and publishes its voice list at `/voices/all` rather than
36
+ * per model — voice ids are under the `"name"` key, not `"id"`. When no TTS entry
37
+ * carries its own voices, a best-effort `/voices/all` fetch fills them in; failure
38
+ * degrades to the free-text voice field, which already works.
23
39
  */
24
40
  export declare function fetchVoiceCatalog(endpoint: string, apiKey?: string | null): Promise<VoiceCatalog>;
25
41
  //# sourceMappingURL=voice_proxy.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"voice_proxy.d.ts","sourceRoot":"","sources":["../../../src/cli/web/voice_proxy.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AACjC,OAAO,KAAK,EAAE,eAAe,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAGpE,OAAO,KAAK,EAAE,YAAY,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AAIzE,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,eAAe,GAAG,iBAAiB,GAAG,IAAI,CAUnF;AAED;;0EAE0E;AAC1E,wBAAsB,YAAY,IAAI,OAAO,CAAC;IAAE,KAAK,EAAE,WAAW,CAAA;CAAE,GAAG;IAAE,KAAK,EAAE,MAAM,CAAA;CAAE,CAAC,CAUxF;AASD,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,WAAW,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAG3E;AAOD,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,IAAI,GAAG,IAAI,CA0ElD;AAED;;;;;;;;GAQG;AACH,wBAAsB,iBAAiB,CACrC,QAAQ,EAAE,MAAM,EAChB,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,GACrB,OAAO,CAAC,YAAY,CAAC,CAmDvB"}
1
+ {"version":3,"file":"voice_proxy.d.ts","sourceRoot":"","sources":["../../../src/cli/web/voice_proxy.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AACjC,OAAO,KAAK,EAAE,eAAe,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAGpE,OAAO,KAAK,EAAE,YAAY,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AAIzE,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,eAAe,GAAG,iBAAiB,GAAG,IAAI,CAUnF;AAED;;0EAE0E;AAC1E,wBAAsB,YAAY,IAAI,OAAO,CAAC;IAAE,KAAK,EAAE,WAAW,CAAA;CAAE,GAAG;IAAE,KAAK,EAAE,MAAM,CAAA;CAAE,CAAC,CAUxF;AASD,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,WAAW,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAE3E;AAED;uEACuE;AACvE,wBAAgB,WAAW,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,GAAG,IAAI,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAGrF;AAED;;6CAE6C;AAC7C,wBAAgB,SAAS,CAAC,KAAK,EAAE,WAAW,GAAG;IAAE,QAAQ,EAAE,MAAM,CAAC;IAAC,MAAM,CAAC,EAAE,MAAM,CAAA;CAAE,CAInF;AAOD,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,IAAI,GAAG,IAAI,CA2ElD;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAsB,iBAAiB,CACrC,QAAQ,EAAE,MAAM,EAChB,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,GACrB,OAAO,CAAC,YAAY,CAAC,CA6DvB"}