@hyperwindmill/caretaker-cli 0.14.1 β†’ 0.15.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 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/cli/index.ts"],"names":[],"mappings":"AAgBA,wBAAsB,MAAM,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CA2E1D"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/cli/index.ts"],"names":[],"mappings":"AAgBA,wBAAsB,MAAM,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAqF1D"}
package/dist/cli/index.js CHANGED
@@ -26,8 +26,17 @@ export async function runCli(argv) {
26
26
  }
27
27
  // Read the version from package.json at runtime (relative to this module, not
28
28
  // the CWD) so it tracks the single Changesets-managed version without a static
29
- // JSON import that would break tsc's rootDir constraint.
30
- const { version } = JSON.parse(readFileSync(new URL('../../package.json', import.meta.url), 'utf8'));
29
+ // JSON import that would break tsc's rootDir constraint. Guarded: this runs for
30
+ // every subcommand, and package.json is not always co-located with dist/ (e.g.
31
+ // the Electron desktop bundle ships dist/ only) β€” an unreadable file must never
32
+ // take the whole process down, only degrade the reported version.
33
+ let version = '0.0.0';
34
+ try {
35
+ version = JSON.parse(readFileSync(new URL('../../package.json', import.meta.url), 'utf8')).version;
36
+ }
37
+ catch {
38
+ // ponytail: fall back to a placeholder version if package.json isn't bundled
39
+ }
31
40
  const program = new Command();
32
41
  program
33
42
  .name('caretaker-cli')
@@ -1 +1 @@
1
- {"version":3,"file":"server.d.ts","sourceRoot":"","sources":["../../../src/cli/web/server.ts"],"names":[],"mappings":"AASA,OAAO,KAAK,OAAO,MAAM,wBAAwB,CAAC;AAwClD,OAAO,KAAK,EAAE,WAAW,EAAE,cAAc,EAAgC,MAAM,gBAAgB,CAAC;AAChG,OAAO,KAAK,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IAQ7B,OAAO,CAAC,QAAQ,CAAC,IAAI;IAPvB,OAAO,CAAC,UAAU,CAAkC;IACpD,OAAO,CAAC,OAAO,CAAuB;IACtC,OAAO,CAAC,QAAQ,CAAgC;IAChD,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAc;IACzC,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAC,CAAS;gBAGjB,IAAI,EAAE;QACrB,KAAK,EAAE,WAAW,CAAC;QACnB,QAAQ,EAAE,cAAc,CAAC;QACzB,KAAK,EAAE,OAAO,CAAC,IAAI,EAAE,CAAC;QACtB,UAAU,EAAE,MAAM,CAAC;QACnB,SAAS,CAAC,EAAE,MAAM,CAAC;KACpB;IAMH,IAAI,SAAS,IAAI,OAAO,CAEvB;IAED,eAAe,IAAI,GAAG;IAIhB,KAAK,CACT,MAAM,EAAE,MAAM,EACd,EAAE,EAAE,aAAa,EACjB,cAAc,CAAC,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE,CAAC,GACrE,OAAO,CAAC,IAAI,CAAC;IA+EhB,KAAK,IAAI,IAAI;CAGd;AAED,wBAAsB,WAAW,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CA47B3E"}
@@ -20,6 +20,8 @@ import { listForAgent, readSession, deleteSession, computeContextUsage, createSe
20
20
  import { startBackgroundScheduler, loadTaskRuns } from './scheduler.js';
21
21
  import { fsRouter } from './fs.js';
22
22
  import { activationStatus, resolvePlanningEnabled } from './scheduler/task_roles.js';
23
+ import { registerVoiceProxy, voiceClientConfig, fetchVoiceCatalog } from './voice_proxy.js';
24
+ import { registerVoiceBackend, maybeAutoStartBackend } from './voice_backend.js';
23
25
  // Resolve Webview static files path.
24
26
  // Published npm package ships the assets under dist/webview (see scripts/copy-webview.mjs);
25
27
  // in the monorepo dev tree they live in the sibling webview-ui package.
@@ -128,6 +130,8 @@ export async function startServer(port, host) {
128
130
  const app = new Hono();
129
131
  app.route('/api/fs', fsRouter);
130
132
  registerTaskBridge(app);
133
+ registerVoiceProxy(app);
134
+ registerVoiceBackend(app);
131
135
  // Pure-Node static serving with absolute path validation and fallback
132
136
  app.get('/', (c) => {
133
137
  try {
@@ -158,6 +162,23 @@ export async function startServer(port, host) {
158
162
  c.header('Content-Type', 'application/json');
159
163
  return c.body(file);
160
164
  });
165
+ app.get('/vad/:file', (c) => {
166
+ const name = c.req.param('file');
167
+ // Serve only from the flat vad directory; reject any traversal attempt.
168
+ if (!/^[A-Za-z0-9._-]+$/.test(name))
169
+ return c.text('Not found', 404);
170
+ const full = path.join(webviewDistPath, 'vad', name);
171
+ if (!fs.existsSync(full))
172
+ return c.text('Not found', 404);
173
+ const type = name.endsWith('.wasm')
174
+ ? 'application/wasm'
175
+ : name.endsWith('.onnx')
176
+ ? 'application/octet-stream'
177
+ : name.endsWith('.mjs') || name.endsWith('.js')
178
+ ? 'text/javascript'
179
+ : 'application/octet-stream';
180
+ return c.body(fs.readFileSync(full), 200, { 'content-type': type });
181
+ });
161
182
  // Attachments REST endpoint
162
183
  app.get('/api/attachments/:sessionId/:id', async (c) => {
163
184
  const sessionId = c.req.param('sessionId');
@@ -551,6 +572,9 @@ export async function startServer(port, host) {
551
572
  console.log(`\nπŸš€ Caretaker Server running at http://${host}:${port}\n`);
552
573
  // Start the background scheduler trigger daemon
553
574
  startBackgroundScheduler();
575
+ // Opt-in: start the managed local speech backend if configured to. Never
576
+ // awaited β€” a first run pulls 2.08 GB and must not hang server boot.
577
+ maybeAutoStartBackend();
554
578
  wss.on('connection', async (ws) => {
555
579
  let controller = null;
556
580
  let currentAgent = null;
@@ -581,6 +605,7 @@ export async function startServer(port, host) {
581
605
  provider: a.provider,
582
606
  }));
583
607
  post({ type: 'agentsLoaded', agents: agentSummaries });
608
+ post({ type: 'voiceConfig', voice: voiceClientConfig(await loadConfig()) });
584
609
  // Select the first agent as default if none is active
585
610
  if (!currentAgent && agents.length > 0) {
586
611
  await selectAgentInternal(agents[0], providers);
@@ -830,6 +855,7 @@ export async function startServer(port, host) {
830
855
  case 'saveConfig':
831
856
  try {
832
857
  await saveConfig(msg.config);
858
+ post({ type: 'voiceConfig', voice: voiceClientConfig(msg.config) });
833
859
  void loadAgentsAndSend();
834
860
  void sendSettingsData();
835
861
  }
@@ -977,6 +1003,15 @@ export async function startServer(port, host) {
977
1003
  });
978
1004
  }
979
1005
  return;
1006
+ case 'fetchVoiceModels':
1007
+ try {
1008
+ const catalog = await fetchVoiceCatalog(msg.endpoint, msg.apiKey ?? null);
1009
+ post({ type: 'voiceModelsFetched', result: { ok: true, catalog } });
1010
+ }
1011
+ catch (err) {
1012
+ post({ type: 'voiceModelsFetched', result: { ok: false, error: String(err) } });
1013
+ }
1014
+ return;
980
1015
  case 'getTaskRuns':
981
1016
  try {
982
1017
  const runs = await loadTaskRuns(msg.taskId);
@@ -0,0 +1,57 @@
1
+ import type { Hono } from 'hono';
2
+ import type { VoiceConfig } from 'caretaker-types';
3
+ export type BackendStatus = {
4
+ /** Why the affordance may be unavailable, distinguished because the fixes differ. */
5
+ docker: 'ok' | 'absent' | 'denied' | 'down';
6
+ container: 'running' | 'stopped' | 'absent';
7
+ imagePresent: boolean;
8
+ /** Port parsed out of the endpoint, or null when it is not loopback. */
9
+ port: number | null;
10
+ /** True when /v1/models answers β€” running is not the same as ready. */
11
+ responding: boolean;
12
+ };
13
+ export type StartProgress = {
14
+ step: 'image' | 'run' | 'ready' | 'models' | 'done' | 'error';
15
+ message: string;
16
+ /** Present only on the terminal line ('done' | 'error'). */
17
+ status?: BackendStatus;
18
+ };
19
+ interface BackendDeps {
20
+ containerState: (name: string) => Promise<'running' | 'stopped' | 'absent'>;
21
+ dockerInfo: () => Promise<{
22
+ ok: true;
23
+ } | {
24
+ ok: false;
25
+ code?: string;
26
+ stderr: string;
27
+ }>;
28
+ imagePresent: (image: string) => Promise<boolean>;
29
+ /** Streams docker's own pull output line by line β€” not parsed into a
30
+ * percentage, just passed through as progress. */
31
+ pullImage: (image: string) => AsyncGenerator<string>;
32
+ runContainer: (args: string[]) => Promise<void>;
33
+ startContainer: (name: string) => Promise<void>;
34
+ stopContainer: (name: string) => Promise<void>;
35
+ }
36
+ /** @internal Test-only seam: swap the docker layer so tests never need a real
37
+ * Docker daemon. Pass null to restore the real implementation. */
38
+ export declare function setVoiceBackendDepsForTest(overrides: Partial<BackendDeps> | null): void;
39
+ /** Port when the endpoint is loopback, else null. Exported for tests. */
40
+ export declare function loopbackPort(endpoint: string): number | null;
41
+ export declare function probeBackend(endpoint: string): Promise<BackendStatus>;
42
+ export declare function startBackend(voice: VoiceConfig): AsyncGenerator<StartProgress>;
43
+ /** `docker stop` only β€” never `rm`, never touches the volume. Stopping must
44
+ * not cost a multi-gigabyte re-download; removing the container or its cache
45
+ * is not offered, `docker` in a terminal remains the way to do that. */
46
+ export declare function stopBackend(): Promise<void>;
47
+ /** @internal Test-only seam: observe the in-flight guard without inferring it
48
+ * from side effects (call counts, timing) β€” deterministic instead of racy. */
49
+ export declare function isBackendStartInFlightForTest(): boolean;
50
+ export declare function registerVoiceBackend(app: Hono): void;
51
+ /** Fire-and-forget: called once right after `serve()` in server.ts. Must
52
+ * never block server boot (a first run pulls 2.08 GB) and must never throw
53
+ * out of the caller β€” every failure is logged and otherwise swallowed, and
54
+ * the UI learns the outcome by polling GET /api/voice/backend. */
55
+ export declare function maybeAutoStartBackend(): void;
56
+ export {};
57
+ //# sourceMappingURL=voice_backend.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"voice_backend.d.ts","sourceRoot":"","sources":["../../../src/cli/web/voice_backend.ts"],"names":[],"mappings":"AAUA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAEjC,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAoBnD,MAAM,MAAM,aAAa,GAAG;IAC1B,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D;mEACmE;AACnE,wBAAgB,0BAA0B,CAAC,SAAS,EAAE,OAAO,CAAC,WAAW,CAAC,GAAG,IAAI,GAAG,IAAI,CAEvF;AASD,yEAAyE;AACzE,wBAAgB,YAAY,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAU5D;AAgCD,wBAAsB,YAAY,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,aAAa,CAAC,CAS3E;AAiDD,wBAAuB,YAAY,CAAC,KAAK,EAAE,WAAW,GAAG,cAAc,CAAC,aAAa,CAAC,CA4ErF;AAED;;yEAEyE;AACzE,wBAAsB,WAAW,IAAI,OAAO,CAAC,IAAI,CAAC,CAEjD;AAYD;+EAC+E;AAC/E,wBAAgB,6BAA6B,IAAI,OAAO,CAEvD;AAsBD,wBAAgB,oBAAoB,CAAC,GAAG,EAAE,IAAI,GAAG,IAAI,CA+BpD;AAED;;;mEAGmE;AACnE,wBAAgB,qBAAqB,IAAI,IAAI,CAE5C"}
@@ -0,0 +1,418 @@
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).
9
+ import { execFile, spawn } from 'node:child_process';
10
+ import { promisify } from 'node:util';
11
+ import { stream } from 'hono/streaming';
12
+ import { commandEnv, probeShellEnv } from '../../harness/tools/builtin/shell-env.js';
13
+ import { containerState } from '../../lib/docker.js';
14
+ import { loadConfig } from '../../store/json.js';
15
+ import { resolveVoice, voiceAuthHeaders } from './voice_proxy.js';
16
+ 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';
24
+ const READY_TIMEOUT_MS = 60_000;
25
+ const READY_POLL_INTERVAL_MS = 500;
26
+ const PROBE_TIMEOUT_MS = 2_000;
27
+ async function dockerExec(args) {
28
+ return exec('docker', args, { env: commandEnv(), maxBuffer: 8 * 1024 * 1024 });
29
+ }
30
+ /** Bridges a child process's stdout+stderr into an async generator of lines.
31
+ * Used only for `docker pull`, whose progress bars use `\r` rather than `\n`. */
32
+ async function* streamLines(proc) {
33
+ const queue = [];
34
+ let notify = null;
35
+ let done = false;
36
+ let failure = null;
37
+ const wake = () => {
38
+ if (notify) {
39
+ const n = notify;
40
+ notify = null;
41
+ n();
42
+ }
43
+ };
44
+ const push = (chunk) => {
45
+ for (const line of chunk.toString('utf8').split(/\r\n|\r|\n/)) {
46
+ if (line.trim().length > 0)
47
+ queue.push(line);
48
+ }
49
+ wake();
50
+ };
51
+ proc.stdout?.on('data', push);
52
+ proc.stderr?.on('data', push);
53
+ proc.on('error', (err) => {
54
+ failure = err;
55
+ done = true;
56
+ wake();
57
+ });
58
+ proc.on('close', (code) => {
59
+ done = true;
60
+ if (code !== 0 && !failure)
61
+ failure = new Error(`docker pull exited with code ${code}`);
62
+ wake();
63
+ });
64
+ for (;;) {
65
+ if (queue.length > 0) {
66
+ yield queue.shift();
67
+ continue;
68
+ }
69
+ if (done) {
70
+ if (failure)
71
+ throw failure;
72
+ return;
73
+ }
74
+ await new Promise((resolve) => {
75
+ notify = resolve;
76
+ });
77
+ }
78
+ }
79
+ const defaultDeps = {
80
+ containerState,
81
+ async dockerInfo() {
82
+ try {
83
+ await dockerExec(['info']);
84
+ return { ok: true };
85
+ }
86
+ catch (err) {
87
+ const e = err;
88
+ return { ok: false, code: e.code, stderr: e.stderr ?? e.message ?? '' };
89
+ }
90
+ },
91
+ async imagePresent(image) {
92
+ try {
93
+ await dockerExec(['image', 'inspect', image]);
94
+ return true;
95
+ }
96
+ catch {
97
+ return false;
98
+ }
99
+ },
100
+ pullImage(image) {
101
+ const proc = spawn('docker', ['pull', image], { env: commandEnv() });
102
+ return streamLines(proc);
103
+ },
104
+ async runContainer(args) {
105
+ await dockerExec(args);
106
+ },
107
+ async startContainer(name) {
108
+ await dockerExec(['start', name]);
109
+ },
110
+ async stopContainer(name) {
111
+ await dockerExec(['stop', name]);
112
+ },
113
+ };
114
+ let deps = defaultDeps;
115
+ /** @internal Test-only seam: swap the docker layer so tests never need a real
116
+ * Docker daemon. Pass null to restore the real implementation. */
117
+ export function setVoiceBackendDepsForTest(overrides) {
118
+ deps = overrides ? { ...defaultDeps, ...overrides } : defaultDeps;
119
+ }
120
+ // --- Port / endpoint parsing --------------------------------------------
121
+ // Node's WHATWG URL keeps the brackets in `.hostname` for a bracketed IPv6
122
+ // authority (verified: `new URL('http://[::1]:1/').hostname === '[::1]'`,
123
+ // not `'::1'`), so the literal bracketed form is what we must match here.
124
+ const LOOPBACK_HOSTS = new Set(['127.0.0.1', 'localhost', '[::1]']);
125
+ /** Port when the endpoint is loopback, else null. Exported for tests. */
126
+ export function loopbackPort(endpoint) {
127
+ let parsed;
128
+ try {
129
+ parsed = new URL(endpoint);
130
+ }
131
+ catch {
132
+ return null;
133
+ }
134
+ if (!LOOPBACK_HOSTS.has(parsed.hostname))
135
+ return null;
136
+ if (parsed.port)
137
+ return Number(parsed.port);
138
+ return parsed.protocol === 'https:' ? 443 : 80;
139
+ }
140
+ function joinUrl(endpoint, suffix) {
141
+ return `${endpoint.replace(/\/+$/, '')}${suffix}`;
142
+ }
143
+ /** Short-timeout GET, independent of Docker β€” a remote or hand-run backend
144
+ * still reports `responding: true`. */
145
+ async function probeResponding(endpoint, headers = {}) {
146
+ const ctrl = new AbortController();
147
+ const timer = setTimeout(() => ctrl.abort(), PROBE_TIMEOUT_MS);
148
+ try {
149
+ const res = await fetch(joinUrl(endpoint, '/models'), { headers, signal: ctrl.signal });
150
+ return res.ok;
151
+ }
152
+ catch {
153
+ return false;
154
+ }
155
+ finally {
156
+ clearTimeout(timer);
157
+ }
158
+ }
159
+ async function classifyDocker() {
160
+ const info = await deps.dockerInfo();
161
+ if (info.ok)
162
+ return 'ok';
163
+ if (info.code === 'ENOENT')
164
+ return 'absent';
165
+ if (/permission denied/i.test(info.stderr))
166
+ return 'denied';
167
+ return 'down';
168
+ }
169
+ export async function probeBackend(endpoint) {
170
+ const port = loopbackPort(endpoint);
171
+ const docker = await classifyDocker();
172
+ // Coherent status without throwing: don't even ask Docker for container /
173
+ // image state when it isn't there to ask.
174
+ const container = docker === 'ok' ? await deps.containerState(CONTAINER_NAME) : 'absent';
175
+ const imagePresent = docker === 'ok' ? await deps.imagePresent(IMAGE) : false;
176
+ const responding = await probeResponding(endpoint);
177
+ return { docker, container, imagePresent, port, responding };
178
+ }
179
+ function runArgs(port) {
180
+ return [
181
+ 'run',
182
+ '-d',
183
+ '--name',
184
+ CONTAINER_NAME,
185
+ '-p',
186
+ `127.0.0.1:${port}:8000`,
187
+ '-v',
188
+ VOLUME,
189
+ IMAGE,
190
+ ];
191
+ }
192
+ function errMsg(err) {
193
+ return err instanceof Error ? err.message : String(err);
194
+ }
195
+ async function pollReady(voice) {
196
+ const deadline = Date.now() + READY_TIMEOUT_MS;
197
+ const headers = voiceAuthHeaders(voice);
198
+ for (;;) {
199
+ if (await probeResponding(voice.endpoint, headers))
200
+ return true;
201
+ if (Date.now() >= deadline)
202
+ return false;
203
+ await new Promise((resolve) => setTimeout(resolve, READY_POLL_INTERVAL_MS));
204
+ }
205
+ }
206
+ /** POST <endpoint>/models/<id> β€” not optional: Speaches does not fetch models
207
+ * on demand, so skipping this leaves the backend reporting healthy and then
208
+ * 404ing on the first real request. An already-installed model commonly
209
+ * answers 409 rather than 2xx; that is success, not failure.
210
+ *
211
+ * Model ids are typically `org/name` (e.g. `Systran/faster-whisper-small`)
212
+ * and Speaches' route captures the id verbatim including the slash β€” so the
213
+ * id goes in the path unencoded, not through encodeURIComponent (which would
214
+ * turn it into `%2F` and very likely 404 against a path-style route match). */
215
+ async function installModel(voice, modelId) {
216
+ const res = await fetch(joinUrl(voice.endpoint, `/models/${modelId}`), {
217
+ method: 'POST',
218
+ headers: voiceAuthHeaders(voice),
219
+ });
220
+ if (res.ok || res.status === 409)
221
+ return;
222
+ const body = await res.text().catch(() => '');
223
+ throw new Error(`${res.status} ${res.statusText}: ${body.slice(0, 300)}`);
224
+ }
225
+ export async function* startBackend(voice) {
226
+ const endpoint = voice.endpoint;
227
+ const port = loopbackPort(endpoint);
228
+ if (port == null) {
229
+ yield {
230
+ step: 'error',
231
+ message: `Cannot manage a local backend for a non-loopback endpoint (${endpoint}).`,
232
+ status: await probeBackend(endpoint),
233
+ };
234
+ return;
235
+ }
236
+ // 1. Image
237
+ try {
238
+ if (await deps.imagePresent(IMAGE)) {
239
+ yield { step: 'image', message: `Image ${IMAGE} already present.` };
240
+ }
241
+ else {
242
+ yield { step: 'image', message: `Pulling ${IMAGE} β€” first run downloads about 2 GB.` };
243
+ for await (const line of deps.pullImage(IMAGE)) {
244
+ yield { step: 'image', message: line };
245
+ }
246
+ }
247
+ }
248
+ catch (err) {
249
+ yield { step: 'error', message: errMsg(err), status: await probeBackend(endpoint) };
250
+ return;
251
+ }
252
+ // 2. Run β€” idempotent, so two caretaker instances or a hand/compose-started
253
+ // container are all fine.
254
+ try {
255
+ const state = await deps.containerState(CONTAINER_NAME);
256
+ if (state === 'running') {
257
+ yield { step: 'run', message: 'Container already running.' };
258
+ }
259
+ else if (state === 'stopped') {
260
+ yield { step: 'run', message: 'Starting the existing container.' };
261
+ await deps.startContainer(CONTAINER_NAME);
262
+ }
263
+ else {
264
+ yield { step: 'run', message: `Creating the container on port ${port}.` };
265
+ await deps.runContainer(runArgs(port));
266
+ }
267
+ }
268
+ catch (err) {
269
+ yield { step: 'error', message: errMsg(err), status: await probeBackend(endpoint) };
270
+ return;
271
+ }
272
+ // 3. Readiness β€” running is not the same as ready.
273
+ yield { step: 'ready', message: 'Waiting for the backend to respond…' };
274
+ if (!(await pollReady(voice))) {
275
+ yield {
276
+ step: 'error',
277
+ message: `Timed out after ${READY_TIMEOUT_MS / 1000}s waiting for ${endpoint}/models to respond.`,
278
+ status: await probeBackend(endpoint),
279
+ };
280
+ return;
281
+ }
282
+ yield { step: 'ready', message: 'Backend is responding.' };
283
+ // 4. Models β€” required, see installModel's comment.
284
+ const modelIds = [voice.sttModel, voice.ttsModel].filter((id) => typeof id === 'string' && id.trim().length > 0);
285
+ for (const id of modelIds) {
286
+ try {
287
+ await installModel(voice, id);
288
+ yield { step: 'models', message: `Model ${id} ready.` };
289
+ }
290
+ catch (err) {
291
+ yield {
292
+ step: 'error',
293
+ message: `Failed to install model ${id}: ${errMsg(err)}`,
294
+ status: await probeBackend(endpoint),
295
+ };
296
+ return;
297
+ }
298
+ }
299
+ yield { step: 'done', message: 'Backend started.', status: await probeBackend(endpoint) };
300
+ }
301
+ /** `docker stop` only β€” never `rm`, never touches the volume. Stopping must
302
+ * not cost a multi-gigabyte re-download; removing the container or its cache
303
+ * is not offered, `docker` in a terminal remains the way to do that. */
304
+ export async function stopBackend() {
305
+ await deps.stopContainer(CONTAINER_NAME);
306
+ }
307
+ // --- HTTP surface + auto-start -------------------------------------------
308
+ // The realistic collision here is auto-start-at-boot racing the user
309
+ // pressing Start; there is never more than one caretaker web-server process
310
+ // per CARETAKER_HOME in the ordinary case, so a plain module-level boolean
311
+ // is enough β€” no job queue, no lock file. The check and the set below are
312
+ // both synchronous (no `await` between them), so two overlapping calls in
313
+ // the same process can never both pass the check: Node runs one at a time,
314
+ // and nothing yields control between the read and the write.
315
+ let backendStarting = false;
316
+ /** @internal Test-only seam: observe the in-flight guard without inferring it
317
+ * from side effects (call counts, timing) β€” deterministic instead of racy. */
318
+ export function isBackendStartInFlightForTest() {
319
+ return backendStarting;
320
+ }
321
+ /** Same generator contract as `startBackend`, plus the one-at-a-time rule.
322
+ * A caller that loses the race gets a single terminal line carrying the
323
+ * current status rather than a second concurrent `docker pull`. */
324
+ async function* startBackendGuarded(voice) {
325
+ if (backendStarting) {
326
+ yield {
327
+ step: 'done',
328
+ message: 'A start is already in progress; showing the current status.',
329
+ status: await probeBackend(voice.endpoint),
330
+ };
331
+ return;
332
+ }
333
+ backendStarting = true;
334
+ try {
335
+ yield* startBackend(voice);
336
+ }
337
+ finally {
338
+ backendStarting = false;
339
+ }
340
+ }
341
+ export function registerVoiceBackend(app) {
342
+ app.get('/api/voice/backend', async (c) => {
343
+ const config = await loadConfig();
344
+ const status = await probeBackend(config.voice?.endpoint ?? '');
345
+ return c.json(status);
346
+ });
347
+ app.post('/api/voice/backend/start', async (c) => {
348
+ const resolved = await resolveVoice();
349
+ if ('error' in resolved)
350
+ return c.text(resolved.error, 400);
351
+ const { voice } = resolved;
352
+ c.header('Content-Type', 'application/x-ndjson');
353
+ return stream(c, async (s) => {
354
+ for await (const progress of startBackendGuarded(voice)) {
355
+ await s.writeln(JSON.stringify(progress));
356
+ }
357
+ });
358
+ });
359
+ app.post('/api/voice/backend/stop', async (c) => {
360
+ const config = await loadConfig();
361
+ try {
362
+ await stopBackend();
363
+ }
364
+ catch {
365
+ // No such container, daemon unreachable, etc. β€” the truth is in the
366
+ // re-probe below, not in a 500 for an action that is already done.
367
+ }
368
+ const status = await probeBackend(config.voice?.endpoint ?? '');
369
+ return c.json(status);
370
+ });
371
+ }
372
+ /** Fire-and-forget: called once right after `serve()` in server.ts. Must
373
+ * never block server boot (a first run pulls 2.08 GB) and must never throw
374
+ * out of the caller β€” every failure is logged and otherwise swallowed, and
375
+ * the UI learns the outcome by polling GET /api/voice/backend. */
376
+ export function maybeAutoStartBackend() {
377
+ void runAutoStart();
378
+ }
379
+ async function runAutoStart() {
380
+ let voice;
381
+ try {
382
+ // Boot races the interactive-shell probe that `commandEnv()` reads, and
383
+ // losing that race would spawn docker with an unprobed PATH β€” an ENOENT
384
+ // there is classified as `docker: 'absent'`, telling the user Docker is
385
+ // not installed when it is merely not on this process's PATH. Awaiting is
386
+ // free: the probe is cached and shared, and we are already off the boot path.
387
+ await probeShellEnv();
388
+ voice = (await loadConfig()).voice;
389
+ }
390
+ catch (err) {
391
+ console.error(`[voice] auto-start: could not load config: ${errMsg(err)}`);
392
+ return;
393
+ }
394
+ if (!voice || voice.enabled !== true || voice.autoStartBackend !== true)
395
+ return;
396
+ if (loopbackPort(voice.endpoint) == null)
397
+ return;
398
+ console.log('[voice] auto-starting the managed local speech backend…');
399
+ // A 2 GB pull emits one line per layer, all under step 'image': log the first
400
+ // and drop the rest. Every other step emits a handful of distinct messages
401
+ // that each say something a server log wants β€” which model was installed,
402
+ // whether the readiness wait ever ended β€” so those are not collapsed.
403
+ let loggedImageLine = false;
404
+ try {
405
+ for await (const progress of startBackendGuarded(voice)) {
406
+ if (progress.step === 'image' && loggedImageLine)
407
+ continue;
408
+ loggedImageLine = progress.step === 'image';
409
+ const log = progress.step === 'error' ? console.error : console.log;
410
+ log(`[voice] ${progress.message}`);
411
+ }
412
+ }
413
+ catch (err) {
414
+ // startBackend/startBackendGuarded report failures as an 'error' progress
415
+ // line rather than throwing; this only guards a genuinely unexpected throw.
416
+ console.error(`[voice] auto-start failed: ${errMsg(err)}`);
417
+ }
418
+ }
@@ -0,0 +1,25 @@
1
+ import type { Hono } from 'hono';
2
+ import type { CaretakerConfig, VoiceConfig } from 'caretaker-types';
3
+ import type { VoiceCatalog, VoiceClientConfig } from 'webview-ui/bridge';
4
+ export declare function voiceClientConfig(config: CaretakerConfig): VoiceClientConfig | null;
5
+ /** Resolve the usable voice config, or a reason it cannot be used. Shared with
6
+ * voice_backend.ts so the two surfaces refuse for the same reasons, in the same
7
+ * words (the HTTP status is the caller's choice, the wording is not). */
8
+ export declare function resolveVoice(): Promise<{
9
+ voice: VoiceConfig;
10
+ } | {
11
+ error: string;
12
+ }>;
13
+ export declare function voiceAuthHeaders(voice: VoiceConfig): Record<string, string>;
14
+ export declare function registerVoiceProxy(app: Hono): void;
15
+ /**
16
+ * Read a speech endpoint's installed models so the settings form can offer real
17
+ * choices instead of free text.
18
+ *
19
+ * Speaches reports `task` per model and embeds each TTS model's own voices β€” and
20
+ * those are correctly scoped, unlike the global /v1/audio/voices catalogue, which
21
+ * ignores its model_id parameter. A plain OpenAI-compatible endpoint reports
22
+ * neither, so every id is offered for both tasks and the voice stays free text.
23
+ */
24
+ export declare function fetchVoiceCatalog(endpoint: string, apiKey?: string | null): Promise<VoiceCatalog>;
25
+ //# sourceMappingURL=voice_proxy.d.ts.map
@@ -0,0 +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"}