@ds-hu/dsh-bvi-local 0.0.0-stage → 0.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.
@@ -0,0 +1,762 @@
1
+ /**
2
+ * Host-side lifecycle of one family worker process.
3
+ *
4
+ * The provider owns one runtime per registered family. The runtime forks the worker entry, keeps
5
+ * its stderr as the diagnostic tail, waits for the single-line `{"port":N}` readiness frame and a
6
+ * loopback health check, serializes transcription requests through one in-flight slot, enforces an
7
+ * inference deadline and an idle reclaim timer, and reports state transitions (`starting`,
8
+ * `ready`, `idle`, `failed`) to the provider so the official preparation state stays honest.
9
+ *
10
+ * Every request carries the model input as a WAV body; the bearer token is per process and never
11
+ * leaves this module. A crashed or timed-out worker is killed and marked `failed`; preparation can
12
+ * start a fresh process without re-downloading anything. `dispose()` synchronously withdraws the
13
+ * worker and joins its exit, so unloading the provider never leaves an orphan process.
14
+ *
15
+ * The streaming client (`startStream/pushStream/finishStream/cancelStream`) speaks the worker's
16
+ * X-ASR `/stream/*` routes over the same transport. One live stream is tracked per runtime: it
17
+ * suppresses the idle reclaim, keeps ordinary transcriptions waiting until it is released (the
18
+ * native recognizer is shared), and is dropped when the worker crashes or the runtime is stopped.
19
+ *
20
+ * @module @ds-hu/dsh-bvi-local/worker/runtime
21
+ */
22
+ import { fork } from 'node:child_process'
23
+ import { randomBytes } from 'node:crypto'
24
+ import { fileURLToPath } from 'node:url'
25
+
26
+ /** Largest stderr tail kept for error messages. */
27
+ const MAX_STDERR_BYTES = 64 * 1024
28
+ /** Largest readiness line accepted from the worker (the real one is ~20 bytes). */
29
+ const MAX_READY_LINE_BYTES = 4 * 1024
30
+
31
+ /** Default deadline for loading the model and publishing the port. */
32
+ export const DEFAULT_HANDSHAKE_TIMEOUT_MS = 10 * 60_000
33
+ /** Default deadline for one transcription round-trip. */
34
+ export const DEFAULT_INFERENCE_TIMEOUT_MS = 120_000
35
+ /** Default idle reclaim: stop the worker after five quiet minutes (0 keeps it alive). */
36
+ export const DEFAULT_IDLE_TIMEOUT_MS = 5 * 60_000
37
+ /** Accepted but not yet finished transcriptions (the worker itself decodes one at a time). */
38
+ export const DEFAULT_MAX_PENDING = 4
39
+ /** Grace period between SIGTERM and SIGKILL. */
40
+ const DEFAULT_GRACE_MS = 1_000
41
+ /** Default worker entry next to this module. */
42
+ const DEFAULT_ENTRY_PATH = fileURLToPath(new URL('./entry.js', import.meta.url))
43
+ /** Largest raw PCM16LE chunk forwarded to a streaming worker (the service matches this bound). */
44
+ export const MAX_STREAM_CHUNK_BYTES = 1024 * 1024
45
+ /** Smallest meaningful streaming chunk (one mono 16 kHz PCM16 sample). */
46
+ const MIN_STREAM_CHUNK_BYTES = 2
47
+
48
+ /** A worker that is unavailable, crashed, timed out or rejected input, with a stable code. */
49
+ export class WorkerError extends Error {
50
+ /**
51
+ * @param {'not-ready'|'queue-full'|'timeout'|'crash'|'protocol'|'http'|'invalid-input'|'disposed'} code - stable code.
52
+ * @param {string} message - human-readable explanation.
53
+ * @param {ErrorOptions} [options] - native error options.
54
+ */
55
+ constructor(code, message, options) {
56
+ super(message, options)
57
+ this.name = 'WorkerError'
58
+ this.code = code
59
+ }
60
+ }
61
+
62
+ /**
63
+ * @param {AbortSignal|undefined} signal - cancellation signal.
64
+ * @returns {void}
65
+ * @throws {Error} when the signal is already aborted.
66
+ */
67
+ function throwIfAborted(signal) {
68
+ if (signal !== undefined) signal.throwIfAborted()
69
+ }
70
+
71
+ /**
72
+ * @param {AbortSignal} signal - aborted signal.
73
+ * @returns {Error} the abort reason or a plain abort error.
74
+ */
75
+ function abortReasonOf(signal) {
76
+ const reason = signal.reason
77
+ if (reason instanceof Error) return reason
78
+ const error = new Error('The local speech worker request was cancelled')
79
+ error.name = 'AbortError'
80
+ return error
81
+ }
82
+
83
+ /**
84
+ * @param {unknown} error - thrown value.
85
+ * @returns {string} readable message.
86
+ */
87
+ function messageOf(error) {
88
+ return error instanceof Error ? error.message : String(error)
89
+ }
90
+
91
+ /**
92
+ * @param {unknown} value - candidate.
93
+ * @returns {value is Record<string, any>} whether the value is a plain JSON object.
94
+ */
95
+ function isPlainObject(value) {
96
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
97
+ }
98
+
99
+ /** Manages one worker process for one local model family. */
100
+ export class WorkerRuntime {
101
+ /** @type {Set<Function>} */
102
+ #listeners = new Set()
103
+ /** @type {'idle'|'starting'|'ready'|'failed'} */
104
+ #state = 'idle'
105
+ /** @type {string|undefined} */
106
+ #message
107
+ /** @type {{ child: import('node:child_process').ChildProcess, port: number, token: string, variantId: string }|null} */
108
+ #worker = null
109
+ /** @type {Promise<void>|null} */
110
+ #starting = null
111
+ /** @type {Promise<unknown>} */
112
+ #tail = Promise.resolve()
113
+ /** @type {number} */
114
+ #pending = 0
115
+ /** @type {NodeJS.Timeout|undefined} */
116
+ #idleTimer
117
+ /** @type {boolean} */
118
+ #disposed = false
119
+ /** @type {AbortController} */
120
+ #lifetime = new AbortController()
121
+ /** @type {boolean} */
122
+ #stopping = false
123
+ /** @type {{ id: string, language: string }|null} */
124
+ #stream = null
125
+ /** @type {Set<() => void>} */
126
+ #streamWaiters = new Set()
127
+
128
+ /**
129
+ * @param {{
130
+ * family: string,
131
+ * entryPath?: string,
132
+ * handshakeTimeoutMs?: number,
133
+ * inferenceTimeoutMs?: number,
134
+ * idleTimeoutMs?: number,
135
+ * maxPending?: number,
136
+ * graceMs?: number,
137
+ * forkImpl?: typeof fork,
138
+ * fetchImpl?: typeof fetch,
139
+ * logger?: (message: string) => void,
140
+ * }} options - family identity and lifecycle tuning.
141
+ */
142
+ constructor(options) {
143
+ this.#options = {
144
+ family: options.family,
145
+ entryPath: options.entryPath ?? DEFAULT_ENTRY_PATH,
146
+ handshakeTimeoutMs: options.handshakeTimeoutMs ?? DEFAULT_HANDSHAKE_TIMEOUT_MS,
147
+ inferenceTimeoutMs: options.inferenceTimeoutMs ?? DEFAULT_INFERENCE_TIMEOUT_MS,
148
+ idleTimeoutMs: options.idleTimeoutMs ?? DEFAULT_IDLE_TIMEOUT_MS,
149
+ maxPending: options.maxPending ?? DEFAULT_MAX_PENDING,
150
+ graceMs: options.graceMs ?? DEFAULT_GRACE_MS,
151
+ forkImpl: options.forkImpl ?? fork,
152
+ fetchImpl: options.fetchImpl ?? fetch,
153
+ logger: options.logger ?? (() => undefined),
154
+ }
155
+ }
156
+
157
+ /** @type {{ family: string, entryPath: string, handshakeTimeoutMs: number, inferenceTimeoutMs: number, idleTimeoutMs: number, maxPending: number, graceMs: number, forkImpl: typeof fork, fetchImpl: typeof fetch, logger: (message: string) => void }} */
158
+ #options
159
+
160
+ /**
161
+ * Observe runtime state transitions.
162
+ * @param {() => void} listener - invalidation callback.
163
+ * @returns {() => void} unsubscribe function.
164
+ */
165
+ subscribe(listener) {
166
+ this.#listeners.add(listener)
167
+ return () => { this.#listeners.delete(listener) }
168
+ }
169
+
170
+ /**
171
+ * @returns {{ state: 'idle'|'starting'|'ready'|'failed', message?: string, streaming: boolean }} latest runtime state.
172
+ */
173
+ snapshot() {
174
+ const snapshot = { state: this.#state, streaming: this.#stream !== null }
175
+ return this.#message === undefined ? snapshot : { ...snapshot, message: this.#message }
176
+ }
177
+
178
+ /**
179
+ * @param {'idle'|'starting'|'ready'|'failed'} state - next state.
180
+ * @param {string} [message] - diagnostic for `failed`.
181
+ * @returns {void}
182
+ */
183
+ #setState(state, message) {
184
+ if (this.#state === state && this.#message === message) return
185
+ this.#state = state
186
+ this.#message = message
187
+ for (const listener of this.#listeners) listener()
188
+ }
189
+
190
+ /**
191
+ * @returns {void}
192
+ */
193
+ #clearIdle() {
194
+ if (this.#idleTimer !== undefined) {
195
+ clearTimeout(this.#idleTimer)
196
+ this.#idleTimer = undefined
197
+ }
198
+ }
199
+
200
+ /**
201
+ * @returns {void}
202
+ */
203
+ #scheduleIdle() {
204
+ this.#clearIdle()
205
+ const { idleTimeoutMs } = this.#options
206
+ if (!(idleTimeoutMs > 0) || this.#disposed || this.#state !== 'ready' || this.#pending > 0 || this.#stream !== null) return
207
+ this.#idleTimer = setTimeout(() => {
208
+ this.#idleTimer = undefined
209
+ if (this.#state !== 'ready' || this.#pending > 0) return
210
+ void this.stop('idle').catch(() => undefined)
211
+ }, idleTimeoutMs)
212
+ this.#idleTimer.unref?.()
213
+ }
214
+
215
+ /**
216
+ * Release the live streaming session and wake the transcriptions waiting on it.
217
+ * @returns {void}
218
+ */
219
+ #releaseStream() {
220
+ this.#stream = null
221
+ for (const resolve of this.#streamWaiters) resolve()
222
+ this.#streamWaiters.clear()
223
+ this.#scheduleIdle()
224
+ }
225
+
226
+ /**
227
+ * Resolve once no streaming session is live.
228
+ * @param {AbortSignal|undefined} signal - caller cancellation.
229
+ * @returns {Promise<void>} resolves when the stream was released.
230
+ */
231
+ #streamIdle(signal) {
232
+ if (this.#stream === null) return Promise.resolve()
233
+ return raceWithAbort(new Promise((resolve) => { this.#streamWaiters.add(resolve) }), signal)
234
+ }
235
+
236
+ /**
237
+ * Validate that a known live stream is being addressed on a ready worker.
238
+ * @param {string} streamId - opaque session id returned by `startStream`.
239
+ * @returns {{ id: string, language: string }} the live session.
240
+ * @throws {WorkerError} when the runtime, worker or session is not in the expected state.
241
+ */
242
+ #requireStream(streamId) {
243
+ if (this.#disposed) throw new WorkerError('disposed', 'The local speech worker runtime is disposed')
244
+ if (this.#state !== 'ready' || this.#worker === null) {
245
+ throw new WorkerError('not-ready', this.#state === 'failed' && this.#message !== undefined
246
+ ? this.#message
247
+ : 'The local speech worker is not running; prepare the model first')
248
+ }
249
+ const stream = this.#stream
250
+ if (stream === null) throw new WorkerError('not-ready', 'No local streaming session is active')
251
+ if (stream.id !== streamId) throw new WorkerError('invalid-input', `Unknown local streaming session: ${String(streamId)}`)
252
+ return stream
253
+ }
254
+
255
+ /**
256
+ * Map a non-200 streaming answer onto the runtime error taxonomy.
257
+ * @param {number} status - HTTP status.
258
+ * @param {Record<string, any>} payload - parsed body.
259
+ * @param {string} action - short infinitive for the fallback message.
260
+ * @returns {WorkerError} the mapped failure.
261
+ */
262
+ #streamFailure(status, payload, action) {
263
+ const detail = typeof payload.error === 'string' ? payload.error : `Local speech worker returned HTTP ${status}`
264
+ if (status === 400 || status === 404 || status === 413 || status === 415) return new WorkerError('invalid-input', detail)
265
+ if (status === 409 || status === 429) return new WorkerError('queue-full', detail)
266
+ return new WorkerError('http', `${detail} (while trying to ${action})`)
267
+ }
268
+
269
+ /**
270
+ * POST one authenticated loopback request and parse the JSON answer.
271
+ * @param {string} path - route with query string.
272
+ * @param {{ body?: Uint8Array, contentType?: string, signal?: AbortSignal, timeoutMs?: number, label?: string }} [options] - body, headers and cancellation.
273
+ * @returns {Promise<{ status: number, payload: Record<string, any> }>} response status and parsed body.
274
+ * @throws {WorkerError} when the worker is not ready, timed out or the transport failed.
275
+ */
276
+ async #request(path, options = {}) {
277
+ const info = this.#worker
278
+ if (this.#disposed) throw new WorkerError('disposed', 'The local speech worker runtime is disposed')
279
+ if (this.#state !== 'ready' || info === null) {
280
+ throw new WorkerError('not-ready', this.#state === 'failed' && this.#message !== undefined
281
+ ? this.#message
282
+ : 'The local speech worker is not running; prepare the model first')
283
+ }
284
+ const label = options.label ?? 'Local speech worker request'
285
+ const timeoutMs = options.timeoutMs ?? this.#options.inferenceTimeoutMs
286
+ const timeout = AbortSignal.timeout(timeoutMs)
287
+ let timedOut = false
288
+ timeout.addEventListener('abort', () => { timedOut = true }, { once: true })
289
+ const combined = options.signal === undefined ? timeout : AbortSignal.any([options.signal, timeout])
290
+ /** @type {Record<string, string>} */
291
+ const headers = { authorization: `Bearer ${info.token}` }
292
+ if (options.contentType !== undefined) headers['content-type'] = options.contentType
293
+ if (options.body !== undefined) headers['content-length'] = String(options.body.byteLength)
294
+ /** @type {Response} */
295
+ let response
296
+ try {
297
+ response = await this.#options.fetchImpl(`http://127.0.0.1:${info.port}${path}`, {
298
+ method: 'POST',
299
+ headers,
300
+ body: options.body,
301
+ signal: combined,
302
+ })
303
+ } catch (error) {
304
+ if (options.signal !== undefined && options.signal.aborted) throw abortReasonOf(options.signal)
305
+ if (timedOut) {
306
+ await this.stop('timeout').catch(() => undefined)
307
+ throw new WorkerError('timeout', `${label} timed out after ${timeoutMs} ms`)
308
+ }
309
+ throw new WorkerError('crash', `${label} failed: ${messageOf(error)}`, { cause: error })
310
+ }
311
+ const payload = await response.json().catch(() => ({}))
312
+ if (!isPlainObject(payload)) return { status: response.status, payload: {} }
313
+ return { status: response.status, payload }
314
+ }
315
+
316
+ /**
317
+ * Wait for the worker's single readiness line, its exit, or cancellation.
318
+ * @param {import('node:child_process').ChildProcess} child - running worker.
319
+ * @param {AbortSignal} signal - combined caller + deadline signal.
320
+ * @param {() => string} stderrTail - current stderr tail for diagnostics.
321
+ * @returns {Promise<number>} loopback port.
322
+ */
323
+ #handshake(child, signal, stderrTail) {
324
+ return new Promise((resolve, reject) => {
325
+ /** @type {string} */
326
+ let buffer = ''
327
+ let settled = false
328
+ const finish = (settle, value) => {
329
+ if (settled) return
330
+ settled = true
331
+ signal.removeEventListener('abort', onAbort)
332
+ child.stdout?.off('data', onData)
333
+ child.off('exit', onExit)
334
+ child.off('error', onError)
335
+ settle(value)
336
+ }
337
+ const onAbort = () => finish(reject, abortReasonOf(signal))
338
+ const onExit = (code, signalName) => {
339
+ const tail = stderrTail()
340
+ finish(reject, new WorkerError('crash', `Local speech worker exited before it was ready (${signalName ?? `code ${code}`})${tail === '' ? '' : `: ${tail}`}`))
341
+ }
342
+ const onError = (error) => finish(reject, new WorkerError('crash', `Local speech worker could not start: ${messageOf(error)}`, { cause: error }))
343
+ const onData = (chunk) => {
344
+ buffer += chunk.toString('utf8')
345
+ const newline = buffer.indexOf('\n')
346
+ if (newline < 0) {
347
+ if (buffer.length > MAX_READY_LINE_BYTES) {
348
+ finish(reject, new WorkerError('protocol', `Local speech worker printed an oversized readiness line: ${buffer.slice(0, 200)}`))
349
+ }
350
+ return
351
+ }
352
+ const line = buffer.slice(0, newline).trim()
353
+ /** @type {unknown} */
354
+ let parsed
355
+ try {
356
+ parsed = JSON.parse(line)
357
+ } catch {
358
+ finish(reject, new WorkerError('protocol', `Local speech worker printed an unexpected readiness line: ${line.slice(0, 200)}`))
359
+ return
360
+ }
361
+ const port = isPlainObject(parsed) ? parsed.port : undefined
362
+ if (!Number.isSafeInteger(port) || /** @type {number} */ (port) <= 0 || /** @type {number} */ (port) > 65_535) {
363
+ finish(reject, new WorkerError('protocol', `Local speech worker reported an invalid port: ${line.slice(0, 200)}`))
364
+ return
365
+ }
366
+ finish(resolve, /** @type {number} */ (port))
367
+ }
368
+ if (signal.aborted) {
369
+ finish(reject, abortReasonOf(signal))
370
+ return
371
+ }
372
+ signal.addEventListener('abort', onAbort, { once: true })
373
+ child.stdout?.on('data', onData)
374
+ child.once('exit', onExit)
375
+ child.once('error', onError)
376
+ })
377
+ }
378
+
379
+ /**
380
+ * Start one worker process and wait until it accepts requests.
381
+ * @param {{ variantId: string, variantDir: string, threads: number, vadPath?: string, maxAudioBytes?: number }} request - model layout for the worker.
382
+ * @param {AbortSignal|undefined} signal - preparation cancellation.
383
+ * @returns {Promise<void>} resolves when the worker is ready.
384
+ */
385
+ async #start(request, signal) {
386
+ throwIfAborted(signal)
387
+ const deadline = new AbortController()
388
+ let timedOut = false
389
+ const timer = setTimeout(() => { timedOut = true; deadline.abort() }, this.#options.handshakeTimeoutMs)
390
+ timer.unref?.()
391
+ const combined = signal === undefined ? deadline.signal : AbortSignal.any([signal, deadline.signal])
392
+ const token = randomBytes(32).toString('hex')
393
+ const payload = {
394
+ family: this.#options.family,
395
+ variantId: request.variantId,
396
+ variantDir: request.variantDir,
397
+ config: {
398
+ threads: request.threads,
399
+ vadPath: request.vadPath,
400
+ maxAudioBytes: request.maxAudioBytes,
401
+ },
402
+ }
403
+ let stderrTail = ''
404
+ /** @type {import('node:child_process').ChildProcess|undefined} */
405
+ let child
406
+ const kill = () => {
407
+ try {
408
+ if (child !== undefined && child.exitCode === null && child.signalCode === null) child.kill('SIGKILL')
409
+ } catch {
410
+ // The process is already gone; the handshake failure is the useful error.
411
+ }
412
+ }
413
+ try {
414
+ child = this.#options.forkImpl(this.#options.entryPath, [JSON.stringify(payload)], {
415
+ env: {
416
+ ...process.env,
417
+ BVI_SPEECH_TOKEN: token,
418
+ ELECTRON_RUN_AS_NODE: '1',
419
+ },
420
+ stdio: ['ignore', 'pipe', 'pipe', 'ipc'],
421
+ serialization: 'json',
422
+ windowsHide: true,
423
+ })
424
+ child.stderr?.on('data', (chunk) => {
425
+ stderrTail += chunk.toString('utf8')
426
+ if (stderrTail.length > MAX_STDERR_BYTES) stderrTail = stderrTail.slice(-MAX_STDERR_BYTES)
427
+ })
428
+ // Nothing else is expected on stdout; drain it so the worker can never block on a full pipe.
429
+ child.stdout?.on('data', () => undefined)
430
+ const port = await this.#handshake(child, combined, () => stderrTail.trim())
431
+ let health
432
+ try {
433
+ health = await this.#options.fetchImpl(`http://127.0.0.1:${port}/health`, {
434
+ headers: { authorization: `Bearer ${token}` },
435
+ signal: combined,
436
+ })
437
+ } catch (error) {
438
+ throwIfAborted(signal)
439
+ throw new WorkerError('protocol', `Local speech worker health check failed: ${messageOf(error)}`, { cause: error })
440
+ }
441
+ if (!health.ok) throw new WorkerError('protocol', `Local speech worker health check returned HTTP ${health.status}`)
442
+ const info = { child, port, token, variantId: request.variantId }
443
+ this.#worker = info
444
+ child.once('exit', (code, signalName) => {
445
+ if (this.#worker !== info) return
446
+ this.#worker = null
447
+ this.#clearIdle()
448
+ if (this.#disposed) {
449
+ this.#setState('idle')
450
+ this.#releaseStream()
451
+ return
452
+ }
453
+ if (this.#stopping) {
454
+ this.#releaseStream()
455
+ return
456
+ }
457
+ const tail = stderrTail.trim()
458
+ const detail = `Local speech worker exited (${signalName ?? `code ${code}`})${tail === '' ? '' : `: ${tail}`}`
459
+ this.#options.logger(detail)
460
+ this.#setState('failed', detail)
461
+ this.#releaseStream()
462
+ })
463
+ this.#setState('ready')
464
+ this.#scheduleIdle()
465
+ } catch (error) {
466
+ kill()
467
+ this.#worker = null
468
+ if (signal !== undefined && signal.aborted) {
469
+ if (!this.#disposed) this.#setState('idle')
470
+ throw abortReasonOf(signal)
471
+ }
472
+ if (this.#lifetime.signal.aborted) {
473
+ if (!this.#disposed) this.#setState('idle')
474
+ throw abortReasonOf(this.#lifetime.signal)
475
+ }
476
+ const failure = timedOut
477
+ ? new WorkerError('timeout', `Local speech worker did not become ready within ${this.#options.handshakeTimeoutMs} ms${stderrTail.trim() === '' ? '' : `: ${stderrTail.trim()}`}`)
478
+ : error instanceof WorkerError
479
+ ? error
480
+ : new WorkerError('crash', `Unable to start the local speech worker: ${messageOf(error)}`, { cause: error })
481
+ if (!this.#disposed) this.#setState('failed', failure.message)
482
+ throw failure
483
+ } finally {
484
+ clearTimeout(timer)
485
+ }
486
+ }
487
+
488
+ /**
489
+ * Ensure a worker for this variant is running, restarting a crashed or idle one when needed.
490
+ * @param {{ variantId: string, variantDir: string, threads: number, vadPath?: string, maxAudioBytes?: number }} request - model layout.
491
+ * @param {AbortSignal} [signal] - preparation cancellation.
492
+ * @returns {Promise<void>} resolves when the worker is ready.
493
+ */
494
+ async ensureStarted(request, signal) {
495
+ if (this.#disposed) throw new WorkerError('disposed', 'The local speech worker runtime is disposed')
496
+ throwIfAborted(signal)
497
+ if (this.#lifetime.signal.aborted) throw abortReasonOf(this.#lifetime.signal)
498
+ const allowed = signal === undefined
499
+ ? this.#lifetime.signal
500
+ : AbortSignal.any([signal, this.#lifetime.signal])
501
+ if (this.#starting !== null) {
502
+ await raceWithAbort(this.#starting, signal)
503
+ if (this.#state === 'ready' && this.#worker?.variantId === request.variantId) return
504
+ }
505
+ if (this.#state === 'ready' && this.#worker !== null) {
506
+ if (this.#worker.variantId === request.variantId) {
507
+ this.#clearIdle()
508
+ return
509
+ }
510
+ await this.stop('switch-variant')
511
+ throwIfAborted(signal)
512
+ }
513
+ this.#clearIdle()
514
+ this.#setState('starting')
515
+ const starting = this.#start(request, allowed)
516
+ this.#starting = starting
517
+ try {
518
+ await starting
519
+ } finally {
520
+ if (this.#starting === starting) this.#starting = null
521
+ }
522
+ }
523
+
524
+ /**
525
+ * Recognize one canonical WAV recording.
526
+ *
527
+ * A live streaming session owns the recognizer until it finishes or is cancelled, so a batch
528
+ * transcription issued meanwhile waits for it instead of racing the same native model.
529
+ * @param {{ audio: Uint8Array, language: string, signal?: AbortSignal }} request - audio and language hint.
530
+ * @returns {Promise<{ text: string, audioSeconds: number, inferenceSeconds: number }>} transcript.
531
+ * @throws {WorkerError} when the worker is unavailable, busy, timed out or rejected the audio.
532
+ */
533
+ async transcribe(request) {
534
+ const { audio, language, signal } = request
535
+ if (this.#disposed) throw new WorkerError('disposed', 'The local speech worker runtime is disposed')
536
+ if (this.#state !== 'ready' || this.#worker === null) {
537
+ throw new WorkerError('not-ready', this.#state === 'failed' && this.#message !== undefined
538
+ ? this.#message
539
+ : 'The local speech worker is not running; prepare the model first')
540
+ }
541
+ if (this.#stream !== null) await this.#streamIdle(signal)
542
+ if (this.#pending >= this.#options.maxPending) {
543
+ throw new WorkerError('queue-full', `The local speech worker already has ${this.#pending} pending transcriptions`)
544
+ }
545
+ this.#pending += 1
546
+ this.#clearIdle()
547
+ const job = async () => {
548
+ const { status, payload } = await this.#request(`/transcribe?language=${encodeURIComponent(language)}`, {
549
+ body: audio,
550
+ contentType: 'audio/wav',
551
+ signal,
552
+ label: 'Local transcription',
553
+ })
554
+ if (status === 200) {
555
+ if (typeof payload.text !== 'string' || typeof payload.audioSeconds !== 'number' || typeof payload.inferenceSeconds !== 'number') {
556
+ throw new WorkerError('protocol', 'Local speech worker returned an invalid transcript payload')
557
+ }
558
+ return { text: payload.text, audioSeconds: payload.audioSeconds, inferenceSeconds: payload.inferenceSeconds }
559
+ }
560
+ const detail = typeof payload.error === 'string' ? payload.error : `Local speech worker returned HTTP ${status}`
561
+ if (status === 400 || status === 413) throw new WorkerError('invalid-input', detail)
562
+ if (status === 429) throw new WorkerError('queue-full', detail)
563
+ throw new WorkerError('http', detail)
564
+ }
565
+ const run = this.#tail.then(job, job)
566
+ this.#tail = run.then(() => undefined, () => undefined)
567
+ try {
568
+ return await run
569
+ } finally {
570
+ this.#pending -= 1
571
+ if (this.#pending === 0) this.#scheduleIdle()
572
+ }
573
+ }
574
+
575
+ /**
576
+ * Open one live streaming session on the X-ASR worker.
577
+ * @param {{ language?: string, signal?: AbortSignal }} [request] - selected language and cancellation.
578
+ * @returns {Promise<{ streamId: string }>} opaque worker session id.
579
+ * @throws {WorkerError} when the worker is not ready or already has a live stream.
580
+ */
581
+ async startStream(request = {}) {
582
+ const language = typeof request.language === 'string' && request.language !== '' ? request.language : 'auto'
583
+ if (this.#disposed) throw new WorkerError('disposed', 'The local speech worker runtime is disposed')
584
+ if (this.#stream !== null) throw new WorkerError('queue-full', 'A local streaming session is already active')
585
+ const { status, payload } = await this.#request(`/stream/start?language=${encodeURIComponent(language)}`, {
586
+ signal: request.signal,
587
+ label: 'Local streaming start',
588
+ })
589
+ if (status !== 200) throw this.#streamFailure(status, payload, 'start the streaming session')
590
+ if (typeof payload.streamId !== 'string' || payload.streamId === '') {
591
+ throw new WorkerError('protocol', 'Local speech worker returned an invalid streaming session')
592
+ }
593
+ this.#stream = { id: payload.streamId, language }
594
+ this.#clearIdle()
595
+ return { streamId: payload.streamId }
596
+ }
597
+
598
+ /**
599
+ * Push one raw PCM16LE mono 16 kHz chunk into the live session.
600
+ * @param {string} streamId - opaque session id returned by `startStream`.
601
+ * @param {Uint8Array} pcm - PCM16LE bytes.
602
+ * @param {{ signal?: AbortSignal }} [request] - caller cancellation.
603
+ * @returns {Promise<{ partial: string }>} cumulative transcript so far (may be empty).
604
+ * @throws {WorkerError} when the session is gone or the chunk is invalid.
605
+ */
606
+ async pushStream(streamId, pcm, request = {}) {
607
+ this.#requireStream(streamId)
608
+ if (!(pcm instanceof Uint8Array) || pcm.byteLength < MIN_STREAM_CHUNK_BYTES || pcm.byteLength % 2 !== 0) {
609
+ throw new WorkerError('invalid-input', 'Streaming audio must be a non-empty Uint8Array of whole PCM16LE samples')
610
+ }
611
+ if (pcm.byteLength > MAX_STREAM_CHUNK_BYTES) {
612
+ throw new WorkerError('invalid-input', `Streaming audio chunks must not exceed ${MAX_STREAM_CHUNK_BYTES} bytes`)
613
+ }
614
+ const { status, payload } = await this.#request(`/stream/chunk?stream=${encodeURIComponent(streamId)}`, {
615
+ body: pcm,
616
+ contentType: 'application/octet-stream',
617
+ signal: request.signal,
618
+ label: 'Local streaming chunk',
619
+ })
620
+ if (status !== 200) throw this.#streamFailure(status, payload, 'push streaming audio')
621
+ if (typeof payload.partial !== 'string') {
622
+ throw new WorkerError('protocol', 'Local speech worker returned an invalid streaming partial')
623
+ }
624
+ return { partial: payload.partial }
625
+ }
626
+
627
+ /**
628
+ * Finish the live session with the documented drain protocol and return the final transcript.
629
+ * @param {string} streamId - opaque session id returned by `startStream`.
630
+ * @param {{ signal?: AbortSignal }} [request] - caller cancellation.
631
+ * @returns {Promise<{ text: string, audioSeconds: number, inferenceSeconds: number }>} final transcript.
632
+ * @throws {WorkerError} when the session is gone or the worker failed.
633
+ */
634
+ async finishStream(streamId, request = {}) {
635
+ const stream = this.#requireStream(streamId)
636
+ const started = performance.now()
637
+ try {
638
+ const { status, payload } = await this.#request(`/stream/finish?stream=${encodeURIComponent(streamId)}`, {
639
+ signal: request.signal,
640
+ label: 'Local streaming finish',
641
+ })
642
+ if (status !== 200) throw this.#streamFailure(status, payload, 'finish the streaming session')
643
+ if (typeof payload.text !== 'string' || typeof payload.audioSeconds !== 'number' || !Number.isFinite(payload.audioSeconds)) {
644
+ throw new WorkerError('protocol', 'Local speech worker returned an invalid streaming transcript')
645
+ }
646
+ return {
647
+ text: payload.text,
648
+ audioSeconds: payload.audioSeconds,
649
+ inferenceSeconds: (performance.now() - started) / 1000,
650
+ }
651
+ } finally {
652
+ if (this.#stream === stream) this.#releaseStream()
653
+ }
654
+ }
655
+
656
+ /**
657
+ * Cancel the live session. Tolerant: a session that is already gone answers `{ ok: false }`.
658
+ * @param {string} streamId - opaque session id returned by `startStream`.
659
+ * @param {{ signal?: AbortSignal }} [request] - caller cancellation.
660
+ * @returns {Promise<{ ok: boolean }>} whether the worker acknowledged the cancel.
661
+ * @throws {WorkerError} when the worker itself is not running.
662
+ */
663
+ async cancelStream(streamId, request = {}) {
664
+ const stream = this.#stream
665
+ if (stream === null || stream.id !== streamId) return { ok: false }
666
+ try {
667
+ const { status, payload } = await this.#request(`/stream/cancel?stream=${encodeURIComponent(streamId)}`, {
668
+ signal: request.signal,
669
+ label: 'Local streaming cancel',
670
+ })
671
+ if (status !== 200) throw this.#streamFailure(status, payload, 'cancel the streaming session')
672
+ return { ok: true }
673
+ } finally {
674
+ if (this.#stream === stream) this.#releaseStream()
675
+ }
676
+ }
677
+
678
+ /**
679
+ * Stop the worker process (idle reclaim, variant switch, timeout or dispose).
680
+ * @param {string} [reason] - diagnostic reason passed to the logger.
681
+ * @returns {Promise<void>} resolves after the child process exited.
682
+ */
683
+ async stop(reason = 'stop') {
684
+ this.#clearIdle()
685
+ this.#releaseStream()
686
+ const info = this.#worker
687
+ if (info === null) {
688
+ if (!this.#disposed && this.#state === 'starting') this.#setState('idle')
689
+ return
690
+ }
691
+ this.#stopping = true
692
+ this.#worker = null
693
+ try {
694
+ const exited = new Promise((resolve) => { info.child.once('exit', resolve) })
695
+ info.child.kill('SIGTERM')
696
+ const killTimer = setTimeout(() => {
697
+ if (info.child.exitCode === null && info.child.signalCode === null) info.child.kill('SIGKILL')
698
+ }, this.#options.graceMs)
699
+ killTimer.unref?.()
700
+ await exited
701
+ clearTimeout(killTimer)
702
+ if (reason !== 'stop') this.#options.logger(`Local speech worker stopped (${reason})`)
703
+ } finally {
704
+ this.#stopping = false
705
+ if (this.#state === 'ready' || this.#state === 'starting') this.#setState('idle')
706
+ }
707
+ }
708
+
709
+ /**
710
+ * Stop the worker and refuse future starts. Idempotent.
711
+ * @returns {Promise<void>} resolves after the worker exited.
712
+ */
713
+ async dispose() {
714
+ if (this.#disposed) return
715
+ this.#disposed = true
716
+ this.#lifetime.abort(new Error('The local speech worker runtime was disposed'))
717
+ this.#clearIdle()
718
+ this.#releaseStream()
719
+ const starting = this.#starting
720
+ if (starting !== null) {
721
+ try {
722
+ await starting
723
+ } catch {
724
+ // The start was aborted above; the worker child is killed by its own error path.
725
+ }
726
+ }
727
+ const info = this.#worker
728
+ if (info !== null) {
729
+ this.#worker = null
730
+ const exited = new Promise((resolve) => { info.child.once('exit', resolve) })
731
+ info.child.kill('SIGTERM')
732
+ const killTimer = setTimeout(() => {
733
+ if (info.child.exitCode === null && info.child.signalCode === null) info.child.kill('SIGKILL')
734
+ }, this.#options.graceMs)
735
+ killTimer.unref?.()
736
+ await exited
737
+ clearTimeout(killTimer)
738
+ }
739
+ this.#setState('idle')
740
+ this.#listeners.clear()
741
+ }
742
+ }
743
+
744
+ /**
745
+ * Wait for `promise` but reject early when the caller's signal aborts.
746
+ * @template T
747
+ * @param {Promise<T>} promise - task to join.
748
+ * @param {AbortSignal|undefined} signal - caller cancellation.
749
+ * @returns {Promise<T>} the task result.
750
+ */
751
+ function raceWithAbort(promise, signal) {
752
+ if (signal === undefined) return promise
753
+ if (signal.aborted) return Promise.reject(abortReasonOf(signal))
754
+ return new Promise((resolve, reject) => {
755
+ const onAbort = () => reject(abortReasonOf(signal))
756
+ signal.addEventListener('abort', onAbort, { once: true })
757
+ promise.then(
758
+ (value) => { signal.removeEventListener('abort', onAbort); resolve(value) },
759
+ (error) => { signal.removeEventListener('abort', onAbort); reject(error) },
760
+ )
761
+ })
762
+ }