@adea-ai/voice 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.
Files changed (52) hide show
  1. package/README.md +51 -2
  2. package/dist/cli/helpers-cli.d.ts +2 -0
  3. package/dist/cli/helpers-cli.js +102 -0
  4. package/dist/contract/contract.d.ts +138 -0
  5. package/dist/contract/errors.d.ts +26 -0
  6. package/dist/contract/index.d.ts +9 -0
  7. package/dist/contract/index.js +54 -0
  8. package/dist/contract/session.d.ts +58 -0
  9. package/dist/contract/wire.d.ts +188 -0
  10. package/dist/desktop/desktop-voice.d.ts +152 -0
  11. package/dist/desktop/helper-lock.d.ts +83 -0
  12. package/dist/desktop/helper-process.d.ts +92 -0
  13. package/dist/desktop/index.d.ts +7 -0
  14. package/dist/desktop/index.js +1042 -0
  15. package/dist/index-9kerqn9r.js +150 -0
  16. package/dist/index-acm1yvvv.js +290 -0
  17. package/dist/index-r4hz8gk0.js +10 -0
  18. package/dist/index-rehs788p.js +42 -0
  19. package/dist/index-s270cw30.js +295 -0
  20. package/dist/index-tvz9s9nz.js +77 -0
  21. package/dist/index.d.ts +7 -0
  22. package/dist/index.js +86 -0
  23. package/dist/settings/index.d.ts +5 -0
  24. package/dist/settings/index.js +34 -0
  25. package/dist/settings/settings.d.ts +163 -0
  26. package/dist/web/index.d.ts +15 -0
  27. package/dist/web/index.js +1287 -0
  28. package/dist/web/stt/speech-recognition.d.ts +105 -0
  29. package/dist/web/tts/phonon.d.ts +139 -0
  30. package/dist/web/tts/player.d.ts +115 -0
  31. package/dist/web/tts/system-voices.d.ts +122 -0
  32. package/dist/web/turns.d.ts +101 -0
  33. package/package.json +68 -4
  34. package/src/cli/helpers-cli.ts +119 -0
  35. package/src/contract/contract.ts +365 -0
  36. package/src/contract/errors.ts +98 -0
  37. package/src/contract/index.ts +9 -0
  38. package/src/contract/session.ts +65 -0
  39. package/src/contract/wire.ts +263 -0
  40. package/src/desktop/desktop-voice.ts +933 -0
  41. package/src/desktop/helper-lock.ts +375 -0
  42. package/src/desktop/helper-process.ts +401 -0
  43. package/src/desktop/index.ts +16 -0
  44. package/src/index.ts +7 -0
  45. package/src/settings/index.ts +5 -0
  46. package/src/settings/settings.ts +478 -0
  47. package/src/web/index.ts +15 -0
  48. package/src/web/stt/speech-recognition.ts +583 -0
  49. package/src/web/tts/phonon.ts +386 -0
  50. package/src/web/tts/player.ts +271 -0
  51. package/src/web/tts/system-voices.ts +401 -0
  52. package/src/web/turns.ts +224 -0
@@ -0,0 +1,105 @@
1
+ /**
2
+ * Browser dictation over the Web Speech API, with an explicit local/network policy (issues #21
3
+ * and #37).
4
+ *
5
+ * The browser's recognizer is not automatically offline: Chrome's service-based recognition sends
6
+ * audio to Google, and Safari/Chrome differ per OS version. This module therefore exposes **two
7
+ * providers over one implementation**:
8
+ *
9
+ * - `web.speech-recognition-local` (`execution: "onDevice"`): only available when the browser can
10
+ * run recognition on-device *and* confirms a model for the locale. It is the only entry in the
11
+ * routing chain, so routing never silently reaches the network.
12
+ * - `web.speech-recognition-service` (`execution: "network"`): the host must select it explicitly,
13
+ * with a privacy notice and `allowNetwork: true`. Routing refuses it (`networkRequired`).
14
+ *
15
+ * The session keeps the platform-neutral event contract from #19: `partial` snapshots with
16
+ * `finalizedText`/`volatileText`/`sequence`, exactly one terminal `final`/`failed`/`cancelled`, and
17
+ * deadlines that end a stuck session instead of hanging it.
18
+ */
19
+ import { type VoiceProviderAvailability, type VoiceProviderDescriptor } from "../../contract/contract";
20
+ export interface RecognitionAlternative {
21
+ readonly transcript: string;
22
+ readonly confidence?: number;
23
+ }
24
+ export interface RecognitionResult {
25
+ readonly isFinal: boolean;
26
+ readonly length: number;
27
+ readonly [index: number]: RecognitionAlternative;
28
+ }
29
+ export interface RecognitionResultList {
30
+ readonly length: number;
31
+ readonly [index: number]: RecognitionResult;
32
+ }
33
+ export interface SpeechRecognitionEventLike {
34
+ readonly resultIndex: number;
35
+ readonly results: RecognitionResultList;
36
+ }
37
+ export interface SpeechRecognitionErrorEventLike {
38
+ readonly error: string;
39
+ readonly message?: string;
40
+ }
41
+ /** The subset of `SpeechRecognition` this adapter uses. */
42
+ export interface SpeechRecognitionLike {
43
+ lang: string;
44
+ continuous: boolean;
45
+ interimResults: boolean;
46
+ maxAlternatives: number;
47
+ /** Chrome's on-device flag; ignored by browsers that do not implement it. */
48
+ processLocally?: boolean;
49
+ onstart: (() => void) | null;
50
+ onresult: ((event: SpeechRecognitionEventLike) => void) | null;
51
+ onerror: ((event: SpeechRecognitionErrorEventLike) => void) | null;
52
+ onend: (() => void) | null;
53
+ start(): void;
54
+ stop(): void;
55
+ abort(): void;
56
+ }
57
+ export type RecognitionModelState = "available" | "downloadable" | "downloading" | "unavailable";
58
+ /** Chrome's on-device lifecycle methods, which live on the constructor, not the instance. */
59
+ export interface SpeechRecognitionConstructor {
60
+ new (): SpeechRecognitionLike;
61
+ available?(options: {
62
+ langs: string[];
63
+ processLocally?: boolean;
64
+ }): Promise<RecognitionModelState>;
65
+ install?(options: {
66
+ langs: string[];
67
+ }): Promise<boolean>;
68
+ }
69
+ export interface SpeechRecognitionEnvironment {
70
+ /** The constructor, or undefined where the browser has no Web Speech API. */
71
+ readonly SpeechRecognition?: SpeechRecognitionConstructor;
72
+ /** Safari's prefixed constructor. Present without the unprefixed name on Safari and older WebKit. */
73
+ readonly webkitSpeechRecognition?: SpeechRecognitionConstructor;
74
+ readonly now?: () => number;
75
+ readonly sleep?: (milliseconds: number) => Promise<void>;
76
+ }
77
+ /** The recognizer constructor this browser exposes, unprefixed first. */
78
+ export declare function recognitionConstructor(environment: SpeechRecognitionEnvironment): SpeechRecognitionConstructor | undefined;
79
+ export { DEFAULT_ENDPOINTING, type EndpointingOptions, type PartialTranscript, type SessionEvent, type TranscriptionProvider, type TranscriptionSession, type TranscriptionSessionOptions, } from "../../contract/session";
80
+ import { type TranscriptionProvider, type TranscriptionSession, type TranscriptionSessionOptions } from "../../contract/session";
81
+ export declare const LOCAL_RECOGNITION_ID = "web.speech-recognition-local";
82
+ export declare const SERVICE_RECOGNITION_ID = "web.speech-recognition-service";
83
+ export declare function browserRecognitionLocal(environment?: SpeechRecognitionEnvironment): BrowserRecognitionProvider;
84
+ export declare function browserRecognitionService(environment?: SpeechRecognitionEnvironment): BrowserRecognitionProvider;
85
+ /**
86
+ * The recognizer as a provider. `mode` decides which of the two descriptors it carries; the
87
+ * implementation is the same and the policy difference is the point.
88
+ */
89
+ export declare class BrowserRecognitionProvider implements TranscriptionProvider {
90
+ readonly descriptor: VoiceProviderDescriptor;
91
+ private readonly environment;
92
+ private readonly mode;
93
+ constructor(mode: "local" | "service", environment: SpeechRecognitionEnvironment);
94
+ /** Probes the browser. Prompts for nothing, sends nothing. */
95
+ availability(locale: string): Promise<VoiceProviderAvailability>;
96
+ /**
97
+ * Installs the on-device model where the browser exposes an install path (#37 consent step).
98
+ * Downloading is never implied: the host passes `allowDownload: true` only after the person
99
+ * agreed to it (for example `settings.models.allowDownload`), otherwise this refuses.
100
+ */
101
+ installModel(locale: string, options: {
102
+ readonly allowDownload: boolean;
103
+ }): Promise<boolean>;
104
+ createSession(options: TranscriptionSessionOptions): Promise<TranscriptionSession>;
105
+ }
@@ -0,0 +1,139 @@
1
+ /**
2
+ * Phonon 31M as the browser's local English voice (issue #27).
3
+ *
4
+ * Three rules shape this adapter:
5
+ *
6
+ * 1. **Nothing downloads by itself.** `availability` is `modelNotInstalled` until the host has the
7
+ * person's consent and calls `load()`; routing reports `modelDownloadDisabled` unless the host
8
+ * opted into the install, so a page that never uses voice never fetches a model.
9
+ * 2. **Only the cleared family.** Phonon 31M English is Apache-2.0 and is the only family this
10
+ * adapter accepts. Phonon 40M (Spanish/multilingual) is CC BY-NC 4.0 and reports
11
+ * `licenseNotAccepted` rather than loading; the ES-419 path belongs to platform voices (#36).
12
+ * 3. **Cancellation is a request cancel, not a mute.** The engine's `AbortSignal` stops generation
13
+ * in the worker; the player flushes what this utterance scheduled (and only that). Both happen in
14
+ * `cancel()`, and `done` settles when playback drained, not when generation finished.
15
+ *
16
+ * The runtime, the player and the clock are injected so the policies and the pump are testable
17
+ * without a browser.
18
+ */
19
+ import type { LoadProgress, ModelSpec } from "phonon-tts";
20
+ import { type VoiceProvider, type VoiceProviderAvailability, type VoiceProviderDescriptor } from "../../contract/contract";
21
+ import { type AudioContextFactory } from "./player";
22
+ export type PhononFamily = "phonon-31m-en" | "phonon-40m";
23
+ /** Where the checkpoint comes from. Both forms are explicit; there is no implicit default. */
24
+ export type PhononModelSource = {
25
+ readonly kind: "pinned";
26
+ } | {
27
+ readonly kind: "urls";
28
+ readonly spec: ModelSpec;
29
+ };
30
+ export interface PhononSpeechStats {
31
+ readonly frames?: number;
32
+ readonly samples?: number;
33
+ readonly firstAudioMs?: number | null;
34
+ readonly totalMs?: number;
35
+ readonly cancelled: boolean;
36
+ }
37
+ export interface PhononSpeechStream extends AsyncIterable<Float32Array> {
38
+ readonly sampleRate: number;
39
+ readonly done: Promise<PhononSpeechStats>;
40
+ cancel(): void;
41
+ }
42
+ /** The subset of `phonon-tts`'s `PhononTTS` this adapter uses. */
43
+ export interface PhononEngine {
44
+ readonly sampleRate: number;
45
+ readonly voices: string[];
46
+ readonly languages: string[];
47
+ readonly device?: string;
48
+ readonly threads?: number;
49
+ stream(text: string, options?: {
50
+ voice?: string;
51
+ temperature?: number;
52
+ seed?: number | bigint;
53
+ signal?: AbortSignal;
54
+ }): PhononSpeechStream;
55
+ dispose(): void;
56
+ }
57
+ export interface PhononLoadRequest {
58
+ readonly lang: string;
59
+ readonly model?: ModelSpec | string;
60
+ readonly quant?: "q8" | "f32";
61
+ readonly cache?: boolean;
62
+ readonly onProgress?: (progress: LoadProgress) => void;
63
+ readonly device?: "cpu" | "auto" | "webgpu";
64
+ readonly threads?: number | "auto";
65
+ }
66
+ export interface PhononRuntime {
67
+ load(request: PhononLoadRequest): Promise<PhononEngine>;
68
+ }
69
+ /** The shipped runtime: `phonon-tts@0.7.1`, loaded on demand so nothing loads it eagerly. */
70
+ export declare const defaultPhononRuntime: PhononRuntime;
71
+ /** Deletes every model file the package cached. Exposed so settings can offer it. */
72
+ export declare function clearPhononCache(): Promise<boolean>;
73
+ export interface PhononProviderOptions {
74
+ /** Only `en` locales are served. Default `en`. */
75
+ readonly locale?: string;
76
+ /** Which family this build carries. Default `phonon-31m-en`. */
77
+ readonly family?: PhononFamily;
78
+ /** Required for `family: "phonon-31m-en"`: pinned Hub revision or explicit asset URLs. */
79
+ readonly model?: PhononModelSource;
80
+ readonly runtime?: PhononRuntime;
81
+ readonly device?: "cpu" | "auto" | "webgpu";
82
+ readonly threads?: number | "auto";
83
+ readonly cache?: boolean;
84
+ /** WebAssembly SIMD probe; injected in tests. */
85
+ readonly supportsSimd?: () => boolean;
86
+ readonly audioContextFactory?: AudioContextFactory;
87
+ readonly now?: () => number;
88
+ }
89
+ export interface SpeakOptions {
90
+ readonly voice?: string;
91
+ readonly temperature?: number;
92
+ readonly seed?: number | bigint;
93
+ /** Called with the first scheduled PCM chunk's latency, in milliseconds. */
94
+ readonly onFirstAudio?: (milliseconds: number) => void;
95
+ readonly onChunk?: (samples: number) => void;
96
+ }
97
+ export interface SpeechHandle {
98
+ /** Resolves when playback drained or cancellation finished; rejects with a `VoiceError`. */
99
+ readonly done: Promise<PhononSpeechStats>;
100
+ /** Request cancel: stops the worker's generation and flushes playback. Idempotent. */
101
+ cancel(): void;
102
+ }
103
+ export declare const PHONON_PROVIDER_ID = "web.phonon";
104
+ export declare const PHONON_EN_FAMILY = "phonon-31m-en";
105
+ export declare class PhononProvider implements VoiceProvider {
106
+ readonly descriptor: VoiceProviderDescriptor;
107
+ private readonly options;
108
+ private engine;
109
+ private player;
110
+ private loading;
111
+ /** Callers still waiting on `loading` (not aborted). Zero when it lands means nobody wants it. */
112
+ private loadWaiters;
113
+ private readonly progressListeners;
114
+ constructor(options?: PhononProviderOptions);
115
+ /** Whether the checkpoint is loaded in this page. */
116
+ get isLoaded(): boolean;
117
+ /** Voices the loaded checkpoint offers. Empty before `load()`. */
118
+ get voices(): readonly string[];
119
+ availability(locale: string): Promise<VoiceProviderAvailability>;
120
+ /**
121
+ * Downloads the checkpoint (explicitly, with progress) and loads it in a worker. Idempotent:
122
+ * concurrent callers share one download, and each gets its own progress callbacks.
123
+ *
124
+ * `signal` is per caller: aborting it rejects *that* caller with `cancelled` right away and
125
+ * detaches its progress listener, without affecting other callers. `phonon-tts@0.7.1`'s
126
+ * `PhononTTS.load` takes no `AbortSignal`, so the download itself cannot be interrupted; when it
127
+ * lands and every caller has aborted, the engine is disposed instead of kept.
128
+ */
129
+ load(options?: {
130
+ onProgress?: (progress: LoadProgress) => void;
131
+ signal?: AbortSignal;
132
+ }): Promise<PhononEngine>;
133
+ private startLoading;
134
+ /** Speaks one request: streams PCM into the player, cancellable at any point. */
135
+ speak(text: string, options?: SpeakOptions): SpeechHandle;
136
+ /** Stops generation and playback and frees the worker. */
137
+ dispose(): void;
138
+ private playerFor;
139
+ }
@@ -0,0 +1,115 @@
1
+ /**
2
+ * Scheduled PCM playback for streaming synthesis.
3
+ *
4
+ * The engine yields mono float chunks in real time; this player schedules each one on the
5
+ * AudioContext clock with a small lead so chunk boundaries do not click, and it owns the only
6
+ * mutable playback state: stop (barge-in) flushes every scheduled source, suspend/resume follow
7
+ * the platform's audio focus rules, and dispose closes the context so nothing outlives the
8
+ * component.
9
+ *
10
+ * Browser globals are injected (`AudioContextFactory`), so the scheduling logic is testable.
11
+ */
12
+ export interface AudioBufferLike {
13
+ readonly duration: number;
14
+ readonly numberOfChannels?: number;
15
+ readonly length?: number;
16
+ getChannelData?(channel: number): Float32Array;
17
+ }
18
+ export interface AudioBufferSourceLike {
19
+ buffer: unknown;
20
+ onended: (() => void) | null;
21
+ connect(destination: unknown): void;
22
+ disconnect?(destination?: unknown): void;
23
+ start(when?: number): void;
24
+ stop(when?: number): void;
25
+ }
26
+ export interface AudioContextLike {
27
+ readonly currentTime: number;
28
+ readonly destination: unknown;
29
+ readonly state?: string;
30
+ createBuffer(channels: number, length: number, sampleRate: number): AudioBufferLike;
31
+ createBufferSource(): AudioBufferSourceLike;
32
+ resume?(): Promise<void>;
33
+ suspend?(): Promise<void>;
34
+ close?(): Promise<void>;
35
+ }
36
+ export interface AudioContextFactory {
37
+ create(options: {
38
+ sampleRate: number;
39
+ }): AudioContextLike;
40
+ }
41
+ export interface StreamingPcmPlayerOptions {
42
+ readonly sampleRate: number;
43
+ readonly factory?: AudioContextFactory;
44
+ /** Scheduling lead ahead of the context clock, in seconds. Default 0.05. */
45
+ readonly leadSeconds?: number;
46
+ /** Called when the first chunk of the current utterance is scheduled. */
47
+ readonly onFirstAudio?: (atContextTime: number) => void;
48
+ /** Called when every scheduled chunk has played. */
49
+ readonly onDrained?: () => void;
50
+ }
51
+ export declare const defaultAudioContextFactory: AudioContextFactory;
52
+ /**
53
+ * One utterance's slice of the player's schedule: its own sources, its own stop, and a `drained`
54
+ * promise that settles when its last scheduled chunk has played (or it was stopped). Stopping one
55
+ * utterance leaves the others scheduled.
56
+ */
57
+ export declare class PlaybackUtterance {
58
+ private readonly player;
59
+ readonly sources: Set<AudioBufferSourceLike>;
60
+ private sealed;
61
+ private stoppedFlag;
62
+ private settled;
63
+ private resolveDrained;
64
+ /** Resolves `true` when everything scheduled played, `false` when the utterance was stopped. */
65
+ readonly drained: Promise<boolean>;
66
+ constructor(player: StreamingPcmPlayer);
67
+ /** Whether `stop()` (or the player's stop/dispose) ended this utterance. */
68
+ get stopped(): boolean;
69
+ /** Schedules one chunk of this utterance; null after `finish()`/`stop()` or when disposed. */
70
+ enqueue(pcm: Float32Array): number | null;
71
+ /** No more chunks will come: `drained` resolves once the scheduled ones have played. */
72
+ finish(): Promise<boolean>;
73
+ /** Stops and discards only this utterance's scheduled audio. Idempotent. */
74
+ stop(): void;
75
+ /** @internal called by the player when one of this utterance's sources ended. */
76
+ ended(source: AudioBufferSourceLike): void;
77
+ private check;
78
+ private settle;
79
+ }
80
+ export declare class StreamingPcmPlayer {
81
+ private readonly context;
82
+ private readonly sampleRate;
83
+ private readonly leadSeconds;
84
+ private readonly onFirstAudio;
85
+ private readonly onDrained;
86
+ private sources;
87
+ private readonly endsAt;
88
+ private readonly owners;
89
+ private readonly utterances;
90
+ private nextStartTime;
91
+ private firstAudioReported;
92
+ private disposed;
93
+ constructor(options: StreamingPcmPlayerOptions);
94
+ /**
95
+ * Starts an utterance: a group of chunks with its own stop and drain. Utterances queue behind
96
+ * each other on the same schedule, so they never overlap.
97
+ */
98
+ beginUtterance(): PlaybackUtterance;
99
+ /** Schedules one chunk and returns the context time it starts at, or null when disposed. */
100
+ enqueue(pcm: Float32Array): number | null;
101
+ /** @internal Schedules one chunk for `owner` (or for no utterance). */
102
+ schedule(pcm: Float32Array, owner: PlaybackUtterance | undefined): number | null;
103
+ /** Stops playback and throws away everything scheduled, for every utterance: the barge-in path. */
104
+ stop(): void;
105
+ /** @internal Stops only `utterance`'s sources and closes the gap they leave in the schedule. */
106
+ unschedule(utterance: PlaybackUtterance): void;
107
+ private forget;
108
+ private halt;
109
+ /** Whether something is scheduled or playing. */
110
+ get isPlaying(): boolean;
111
+ suspend(): Promise<void>;
112
+ resume(): Promise<void>;
113
+ /** Stops playback and closes the context. Idempotent. */
114
+ dispose(): Promise<void>;
115
+ }
@@ -0,0 +1,122 @@
1
+ /**
2
+ * Platform voices as the browser's fallback for languages Phonon cannot ship (issue #36).
3
+ *
4
+ * `speechSynthesis` is not uniformly offline: the voices a browser exposes can be local
5
+ * (`localService === true`) or remote, and the two are indistinguishable to a person unless the
6
+ * app says so. This provider is therefore **local-voice only** by default: a locale with no local
7
+ * voice reports `networkRequired`, not "available", and a remote voice is only used when the host
8
+ * passes `allowNetwork: true` after a privacy notice.
9
+ *
10
+ * Phonon stays the English default; this provider answers for ES-419 and for English devices where
11
+ * the person declines the model download.
12
+ */
13
+ import { type VoiceProvider, type VoiceProviderAvailability, type VoiceProviderDescriptor } from "../../contract/contract";
14
+ export interface SynthesisVoiceLike {
15
+ readonly name: string;
16
+ readonly lang: string;
17
+ readonly localService?: boolean;
18
+ readonly default?: boolean;
19
+ readonly voiceURI?: string;
20
+ }
21
+ export interface SynthesisUtteranceLike {
22
+ text: string;
23
+ lang: string;
24
+ voice: SynthesisVoiceLike | null;
25
+ rate: number;
26
+ pitch: number;
27
+ volume: number;
28
+ onstart: (() => void) | null;
29
+ onend: (() => void) | null;
30
+ onerror: ((event: {
31
+ error: string;
32
+ }) => void) | null;
33
+ }
34
+ export interface SpeechSynthesisLike {
35
+ getVoices(): SynthesisVoiceLike[];
36
+ speak(utterance: SynthesisUtteranceLike): void;
37
+ cancel(): void;
38
+ pause?(): void;
39
+ resume?(): void;
40
+ readonly speaking?: boolean;
41
+ readonly pending?: boolean;
42
+ /** `voiceschanged` fires when the browser finished loading its voice list (Chrome loads late). */
43
+ addEventListener?(type: "voiceschanged", listener: () => void): void;
44
+ removeEventListener?(type: "voiceschanged", listener: () => void): void;
45
+ }
46
+ /** A timer handle; only passed back to `clearTimeout`. */
47
+ export type TimerHandle = unknown;
48
+ export interface SystemVoicesEnvironment {
49
+ readonly speechSynthesis?: SpeechSynthesisLike;
50
+ readonly Utterance?: new (text: string) => SynthesisUtteranceLike;
51
+ /** The browser's own constructor name; used when `Utterance` is not injected. */
52
+ readonly SpeechSynthesisUtterance?: new (text: string) => SynthesisUtteranceLike;
53
+ readonly now?: () => number;
54
+ /** Timers for the voice-list wait and the speech watchdog. Default: the global timers. */
55
+ readonly setTimeout?: (callback: () => void, milliseconds: number) => TimerHandle;
56
+ readonly clearTimeout?: (handle: TimerHandle) => void;
57
+ /** How long the first probe waits for `voiceschanged` when the list is empty. Default 1500 ms. */
58
+ readonly voicesTimeoutMs?: number;
59
+ }
60
+ export interface SpeakWithPlatformVoiceOptions {
61
+ /** A BCP-47 tag. Selects a local voice of this language and sets the utterance language. */
62
+ readonly locale?: string;
63
+ /** An exact voice name; wins over `locale` when both are given. */
64
+ readonly voiceName?: string;
65
+ readonly rate?: number;
66
+ readonly pitch?: number;
67
+ readonly volume?: number;
68
+ /** Whether the host has consent for a remote voice. Default false. */
69
+ readonly allowNetwork?: boolean;
70
+ readonly onStart?: () => void;
71
+ readonly onEnd?: () => void;
72
+ /**
73
+ * Reject with `failed` if the browser never reports an end (Chrome can drop `end` events).
74
+ * Default: 15 s plus 200 ms per character, scaled by `rate`.
75
+ */
76
+ readonly timeoutMs?: number;
77
+ }
78
+ export interface PlatformSpeechHandle {
79
+ readonly done: Promise<void>;
80
+ cancel(): void;
81
+ }
82
+ export declare const SYSTEM_VOICES_ID = "web.system-voices";
83
+ export declare class SystemVoiceProvider implements VoiceProvider {
84
+ readonly descriptor: VoiceProviderDescriptor;
85
+ private readonly environment;
86
+ /** Requests in browser queue order that have not settled. */
87
+ private inFlight;
88
+ private voicesReady;
89
+ constructor(environment?: SystemVoicesEnvironment);
90
+ private get Utterance();
91
+ /** Voices the browser exposes for a locale, split by where they run. */
92
+ voices(locale: string): {
93
+ local: SynthesisVoiceLike[];
94
+ remote: SynthesisVoiceLike[];
95
+ };
96
+ /**
97
+ * Resolves once the browser has a voice list, or after `voicesTimeoutMs`. Chrome returns an empty
98
+ * list until `voiceschanged`, which would otherwise read as "no voice installed".
99
+ */
100
+ waitForVoices(): Promise<void>;
101
+ availability(locale: string): Promise<VoiceProviderAvailability>;
102
+ /**
103
+ * Speaks with a platform voice. Local voices only unless `allowNetwork` is set. With `locale`,
104
+ * the voice is a local voice of that language (exact tag first, then the language's default).
105
+ */
106
+ speak(text: string, options?: SpeakWithPlatformVoiceOptions): PlatformSpeechHandle;
107
+ /** Whether a synthesis request is in flight. */
108
+ get isSpeaking(): boolean;
109
+ private selectVoice;
110
+ /** Wires one utterance object's events to its request. A rebuilt utterance is wired again. */
111
+ private bind;
112
+ /**
113
+ * Ends one request early (cancel or watchdog) without touching the others' promises. The browser
114
+ * can only cancel its whole queue, so the other unstarted requests are re-queued afterwards.
115
+ */
116
+ private abandon;
117
+ /** Cancels the browser queue and re-queues every unsettled request that had not started. */
118
+ private purge;
119
+ private settle;
120
+ private setTimer;
121
+ private clearTimer;
122
+ }
@@ -0,0 +1,101 @@
1
+ /**
2
+ * The browser side of the engine-agnostic voice turn manager (#34).
3
+ *
4
+ * A turn is one person→assistant exchange: the person speaks, they get a transcript, the assistant
5
+ * answers, and the person can talk over it. The manager owns exactly that state machine and nothing
6
+ * engine-specific: dictation arrives through the shared `TranscriptionSession` contract, speech
7
+ * leaves through a `SpeechSink` the host provides (Phonon, a platform voice, anything), and
8
+ * barge-in arrives through `notifySpeechDetected()` — from the microphone's voice detector, a
9
+ * key press, or the start of a new recognition session.
10
+ *
11
+ * The rule that matters: **barge-in stops speech with a request cancel, not a mute**, and a turn
12
+ * always ends in exactly one terminal event. Starting a new turn while the assistant is still
13
+ * talking is the common case on a page, so it is the default, not an option.
14
+ */
15
+ import type { PartialTranscript, TranscriptionProvider } from "./stt/speech-recognition";
16
+ import { VoiceError } from "../contract/errors";
17
+ /** What the assistant does with its answer. The manager never knows which engine is behind it. */
18
+ export interface SpeechSink {
19
+ speak(text: string, options?: {
20
+ signal?: AbortSignal;
21
+ }): {
22
+ done: Promise<unknown>;
23
+ cancel(): void;
24
+ };
25
+ }
26
+ export type TurnEvent = {
27
+ readonly type: "listening";
28
+ } | {
29
+ readonly type: "partial";
30
+ readonly partial: PartialTranscript;
31
+ } | {
32
+ readonly type: "transcript";
33
+ readonly text: string;
34
+ } | {
35
+ readonly type: "speaking";
36
+ readonly text: string;
37
+ } | {
38
+ readonly type: "speech-finished";
39
+ } | {
40
+ readonly type: "speech-cancelled";
41
+ } | {
42
+ readonly type: "barge-in";
43
+ } | {
44
+ readonly type: "failed";
45
+ readonly error: VoiceError;
46
+ } | {
47
+ readonly type: "cancelled";
48
+ };
49
+ export interface TurnManagerOptions {
50
+ readonly transcription: TranscriptionProvider;
51
+ readonly synthesis: SpeechSink;
52
+ /** Locale for every session this manager starts. */
53
+ readonly locale: string;
54
+ /** Whether the host has consented to the browser's service recognizer. */
55
+ readonly allowNetwork?: boolean;
56
+ /** Stop the assistant's speech when the person starts talking. Default true. */
57
+ readonly bargeInOnSpeech?: boolean;
58
+ /** Receives an error thrown by an event listener. Default: `console.error`. */
59
+ readonly onListenerError?: (error: unknown) => void;
60
+ }
61
+ /**
62
+ * One conversation's turns. `startListening()` and `speak()` are the two entry points a page
63
+ * needs; `events()` is one ordered stream for the UI.
64
+ */
65
+ export declare class VoiceTurnManager {
66
+ private readonly options;
67
+ private readonly listeners;
68
+ private session;
69
+ private speech;
70
+ /** Bumped by every `startListening()` and by `cancel()`: an older start that resumes is stale. */
71
+ private generation;
72
+ private finished;
73
+ constructor(options: TurnManagerOptions);
74
+ /** Subscribes to turn events. Returns an unsubscribe function. */
75
+ onEvent(listener: (event: TurnEvent) => void): () => void;
76
+ /**
77
+ * Starts a dictation turn. If the assistant is speaking, that speech is cancelled first and a
78
+ * `barge-in` event is emitted — the person talking over the assistant always wins.
79
+ */
80
+ startListening(): Promise<void>;
81
+ /** Stops needing audio: the session finalizes with what it heard. */
82
+ stopListening(): Promise<void>;
83
+ /** Speaks an answer. A previous answer is cancelled first; the sink decides how it plays. */
84
+ speak(text: string): {
85
+ done: Promise<unknown>;
86
+ cancel(): void;
87
+ };
88
+ /** The person started talking (voice detector, key press, or a new session). */
89
+ notifySpeechDetected(): void;
90
+ /** Tears both halves down. Idempotent; emits one terminal event. */
91
+ cancel(): Promise<void>;
92
+ /**
93
+ * `barge-in`: the person talked over the answer (`barge-in` + `speech-cancelled`).
94
+ * `replaced`: a newer answer or the host stopped it (`speech-cancelled`).
95
+ * `cancel`: the manager is tearing down; its own `cancelled` is the terminal event.
96
+ */
97
+ private stopSpeech;
98
+ private consume;
99
+ private forward;
100
+ private emit;
101
+ }
package/package.json CHANGED
@@ -1,6 +1,70 @@
1
1
  {
2
2
  "name": "@adea-ai/voice",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "The Adea Voice SDK: the shared speech provider contract, unified per-device voice settings, the desktop client for the pinned Apple/transcribe.cpp/audio.cpp helpers, and the browser providers.",
5
+ "license": "Apache-2.0",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://gitlab.com/adea-ai/misc/voice.git",
9
+ "directory": "packages/voice-sdk"
10
+ },
11
+ "type": "module",
12
+ "sideEffects": false,
13
+ "files": [
14
+ "dist",
15
+ "src",
16
+ "README.md"
17
+ ],
18
+ "main": "./dist/index.js",
19
+ "types": "./dist/index.d.ts",
20
+ "exports": {
21
+ ".": {
22
+ "types": "./dist/index.d.ts",
23
+ "bun": "./src/index.ts",
24
+ "import": "./dist/index.js"
25
+ },
26
+ "./contract": {
27
+ "types": "./dist/contract/index.d.ts",
28
+ "bun": "./src/contract/index.ts",
29
+ "import": "./dist/contract/index.js"
30
+ },
31
+ "./settings": {
32
+ "types": "./dist/settings/index.d.ts",
33
+ "bun": "./src/settings/index.ts",
34
+ "import": "./dist/settings/index.js"
35
+ },
36
+ "./web": {
37
+ "types": "./dist/web/index.d.ts",
38
+ "bun": "./src/web/index.ts",
39
+ "import": "./dist/web/index.js"
40
+ },
41
+ "./desktop": {
42
+ "types": "./dist/desktop/index.d.ts",
43
+ "bun": "./src/desktop/index.ts",
44
+ "import": "./dist/desktop/index.js"
45
+ },
46
+ "./package.json": "./package.json"
47
+ },
48
+ "bin": {
49
+ "adea-voice-helpers": "./dist/cli/helpers-cli.js"
50
+ },
51
+ "scripts": {
52
+ "build": "rm -rf dist && bun build src/index.ts src/contract/index.ts src/settings/index.ts src/web/index.ts src/desktop/index.ts src/cli/helpers-cli.ts --outdir dist --root src --target node --format esm --splitting --packages external && tsc -p tsconfig.build.json",
53
+ "test": "bun test",
54
+ "typecheck": "tsc --noEmit"
55
+ },
56
+ "dependencies": {
57
+ "phonon-tts": "0.7.1"
58
+ },
59
+ "devDependencies": {
60
+ "bun-types": "1.4.4",
61
+ "typescript": "5.9.3"
62
+ },
63
+ "engines": {
64
+ "bun": ">=1.2",
65
+ "node": ">=22"
66
+ },
67
+ "publishConfig": {
68
+ "access": "public"
69
+ }
70
+ }