@oxvo/ai-live-assist 7.4.50 → 7.5.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 (163) hide show
  1. package/cjs/AiLiveAssist.d.ts +76 -11
  2. package/cjs/AiLiveAssist.js +1771 -298
  3. package/cjs/client.d.ts +19 -0
  4. package/cjs/client.js +51 -0
  5. package/cjs/context.d.ts +23 -1
  6. package/cjs/context.js +713 -126
  7. package/cjs/control.d.ts +2 -0
  8. package/cjs/control.js +42 -3
  9. package/cjs/ctaOffer.d.ts +11 -0
  10. package/cjs/ctaOffer.js +185 -0
  11. package/cjs/dialogFocusScope.js +1 -1
  12. package/cjs/guideAdmission.d.ts +46 -0
  13. package/cjs/guideAdmission.js +397 -0
  14. package/cjs/guideHost.d.ts +47 -0
  15. package/cjs/guideHost.js +48 -0
  16. package/cjs/guideInstallation.d.ts +12 -0
  17. package/cjs/guideInstallation.js +60 -0
  18. package/cjs/guideInstaller.d.ts +4 -0
  19. package/cjs/guideInstaller.js +116 -0
  20. package/cjs/guideMount.d.ts +22 -0
  21. package/cjs/guideMount.js +84 -0
  22. package/cjs/guideRecording.d.ts +64 -0
  23. package/cjs/guideRecording.js +176 -0
  24. package/cjs/guideRecordingSession.d.ts +35 -0
  25. package/cjs/guideRecordingSession.js +167 -0
  26. package/cjs/guideSubjectStore.d.ts +32 -0
  27. package/cjs/guideSubjectStore.js +105 -0
  28. package/cjs/guideTypes.d.ts +117 -0
  29. package/cjs/guideTypes.js +15 -0
  30. package/cjs/index.d.ts +6 -0
  31. package/cjs/index.js +25 -11
  32. package/cjs/liveAudioProcessor.d.ts +92 -0
  33. package/cjs/liveAudioProcessor.js +269 -0
  34. package/cjs/liveAudioQueue.d.ts +40 -0
  35. package/cjs/liveAudioQueue.js +130 -0
  36. package/cjs/liveAudioWorklet.d.ts +1 -0
  37. package/cjs/liveAudioWorklet.js +63 -0
  38. package/cjs/liveBrowserDetector.d.ts +16 -0
  39. package/cjs/liveBrowserDetector.js +75 -0
  40. package/cjs/liveBrowserDetectorWorker.d.ts +1 -0
  41. package/cjs/liveBrowserDetectorWorker.js +72 -0
  42. package/cjs/liveControlChannel.d.ts +176 -0
  43. package/cjs/liveControlChannel.js +829 -0
  44. package/cjs/liveDuplexMedia.d.ts +204 -0
  45. package/cjs/liveDuplexMedia.js +740 -0
  46. package/cjs/liveGuideAdmission.d.ts +21 -0
  47. package/cjs/liveGuideAdmission.js +94 -0
  48. package/cjs/liveGuideWidget.d.ts +68 -0
  49. package/cjs/liveGuideWidget.js +451 -0
  50. package/cjs/liveSpeechAssets.d.ts +36 -0
  51. package/cjs/liveSpeechAssets.js +39 -0
  52. package/cjs/liveSpeechCaptureBridge.d.ts +32 -0
  53. package/cjs/liveSpeechCaptureBridge.js +140 -0
  54. package/cjs/liveSpeechDetector.d.ts +62 -0
  55. package/cjs/liveSpeechDetector.js +206 -0
  56. package/cjs/liveSpeechModel.d.ts +46 -0
  57. package/cjs/liveSpeechModel.js +105 -0
  58. package/cjs/liveSpeechResampler.d.ts +22 -0
  59. package/cjs/liveSpeechResampler.js +93 -0
  60. package/cjs/liveSpeechWorker.d.ts +56 -0
  61. package/cjs/liveSpeechWorker.js +143 -0
  62. package/cjs/locales/resources.js +568 -8
  63. package/cjs/media.d.ts +11 -0
  64. package/cjs/media.js +78 -9
  65. package/cjs/messages.js +22 -8
  66. package/cjs/pageAssistancePreference.d.ts +15 -3
  67. package/cjs/pageAssistancePreference.js +46 -7
  68. package/cjs/preview.d.ts +4 -1
  69. package/cjs/preview.js +42 -1
  70. package/cjs/recording.d.ts +12 -0
  71. package/cjs/recording.js +150 -0
  72. package/cjs/standalone.d.ts +6 -0
  73. package/cjs/standalone.js +12 -0
  74. package/cjs/types.d.ts +31 -5
  75. package/cjs/types.js +14 -0
  76. package/cjs/ui.d.ts +128 -4
  77. package/cjs/ui.js +1918 -276
  78. package/cjs/version.d.ts +1 -1
  79. package/cjs/version.js +1 -1
  80. package/cjs/voicePresenceUi.d.ts +52 -4
  81. package/cjs/voicePresenceUi.js +659 -57
  82. package/lib/AiLiveAssist.d.ts +76 -11
  83. package/lib/AiLiveAssist.js +1772 -299
  84. package/lib/client.d.ts +19 -0
  85. package/lib/client.js +51 -0
  86. package/lib/context.d.ts +23 -1
  87. package/lib/context.js +713 -126
  88. package/lib/control.d.ts +2 -0
  89. package/lib/control.js +42 -3
  90. package/lib/ctaOffer.d.ts +11 -0
  91. package/lib/ctaOffer.js +179 -0
  92. package/lib/dialogFocusScope.js +1 -1
  93. package/lib/guideAdmission.d.ts +46 -0
  94. package/lib/guideAdmission.js +392 -0
  95. package/lib/guideHost.d.ts +47 -0
  96. package/lib/guideHost.js +42 -0
  97. package/lib/guideInstallation.d.ts +12 -0
  98. package/lib/guideInstallation.js +56 -0
  99. package/lib/guideInstaller.d.ts +4 -0
  100. package/lib/guideInstaller.js +113 -0
  101. package/lib/guideMount.d.ts +22 -0
  102. package/lib/guideMount.js +77 -0
  103. package/lib/guideRecording.d.ts +64 -0
  104. package/lib/guideRecording.js +172 -0
  105. package/lib/guideRecordingSession.d.ts +35 -0
  106. package/lib/guideRecordingSession.js +163 -0
  107. package/lib/guideSubjectStore.d.ts +32 -0
  108. package/lib/guideSubjectStore.js +101 -0
  109. package/lib/guideTypes.d.ts +117 -0
  110. package/lib/guideTypes.js +11 -0
  111. package/lib/index.d.ts +6 -0
  112. package/lib/index.js +21 -10
  113. package/lib/liveAudioProcessor.d.ts +92 -0
  114. package/lib/liveAudioProcessor.js +265 -0
  115. package/lib/liveAudioQueue.d.ts +40 -0
  116. package/lib/liveAudioQueue.js +126 -0
  117. package/lib/liveAudioWorklet.d.ts +1 -0
  118. package/lib/liveAudioWorklet.js +61 -0
  119. package/lib/liveBrowserDetector.d.ts +16 -0
  120. package/lib/liveBrowserDetector.js +71 -0
  121. package/lib/liveBrowserDetectorWorker.d.ts +1 -0
  122. package/lib/liveBrowserDetectorWorker.js +70 -0
  123. package/lib/liveControlChannel.d.ts +176 -0
  124. package/lib/liveControlChannel.js +825 -0
  125. package/lib/liveDuplexMedia.d.ts +204 -0
  126. package/lib/liveDuplexMedia.js +736 -0
  127. package/lib/liveGuideAdmission.d.ts +21 -0
  128. package/lib/liveGuideAdmission.js +90 -0
  129. package/lib/liveGuideWidget.d.ts +68 -0
  130. package/lib/liveGuideWidget.js +447 -0
  131. package/lib/liveSpeechAssets.d.ts +36 -0
  132. package/lib/liveSpeechAssets.js +35 -0
  133. package/lib/liveSpeechCaptureBridge.d.ts +32 -0
  134. package/lib/liveSpeechCaptureBridge.js +136 -0
  135. package/lib/liveSpeechDetector.d.ts +62 -0
  136. package/lib/liveSpeechDetector.js +202 -0
  137. package/lib/liveSpeechModel.d.ts +46 -0
  138. package/lib/liveSpeechModel.js +101 -0
  139. package/lib/liveSpeechResampler.d.ts +22 -0
  140. package/lib/liveSpeechResampler.js +89 -0
  141. package/lib/liveSpeechWorker.d.ts +56 -0
  142. package/lib/liveSpeechWorker.js +137 -0
  143. package/lib/locales/resources.js +568 -8
  144. package/lib/media.d.ts +11 -0
  145. package/lib/media.js +77 -8
  146. package/lib/messages.js +22 -8
  147. package/lib/pageAssistancePreference.d.ts +15 -3
  148. package/lib/pageAssistancePreference.js +46 -7
  149. package/lib/preview.d.ts +4 -1
  150. package/lib/preview.js +42 -1
  151. package/lib/recording.d.ts +12 -0
  152. package/lib/recording.js +146 -0
  153. package/lib/standalone.d.ts +6 -0
  154. package/lib/standalone.js +6 -0
  155. package/lib/types.d.ts +31 -5
  156. package/lib/types.js +14 -0
  157. package/lib/ui.d.ts +128 -4
  158. package/lib/ui.js +1919 -277
  159. package/lib/version.d.ts +1 -1
  160. package/lib/version.js +1 -1
  161. package/lib/voicePresenceUi.d.ts +52 -4
  162. package/lib/voicePresenceUi.js +659 -57
  163. package/package.json +16 -1
@@ -0,0 +1,736 @@
1
+ const validId = (value) => typeof value === 'string' && value.length > 0 && value.length <= 256 && !/[\u0000-\u001f\u007f]/.test(value);
2
+ const validEpoch = (value) => typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;
3
+ const mediaError = () => new Error('Live voice media is unavailable.');
4
+ const isAuthorizationHandle = (value) => {
5
+ if (!value || typeof value !== 'object' || !Object.isFrozen(value) || Reflect.ownKeys(value).length !== 0)
6
+ return false;
7
+ const prototype = Object.getPrototypeOf(value);
8
+ return prototype === Object.prototype || prototype === null;
9
+ };
10
+ export class LiveDuplexMedia {
11
+ constructor(options) {
12
+ this.options = options;
13
+ this.phase = 'new';
14
+ this.epoch = -1;
15
+ this.context = null;
16
+ this.microphone = null;
17
+ this.source = null;
18
+ this.node = null;
19
+ this.destination = null;
20
+ this.pull = null;
21
+ this.detector = null;
22
+ this.peer = null;
23
+ this.channel = null;
24
+ this.remote = null;
25
+ this.operation = null;
26
+ this.pendingWake = null;
27
+ this.offerPending = false;
28
+ this.wakeAcknowledged = false;
29
+ this.activeAcknowledged = false;
30
+ this.retirementAcknowledged = false;
31
+ this.retirementCompleteAcknowledged = false;
32
+ this.retirementCompleting = false;
33
+ this.lastRetired = null;
34
+ this.answerAuthorization = null;
35
+ this.startedAuthorization = null;
36
+ this.modelReady = false;
37
+ this.workletReady = false;
38
+ this.detectorAttached = false;
39
+ this.captureReady = false;
40
+ this.playbackReady = false;
41
+ this.contextHasRun = false;
42
+ this.lifetime = new AbortController();
43
+ this.listeners = [];
44
+ this.peerListeners = [];
45
+ this.checks = new Set();
46
+ this.stoppedTracks = new WeakSet();
47
+ this.closedDetectors = new WeakSet();
48
+ this.usedOperations = new Set();
49
+ this.usedGenerations = new Set();
50
+ this.wakeTimer = null;
51
+ this.wakeTimerToken = 0;
52
+ this.lastNow = options.dependencies.now();
53
+ this.prepareTimeout = options.prepareTimeoutMs ?? 20000;
54
+ this.controlTimeout = options.controlTimeoutMs ?? 1000;
55
+ if (!Number.isFinite(this.lastNow) || this.lastNow < 0 || !Number.isFinite(this.prepareTimeout) ||
56
+ this.prepareTimeout < 1000 || this.prepareTimeout > 30000 || !validId(options.dataChannelLabel) ||
57
+ !Number.isFinite(this.controlTimeout) || this.controlTimeout < 128 || this.controlTimeout > 2000 ||
58
+ typeof options.workletUrl !== 'string' || options.workletUrl.length < 1 || options.workletUrl.length > 2048 ||
59
+ typeof options.dependencies.isAnswerAuthorized !== 'function' || typeof options.dependencies.isPcmActivationAuthorized !== 'function' ||
60
+ typeof options.dependencies.isTerminalAuthorized !== 'function' ||
61
+ typeof options.dependencies.isPlaybackDrained !== 'function')
62
+ throw mediaError();
63
+ }
64
+ get status() { return this.phase; }
65
+ /** Must be invoked directly in the user's gesture. This method has no RTC/provider operation. */
66
+ async prepare(input) {
67
+ if (this.phase !== 'new' || !validEpoch(input.captureEpoch) || input.signal.aborted ||
68
+ !this.options.dependencies.hasUserActivation() || !this.options.dependencies.isForeground())
69
+ throw mediaError();
70
+ this.phase = 'preparing';
71
+ this.epoch = input.captureEpoch;
72
+ const dependencies = this.options.dependencies;
73
+ const deadline = this.now() + this.prepareTimeout;
74
+ try {
75
+ this.listen(dependencies.lifecycleEvents, 'visibilitychange', () => {
76
+ if (!dependencies.isForeground())
77
+ this.close('foreground');
78
+ });
79
+ this.listen(dependencies.lifecycleEvents, 'pagehide', () => this.close('foreground'));
80
+ this.listen(this.options.audioElement, 'error', () => this.close('playback'));
81
+ const context = dependencies.createAudioContext();
82
+ this.context = context;
83
+ if (!Number.isSafeInteger(context.sampleRate) || context.sampleRate < 8000 || context.sampleRate > 96000)
84
+ throw mediaError();
85
+ this.listen(context, 'statechange', () => {
86
+ if (context.state === 'running')
87
+ this.contextHasRun = true;
88
+ else if (this.contextHasRun && this.phase !== 'closed')
89
+ this.close('context');
90
+ this.pulse();
91
+ });
92
+ // Both permission and resume requests begin synchronously in the gesture.
93
+ const resuming = this.guard(context.resume(), deadline, input.signal);
94
+ void resuming.catch(() => undefined); // Also observed by Promise.all below.
95
+ const acquiring = this.guard(dependencies.getUserMedia({ audio: {
96
+ echoCancellation: { exact: true }, autoGainControl: true, noiseSuppression: true, channelCount: { ideal: 1 },
97
+ }, video: false }).then(stream => {
98
+ // Own a returned stream immediately, even if context.resume is still
99
+ // pending or another preparation branch fails before Promise.all settles.
100
+ if (this.phase === 'closed' || input.signal.aborted)
101
+ this.stopStream(stream);
102
+ else
103
+ this.microphone = stream;
104
+ return stream;
105
+ }), deadline, input.signal, stream => this.stopStream(stream));
106
+ const [stream] = await Promise.all([acquiring, resuming]);
107
+ this.assertCurrent(input.signal, deadline);
108
+ this.microphone = stream;
109
+ const tracks = stream.getAudioTracks();
110
+ const track = tracks[0];
111
+ if (tracks.length !== 1 || stream.getVideoTracks().length !== 0 || !track || track.readyState !== 'live' || !track.enabled)
112
+ throw mediaError();
113
+ const echo = track.getSettings().echoCancellation;
114
+ if (echo !== true && echo !== 'all' && echo !== 'remote-only')
115
+ throw mediaError();
116
+ this.listen(track, 'ended', () => this.close('capture'));
117
+ this.listen(track, 'mute', () => { if (this.captureReady)
118
+ this.close('capture'); });
119
+ this.contextHasRun = context.state === 'running';
120
+ if (!this.contextHasRun)
121
+ throw mediaError();
122
+ await this.guard(context.audioWorklet.addModule(this.options.workletUrl), deadline, input.signal);
123
+ this.assertCurrent(input.signal, deadline);
124
+ const node = dependencies.createWorklet(context, { numberOfInputs: 1, numberOfOutputs: 1, outputChannelCount: [1],
125
+ channelCount: 1, channelCountMode: 'explicit', processorOptions: { captureEpoch: this.epoch } });
126
+ this.node = node;
127
+ this.listen(node.port, 'message', event => this.workletMessage(event.data));
128
+ this.listen(node, 'processorerror', () => this.close('worklet'));
129
+ node.port.start();
130
+ const detector = await this.guard(dependencies.createDetector({ captureEpoch: this.epoch, sampleRate: context.sampleRate,
131
+ signal: this.lifetime.signal, onFault: () => this.close('detector') }).then(resource => {
132
+ if (this.phase === 'closed' || input.signal.aborted)
133
+ this.closeDetector(resource);
134
+ else
135
+ this.detector = resource;
136
+ return resource;
137
+ }), deadline, input.signal, resource => this.closeDetector(resource));
138
+ this.assertCurrent(input.signal, deadline);
139
+ this.detector = detector;
140
+ const ready = await this.guard(detector.ready, deadline, input.signal);
141
+ if (ready.captureEpoch !== this.epoch || ready.sampleRate !== context.sampleRate)
142
+ throw mediaError();
143
+ this.modelReady = true;
144
+ node.port.postMessage({ type: 'attach_detector', captureEpoch: this.epoch }, [detector.port]);
145
+ await this.waitFor(() => this.workletReady && this.detectorAttached, deadline, input.signal);
146
+ this.destination = context.createMediaStreamDestination();
147
+ const outgoing = this.destination.stream.getAudioTracks();
148
+ if (outgoing.length !== 1 || !outgoing[0] || outgoing[0] === track || outgoing[0].id === track.id ||
149
+ outgoing[0].readyState !== 'live' || !outgoing[0].enabled)
150
+ throw mediaError();
151
+ this.listen(outgoing[0], 'ended', () => this.close('capture'));
152
+ this.pull = context.createGain();
153
+ this.pull.gain.value = 0;
154
+ this.source = context.createMediaStreamSource(stream);
155
+ this.source.connect(node);
156
+ node.connect(this.destination);
157
+ node.connect(this.pull);
158
+ this.pull.connect(context.destination);
159
+ await this.waitFor(() => this.captureReady, deadline, input.signal);
160
+ this.assertHealthy(input.signal, deadline);
161
+ this.phase = 'local';
162
+ const result = { captureEpoch: this.epoch, sampleRate: context.sampleRate };
163
+ this.options.onMetadata({ type: 'prepared', ...result });
164
+ return result;
165
+ }
166
+ catch {
167
+ this.close(input.signal.aborted ? 'aborted' : 'capture');
168
+ throw mediaError();
169
+ }
170
+ }
171
+ /** May preserve an onset during old-generation retirement; it never creates an RTC connection. */
172
+ async bufferWake(binding, signal) {
173
+ if ((this.phase !== 'local' && this.phase !== 'retiring') || this.pendingWake || !this.validNewWake(binding))
174
+ throw mediaError();
175
+ this.assertHealthy(signal, binding.deadlineAt);
176
+ this.pendingWake = Object.freeze({ operationId: binding.operationId, captureEpoch: binding.captureEpoch, deadlineAt: binding.deadlineAt });
177
+ this.wakeAcknowledged = false;
178
+ this.armWakeDeadline(binding.deadlineAt);
179
+ try {
180
+ this.node.port.postMessage({ type: 'begin_wake', captureEpoch: this.epoch, operationId: binding.operationId });
181
+ await this.waitFor(() => this.wakeAcknowledged, binding.deadlineAt, signal);
182
+ }
183
+ catch {
184
+ this.close(signal.aborted ? 'aborted' : 'worklet');
185
+ throw mediaError();
186
+ }
187
+ }
188
+ /** Local, unpaid offer preparation. The server needs this exact SDP before
189
+ * it can claim a paid stream; no provider generation is invented here. */
190
+ async createOffer(binding, signal) {
191
+ // The owner may retain its request object; asynchronous media work must use
192
+ // a stable offer identity even if that external object subsequently changes.
193
+ binding = Object.freeze({ operationId: binding.operationId, captureEpoch: binding.captureEpoch,
194
+ deadlineAt: binding.deadlineAt });
195
+ if (this.phase !== 'local' || this.peer || this.offerPending || !this.validNewWake(binding))
196
+ throw mediaError();
197
+ if (this.pendingWake && !this.matchesWake(this.pendingWake, binding))
198
+ throw mediaError();
199
+ this.offerPending = true;
200
+ try {
201
+ if (!this.pendingWake)
202
+ await this.bufferWake(binding, signal);
203
+ else
204
+ await this.waitFor(() => this.wakeAcknowledged, binding.deadlineAt, signal);
205
+ this.assertHealthy(signal, binding.deadlineAt);
206
+ const pending = this.pendingWake;
207
+ if (!pending || !this.matchesWake(pending, binding))
208
+ throw mediaError();
209
+ const offered = Object.freeze({ ...pending });
210
+ this.phase = 'offering';
211
+ this.usedOperations.add(binding.operationId);
212
+ const peer = this.options.dependencies.createPeerConnection();
213
+ this.peer = peer;
214
+ this.bindPeer(peer, offered);
215
+ const stream = this.destination.stream;
216
+ const track = stream.getAudioTracks()[0];
217
+ if (!track || track.readyState !== 'live' || this.microphone.getTracks().includes(track))
218
+ throw mediaError();
219
+ peer.addTrack(track, stream);
220
+ const channel = peer.createDataChannel(this.options.dataChannelLabel, { ordered: true });
221
+ this.channel = channel;
222
+ this.listen(channel, 'open', () => this.pulse(), this.peerListeners);
223
+ this.listen(channel, 'error', () => this.peerLost(peer, offered, 'data_channel'), this.peerListeners);
224
+ this.listen(channel, 'close', () => this.peerLost(peer, offered, 'data_channel'), this.peerListeners);
225
+ // No channel.send, provider event parsing or native snapshot authorization.
226
+ const offer = await this.guard(peer.createOffer(), binding.deadlineAt, signal);
227
+ this.assertOffer(binding, signal);
228
+ if (offer.type !== 'offer')
229
+ throw mediaError();
230
+ await this.guard(peer.setLocalDescription(offer), binding.deadlineAt, signal);
231
+ await this.waitFor(() => peer.iceGatheringState === 'complete', binding.deadlineAt, signal);
232
+ this.assertOffer(binding, signal);
233
+ const sdp = peer.localDescription?.sdp;
234
+ if (typeof sdp !== 'string' || sdp.length < 1 || sdp.length > 131072)
235
+ throw mediaError();
236
+ this.phase = 'offered';
237
+ return { binding: offered, sdp };
238
+ }
239
+ catch {
240
+ this.close(signal.aborted ? 'aborted' : 'rtc');
241
+ throw mediaError();
242
+ }
243
+ finally {
244
+ this.offerPending = false;
245
+ }
246
+ }
247
+ /** Accept only an application-owned proof of the current persisted started
248
+ * event. Native data-channel events never call this method automatically.
249
+ */
250
+ observeStartedAuthorization(input) {
251
+ const binding = Object.freeze({ operationId: input.binding.operationId, captureEpoch: input.binding.captureEpoch,
252
+ deadlineAt: input.binding.deadlineAt, generationId: input.binding.generationId });
253
+ if ((this.phase !== 'offered' && this.phase !== 'connecting') || !validId(binding.generationId) ||
254
+ !isAuthorizationHandle(input.startedReceipt) ||
255
+ (this.operation ? !this.matches(this.operation, binding) :
256
+ !this.pendingWake || !this.matchesWake(this.pendingWake, binding) || this.usedGenerations.has(binding.generationId)) ||
257
+ (this.startedAuthorization && !this.matches(this.startedAuthorization.binding, binding)))
258
+ return false;
259
+ try {
260
+ this.assertOffer(binding, this.lifetime.signal);
261
+ if (!this.options.dependencies.isPcmActivationAuthorized(binding, input.startedReceipt))
262
+ return false;
263
+ // An early started proof may precede the answer, but is never itself a
264
+ // generation promotion, native SDP authorization, or permission for PCM.
265
+ this.startedAuthorization = Object.freeze({ binding, receipt: input.startedReceipt });
266
+ this.pulse();
267
+ return true;
268
+ }
269
+ catch {
270
+ this.close('authority');
271
+ return false;
272
+ }
273
+ }
274
+ async acceptVerifiedAnswer(input, signal) {
275
+ input = { ...input, binding: Object.freeze({ operationId: input.binding.operationId, captureEpoch: input.binding.captureEpoch,
276
+ deadlineAt: input.binding.deadlineAt, generationId: input.binding.generationId }) };
277
+ if (this.phase !== 'offered' || this.operation || !this.pendingWake || !this.matchesWake(this.pendingWake, input.binding) ||
278
+ !validId(input.binding.generationId) || this.usedGenerations.has(input.binding.generationId) ||
279
+ typeof input.answerSdp !== 'string' || input.answerSdp.length < 1 || input.answerSdp.length > 131072)
280
+ throw mediaError();
281
+ try {
282
+ this.assertOffer(input.binding, signal);
283
+ if (!isAuthorizationHandle(input.preparedReceipt) ||
284
+ !this.options.dependencies.isAnswerAuthorized(input.binding, input.answerSdp, input.preparedReceipt) ||
285
+ (this.startedAuthorization && !this.matches(this.startedAuthorization.binding, input.binding))) {
286
+ this.close('authority');
287
+ throw mediaError();
288
+ }
289
+ this.operation = input.binding;
290
+ this.usedGenerations.add(input.binding.generationId);
291
+ const prepared = Object.freeze({ binding: this.operation, answerSdp: input.answerSdp, receipt: input.preparedReceipt });
292
+ this.answerAuthorization = prepared;
293
+ this.phase = 'connecting';
294
+ const peer = this.peer;
295
+ await this.guard(peer.setRemoteDescription({ type: 'answer', sdp: prepared.answerSdp }), input.binding.deadlineAt, signal);
296
+ await this.waitFor(() => peer.connectionState === 'connected' && this.channel?.readyState === 'open' && this.playbackReady &&
297
+ this.hasStartedAuthorization(), input.binding.deadlineAt, signal);
298
+ this.assertOperation(input.binding, signal);
299
+ // Both independent authorities must remain current immediately before PCM release.
300
+ if (this.answerAuthorization !== prepared ||
301
+ !this.options.dependencies.isAnswerAuthorized(prepared.binding, prepared.answerSdp, prepared.receipt) || !this.hasStartedAuthorization()) {
302
+ this.close('authority');
303
+ throw mediaError();
304
+ }
305
+ this.activeAcknowledged = false;
306
+ this.node.port.postMessage({ type: 'activate', captureEpoch: this.epoch, operationId: input.binding.operationId });
307
+ await this.waitFor(() => this.activeAcknowledged, input.binding.deadlineAt, signal);
308
+ this.assertOperation(input.binding, signal);
309
+ this.phase = 'active';
310
+ this.pendingWake = null;
311
+ this.clearWakeDeadline();
312
+ this.options.onMetadata({ type: 'active', binding: this.operation });
313
+ }
314
+ catch {
315
+ this.close(signal.aborted ? 'aborted' : 'rtc');
316
+ throw mediaError();
317
+ }
318
+ }
319
+ /** Stops outgoing PCM before the owner dispatches provider retirement. Capture
320
+ * and detector continuity remain intact, including a wake crossing the close.
321
+ */
322
+ async beginRetirement(binding, signal) {
323
+ if ((this.phase !== 'active' && this.phase !== 'retiring') || !this.operation || !this.matches(this.operation, binding))
324
+ throw mediaError();
325
+ const retiring = this.operation;
326
+ const deadline = this.now() + this.controlTimeout;
327
+ try {
328
+ this.assertHealthy(signal, deadline);
329
+ if (this.phase === 'active') {
330
+ this.phase = 'retiring';
331
+ this.answerAuthorization = null;
332
+ this.startedAuthorization = null;
333
+ this.retirementAcknowledged = false;
334
+ this.retirementCompleteAcknowledged = false;
335
+ this.node.port.postMessage({ type: 'begin_retirement', captureEpoch: this.epoch, operationId: this.operation.operationId });
336
+ }
337
+ // Duplicate calls observe the same ACK, never reseed/erase an existing wake.
338
+ await this.waitFor(() => this.retirementAcknowledged, deadline, signal);
339
+ this.assertHealthy(signal, deadline);
340
+ if (this.lastRetired && this.matches(this.lastRetired, retiring))
341
+ return;
342
+ this.options.onMetadata({ type: 'retiring', binding: retiring });
343
+ }
344
+ catch {
345
+ this.close(signal.aborted ? 'aborted' : 'worklet');
346
+ throw mediaError();
347
+ }
348
+ }
349
+ /** A native RTC close is not terminal provider proof. The owning application
350
+ * must verify the exact persisted receipt and actual playback drain first.
351
+ */
352
+ async retireToLocal(input, signal) {
353
+ if (this.lastRetired && this.matches(this.lastRetired, input.binding))
354
+ return;
355
+ if (this.phase !== 'retiring' || !this.operation || !this.matches(this.operation, input.binding) ||
356
+ !this.retirementAcknowledged || this.retirementCompleting)
357
+ throw mediaError();
358
+ const binding = this.operation;
359
+ // Not-yet-terminal/not-yet-drained is a retryable owner decision, with no
360
+ // local close/rearm side effects and no claim that a provider is now free.
361
+ if (!this.options.dependencies.isTerminalAuthorized(binding, input.terminalReceipt) ||
362
+ !this.options.dependencies.isPlaybackDrained(binding, this.options.audioElement))
363
+ throw mediaError();
364
+ const deadline = Math.min(this.now() + this.controlTimeout, this.pendingWake?.deadlineAt ?? Infinity);
365
+ this.retirementCompleting = true;
366
+ try {
367
+ this.assertHealthy(signal, deadline);
368
+ if (!this.closePeer()) {
369
+ this.close('rtc');
370
+ throw mediaError();
371
+ }
372
+ this.node.port.postMessage({ type: 'complete_retirement', captureEpoch: this.epoch, operationId: binding.operationId });
373
+ await this.waitFor(() => this.retirementCompleteAcknowledged, deadline, signal);
374
+ this.assertHealthy(signal, deadline);
375
+ this.lastRetired = binding;
376
+ this.operation = null;
377
+ this.phase = 'local';
378
+ // Keep pendingWake, its original deadline, the capture epoch and VAD state.
379
+ this.options.onMetadata({ type: 'retired', binding });
380
+ }
381
+ catch {
382
+ this.close(signal.aborted ? 'aborted' : 'worklet');
383
+ throw mediaError();
384
+ }
385
+ finally {
386
+ this.retirementCompleting = false;
387
+ }
388
+ }
389
+ close(reason = 'ended') {
390
+ if (this.phase === 'closed')
391
+ return;
392
+ const binding = this.operation;
393
+ const pendingWake = this.pendingWake;
394
+ this.phase = 'closed';
395
+ this.lifetime.abort();
396
+ this.clearWakeDeadline();
397
+ this.pulse();
398
+ for (const remove of this.listeners.splice(0))
399
+ remove();
400
+ try {
401
+ this.node?.port.postMessage({ type: 'close', captureEpoch: this.epoch });
402
+ }
403
+ catch { /* Already gone. */ }
404
+ this.closePeer();
405
+ if (this.detector)
406
+ this.closeDetector(this.detector);
407
+ this.detector = null;
408
+ this.stopStream(this.microphone);
409
+ this.microphone = null;
410
+ this.stopStream(this.destination?.stream ?? null);
411
+ for (const node of [this.source, this.node, this.destination, this.pull]) {
412
+ try {
413
+ node?.disconnect();
414
+ }
415
+ catch { /* Node may already be disconnected. */ }
416
+ }
417
+ try {
418
+ this.node?.port.close();
419
+ }
420
+ catch { /* Port may already be closed. */ }
421
+ const context = this.context;
422
+ this.context = null;
423
+ this.source = null;
424
+ this.node = null;
425
+ this.destination = null;
426
+ this.pull = null;
427
+ try {
428
+ if (context)
429
+ void context.close().catch(() => undefined);
430
+ }
431
+ catch { /* Continue terminal notification. */ }
432
+ this.operation = null;
433
+ this.pendingWake = null;
434
+ this.options.onFailSafeClose({ reason, binding, pendingWake, requiresProviderReconciliation: binding !== null || pendingWake !== null });
435
+ }
436
+ bindPeer(peer, binding) {
437
+ this.listen(peer, 'icegatheringstatechange', () => this.pulse(), this.peerListeners);
438
+ this.listen(peer, 'connectionstatechange', () => {
439
+ if (this.peer !== peer || this.phase === 'closed')
440
+ return;
441
+ const operation = this.operation;
442
+ if (operation && this.matchesWake(operation, binding)) {
443
+ this.options.onMetadata({ type: 'connection', binding: operation, state: peer.connectionState });
444
+ }
445
+ if (['failed', 'closed', 'disconnected'].includes(peer.connectionState))
446
+ this.peerLost(peer, binding, 'peer');
447
+ this.pulse();
448
+ }, this.peerListeners);
449
+ this.listen(peer, 'track', event => {
450
+ const track = event.track;
451
+ if (this.peer !== peer || this.phase === 'closed' || track.kind !== 'audio' || this.remote) {
452
+ this.stopTrack(track);
453
+ if (this.peer === peer && this.phase !== 'closed')
454
+ this.close('rtc');
455
+ return;
456
+ }
457
+ try {
458
+ this.remote = this.options.dependencies.createMediaStream([track]);
459
+ const audio = this.options.audioElement;
460
+ audio.srcObject = this.remote;
461
+ this.listen(track, 'ended', () => { if (this.peer === peer && this.phase !== 'retiring')
462
+ this.close('playback'); }, this.peerListeners);
463
+ void this.guard(audio.play(), binding.deadlineAt, this.lifetime.signal).then(() => {
464
+ if (this.peer !== peer || this.phase === 'closed')
465
+ return;
466
+ this.playbackReady = true;
467
+ this.pulse();
468
+ }).catch(() => { if (this.peer === peer)
469
+ this.close('playback'); });
470
+ }
471
+ catch {
472
+ this.stopTrack(track);
473
+ this.close('playback');
474
+ }
475
+ }, this.peerListeners);
476
+ }
477
+ peerLost(peer, binding, source) {
478
+ if (this.peer !== peer || this.phase === 'closed')
479
+ return;
480
+ // Expected transport loss during retirement is not durable provider proof.
481
+ // Preserve continuous capture; the owner must still reconcile the old stream.
482
+ if (this.phase === 'retiring' && this.operation && this.matchesWake(this.operation, binding)) {
483
+ this.options.onMetadata({ type: 'retirement_transport_lost', binding: this.operation, source });
484
+ }
485
+ else
486
+ this.close('rtc');
487
+ }
488
+ closePeer() {
489
+ this.answerAuthorization = null;
490
+ this.startedAuthorization = null;
491
+ const peer = this.peer;
492
+ this.peer = null;
493
+ for (const remove of this.peerListeners.splice(0))
494
+ remove();
495
+ try {
496
+ this.channel?.close();
497
+ }
498
+ catch { /* Continue cleanup. */ }
499
+ this.channel = null;
500
+ try {
501
+ peer?.close();
502
+ }
503
+ catch { /* Continue cleanup. */ }
504
+ try {
505
+ this.options.audioElement.pause();
506
+ }
507
+ catch { /* Continue capture cleanup. */ }
508
+ try {
509
+ this.options.audioElement.srcObject = null;
510
+ }
511
+ catch { /* Continue capture cleanup. */ }
512
+ this.stopStream(this.remote);
513
+ this.remote = null;
514
+ this.playbackReady = false;
515
+ return !peer || peer.connectionState === 'closed';
516
+ }
517
+ workletMessage(raw) {
518
+ if (this.phase === 'closed' || !raw || typeof raw !== 'object' || Array.isArray(raw))
519
+ return;
520
+ const message = raw;
521
+ if (validEpoch(message.captureEpoch) && message.captureEpoch < this.epoch)
522
+ return;
523
+ if (message.captureEpoch !== this.epoch) {
524
+ this.close('protocol');
525
+ return;
526
+ }
527
+ switch (message.type) {
528
+ case 'ready':
529
+ if (message.sampleRate !== this.context?.sampleRate) {
530
+ this.close('protocol');
531
+ return;
532
+ }
533
+ this.workletReady = true;
534
+ break;
535
+ case 'detector_attached':
536
+ this.detectorAttached = true;
537
+ break;
538
+ case 'capture_ready':
539
+ if (!this.modelReady || !this.detectorAttached || !validEpoch(message.sourceStart)) {
540
+ this.close('protocol');
541
+ return;
542
+ }
543
+ this.captureReady = true;
544
+ break;
545
+ case 'wake_buffering':
546
+ if (message.operationId === this.pendingWake?.operationId)
547
+ this.wakeAcknowledged = true;
548
+ break;
549
+ case 'active':
550
+ if (this.phase === 'connecting' && message.operationId === this.operation?.operationId)
551
+ this.activeAcknowledged = true;
552
+ break;
553
+ case 'retirement_buffering':
554
+ if (this.phase === 'retiring' && message.operationId === this.operation?.operationId)
555
+ this.retirementAcknowledged = true;
556
+ break;
557
+ case 'retirement_complete':
558
+ if (this.phase === 'retiring' && this.retirementCompleting && message.operationId === this.operation?.operationId) {
559
+ this.retirementCompleteAcknowledged = true;
560
+ }
561
+ break;
562
+ case 'heartbeat':
563
+ if (validEpoch(message.sourceEnd) && validEpoch(message.bufferedFrames) && typeof message.active === 'boolean') {
564
+ this.options.onMetadata({ type: 'heartbeat', captureEpoch: this.epoch, sourceEnd: message.sourceEnd,
565
+ bufferedFrames: message.bufferedFrames, active: message.active });
566
+ }
567
+ break;
568
+ case 'fault':
569
+ this.close('worklet');
570
+ return;
571
+ default:
572
+ this.close('protocol');
573
+ return;
574
+ }
575
+ this.pulse();
576
+ }
577
+ hasStartedAuthorization() {
578
+ const proof = this.startedAuthorization;
579
+ if (!proof || !this.operation || !this.matches(proof.binding, this.operation))
580
+ return false;
581
+ try {
582
+ if (this.options.dependencies.isPcmActivationAuthorized(this.operation, proof.receipt))
583
+ return true;
584
+ }
585
+ catch { /* Callback failures cannot authorize PCM or escape an event handler. */ }
586
+ this.close('authority');
587
+ return false;
588
+ }
589
+ validNewWake(binding) {
590
+ const now = this.now();
591
+ return validId(binding.operationId) && binding.captureEpoch === this.epoch &&
592
+ Number.isFinite(binding.deadlineAt) && binding.deadlineAt > now && binding.deadlineAt - now <= 6000 &&
593
+ !this.usedOperations.has(binding.operationId) && this.usedOperations.size < 64;
594
+ }
595
+ matches(a, b) {
596
+ return this.matchesWake(a, b) && a.generationId === b.generationId;
597
+ }
598
+ matchesWake(a, b) {
599
+ return a.operationId === b.operationId && a.captureEpoch === b.captureEpoch && a.deadlineAt === b.deadlineAt;
600
+ }
601
+ assertOperation(binding, signal) {
602
+ this.assertHealthy(signal, binding.deadlineAt);
603
+ if (!this.operation || !this.matches(this.operation, binding))
604
+ throw mediaError();
605
+ }
606
+ assertOffer(binding, signal) {
607
+ this.assertHealthy(signal, binding.deadlineAt);
608
+ if (!this.peer || !this.pendingWake || !this.matchesWake(this.pendingWake, binding))
609
+ throw mediaError();
610
+ }
611
+ assertHealthy(signal, deadline) {
612
+ this.assertCurrent(signal, deadline);
613
+ if (!this.options.dependencies.isForeground()) {
614
+ this.close('foreground');
615
+ throw mediaError();
616
+ }
617
+ if (this.context?.state !== 'running') {
618
+ this.close('context');
619
+ throw mediaError();
620
+ }
621
+ if (!this.modelReady || !this.workletReady || !this.detectorAttached || !this.captureReady ||
622
+ !this.microphone?.getAudioTracks().every(track => track.readyState === 'live' && track.enabled && !track.muted) ||
623
+ !this.destination?.stream.getAudioTracks().every(track => track.readyState === 'live' && track.enabled)) {
624
+ this.close('capture');
625
+ throw mediaError();
626
+ }
627
+ }
628
+ assertCurrent(signal, deadline) {
629
+ if (this.phase === 'closed' || signal.aborted || this.lifetime.signal.aborted)
630
+ throw mediaError();
631
+ if (this.now() >= deadline) {
632
+ this.close('timeout');
633
+ throw mediaError();
634
+ }
635
+ }
636
+ now() {
637
+ const now = this.options.dependencies.now();
638
+ if (!Number.isFinite(now) || now < this.lastNow) {
639
+ this.close('clock');
640
+ throw mediaError();
641
+ }
642
+ this.lastNow = now;
643
+ return now;
644
+ }
645
+ waitFor(predicate, deadline, signal) {
646
+ return this.guard(new Promise((resolve, reject) => {
647
+ const check = () => {
648
+ if (this.phase === 'closed') {
649
+ this.checks.delete(check);
650
+ reject(mediaError());
651
+ }
652
+ else if (predicate()) {
653
+ this.checks.delete(check);
654
+ resolve();
655
+ }
656
+ };
657
+ this.checks.add(check);
658
+ check();
659
+ }), deadline, signal);
660
+ }
661
+ guard(pending, deadline, signal, disposeLate) {
662
+ return new Promise((resolve, reject) => {
663
+ let settled = false;
664
+ const finish = (action) => {
665
+ if (settled)
666
+ return;
667
+ settled = true;
668
+ this.options.dependencies.cancel(timer);
669
+ signal.removeEventListener('abort', aborted);
670
+ this.lifetime.signal.removeEventListener('abort', aborted);
671
+ action();
672
+ };
673
+ const aborted = () => finish(() => reject(mediaError()));
674
+ const timer = this.options.dependencies.schedule(() => {
675
+ this.close('timeout');
676
+ finish(() => reject(mediaError()));
677
+ }, Math.max(0, deadline - this.lastNow));
678
+ signal.addEventListener('abort', aborted, { once: true });
679
+ this.lifetime.signal.addEventListener('abort', aborted, { once: true });
680
+ if (signal.aborted || this.lifetime.signal.aborted)
681
+ aborted();
682
+ pending.then(value => {
683
+ if (settled || this.phase === 'closed' || signal.aborted || this.lifetime.signal.aborted) {
684
+ disposeLate?.(value);
685
+ return;
686
+ }
687
+ try {
688
+ this.assertCurrent(signal, deadline);
689
+ finish(() => resolve(value));
690
+ }
691
+ catch {
692
+ disposeLate?.(value);
693
+ finish(() => reject(mediaError()));
694
+ }
695
+ }, () => finish(() => reject(mediaError())));
696
+ });
697
+ }
698
+ armWakeDeadline(deadline) {
699
+ this.clearWakeDeadline();
700
+ const token = this.wakeTimerToken;
701
+ this.wakeTimer = this.options.dependencies.schedule(() => { if (token === this.wakeTimerToken)
702
+ this.close('timeout'); }, deadline - this.lastNow);
703
+ }
704
+ clearWakeDeadline() {
705
+ this.wakeTimerToken++;
706
+ if (this.wakeTimer !== null)
707
+ this.options.dependencies.cancel(this.wakeTimer);
708
+ this.wakeTimer = null;
709
+ }
710
+ pulse() { for (const check of [...this.checks])
711
+ check(); }
712
+ listen(target, type, callback, removals = this.listeners) {
713
+ target.addEventListener(type, callback);
714
+ removals.push(() => target.removeEventListener(type, callback));
715
+ }
716
+ stopTrack(track) {
717
+ if (this.stoppedTracks.has(track))
718
+ return;
719
+ this.stoppedTracks.add(track);
720
+ try {
721
+ track.stop();
722
+ }
723
+ catch { /* Other resource cleanup must continue. */ }
724
+ }
725
+ stopStream(stream) { for (const track of stream?.getTracks() ?? [])
726
+ this.stopTrack(track); }
727
+ closeDetector(detector) {
728
+ if (this.closedDetectors.has(detector))
729
+ return;
730
+ this.closedDetectors.add(detector);
731
+ try {
732
+ detector.close();
733
+ }
734
+ catch { /* Other resource cleanup must continue. */ }
735
+ }
736
+ }