@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,691 @@
1
+ /**
2
+ * The official `ctx.speechToText` provider of one local model family.
3
+ *
4
+ * The provider owns everything the official seam expects for a downloadable local model:
5
+ *
6
+ * - `info` (id, display name, host-local location, languages, setup estimate, download origins),
7
+ * - `preparation` — an official-word-list state machine (`unprepared`, `checking`, `downloading`,
8
+ * `loading`, `waking`, `ready`, `standby`, `cancelled`, `failed`) with snapshot/subscribe/
9
+ * prepare/cancel; preparation is idempotent per variant and one task runs at a time,
10
+ * - `transcribe` — canonical WAV validation through the core helpers, a prepared/standby check,
11
+ * then one worker round-trip returning `{ text, audioSeconds, inferenceSeconds }`.
12
+ * - `bviStreaming` — only on families whose catalog record declares `streaming: true` (X-ASR):
13
+ * a service-facing live session (`start({ language })` → `push/finish/cancel`) backed by the
14
+ * worker's private `/stream/*` routes. The batch `transcribe` path is untouched.
15
+ *
16
+ * The selected variant comes from the official `prepare(options)` call (`options.variant`, an
17
+ * extension of the official type used by our service) with a fallback to the bundle's
18
+ * `config.json` (`local[providerId].variant`), so a non-default variant also works when the
19
+ * provider is driven directly (smoke tests, scripts).
20
+ *
21
+ * All model files live under `<dataRoot>/<family>/<variant>/`; the shared Silero VAD model lives
22
+ * under `<dataRoot>/_shared/`. The data root is the row's `config.dataRoot` (an absolute model
23
+ * directory), never a guessed home directory.
24
+ *
25
+ * @module @ds-hu/dsh-bvi-local/provider
26
+ */
27
+ import { join } from 'node:path'
28
+ import { MAX_WAV_BYTES, ProviderError, validateWav } from '@ds-hu/dsh-bvi-core'
29
+ import { SHARED_ASSETS } from '@ds-hu/dsh-bvi-core/catalog/local.js'
30
+ import { downloadSourcesForVariant, ensureVariantInstalled } from './provision/install.js'
31
+ import { MAX_STREAM_CHUNK_BYTES, WorkerError, WorkerRuntime } from './worker/runtime.js'
32
+
33
+ /** Official preparation phases that describe work in progress. */
34
+ const IN_FLIGHT_PHASES = new Set(['checking', 'downloading', 'loading', 'waking', 'cancelling'])
35
+
36
+ /**
37
+ * @param {unknown} error - thrown value.
38
+ * @returns {string} readable message.
39
+ */
40
+ function messageOf(error) {
41
+ return error instanceof Error ? error.message : String(error)
42
+ }
43
+
44
+ /**
45
+ * @param {unknown} value - candidate byte count.
46
+ * @returns {number|undefined} a rounded non-negative byte count.
47
+ */
48
+ function bytesOf(value) {
49
+ return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? Math.round(value) : undefined
50
+ }
51
+
52
+ /**
53
+ * Map a worker/runtime failure onto the ProviderError taxonomy the service relays to the client.
54
+ * @param {unknown} error - thrown value.
55
+ * @returns {import('@ds-hu/dsh-bvi-core').ProviderError} stable provider failure.
56
+ */
57
+ function streamFailureOf(error) {
58
+ if (error instanceof ProviderError) return error
59
+ const message = messageOf(error)
60
+ const code = error instanceof WorkerError ? error.code : undefined
61
+ switch (code) {
62
+ case 'timeout':
63
+ return new ProviderError('timeout', message, { cause: error })
64
+ case 'http':
65
+ return new ProviderError('http', message, { cause: error })
66
+ case 'protocol':
67
+ return new ProviderError('parse', message, { cause: error })
68
+ case 'invalid-input':
69
+ case 'not-ready':
70
+ case 'queue-full':
71
+ case 'disposed':
72
+ return new ProviderError('unsupported', message, { cause: error })
73
+ default:
74
+ return new ProviderError('network', message, { cause: error })
75
+ }
76
+ }
77
+
78
+ /** One live streaming session; the service relay forwards its three methods. */
79
+ class LocalStreamingSession {
80
+ /** @type {'live'|'finishing'|'finished'|'failed'|'cancelled'} */
81
+ #state = 'live'
82
+ /** @type {Promise<{ text: string, audioSeconds: number, inferenceSeconds: number }>|null} */
83
+ #finishPromise = null
84
+
85
+ /**
86
+ * @param {WorkerRuntime} runtime - parent runtime of the prepared worker.
87
+ * @param {string} streamId - opaque worker session id.
88
+ * @param {() => void} onEnd - invoked once when the session stops holding the provider slot.
89
+ */
90
+ constructor(runtime, streamId, onEnd) {
91
+ this.#runtime = runtime
92
+ this.#streamId = streamId
93
+ this.#onEnd = onEnd
94
+ }
95
+
96
+ /** @type {WorkerRuntime} */
97
+ #runtime
98
+ /** @type {string} */
99
+ #streamId
100
+ /** @type {() => void} */
101
+ #onEnd
102
+
103
+ /**
104
+ * Append one PCM16LE mono 16 kHz chunk.
105
+ * @param {Uint8Array} pcm - raw little-endian samples.
106
+ * @returns {Promise<{ partial: string }>} cumulative transcript so far.
107
+ * @throws {ProviderError} when the session is closed or the chunk is invalid.
108
+ */
109
+ async push(pcm) {
110
+ if (this.#state !== 'live') throw new ProviderError('unsupported', 'The streaming session is not live')
111
+ if (!(pcm instanceof Uint8Array) || pcm.byteLength < 2 || pcm.byteLength % 2 !== 0) {
112
+ throw new ProviderError('unsupported', 'Streaming audio must be a non-empty Uint8Array of whole PCM16LE samples')
113
+ }
114
+ if (pcm.byteLength > MAX_STREAM_CHUNK_BYTES) {
115
+ throw new ProviderError('unsupported', `Streaming audio chunks must not exceed ${MAX_STREAM_CHUNK_BYTES} bytes`)
116
+ }
117
+ try {
118
+ return await this.#runtime.pushStream(this.#streamId, pcm)
119
+ } catch (error) {
120
+ throw streamFailureOf(error)
121
+ }
122
+ }
123
+
124
+ /**
125
+ * Finish the session. The first call settles the transcript; later calls join that settlement.
126
+ * @returns {Promise<{ text: string, audioSeconds: number, inferenceSeconds: number }>} final transcript.
127
+ * @throws {ProviderError} when the session is closed or the worker failed.
128
+ */
129
+ finish() {
130
+ if (this.#finishPromise !== null) return this.#finishPromise
131
+ if (this.#state !== 'live') return Promise.reject(new ProviderError('unsupported', 'The streaming session is not live'))
132
+ this.#state = 'finishing'
133
+ this.#finishPromise = (async () => {
134
+ try {
135
+ const result = await this.#runtime.finishStream(this.#streamId)
136
+ this.#state = 'finished'
137
+ return result
138
+ } catch (error) {
139
+ this.#state = 'failed'
140
+ throw streamFailureOf(error)
141
+ } finally {
142
+ this.#onEnd()
143
+ }
144
+ })()
145
+ return this.#finishPromise
146
+ }
147
+
148
+ /**
149
+ * Abort the session and release the worker stream. Idempotent; a finished session is untouched.
150
+ * @returns {Promise<void>} resolves after the worker acknowledged (or after a failure was swallowed).
151
+ */
152
+ async cancel() {
153
+ if (this.#state === 'cancelled' || this.#state === 'finished' || this.#state === 'failed') return
154
+ if (this.#state === 'finishing') {
155
+ try {
156
+ await this.#finishPromise
157
+ } catch {
158
+ // A finish that already failed is reported to its caller, not to the cancelling one.
159
+ }
160
+ return
161
+ }
162
+ this.#state = 'cancelled'
163
+ try {
164
+ await this.#runtime.cancelStream(this.#streamId)
165
+ } catch {
166
+ // The worker may be gone; cancelling must still release the provider slot.
167
+ } finally {
168
+ this.#onEnd()
169
+ }
170
+ }
171
+ }
172
+
173
+ /**
174
+ * @param {{ runtime: { segmentation: string } }} model - catalog record.
175
+ * @returns {boolean} whether preparing this family must also install the shared VAD model.
176
+ */
177
+ function needsVad(model) {
178
+ return model.runtime.segmentation === 'vad' || model.runtime.segmentation === 'vad-long'
179
+ }
180
+
181
+ /**
182
+ * One local-model provider: official metadata, preparation state machine and worker-backed
183
+ * transcription.
184
+ */
185
+ export class LocalProvider {
186
+ /** @type {{ phase: string, [key: string]: any }} */
187
+ #state = { phase: 'unprepared' }
188
+ /** @type {Set<Function>} */
189
+ #listeners = new Set()
190
+ /** @type {{ variant: Record<string, any>, variantDir: string, vadPath: string|undefined }|null} */
191
+ #active = null
192
+ /** @type {{ explicit: boolean, variantId: string|undefined, downloadSource: string|undefined, controller: AbortController, promise: Promise<void> }|null} */
193
+ #preparing = null
194
+ /** @type {Promise<void>|null} */
195
+ #wakePromise = null
196
+ /** @type {LocalStreamingSession|null} */
197
+ #stream = null
198
+ /** @type {boolean} */
199
+ #disposed = false
200
+
201
+ /**
202
+ * @param {{
203
+ * model: Record<string, any>,
204
+ * dataRoot: string,
205
+ * readSelectedVariant?: (providerId: string) => Promise<string|undefined>,
206
+ * fetchImpl?: typeof fetch,
207
+ * downloadTimeoutMs?: number,
208
+ * workerOptions?: Record<string, any>,
209
+ * logger?: (message: string) => void,
210
+ * }} options - catalog record, model root and transport overrides.
211
+ */
212
+ constructor(options) {
213
+ this.#options = {
214
+ model: options.model,
215
+ dataRoot: options.dataRoot,
216
+ readSelectedVariant: options.readSelectedVariant ?? (async () => undefined),
217
+ fetchImpl: options.fetchImpl,
218
+ downloadTimeoutMs: options.downloadTimeoutMs,
219
+ workerOptions: options.workerOptions ?? {},
220
+ logger: options.logger ?? (() => undefined),
221
+ }
222
+ this.#runtime = new WorkerRuntime({
223
+ family: this.#options.model.family,
224
+ logger: this.#options.logger,
225
+ ...this.#options.workerOptions,
226
+ })
227
+ this.#runtimeUnsubscribe = this.#runtime.subscribe(() => this.#onRuntimeChange())
228
+ this.info = {
229
+ id: this.#options.model.id,
230
+ name: this.#options.model.name.zh,
231
+ location: 'host-local',
232
+ languages: this.#options.model.languages,
233
+ setupEstimate: this.#options.model.setupEstimate,
234
+ downloadSources: this.#options.model.downloadSources,
235
+ }
236
+ this.preparation = {
237
+ snapshot: () => this.snapshot(),
238
+ subscribe: (listener) => this.subscribe(listener),
239
+ prepare: (options) => this.prepare(options),
240
+ cancel: () => this.cancel(),
241
+ }
242
+ // Our own extension object: only the families that declare `streaming: true` get one, and
243
+ // official consumers ignore it. The service checks it before accepting /stream/start.
244
+ this.bviStreaming = this.#options.model.streaming === true
245
+ ? { start: (options) => this.#startStream(options) }
246
+ : undefined
247
+ }
248
+
249
+ /** @type {{ model: Record<string, any>, dataRoot: string, readSelectedVariant: (providerId: string) => Promise<string|undefined>, fetchImpl?: typeof fetch, downloadTimeoutMs?: number, workerOptions: Record<string, any>, logger: (message: string) => void }} */
250
+ #options
251
+ /** @type {WorkerRuntime} */
252
+ #runtime
253
+ /** @type {() => void} */
254
+ #runtimeUnsubscribe
255
+
256
+ /** @type {{ id: string, name: string, location: 'host-local', languages: string[], setupEstimate?: Record<string, number>, downloadSources: string[] }} */
257
+ info
258
+
259
+ /** @type {{ snapshot: () => { phase: string, [key: string]: any }, subscribe: (listener: () => void) => () => void, prepare: (options?: { variant?: string, downloadSource?: string, signal?: AbortSignal }) => Promise<void>, cancel: () => Promise<void> }} */
260
+ preparation
261
+
262
+ /** @type {{ start: (options?: { language?: string }) => Promise<{ push: (pcm: Uint8Array) => Promise<{ partial: string }>, finish: () => Promise<{ text: string, audioSeconds: number, inferenceSeconds: number }>, cancel: () => Promise<void> }> }|undefined} */
263
+ bviStreaming
264
+
265
+ /**
266
+ * Latest official preparation state (a detached copy).
267
+ * @returns {{ phase: string, [key: string]: any }} preparation snapshot.
268
+ */
269
+ snapshot() {
270
+ return { ...this.#state }
271
+ }
272
+
273
+ /**
274
+ * Observe preparation-state changes.
275
+ * @param {() => void} listener - invalidation callback.
276
+ * @returns {() => void} unsubscribe function.
277
+ */
278
+ subscribe(listener) {
279
+ this.#listeners.add(listener)
280
+ return () => { this.#listeners.delete(listener) }
281
+ }
282
+
283
+ /**
284
+ * @param {{ phase: string, [key: string]: any }} state - next official state.
285
+ * @returns {void}
286
+ */
287
+ #publish(state) {
288
+ this.#state = state
289
+ for (const listener of this.#listeners) {
290
+ try {
291
+ listener()
292
+ } catch (error) {
293
+ this.#options.logger(`bvi-local: preparation listener failed: ${messageOf(error)}`)
294
+ }
295
+ }
296
+ }
297
+
298
+ /**
299
+ * React to worker lifecycle changes that happen outside a preparation task (idle reclaim and
300
+ * crashes), keeping the official preparation state honest.
301
+ * @returns {void}
302
+ */
303
+ #onRuntimeChange() {
304
+ if (this.#preparing !== null || this.#wakePromise !== null) return
305
+ const runtime = this.#runtime.snapshot()
306
+ if (runtime.state === 'failed') {
307
+ this.#publish({
308
+ phase: 'failed',
309
+ message: runtime.message ?? 'The local speech worker stopped unexpectedly',
310
+ variant: this.#active?.variant.id,
311
+ })
312
+ } else if (runtime.state === 'idle' && this.#state.phase === 'ready') {
313
+ this.#publish({ phase: 'standby', variant: this.#active?.variant.id })
314
+ }
315
+ }
316
+
317
+ /**
318
+ * Resolve the variant a preparation task should install.
319
+ * @param {{ explicit: boolean, variantId: string|undefined }} task - preparation task.
320
+ * @returns {Promise<Record<string, any>>} catalog variant.
321
+ * @throws {Error} when the explicitly requested variant does not exist.
322
+ */
323
+ async #resolveVariant(task) {
324
+ const model = this.#options.model
325
+ if (task.explicit) {
326
+ const variant = model.variants.find((entry) => entry.id === task.variantId)
327
+ if (variant === undefined) throw new Error(`Unknown local model variant: ${model.id}/${String(task.variantId)}`)
328
+ return variant
329
+ }
330
+ let selected
331
+ try {
332
+ selected = await this.#options.readSelectedVariant(model.id)
333
+ } catch (error) {
334
+ this.#options.logger(`bvi-local: unable to read the selected variant of ${model.id}: ${messageOf(error)}`)
335
+ }
336
+ const found = model.variants.find((entry) => entry.id === selected)
337
+ return found ?? model.variants.find((entry) => entry.id === model.defaultVariant) ?? model.variants[0]
338
+ }
339
+
340
+ /**
341
+ * Reject a download origin the selected variant cannot be fetched from.
342
+ * @param {Record<string, any>} variant - catalog variant.
343
+ * @param {string|undefined} source - origin chosen by the user.
344
+ * @returns {void}
345
+ * @throws {Error} when the source is unknown or cannot serve this variant.
346
+ */
347
+ #assertDownloadSource(variant, source) {
348
+ if (source === undefined) return
349
+ if (!this.#options.model.downloadSources.includes(source)) {
350
+ throw new Error(`Unknown download source for ${this.#options.model.id}: ${source}`)
351
+ }
352
+ if (!downloadSourcesForVariant(this.#options.model, variant).includes(source)) {
353
+ throw new Error(`Variant ${variant.id} of ${this.#options.model.id} is not available from ${source}`)
354
+ }
355
+ }
356
+
357
+ /**
358
+ * Map an installation progress event onto the official preparation state.
359
+ * @param {Record<string, any>} progress - installation event.
360
+ * @returns {void}
361
+ */
362
+ #publishInstallProgress(progress) {
363
+ const variant = this.#preparing?.variantId
364
+ switch (progress.phase) {
365
+ case 'checking':
366
+ this.#publish({ phase: 'checking', step: progress.step ?? 'check', startedAt: Date.now(), variant })
367
+ return
368
+ case 'downloading':
369
+ this.#publish({
370
+ phase: 'downloading',
371
+ step: progress.step,
372
+ resource: typeof progress.resource === 'string' ? progress.resource : this.#options.model.name.zh,
373
+ completedBytes: bytesOf(progress.completedBytes) ?? 0,
374
+ totalBytes: bytesOf(progress.totalBytes),
375
+ variant,
376
+ })
377
+ return
378
+ case 'extracting':
379
+ this.#publish({
380
+ phase: 'loading',
381
+ step: 'model',
382
+ resource: typeof progress.resource === 'string' ? progress.resource : this.#options.model.name.zh,
383
+ completedBytes: bytesOf(progress.completedBytes) ?? 0,
384
+ totalBytes: bytesOf(progress.totalBytes),
385
+ startedAt: Date.now(),
386
+ variant,
387
+ })
388
+ return
389
+ case 'verifying':
390
+ this.#publish({ phase: 'checking', step: 'verify', startedAt: Date.now(), variant })
391
+ return
392
+ default:
393
+ return
394
+ }
395
+ }
396
+
397
+ /**
398
+ * Install the variant and start its worker, publishing official phases as it goes.
399
+ * @param {{ explicit: boolean, variantId: string|undefined, downloadSource: string|undefined, controller: AbortController }} task - preparation task.
400
+ * @returns {Promise<void>} resolves when the state is terminal (`ready`, `failed` or `cancelled`).
401
+ */
402
+ async #runPreparation(task) {
403
+ const model = this.#options.model
404
+ let variant
405
+ try {
406
+ variant = await this.#resolveVariant(task)
407
+ task.variantId = variant.id
408
+ if (task.controller.signal.aborted) throw task.controller.signal.reason
409
+ this.#assertDownloadSource(variant, task.downloadSource)
410
+ this.#publish({ phase: 'checking', step: 'check', startedAt: Date.now(), variant: variant.id })
411
+ if (this.#runtime.snapshot().state === 'ready' && this.#active !== null && this.#active.variant.id !== variant.id) {
412
+ await this.#runtime.stop('variant-switch')
413
+ }
414
+ const vadAsset = needsVad(model) ? SHARED_ASSETS.vad : undefined
415
+ const install = await ensureVariantInstalled({
416
+ root: this.#options.dataRoot,
417
+ model,
418
+ variant,
419
+ vadAsset,
420
+ downloadSource: task.downloadSource,
421
+ signal: task.controller.signal,
422
+ onProgress: (progress) => this.#publishInstallProgress(progress),
423
+ fetchImpl: this.#options.fetchImpl,
424
+ downloadTimeoutMs: this.#options.downloadTimeoutMs,
425
+ })
426
+ if (task.controller.signal.aborted) throw task.controller.signal.reason
427
+ this.#publish({ phase: 'loading', step: 'load', startedAt: Date.now(), variant: variant.id })
428
+ await this.#runtime.ensureStarted({
429
+ variantId: variant.id,
430
+ variantDir: install.variantDir,
431
+ threads: model.runtime.threads,
432
+ vadPath: install.vadPath,
433
+ maxAudioBytes: MAX_WAV_BYTES,
434
+ }, task.controller.signal)
435
+ if (task.controller.signal.aborted) throw task.controller.signal.reason
436
+ this.#active = { variant, variantDir: install.variantDir, vadPath: install.vadPath }
437
+ this.#publish({ phase: 'ready', variant: variant.id })
438
+ } catch (error) {
439
+ const cancelled = task.controller.signal.aborted
440
+ if (!cancelled) this.#options.logger(`bvi-local: preparing ${model.id} failed: ${messageOf(error)}`)
441
+ try {
442
+ await this.#runtime.stop('prepare-failed')
443
+ } catch {
444
+ // The worker is already gone; the preparation error is the useful one.
445
+ }
446
+ if (cancelled) this.#publish({ phase: 'cancelled', variant: task.variantId })
447
+ else this.#publish({ phase: 'failed', message: messageOf(error), variant: task.variantId })
448
+ }
449
+ }
450
+
451
+ /**
452
+ * Start (or join) preparation of one variant.
453
+ *
454
+ * Idempotent when the requested variant is already prepared or being prepared. A second call
455
+ * that asks for a *different* variant while one is in flight is rejected instead of silently
456
+ * joining the wrong work.
457
+ * @param {{ variant?: string, downloadSource?: string, signal?: AbortSignal }} [options] - official options
458
+ * plus our `variant` extension.
459
+ * @returns {Promise<void>} resolves when the preparation task reaches a terminal phase; it never
460
+ * rejects (failures are published as the official `failed` state).
461
+ * @throws {Error} when the provider was disposed, the requested variant is unknown, or another
462
+ * variant is already being prepared.
463
+ */
464
+ prepare(options = {}) {
465
+ if (this.#disposed) throw new Error(`bvi-local: provider ${this.#options.model.id} is disposed`)
466
+ const requested = typeof options.variant === 'string' && options.variant !== '' ? options.variant : undefined
467
+ if (requested !== undefined && !this.#options.model.variants.some((entry) => entry.id === requested)) {
468
+ throw new Error(`Unknown local model variant: ${this.#options.model.id}/${requested}`)
469
+ }
470
+ const current = this.#preparing
471
+ if (current !== null) {
472
+ if (requested !== undefined && current.variantId !== undefined && current.variantId !== requested) {
473
+ throw new Error(`${this.#options.model.id}: ${current.variantId} is already being prepared; cancel it first`)
474
+ }
475
+ return current.promise
476
+ }
477
+ if (this.#state.phase === 'ready' || this.#state.phase === 'standby') {
478
+ if (requested === undefined || requested === this.#active?.variant.id) return Promise.resolve()
479
+ }
480
+ const controller = new AbortController()
481
+ /** @type {{ explicit: boolean, variantId: string|undefined, downloadSource: string|undefined, controller: AbortController, promise: Promise<void> }} */
482
+ const task = {
483
+ explicit: requested !== undefined,
484
+ variantId: requested,
485
+ downloadSource: typeof options.downloadSource === 'string' && options.downloadSource !== '' ? options.downloadSource : undefined,
486
+ controller,
487
+ promise: Promise.resolve(),
488
+ }
489
+ if (options.signal !== undefined) {
490
+ if (options.signal.aborted) {
491
+ controller.abort(options.signal.reason)
492
+ } else {
493
+ options.signal.addEventListener('abort', () => { controller.abort(options.signal?.reason) }, { once: true })
494
+ }
495
+ }
496
+ this.#preparing = task
497
+ task.promise = this.#runPreparation(task).finally(() => {
498
+ if (this.#preparing === task) this.#preparing = null
499
+ })
500
+ return task.promise
501
+ }
502
+
503
+ /**
504
+ * Cancel the active preparation task and wait until its resources settle.
505
+ * @returns {Promise<void>} resolves when the state is `cancelled` (or after the final failure).
506
+ */
507
+ async cancel() {
508
+ const task = this.#preparing
509
+ if (task === null) return
510
+ if (IN_FLIGHT_PHASES.has(this.#state.phase)) {
511
+ this.#publish({ ...this.#state, phase: 'cancelling', startedAt: Date.now() })
512
+ }
513
+ task.controller.abort(new Error('Local model preparation was cancelled'))
514
+ try {
515
+ await task.promise
516
+ } catch {
517
+ // Preparation resolves instead of rejecting; this guard keeps cancel() total.
518
+ }
519
+ }
520
+
521
+ /**
522
+ * Wake a worker that was reclaimed after the idle timeout.
523
+ * @param {{ variant: Record<string, any>, variantDir: string, vadPath: string|undefined }} active - installed layout.
524
+ * @returns {Promise<void>} resolves when the worker is ready again.
525
+ */
526
+ async #wake(active) {
527
+ if (this.#wakePromise !== null) return await this.#wakePromise
528
+ const model = this.#options.model
529
+ this.#publish({ phase: 'waking', startedAt: Date.now(), variant: active.variant.id })
530
+ const promise = (async () => {
531
+ try {
532
+ await this.#runtime.ensureStarted({
533
+ variantId: active.variant.id,
534
+ variantDir: active.variantDir,
535
+ threads: model.runtime.threads,
536
+ vadPath: active.vadPath,
537
+ maxAudioBytes: MAX_WAV_BYTES,
538
+ })
539
+ this.#publish({ phase: 'ready', variant: active.variant.id })
540
+ } catch (error) {
541
+ this.#publish({ phase: 'failed', message: messageOf(error), variant: active.variant.id })
542
+ throw error
543
+ } finally {
544
+ this.#wakePromise = null
545
+ }
546
+ })()
547
+ this.#wakePromise = promise
548
+ return await promise
549
+ }
550
+
551
+ /**
552
+ * Open a live streaming session for the service relay.
553
+ *
554
+ * The catalog flag `streaming: true` is what lets the service offer this; an unprepared
555
+ * provider, an in-flight preparation or a second concurrent session are rejected with the
556
+ * ProviderError taxonomy. A reclaimed (standby) worker is woken exactly like the batch path.
557
+ * @param {{ language?: string }} [options] - selected language, already validated by the caller.
558
+ * @returns {Promise<{ push: (pcm: Uint8Array) => Promise<{ partial: string }>, finish: () => Promise<{ text: string, audioSeconds: number, inferenceSeconds: number }>, cancel: () => Promise<void> }>} live session handle.
559
+ * @throws {ProviderError} when streaming cannot start.
560
+ */
561
+ async #startStream(options = {}) {
562
+ const model = this.#options.model
563
+ if (this.#disposed) throw new ProviderError('unsupported', `bvi-local: provider ${model.id} is disposed`)
564
+ if (this.#preparing !== null) throw new ProviderError('unsupported', `${model.name.zh} is still being prepared; wait until it is ready`)
565
+ if (this.#stream !== null) throw new ProviderError('unsupported', `${model.name.zh} already has an active streaming session`)
566
+ const active = this.#active
567
+ if (active === null) throw new ProviderError('unsupported', `${model.name.zh} is not prepared; download the model first`)
568
+ if (this.#state.phase !== 'ready' && this.#state.phase !== 'standby') {
569
+ throw new ProviderError('unsupported', this.#state.phase === 'failed'
570
+ ? `${model.name.zh} is unavailable: ${typeof this.#state.message === 'string' ? this.#state.message : 'the local speech worker stopped'}`
571
+ : `${model.name.zh} is not prepared; download the model first`)
572
+ }
573
+ const language = typeof options.language === 'string' && options.language !== '' ? options.language : 'auto'
574
+ if (!model.languages.includes(language)) {
575
+ throw new ProviderError('unsupported', `${model.name.zh} does not support language: ${language}`)
576
+ }
577
+ try {
578
+ if (this.#runtime.snapshot().state !== 'ready') await this.#wake(active)
579
+ const { streamId } = await this.#runtime.startStream({ language })
580
+ const session = new LocalStreamingSession(this.#runtime, streamId, () => {
581
+ if (this.#stream === session) this.#stream = null
582
+ })
583
+ this.#stream = session
584
+ return {
585
+ push: (pcm) => session.push(pcm),
586
+ finish: () => session.finish(),
587
+ cancel: () => session.cancel(),
588
+ }
589
+ } catch (error) {
590
+ throw streamFailureOf(error)
591
+ }
592
+ }
593
+
594
+ /**
595
+ * Recognize one recording through the prepared worker.
596
+ * @param {{ audio: Uint8Array, language?: string }} input - official speech input.
597
+ * @param {AbortSignal} [signal] - caller cancellation.
598
+ * @returns {Promise<{ text: string, audioSeconds: number, inferenceSeconds: number }>} transcript.
599
+ * @throws {import('@ds-hu/dsh-bvi-core').WavError} when the audio is not canonical intake.
600
+ * @throws {Error} when no model is prepared or the worker cannot run.
601
+ */
602
+ async transcribe(input, signal) {
603
+ const model = this.#options.model
604
+ // Validating here keeps every malformed payload out of the worker process.
605
+ validateWav(input?.audio)
606
+ if (this.#disposed) throw new Error(`bvi-local: provider ${model.id} is disposed`)
607
+ if (this.#preparing !== null) throw new Error(`${model.name.zh} is still being prepared; wait until it is ready`)
608
+ const active = this.#active
609
+ if (active === null) throw new Error(`${model.name.zh} is not prepared; download the model first`)
610
+ const runtime = this.#runtime.snapshot()
611
+ if (this.#state.phase !== 'ready' && this.#state.phase !== 'standby') {
612
+ throw new Error(this.#state.phase === 'failed'
613
+ ? `${model.name.zh} is unavailable: ${typeof this.#state.message === 'string' ? this.#state.message : 'the local speech worker stopped'}`
614
+ : `${model.name.zh} is not prepared; download the model first`)
615
+ }
616
+ if (runtime.state !== 'ready') await this.#wake(active)
617
+ if (signal !== undefined) signal.throwIfAborted()
618
+ const language = typeof input?.language === 'string' && input.language !== '' ? input.language : 'auto'
619
+ const result = await this.#runtime.transcribe({ audio: /** @type {Uint8Array} */ (input?.audio), language, signal })
620
+ return {
621
+ text: result.text,
622
+ audioSeconds: result.audioSeconds,
623
+ inferenceSeconds: result.inferenceSeconds,
624
+ }
625
+ }
626
+
627
+ /**
628
+ * Stop the worker and refuse future calls. Idempotent; called from the registration disposer.
629
+ * @returns {Promise<void>} resolves after every resource settled.
630
+ */
631
+ async dispose() {
632
+ if (this.#disposed) return
633
+ this.#disposed = true
634
+ const task = this.#preparing
635
+ if (task !== null) {
636
+ task.controller.abort(new Error('Local speech provider unloaded'))
637
+ try {
638
+ await task.promise
639
+ } catch {
640
+ // Preparation resolves instead of rejecting.
641
+ }
642
+ }
643
+ if (this.#wakePromise !== null) {
644
+ try {
645
+ await this.#wakePromise
646
+ } catch {
647
+ // The worker is being torn down anyway.
648
+ }
649
+ }
650
+ const stream = this.#stream
651
+ if (stream !== null) {
652
+ try {
653
+ await stream.cancel()
654
+ } catch {
655
+ // The worker is being torn down anyway.
656
+ }
657
+ this.#stream = null
658
+ }
659
+ await this.#runtime.dispose()
660
+ this.#runtimeUnsubscribe()
661
+ this.#listeners.clear()
662
+ }
663
+ }
664
+
665
+ /**
666
+ * Build one local provider from a catalog record.
667
+ * @param {{
668
+ * model: Record<string, any>,
669
+ * dataRoot: string,
670
+ * readSelectedVariant?: (providerId: string) => Promise<string|undefined>,
671
+ * fetchImpl?: typeof fetch,
672
+ * downloadTimeoutMs?: number,
673
+ * workerOptions?: Record<string, any>,
674
+ * logger?: (message: string) => void,
675
+ * }} options - catalog record, model root and transport overrides.
676
+ * @returns {LocalProvider} provider implementing the official seam.
677
+ */
678
+ export function createLocalProvider(options) {
679
+ return new LocalProvider(options)
680
+ }
681
+
682
+ /**
683
+ * Directory of one variant inside the model root (exported for scripts and diagnostics).
684
+ * @param {string} dataRoot - model root.
685
+ * @param {{ family: string }} model - catalog record.
686
+ * @param {{ id: string }} variant - catalog variant.
687
+ * @returns {string} absolute variant directory.
688
+ */
689
+ export function providerVariantDirectory(dataRoot, model, variant) {
690
+ return join(dataRoot, model.family, variant.id)
691
+ }