@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.
- package/cjs/AiLiveAssist.d.ts +76 -11
- package/cjs/AiLiveAssist.js +1771 -298
- package/cjs/client.d.ts +19 -0
- package/cjs/client.js +51 -0
- package/cjs/context.d.ts +23 -1
- package/cjs/context.js +713 -126
- package/cjs/control.d.ts +2 -0
- package/cjs/control.js +42 -3
- package/cjs/ctaOffer.d.ts +11 -0
- package/cjs/ctaOffer.js +185 -0
- package/cjs/dialogFocusScope.js +1 -1
- package/cjs/guideAdmission.d.ts +46 -0
- package/cjs/guideAdmission.js +397 -0
- package/cjs/guideHost.d.ts +47 -0
- package/cjs/guideHost.js +48 -0
- package/cjs/guideInstallation.d.ts +12 -0
- package/cjs/guideInstallation.js +60 -0
- package/cjs/guideInstaller.d.ts +4 -0
- package/cjs/guideInstaller.js +116 -0
- package/cjs/guideMount.d.ts +22 -0
- package/cjs/guideMount.js +84 -0
- package/cjs/guideRecording.d.ts +64 -0
- package/cjs/guideRecording.js +176 -0
- package/cjs/guideRecordingSession.d.ts +35 -0
- package/cjs/guideRecordingSession.js +167 -0
- package/cjs/guideSubjectStore.d.ts +32 -0
- package/cjs/guideSubjectStore.js +105 -0
- package/cjs/guideTypes.d.ts +117 -0
- package/cjs/guideTypes.js +15 -0
- package/cjs/index.d.ts +6 -0
- package/cjs/index.js +25 -11
- package/cjs/liveAudioProcessor.d.ts +92 -0
- package/cjs/liveAudioProcessor.js +269 -0
- package/cjs/liveAudioQueue.d.ts +40 -0
- package/cjs/liveAudioQueue.js +130 -0
- package/cjs/liveAudioWorklet.d.ts +1 -0
- package/cjs/liveAudioWorklet.js +63 -0
- package/cjs/liveBrowserDetector.d.ts +16 -0
- package/cjs/liveBrowserDetector.js +75 -0
- package/cjs/liveBrowserDetectorWorker.d.ts +1 -0
- package/cjs/liveBrowserDetectorWorker.js +72 -0
- package/cjs/liveControlChannel.d.ts +176 -0
- package/cjs/liveControlChannel.js +829 -0
- package/cjs/liveDuplexMedia.d.ts +204 -0
- package/cjs/liveDuplexMedia.js +740 -0
- package/cjs/liveGuideAdmission.d.ts +21 -0
- package/cjs/liveGuideAdmission.js +94 -0
- package/cjs/liveGuideWidget.d.ts +68 -0
- package/cjs/liveGuideWidget.js +451 -0
- package/cjs/liveSpeechAssets.d.ts +36 -0
- package/cjs/liveSpeechAssets.js +39 -0
- package/cjs/liveSpeechCaptureBridge.d.ts +32 -0
- package/cjs/liveSpeechCaptureBridge.js +140 -0
- package/cjs/liveSpeechDetector.d.ts +62 -0
- package/cjs/liveSpeechDetector.js +206 -0
- package/cjs/liveSpeechModel.d.ts +46 -0
- package/cjs/liveSpeechModel.js +105 -0
- package/cjs/liveSpeechResampler.d.ts +22 -0
- package/cjs/liveSpeechResampler.js +93 -0
- package/cjs/liveSpeechWorker.d.ts +56 -0
- package/cjs/liveSpeechWorker.js +143 -0
- package/cjs/locales/resources.js +568 -8
- package/cjs/media.d.ts +11 -0
- package/cjs/media.js +78 -9
- package/cjs/messages.js +22 -8
- package/cjs/pageAssistancePreference.d.ts +15 -3
- package/cjs/pageAssistancePreference.js +46 -7
- package/cjs/preview.d.ts +4 -1
- package/cjs/preview.js +42 -1
- package/cjs/recording.d.ts +12 -0
- package/cjs/recording.js +150 -0
- package/cjs/standalone.d.ts +6 -0
- package/cjs/standalone.js +12 -0
- package/cjs/types.d.ts +31 -5
- package/cjs/types.js +14 -0
- package/cjs/ui.d.ts +128 -4
- package/cjs/ui.js +1918 -276
- package/cjs/version.d.ts +1 -1
- package/cjs/version.js +1 -1
- package/cjs/voicePresenceUi.d.ts +52 -4
- package/cjs/voicePresenceUi.js +659 -57
- package/lib/AiLiveAssist.d.ts +76 -11
- package/lib/AiLiveAssist.js +1772 -299
- package/lib/client.d.ts +19 -0
- package/lib/client.js +51 -0
- package/lib/context.d.ts +23 -1
- package/lib/context.js +713 -126
- package/lib/control.d.ts +2 -0
- package/lib/control.js +42 -3
- package/lib/ctaOffer.d.ts +11 -0
- package/lib/ctaOffer.js +179 -0
- package/lib/dialogFocusScope.js +1 -1
- package/lib/guideAdmission.d.ts +46 -0
- package/lib/guideAdmission.js +392 -0
- package/lib/guideHost.d.ts +47 -0
- package/lib/guideHost.js +42 -0
- package/lib/guideInstallation.d.ts +12 -0
- package/lib/guideInstallation.js +56 -0
- package/lib/guideInstaller.d.ts +4 -0
- package/lib/guideInstaller.js +113 -0
- package/lib/guideMount.d.ts +22 -0
- package/lib/guideMount.js +77 -0
- package/lib/guideRecording.d.ts +64 -0
- package/lib/guideRecording.js +172 -0
- package/lib/guideRecordingSession.d.ts +35 -0
- package/lib/guideRecordingSession.js +163 -0
- package/lib/guideSubjectStore.d.ts +32 -0
- package/lib/guideSubjectStore.js +101 -0
- package/lib/guideTypes.d.ts +117 -0
- package/lib/guideTypes.js +11 -0
- package/lib/index.d.ts +6 -0
- package/lib/index.js +21 -10
- package/lib/liveAudioProcessor.d.ts +92 -0
- package/lib/liveAudioProcessor.js +265 -0
- package/lib/liveAudioQueue.d.ts +40 -0
- package/lib/liveAudioQueue.js +126 -0
- package/lib/liveAudioWorklet.d.ts +1 -0
- package/lib/liveAudioWorklet.js +61 -0
- package/lib/liveBrowserDetector.d.ts +16 -0
- package/lib/liveBrowserDetector.js +71 -0
- package/lib/liveBrowserDetectorWorker.d.ts +1 -0
- package/lib/liveBrowserDetectorWorker.js +70 -0
- package/lib/liveControlChannel.d.ts +176 -0
- package/lib/liveControlChannel.js +825 -0
- package/lib/liveDuplexMedia.d.ts +204 -0
- package/lib/liveDuplexMedia.js +736 -0
- package/lib/liveGuideAdmission.d.ts +21 -0
- package/lib/liveGuideAdmission.js +90 -0
- package/lib/liveGuideWidget.d.ts +68 -0
- package/lib/liveGuideWidget.js +447 -0
- package/lib/liveSpeechAssets.d.ts +36 -0
- package/lib/liveSpeechAssets.js +35 -0
- package/lib/liveSpeechCaptureBridge.d.ts +32 -0
- package/lib/liveSpeechCaptureBridge.js +136 -0
- package/lib/liveSpeechDetector.d.ts +62 -0
- package/lib/liveSpeechDetector.js +202 -0
- package/lib/liveSpeechModel.d.ts +46 -0
- package/lib/liveSpeechModel.js +101 -0
- package/lib/liveSpeechResampler.d.ts +22 -0
- package/lib/liveSpeechResampler.js +89 -0
- package/lib/liveSpeechWorker.d.ts +56 -0
- package/lib/liveSpeechWorker.js +137 -0
- package/lib/locales/resources.js +568 -8
- package/lib/media.d.ts +11 -0
- package/lib/media.js +77 -8
- package/lib/messages.js +22 -8
- package/lib/pageAssistancePreference.d.ts +15 -3
- package/lib/pageAssistancePreference.js +46 -7
- package/lib/preview.d.ts +4 -1
- package/lib/preview.js +42 -1
- package/lib/recording.d.ts +12 -0
- package/lib/recording.js +146 -0
- package/lib/standalone.d.ts +6 -0
- package/lib/standalone.js +6 -0
- package/lib/types.d.ts +31 -5
- package/lib/types.js +14 -0
- package/lib/ui.d.ts +128 -4
- package/lib/ui.js +1919 -277
- package/lib/version.d.ts +1 -1
- package/lib/version.js +1 -1
- package/lib/voicePresenceUi.d.ts +52 -4
- package/lib/voicePresenceUi.js +659 -57
- package/package.json +16 -1
|
@@ -0,0 +1,825 @@
|
|
|
1
|
+
import { LiveDuplexMedia } from './liveDuplexMedia.js';
|
|
2
|
+
import { VERSION } from './version.js';
|
|
3
|
+
export const LIVE_CONTROL_CLIENT_VERSION = VERSION;
|
|
4
|
+
export const LIVE_CONTROL_CLIENT_CAPABILITIES = ['live_duplex_v1', 'live_local_wake_v1', 'live_fragment_captions_v1'];
|
|
5
|
+
const protocol = 'oxvo-ai-live-assist-v2';
|
|
6
|
+
const path = '/ai-live-assist/v2/live/control';
|
|
7
|
+
const phases = ['voice_off', 'local_listening', 'wake_buffering', 'starting', 'active', 'tentative_idle', 'closing',
|
|
8
|
+
'uncertain', 'muted', 'suspended', 'budget_blocked', 'ended'];
|
|
9
|
+
const unavailable = () => new Error('The AI Guide voice connection is unavailable.');
|
|
10
|
+
const uuid = (value) => typeof value === 'string' && /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value);
|
|
11
|
+
const count = (value) => typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;
|
|
12
|
+
const object = (value, keys) => {
|
|
13
|
+
if (!value || typeof value !== 'object' || Array.isArray(value))
|
|
14
|
+
throw unavailable();
|
|
15
|
+
const result = value;
|
|
16
|
+
const actual = Object.keys(result);
|
|
17
|
+
if (actual.length !== keys.length || actual.some(key => !keys.includes(key)))
|
|
18
|
+
throw unavailable();
|
|
19
|
+
return result;
|
|
20
|
+
};
|
|
21
|
+
const timestamp = (value) => {
|
|
22
|
+
if (typeof value !== 'string' || value.length > 40 || !/^\d{4}-\d\d-\d\dT/.test(value))
|
|
23
|
+
throw unavailable();
|
|
24
|
+
const result = Date.parse(value);
|
|
25
|
+
if (!Number.isFinite(result))
|
|
26
|
+
throw unavailable();
|
|
27
|
+
return result;
|
|
28
|
+
};
|
|
29
|
+
const sdp = (value) => typeof value === 'string' && value.length <= 24576 && value.startsWith('v=0') && !value.includes('\0');
|
|
30
|
+
const bindingFields = ['generationId', 'operationId', 'captureEpoch'];
|
|
31
|
+
const sameBinding = (a, b) => a.generationId === b.generationId && a.operationId === b.operationId &&
|
|
32
|
+
a.captureEpoch === b.captureEpoch && a.deadlineAt === b.deadlineAt;
|
|
33
|
+
const defaultClock = { now: () => performance.now(), wallNow: () => Date.now(),
|
|
34
|
+
schedule: (callback, ms) => setTimeout(callback, ms), cancel: timer => clearTimeout(timer) };
|
|
35
|
+
/** Dedicated Live voice bridge. It performs no HTTP/provider/financial calls,
|
|
36
|
+
* reconnect, session reconstruction, feature enablement or speech inference.
|
|
37
|
+
* Caller-provided capture reports must come from actual current detector/media
|
|
38
|
+
* observations; this class never invents a heartbeat or speech result. */
|
|
39
|
+
export class LiveControlChannel {
|
|
40
|
+
constructor(options) {
|
|
41
|
+
this.lifetime = new AbortController();
|
|
42
|
+
this.proofs = new WeakMap();
|
|
43
|
+
this.hardFencedMedia = new WeakSet();
|
|
44
|
+
this.outbound = new Map();
|
|
45
|
+
this.usedOperations = new Set();
|
|
46
|
+
this.barriers = new Set();
|
|
47
|
+
this.pendingCommands = [];
|
|
48
|
+
this.cleanups = new Set();
|
|
49
|
+
this.socket = null;
|
|
50
|
+
this.media = null;
|
|
51
|
+
this.attempt = null;
|
|
52
|
+
this.pendingWake = null;
|
|
53
|
+
this.ready = null;
|
|
54
|
+
this.connectResolve = null;
|
|
55
|
+
this.connectReject = null;
|
|
56
|
+
this.detachExternal = null;
|
|
57
|
+
this.connectedOnce = false;
|
|
58
|
+
this.closed = false;
|
|
59
|
+
this.sequence = 0;
|
|
60
|
+
this.serverSequence = 0;
|
|
61
|
+
this.serverEpoch = 0;
|
|
62
|
+
this.commandEpoch = 0;
|
|
63
|
+
this.captureEpoch = 0;
|
|
64
|
+
this.requiresGesture = true;
|
|
65
|
+
this.voicePrepared = false;
|
|
66
|
+
const { authorization: authorizationInput, trustedRuntimeOrigin, ...localOptions } = options;
|
|
67
|
+
this.options = { ...localOptions, media: { ...options.media, dependencies: { ...options.media.dependencies } } };
|
|
68
|
+
this.clock = options.clock ?? defaultClock;
|
|
69
|
+
const value = object(authorizationInput, ['schemaVersion', 'protocolVersion', 'providerProtocol', 'status', 'projectId',
|
|
70
|
+
'guideId', 'subjectId', 'sessionId', 'launchRequestId', 'controlCredential', 'controlUrl', 'controlExpiresAt', 'logicalDeadlineAt']);
|
|
71
|
+
if (value.schemaVersion !== 3 || value.protocolVersion !== 2 || value.providerProtocol !== 'live' || value.status !== 'control_authorized' ||
|
|
72
|
+
!count(value.projectId) || value.projectId < 1 || !['guideId', 'subjectId', 'sessionId', 'launchRequestId'].every(key => uuid(value[key])) ||
|
|
73
|
+
typeof value.controlCredential !== 'string' || !/^[A-Za-z0-9_-]{32,256}$/.test(value.controlCredential) ||
|
|
74
|
+
!/^[A-Za-z0-9_.:/-]{1,128}$/.test(options.tabId) || typeof options.onState !== 'function' || typeof options.onClose !== 'function' ||
|
|
75
|
+
typeof options.media.dependencies.isPlaybackDrained !== 'function')
|
|
76
|
+
throw unavailable();
|
|
77
|
+
const trusted = new URL(trustedRuntimeOrigin);
|
|
78
|
+
const target = new URL(String(value.controlUrl));
|
|
79
|
+
if (!['https:', 'http:'].includes(trusted.protocol) || trusted.origin !== options.trustedRuntimeOrigin ||
|
|
80
|
+
trusted.username || trusted.password || target.username || target.password || target.search || target.hash || target.pathname !== path ||
|
|
81
|
+
target.protocol !== (trusted.protocol === 'https:' ? 'wss:' : 'ws:') || target.host !== trusted.host ||
|
|
82
|
+
(trusted.protocol === 'http:' && !['localhost', '127.0.0.1', '[::1]'].includes(trusted.hostname)))
|
|
83
|
+
throw unavailable();
|
|
84
|
+
target.searchParams.set('session', String(value.sessionId));
|
|
85
|
+
this.url = target.href;
|
|
86
|
+
const { controlCredential, ...authorization } = structuredClone(options.authorization);
|
|
87
|
+
this.credential = controlCredential;
|
|
88
|
+
this.authorization = Object.freeze(authorization);
|
|
89
|
+
this.originalMono = this.clock.now();
|
|
90
|
+
this.lastNow = this.originalMono;
|
|
91
|
+
this.originalWall = this.clock.wallNow();
|
|
92
|
+
this.deadline = this.originalMono + Math.min(timestamp(value.controlExpiresAt), timestamp(value.logicalDeadlineAt)) - this.originalWall;
|
|
93
|
+
if (!Number.isFinite(this.originalWall) || !Number.isFinite(this.originalMono) || this.originalMono < 0 ||
|
|
94
|
+
this.deadline <= this.originalMono || this.deadline - this.originalMono > 3600000)
|
|
95
|
+
throw unavailable();
|
|
96
|
+
}
|
|
97
|
+
connect(signal) {
|
|
98
|
+
if (this.connectedOnce || this.closed || signal.aborted || !this.credential)
|
|
99
|
+
return Promise.reject(unavailable());
|
|
100
|
+
this.connectedOnce = true;
|
|
101
|
+
return new Promise((resolve, reject) => {
|
|
102
|
+
this.connectResolve = resolve;
|
|
103
|
+
this.connectReject = reject;
|
|
104
|
+
const abort = () => this.close('aborted');
|
|
105
|
+
signal.addEventListener('abort', abort, { once: true });
|
|
106
|
+
this.detachExternal = () => signal.removeEventListener('abort', abort);
|
|
107
|
+
try {
|
|
108
|
+
this.now();
|
|
109
|
+
const socket = (this.options.createWebSocket ?? ((url, protocols) => new WebSocket(url, protocols)))(this.url, [protocol, `oxvo-auth.${this.credential}`]);
|
|
110
|
+
this.credential = null;
|
|
111
|
+
this.socket = socket;
|
|
112
|
+
this.connectionTimer = this.clock.schedule(() => this.close('timeout'), 5000);
|
|
113
|
+
this.armExpiry();
|
|
114
|
+
socket.addEventListener('open', () => {
|
|
115
|
+
if (this.closed)
|
|
116
|
+
return;
|
|
117
|
+
if (socket.protocol !== protocol) {
|
|
118
|
+
this.close('protocol');
|
|
119
|
+
return;
|
|
120
|
+
}
|
|
121
|
+
this.write('hello', { clientVersion: LIVE_CONTROL_CLIENT_VERSION, liveCapabilities: [...LIVE_CONTROL_CLIENT_CAPABILITIES] }, true);
|
|
122
|
+
});
|
|
123
|
+
socket.addEventListener('message', event => this.receive(event.data));
|
|
124
|
+
socket.addEventListener('error', () => this.close('transport'));
|
|
125
|
+
socket.addEventListener('close', () => this.close('transport'));
|
|
126
|
+
}
|
|
127
|
+
catch {
|
|
128
|
+
this.close('transport');
|
|
129
|
+
}
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
/** Call directly in the visitor's gesture; no microphone is acquired by connect. */
|
|
133
|
+
async prepareVoice(input) {
|
|
134
|
+
this.assertReady();
|
|
135
|
+
if (this.barriers.size || input.captureEpoch !== this.captureEpoch || !uuid(input.operationId) || input.signal.aborted ||
|
|
136
|
+
(this.media && this.media.status !== 'closed') || this.attempt || this.pendingWake)
|
|
137
|
+
throw unavailable();
|
|
138
|
+
const epoch = this.commandEpoch;
|
|
139
|
+
this.voicePrepared = false;
|
|
140
|
+
const media = new LiveDuplexMedia({ ...this.options.media, dependencies: { ...this.options.media.dependencies,
|
|
141
|
+
isAnswerAuthorized: (binding, answer, proof) => this.authorized('answer', binding, proof, answer),
|
|
142
|
+
isPcmActivationAuthorized: (binding, proof) => this.authorized('started', binding, proof),
|
|
143
|
+
isTerminalAuthorized: (binding, proof) => this.authorized('terminal', binding, proof) },
|
|
144
|
+
onMetadata: metadata => this.metadata(media, metadata), onFailSafeClose: () => this.mediaClosed(media) });
|
|
145
|
+
this.media = media;
|
|
146
|
+
try {
|
|
147
|
+
await media.prepare({ captureEpoch: input.captureEpoch, signal: input.signal });
|
|
148
|
+
}
|
|
149
|
+
catch {
|
|
150
|
+
// A rejected gesture has acquired no resources and sent no voice command.
|
|
151
|
+
// Release that unused owner without forcing a new server capture epoch.
|
|
152
|
+
if (media.status === 'new')
|
|
153
|
+
this.hardFencedMedia.add(media);
|
|
154
|
+
media.close('aborted');
|
|
155
|
+
throw unavailable();
|
|
156
|
+
}
|
|
157
|
+
if (this.closed || epoch !== this.commandEpoch || input.signal.aborted) {
|
|
158
|
+
media.close('aborted');
|
|
159
|
+
throw unavailable();
|
|
160
|
+
}
|
|
161
|
+
this.requiresGesture = false;
|
|
162
|
+
if (input.requestInitialGreeting)
|
|
163
|
+
this.beginWake(input.operationId, input.captureEpoch);
|
|
164
|
+
this.command('voice.ready', { operationId: input.operationId, captureEpoch: input.captureEpoch,
|
|
165
|
+
requestInitialGreeting: input.requestInitialGreeting, playbackAuthorized: input.playbackAuthorized });
|
|
166
|
+
}
|
|
167
|
+
reportCapture(input) {
|
|
168
|
+
if (this.requiresGesture || this.media?.status === 'closed')
|
|
169
|
+
return;
|
|
170
|
+
if (input.captureEpoch !== this.captureEpoch || !count(input.sequence) || typeof input.speaking !== 'boolean' || typeof input.playing !== 'boolean')
|
|
171
|
+
throw unavailable();
|
|
172
|
+
this.command('voice.capture', { captureEpoch: input.captureEpoch, captureSequence: input.sequence, speaking: input.speaking, playing: input.playing });
|
|
173
|
+
}
|
|
174
|
+
wake(input) {
|
|
175
|
+
this.assertReady();
|
|
176
|
+
if (this.barriers.size || this.requiresGesture || !['speech', 'spoken_response'].includes(input.reason) ||
|
|
177
|
+
!Number.isFinite(input.bufferedMs) || input.bufferedMs < 0 || input.bufferedMs > 8000)
|
|
178
|
+
throw unavailable();
|
|
179
|
+
this.beginWake(input.operationId, input.captureEpoch);
|
|
180
|
+
this.command('voice.wake', { ...input });
|
|
181
|
+
}
|
|
182
|
+
submitText(input) {
|
|
183
|
+
if (!uuid(input.inputId) || !count(input.inputEpoch) || typeof input.text !== 'string' ||
|
|
184
|
+
input.text.length < 1 || input.text.length > 4000 || !input.text.trim())
|
|
185
|
+
throw unavailable();
|
|
186
|
+
this.command('text.submit', { ...input });
|
|
187
|
+
}
|
|
188
|
+
stop() {
|
|
189
|
+
if (this.closed || !this.ready)
|
|
190
|
+
return;
|
|
191
|
+
this.suppressPlayback();
|
|
192
|
+
if ([...this.outbound.values()].some(item => !item.settled && item.type === 'stop'))
|
|
193
|
+
return;
|
|
194
|
+
this.priority('stop', {});
|
|
195
|
+
const current = this.attempt;
|
|
196
|
+
const pending = this.pendingWake;
|
|
197
|
+
if (pending && pending !== current)
|
|
198
|
+
this.stopAttempt(pending);
|
|
199
|
+
if (current)
|
|
200
|
+
this.stopAttempt(current);
|
|
201
|
+
if (!current && !pending && this.media && this.media.status !== 'closed' && !this.voicePrepared)
|
|
202
|
+
this.fence('pause');
|
|
203
|
+
}
|
|
204
|
+
fence(reason) {
|
|
205
|
+
if (this.closed || !this.ready)
|
|
206
|
+
return;
|
|
207
|
+
if (!['mute', 'pause', 'hidden', 'permission_lost', 'audio_suspended', 'mode_change'].includes(reason))
|
|
208
|
+
throw unavailable();
|
|
209
|
+
this.suppressPlayback();
|
|
210
|
+
this.requiresGesture = true;
|
|
211
|
+
this.priority('voice.fence', { reason });
|
|
212
|
+
if (this.media)
|
|
213
|
+
this.hardFencedMedia.add(this.media);
|
|
214
|
+
for (const attempt of this.attempts()) {
|
|
215
|
+
attempt.stopped = true;
|
|
216
|
+
attempt.abort.abort();
|
|
217
|
+
}
|
|
218
|
+
this.media?.close(reason === 'mute' ? 'muted' : 'aborted');
|
|
219
|
+
}
|
|
220
|
+
end() {
|
|
221
|
+
if (this.closed)
|
|
222
|
+
return;
|
|
223
|
+
if (this.ready)
|
|
224
|
+
this.priority('end', {});
|
|
225
|
+
this.close('ended');
|
|
226
|
+
}
|
|
227
|
+
now() {
|
|
228
|
+
const now = this.clock.now();
|
|
229
|
+
if (!Number.isFinite(now) || now < this.lastNow || now >= this.deadline || this.closed)
|
|
230
|
+
throw unavailable();
|
|
231
|
+
this.lastNow = now;
|
|
232
|
+
return now;
|
|
233
|
+
}
|
|
234
|
+
assertReady() { this.now(); if (!this.ready || this.socket?.readyState !== 1)
|
|
235
|
+
throw unavailable(); }
|
|
236
|
+
armExpiry() {
|
|
237
|
+
this.clock.cancel(this.expiryTimer);
|
|
238
|
+
this.expiryTimer = this.clock.schedule(() => this.close('expired'), Math.max(0, this.deadline - this.clock.now()));
|
|
239
|
+
}
|
|
240
|
+
command(type, payload) {
|
|
241
|
+
this.assertReady();
|
|
242
|
+
if (this.barriers.size) {
|
|
243
|
+
if (type === 'voice.capture')
|
|
244
|
+
this.pendingCommands = this.pendingCommands.filter(value => value.type !== type);
|
|
245
|
+
if (this.pendingCommands.length >= 8) {
|
|
246
|
+
this.close('protocol');
|
|
247
|
+
return;
|
|
248
|
+
}
|
|
249
|
+
this.pendingCommands.push({ type, payload: structuredClone(payload), at: this.now() });
|
|
250
|
+
return;
|
|
251
|
+
}
|
|
252
|
+
this.write(type, payload);
|
|
253
|
+
}
|
|
254
|
+
priority(type, payload) {
|
|
255
|
+
this.pendingCommands = [];
|
|
256
|
+
if (this.barriers.size >= 4) {
|
|
257
|
+
this.close('protocol');
|
|
258
|
+
return;
|
|
259
|
+
}
|
|
260
|
+
if (this.write(type, payload, false, this.commandEpoch + 1)) {
|
|
261
|
+
// The gateway drops earlier queued work on interruption without promising
|
|
262
|
+
// an ACK for every abandoned command. The new barrier's own timer bounds
|
|
263
|
+
// the cut; old command timers must not later kill the retained session.
|
|
264
|
+
for (const item of this.outbound.values()) {
|
|
265
|
+
if (item.barrier === null && !item.settled && item.epoch <= this.commandEpoch) {
|
|
266
|
+
item.settled = true;
|
|
267
|
+
this.clock.cancel(item.timer);
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
this.commandEpoch++;
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
write(type, payload, hello = false, barrier = null) {
|
|
274
|
+
try {
|
|
275
|
+
this.now();
|
|
276
|
+
const socket = this.socket;
|
|
277
|
+
if (!socket || socket.readyState !== 1 || (!hello && !this.ready))
|
|
278
|
+
throw unavailable();
|
|
279
|
+
if ([...this.outbound.values()].filter(item => !item.settled).length >= 32)
|
|
280
|
+
throw unavailable();
|
|
281
|
+
const id = (this.options.randomUUID ?? (() => crypto.randomUUID()))();
|
|
282
|
+
if (!uuid(id) || this.outbound.has(id))
|
|
283
|
+
throw unavailable();
|
|
284
|
+
const frame = { v: 2, providerProtocol: 'live', id, sessionId: this.authorization.sessionId, tabId: this.options.tabId,
|
|
285
|
+
sequence: ++this.sequence, commandEpoch: this.commandEpoch,
|
|
286
|
+
...(hello ? {} : { fencingToken: this.ready?.fencingToken, authorityGeneration: this.ready?.authorityGeneration }), type, payload };
|
|
287
|
+
const encoded = JSON.stringify(frame);
|
|
288
|
+
const bytes = new TextEncoder().encode(encoded).byteLength;
|
|
289
|
+
if (bytes > 32768 || socket.bufferedAmount + bytes > 131072)
|
|
290
|
+
throw unavailable();
|
|
291
|
+
if (!hello) {
|
|
292
|
+
const item = { id, type, epoch: this.commandEpoch, barrier, settled: false,
|
|
293
|
+
timer: this.clock.schedule(() => this.close('timeout'), 2000) };
|
|
294
|
+
this.outbound.set(id, item);
|
|
295
|
+
if (barrier !== null)
|
|
296
|
+
this.barriers.add(id);
|
|
297
|
+
if (this.outbound.size > 128) {
|
|
298
|
+
const oldest = [...this.outbound.values()].find(value => value.settled);
|
|
299
|
+
if (oldest)
|
|
300
|
+
this.outbound.delete(oldest.id);
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
socket.send(encoded);
|
|
304
|
+
return true;
|
|
305
|
+
}
|
|
306
|
+
catch {
|
|
307
|
+
this.close('transport');
|
|
308
|
+
return false;
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
receive(data) {
|
|
312
|
+
if (this.closed)
|
|
313
|
+
return;
|
|
314
|
+
try {
|
|
315
|
+
this.now();
|
|
316
|
+
if (typeof data !== 'string' || new TextEncoder().encode(data).byteLength > 32768)
|
|
317
|
+
throw unavailable();
|
|
318
|
+
// Server frames have exactly two object levels and no arrays. Reject
|
|
319
|
+
// duplicate keys (including escaped aliases) before JSON.parse folds them.
|
|
320
|
+
const stack = [];
|
|
321
|
+
const tokens = /"(?:\\.|[^"\\])*"|[{}]|\[|\]/g;
|
|
322
|
+
for (const match of data.matchAll(tokens)) {
|
|
323
|
+
if (match[0] === '{') {
|
|
324
|
+
stack.push(new Set());
|
|
325
|
+
if (stack.length > 2)
|
|
326
|
+
throw unavailable();
|
|
327
|
+
}
|
|
328
|
+
else if (match[0] === '}')
|
|
329
|
+
stack.pop();
|
|
330
|
+
else if (match[0] === '[' || match[0] === ']')
|
|
331
|
+
throw unavailable();
|
|
332
|
+
else if (data.slice((match.index ?? 0) + match[0].length).trimStart().startsWith(':')) {
|
|
333
|
+
const key = JSON.parse(match[0]);
|
|
334
|
+
const keys = stack.at(-1);
|
|
335
|
+
if (!keys || keys.has(key))
|
|
336
|
+
throw unavailable();
|
|
337
|
+
keys.add(key);
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
const value = object(JSON.parse(data), ['v', 'providerProtocol', 'sessionId', 'sequence', 'commandEpoch', 'type', 'payload']);
|
|
341
|
+
if (value.v !== 2 || value.providerProtocol !== 'live' || value.sessionId !== this.authorization.sessionId ||
|
|
342
|
+
!count(value.sequence) || value.sequence !== this.serverSequence + 1 || !count(value.commandEpoch) ||
|
|
343
|
+
value.commandEpoch < this.serverEpoch || value.commandEpoch > this.commandEpoch || typeof value.type !== 'string')
|
|
344
|
+
throw unavailable();
|
|
345
|
+
this.serverSequence = value.sequence;
|
|
346
|
+
this.serverEpoch = value.commandEpoch;
|
|
347
|
+
const message = value;
|
|
348
|
+
if (!['ready', 'ack', 'state', 'wake.buffer', 'rtc.answer', 'media.activate', 'media.retire', 'media.terminal',
|
|
349
|
+
'playback.suppress', 'capture.stop', 'wake.discard', 'wake.release', 'repeat_after_ready', 'text.answer', 'transcript.delta', 'task.state'].includes(message.type))
|
|
350
|
+
throw unavailable();
|
|
351
|
+
if (message.type === 'ready') {
|
|
352
|
+
this.acceptReady(message);
|
|
353
|
+
return;
|
|
354
|
+
}
|
|
355
|
+
if (!this.ready)
|
|
356
|
+
throw unavailable();
|
|
357
|
+
const cleanup = ['ack', 'media.retire', 'media.terminal', 'playback.suppress', 'capture.stop'].includes(message.type);
|
|
358
|
+
if (message.commandEpoch < this.commandEpoch && !cleanup)
|
|
359
|
+
return;
|
|
360
|
+
this.handle(message);
|
|
361
|
+
}
|
|
362
|
+
catch {
|
|
363
|
+
this.close('protocol');
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
acceptReady(message) {
|
|
367
|
+
const p = object(message.payload, ['fencingToken', 'authorityGeneration', 'commandEpoch', 'credentialExpiresAt', 'logicalDeadlineAt']);
|
|
368
|
+
if (this.ready || message.sequence !== 1 || message.commandEpoch !== 0 || p.commandEpoch !== 0 ||
|
|
369
|
+
!count(p.fencingToken) || p.fencingToken < 1 || !count(p.authorityGeneration) ||
|
|
370
|
+
timestamp(p.credentialExpiresAt) !== timestamp(this.authorization.controlExpiresAt) ||
|
|
371
|
+
timestamp(p.logicalDeadlineAt) > timestamp(this.authorization.logicalDeadlineAt))
|
|
372
|
+
throw unavailable();
|
|
373
|
+
this.deadline = Math.min(this.deadline, this.originalMono + timestamp(p.logicalDeadlineAt) - this.originalWall);
|
|
374
|
+
this.now();
|
|
375
|
+
this.armExpiry();
|
|
376
|
+
this.clock.cancel(this.connectionTimer);
|
|
377
|
+
this.ready = Object.freeze({ ...p });
|
|
378
|
+
this.connectResolve?.(this.ready);
|
|
379
|
+
this.connectResolve = null;
|
|
380
|
+
this.connectReject = null;
|
|
381
|
+
}
|
|
382
|
+
handle(message) {
|
|
383
|
+
const p = message.payload;
|
|
384
|
+
switch (message.type) {
|
|
385
|
+
case 'ack': {
|
|
386
|
+
object(p, ['commandId', 'status']);
|
|
387
|
+
if (!uuid(p.commandId) || !['queued', 'accepted', 'interrupted'].includes(String(p.status)))
|
|
388
|
+
throw unavailable();
|
|
389
|
+
const item = this.outbound.get(p.commandId);
|
|
390
|
+
if (!item)
|
|
391
|
+
throw unavailable();
|
|
392
|
+
if (p.status === 'queued')
|
|
393
|
+
return;
|
|
394
|
+
if (item.barrier !== null && (p.status !== 'accepted' || message.commandEpoch !== item.barrier))
|
|
395
|
+
throw unavailable();
|
|
396
|
+
item.settled = true;
|
|
397
|
+
this.clock.cancel(item.timer);
|
|
398
|
+
this.barriers.delete(item.id);
|
|
399
|
+
if (item.type === 'voice.ready' && p.status === 'accepted' && item.epoch === this.commandEpoch)
|
|
400
|
+
this.voicePrepared = true;
|
|
401
|
+
if (!this.barriers.size) {
|
|
402
|
+
for (const queued of this.pendingCommands.splice(0)) {
|
|
403
|
+
if (queued.type !== 'voice.capture' || this.now() - queued.at < 1000)
|
|
404
|
+
this.write(queued.type, queued.payload);
|
|
405
|
+
}
|
|
406
|
+
if (this.attempt)
|
|
407
|
+
this.offer(this.attempt);
|
|
408
|
+
}
|
|
409
|
+
break;
|
|
410
|
+
}
|
|
411
|
+
case 'state': {
|
|
412
|
+
object(p, ['phase', 'captureEpoch']);
|
|
413
|
+
if (!phases.includes(p.phase) || !count(p.captureEpoch) || p.captureEpoch < this.captureEpoch)
|
|
414
|
+
throw unavailable();
|
|
415
|
+
this.captureEpoch = p.captureEpoch;
|
|
416
|
+
this.options.onState({ phase: p.phase, captureEpoch: p.captureEpoch, requiresUserGesture: this.requiresGesture });
|
|
417
|
+
break;
|
|
418
|
+
}
|
|
419
|
+
case 'wake.buffer': {
|
|
420
|
+
object(p, ['operationId', 'captureEpoch', 'capacityMs', 'remainingMs']);
|
|
421
|
+
const attempt = this.findWake(p);
|
|
422
|
+
if (attempt.stopped || attempt.serverWake || typeof p.capacityMs !== 'number' || p.capacityMs !== 8000 ||
|
|
423
|
+
typeof p.remainingMs !== 'number' || !Number.isFinite(p.remainingMs) || p.remainingMs <= 0 || p.remainingMs > 6000)
|
|
424
|
+
throw unavailable();
|
|
425
|
+
attempt.serverWake = true;
|
|
426
|
+
attempt.cutoff = Math.min(attempt.cutoff, this.now() + p.remainingMs);
|
|
427
|
+
this.armAttempt(attempt);
|
|
428
|
+
this.offer(attempt);
|
|
429
|
+
break;
|
|
430
|
+
}
|
|
431
|
+
case 'rtc.answer': {
|
|
432
|
+
object(p, [...bindingFields, 'answerSdp']);
|
|
433
|
+
const attempt = this.findWake(p);
|
|
434
|
+
if (!uuid(p.generationId) || !sdp(p.answerSdp))
|
|
435
|
+
throw unavailable();
|
|
436
|
+
if (attempt.stopped)
|
|
437
|
+
return;
|
|
438
|
+
if (!attempt.offered || attempt.generationId)
|
|
439
|
+
throw unavailable();
|
|
440
|
+
attempt.generationId = p.generationId;
|
|
441
|
+
const binding = this.binding(attempt);
|
|
442
|
+
attempt.answer = this.proof('answer', attempt, binding, p.answerSdp);
|
|
443
|
+
// Never await answer readiness on the ingress path: media.activate must
|
|
444
|
+
// be handled while this promise waits for persisted-start permission.
|
|
445
|
+
void attempt.media.acceptVerifiedAnswer({ binding, answerSdp: p.answerSdp, preparedReceipt: attempt.answer }, attempt.abort.signal)
|
|
446
|
+
.catch(() => { if (!attempt.stopped && !this.closed)
|
|
447
|
+
this.failAttempt(attempt); });
|
|
448
|
+
break;
|
|
449
|
+
}
|
|
450
|
+
case 'media.activate': {
|
|
451
|
+
object(p, [...bindingFields, 'receiptId']);
|
|
452
|
+
const wake = this.findWake(p);
|
|
453
|
+
if (!uuid(p.receiptId) || !uuid(p.generationId))
|
|
454
|
+
throw unavailable();
|
|
455
|
+
if (wake.stopped)
|
|
456
|
+
return;
|
|
457
|
+
const attempt = this.findGeneration(p);
|
|
458
|
+
if (attempt.started)
|
|
459
|
+
throw unavailable();
|
|
460
|
+
const binding = this.binding(attempt);
|
|
461
|
+
attempt.started = this.proof('started', attempt, binding);
|
|
462
|
+
if (!attempt.media.observeStartedAuthorization({ binding, startedReceipt: attempt.started }))
|
|
463
|
+
throw unavailable();
|
|
464
|
+
break;
|
|
465
|
+
}
|
|
466
|
+
case 'media.retire': {
|
|
467
|
+
object(p, [...bindingFields, 'receiptId']);
|
|
468
|
+
const attempt = this.findGeneration(p, true);
|
|
469
|
+
if (!uuid(p.receiptId))
|
|
470
|
+
throw unavailable();
|
|
471
|
+
attempt.stopped = true;
|
|
472
|
+
this.retire(attempt);
|
|
473
|
+
break;
|
|
474
|
+
}
|
|
475
|
+
case 'media.terminal': {
|
|
476
|
+
object(p, [...bindingFields, 'receiptId']);
|
|
477
|
+
const attempt = this.findGeneration(p, true);
|
|
478
|
+
if (!uuid(p.receiptId) || attempt.terminal)
|
|
479
|
+
throw unavailable();
|
|
480
|
+
attempt.stopped = true;
|
|
481
|
+
attempt.terminal = this.proof('terminal', attempt, this.binding(attempt));
|
|
482
|
+
this.retire(attempt);
|
|
483
|
+
this.finishRetirement(attempt);
|
|
484
|
+
break;
|
|
485
|
+
}
|
|
486
|
+
case 'playback.suppress':
|
|
487
|
+
object(p, []);
|
|
488
|
+
this.suppressPlayback();
|
|
489
|
+
break;
|
|
490
|
+
case 'capture.stop':
|
|
491
|
+
object(p, ['captureEpoch']);
|
|
492
|
+
if (!count(p.captureEpoch))
|
|
493
|
+
throw unavailable();
|
|
494
|
+
if (p.captureEpoch === this.captureEpoch) {
|
|
495
|
+
this.requiresGesture = true;
|
|
496
|
+
this.media?.close('aborted');
|
|
497
|
+
}
|
|
498
|
+
break;
|
|
499
|
+
case 'wake.discard': {
|
|
500
|
+
object(p, ['operationId', 'reason']);
|
|
501
|
+
if (!uuid(p.operationId) || !['stop', 'expired', 'capacity', 'authority'].includes(String(p.reason)))
|
|
502
|
+
throw unavailable();
|
|
503
|
+
const attempt = [...this.attempts()].find(value => value.operationId === p.operationId);
|
|
504
|
+
if (attempt && !attempt.readySent)
|
|
505
|
+
this.stopAttempt(attempt);
|
|
506
|
+
break;
|
|
507
|
+
}
|
|
508
|
+
case 'wake.release':
|
|
509
|
+
object(p, bindingFields);
|
|
510
|
+
if (!this.findGeneration(p).readySent)
|
|
511
|
+
throw unavailable();
|
|
512
|
+
break;
|
|
513
|
+
case 'repeat_after_ready':
|
|
514
|
+
object(p, ['reason']);
|
|
515
|
+
if (!['wake_deadline', 'wake_capacity', 'start_limit', 'detector_unhealthy'].includes(String(p.reason)))
|
|
516
|
+
throw unavailable();
|
|
517
|
+
this.options.onRepeatAfterReady?.(p.reason);
|
|
518
|
+
break;
|
|
519
|
+
case 'text.answer':
|
|
520
|
+
object(p, ['taskId', 'inputEpoch', 'text']);
|
|
521
|
+
if (!uuid(p.taskId) || !count(p.inputEpoch) || typeof p.text !== 'string' || !p.text.length || p.text.length > 16000)
|
|
522
|
+
throw unavailable();
|
|
523
|
+
this.options.onTextAnswer?.({ taskId: p.taskId, inputEpoch: p.inputEpoch, text: p.text });
|
|
524
|
+
break;
|
|
525
|
+
case 'transcript.delta': {
|
|
526
|
+
object(p, ['streamId', 'eventId', 'role', 'startMs', 'endMs', 'text']);
|
|
527
|
+
if (!uuid(p.streamId) || typeof p.eventId !== 'string' || !p.eventId.length || p.eventId.length > 256 ||
|
|
528
|
+
!['user', 'assistant'].includes(String(p.role)) || typeof p.startMs !== 'number' || !Number.isFinite(p.startMs) || p.startMs < 0 ||
|
|
529
|
+
typeof p.endMs !== 'number' || !Number.isFinite(p.endMs) || p.endMs < p.startMs ||
|
|
530
|
+
typeof p.text !== 'string' || !p.text.length || p.text.length > 16000 ||
|
|
531
|
+
!this.attempt || this.attempt.generationId !== p.streamId || this.attempt.stopped)
|
|
532
|
+
throw unavailable();
|
|
533
|
+
this.options.onTranscript?.(p);
|
|
534
|
+
break;
|
|
535
|
+
}
|
|
536
|
+
case 'task.state':
|
|
537
|
+
object(p, ['taskId', 'inputEpoch', 'status']);
|
|
538
|
+
if ((p.taskId !== null && !uuid(p.taskId)) || !count(p.inputEpoch) ||
|
|
539
|
+
!['working', 'waiting', 'blocked', 'cancelled', 'failed', 'fresh_task_required'].includes(String(p.status)))
|
|
540
|
+
throw unavailable();
|
|
541
|
+
this.options.onTaskState?.(p);
|
|
542
|
+
break;
|
|
543
|
+
default: throw unavailable();
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
beginWake(operationId, captureEpoch) {
|
|
547
|
+
const media = this.media;
|
|
548
|
+
if (!uuid(operationId) || this.usedOperations.has(operationId) || this.usedOperations.size >= 64 || captureEpoch !== this.captureEpoch ||
|
|
549
|
+
!media || !['local', 'retiring'].includes(media.status) || this.pendingWake || (this.attempt && !this.attempt.stopped))
|
|
550
|
+
throw unavailable();
|
|
551
|
+
this.usedOperations.add(operationId);
|
|
552
|
+
const deadlineAt = Math.min(this.now() + 6000, this.deadline);
|
|
553
|
+
const attempt = { operationId, captureEpoch, deadlineAt, cutoff: deadlineAt, commandEpoch: this.commandEpoch,
|
|
554
|
+
media, abort: new AbortController(), generationId: null, buffered: false, serverWake: false, offering: false, offered: false,
|
|
555
|
+
stopped: false, localClosed: false, readySent: false, retiredSent: false, answer: null, started: null,
|
|
556
|
+
terminal: null, retirement: null, finishing: false, timer: undefined };
|
|
557
|
+
if (this.attempt)
|
|
558
|
+
this.pendingWake = attempt;
|
|
559
|
+
else
|
|
560
|
+
this.attempt = attempt;
|
|
561
|
+
this.armAttempt(attempt);
|
|
562
|
+
void media.bufferWake(this.wakeBinding(attempt), attempt.abort.signal).then(() => {
|
|
563
|
+
attempt.buffered = true;
|
|
564
|
+
this.offer(attempt);
|
|
565
|
+
}).catch(() => { if (!attempt.stopped && !this.closed)
|
|
566
|
+
this.failAttempt(attempt); });
|
|
567
|
+
}
|
|
568
|
+
armAttempt(attempt) {
|
|
569
|
+
this.clock.cancel(attempt.timer);
|
|
570
|
+
attempt.timer = this.clock.schedule(() => { if (!attempt.readySent && !attempt.stopped)
|
|
571
|
+
this.failAttempt(attempt); }, Math.max(0, attempt.cutoff - this.clock.now()));
|
|
572
|
+
}
|
|
573
|
+
offer(attempt) {
|
|
574
|
+
if (this.closed || attempt.stopped || !attempt.buffered || !attempt.serverWake || attempt.offering || attempt.offered ||
|
|
575
|
+
attempt.media.status !== 'local' || this.attempt !== attempt || this.barriers.size)
|
|
576
|
+
return;
|
|
577
|
+
attempt.offering = true;
|
|
578
|
+
void attempt.media.createOffer(this.wakeBinding(attempt), attempt.abort.signal).then(result => {
|
|
579
|
+
if (!this.current(attempt) || !sdp(result.sdp))
|
|
580
|
+
return;
|
|
581
|
+
attempt.offered = true;
|
|
582
|
+
this.command('rtc.offer', { operationId: attempt.operationId, captureEpoch: attempt.captureEpoch, offerSdp: result.sdp });
|
|
583
|
+
}).catch(() => { if (!attempt.stopped && !this.closed)
|
|
584
|
+
this.failAttempt(attempt); });
|
|
585
|
+
}
|
|
586
|
+
wakeBinding(attempt) { return { operationId: attempt.operationId, captureEpoch: attempt.captureEpoch, deadlineAt: attempt.deadlineAt }; }
|
|
587
|
+
binding(attempt) { if (!attempt.generationId)
|
|
588
|
+
throw unavailable(); return { ...this.wakeBinding(attempt), generationId: attempt.generationId }; }
|
|
589
|
+
attempts() { return new Set([...this.cleanups, ...(this.attempt ? [this.attempt] : []), ...(this.pendingWake ? [this.pendingWake] : [])]); }
|
|
590
|
+
findWake(payload) {
|
|
591
|
+
if (!uuid(payload.operationId) || !count(payload.captureEpoch))
|
|
592
|
+
throw unavailable();
|
|
593
|
+
const attempt = [...this.attempts()].find(value => value.operationId === payload.operationId && value.captureEpoch === payload.captureEpoch);
|
|
594
|
+
if (!attempt)
|
|
595
|
+
throw unavailable();
|
|
596
|
+
return attempt;
|
|
597
|
+
}
|
|
598
|
+
findGeneration(payload, cleanup = false) {
|
|
599
|
+
const attempt = this.findWake(payload);
|
|
600
|
+
if (!uuid(payload.generationId))
|
|
601
|
+
throw unavailable();
|
|
602
|
+
// A Stop can close a still-unpaid local offer before the server discloses its
|
|
603
|
+
// eventual generation. Only cleanup frames may bind that late identity.
|
|
604
|
+
if (cleanup && attempt.stopped && attempt.localClosed && !attempt.generationId)
|
|
605
|
+
attempt.generationId = payload.generationId;
|
|
606
|
+
if (attempt.generationId !== payload.generationId)
|
|
607
|
+
throw unavailable();
|
|
608
|
+
return attempt;
|
|
609
|
+
}
|
|
610
|
+
current(attempt) {
|
|
611
|
+
try {
|
|
612
|
+
return !attempt.stopped && !attempt.abort.signal.aborted && attempt.commandEpoch === this.commandEpoch && this.now() < attempt.cutoff;
|
|
613
|
+
}
|
|
614
|
+
catch {
|
|
615
|
+
return false;
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
proof(purpose, attempt, binding, sdp) {
|
|
619
|
+
const handle = Object.freeze({});
|
|
620
|
+
this.proofs.set(handle, { purpose, attempt, binding, ...(sdp ? { sdp } : {}) });
|
|
621
|
+
return handle;
|
|
622
|
+
}
|
|
623
|
+
authorized(purpose, binding, handle, sdp) {
|
|
624
|
+
if (!handle || typeof handle !== 'object' || this.closed)
|
|
625
|
+
return false;
|
|
626
|
+
const proof = this.proofs.get(handle);
|
|
627
|
+
if (!proof || proof.purpose !== purpose || !sameBinding(binding, proof.binding) || (sdp !== undefined && proof.sdp !== sdp))
|
|
628
|
+
return false;
|
|
629
|
+
if (purpose === 'terminal')
|
|
630
|
+
return proof.attempt.terminal === handle && !proof.attempt.retiredSent;
|
|
631
|
+
return this.current(proof.attempt) && (purpose === 'answer' ? proof.attempt.answer === handle : proof.attempt.started === handle);
|
|
632
|
+
}
|
|
633
|
+
metadata(media, metadata) {
|
|
634
|
+
if (this.closed || !('binding' in metadata))
|
|
635
|
+
return;
|
|
636
|
+
try {
|
|
637
|
+
const attempt = this.findGeneration(metadata.binding);
|
|
638
|
+
if (attempt.media !== media || !sameBinding(metadata.binding, this.binding(attempt)))
|
|
639
|
+
throw unavailable();
|
|
640
|
+
if (metadata.type === 'active') {
|
|
641
|
+
if (!this.current(attempt) || !attempt.answer || !attempt.started || attempt.readySent)
|
|
642
|
+
throw unavailable();
|
|
643
|
+
attempt.readySent = true;
|
|
644
|
+
this.clock.cancel(attempt.timer);
|
|
645
|
+
this.command('media.ready', { generationId: attempt.generationId, operationId: attempt.operationId, captureEpoch: attempt.captureEpoch,
|
|
646
|
+
rtcConnected: true, dataChannelOpen: true, playbackReady: true });
|
|
647
|
+
}
|
|
648
|
+
else if (metadata.type === 'retired')
|
|
649
|
+
this.ackRetired(attempt);
|
|
650
|
+
}
|
|
651
|
+
catch {
|
|
652
|
+
this.close('media');
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
stopAttempt(attempt) {
|
|
656
|
+
if (attempt.stopped)
|
|
657
|
+
return;
|
|
658
|
+
attempt.stopped = true;
|
|
659
|
+
this.clock.cancel(attempt.timer);
|
|
660
|
+
if (attempt.media.status === 'active' && attempt.generationId) {
|
|
661
|
+
attempt.abort.abort();
|
|
662
|
+
this.retire(attempt);
|
|
663
|
+
}
|
|
664
|
+
else {
|
|
665
|
+
// Existing media cannot cancel unfinished RTC setup while retaining its
|
|
666
|
+
// capture owner. A privacy fence obtains a fresh epoch for the next gesture.
|
|
667
|
+
this.requiresGesture = true;
|
|
668
|
+
this.priority('voice.fence', { reason: 'pause' });
|
|
669
|
+
this.hardFencedMedia.add(attempt.media);
|
|
670
|
+
attempt.abort.abort();
|
|
671
|
+
attempt.media.close('aborted');
|
|
672
|
+
if (!attempt.offered)
|
|
673
|
+
this.dropUnpaid(attempt);
|
|
674
|
+
}
|
|
675
|
+
}
|
|
676
|
+
retire(attempt) {
|
|
677
|
+
this.clock.cancel(attempt.timer);
|
|
678
|
+
if (attempt.localClosed) {
|
|
679
|
+
this.finishRetirement(attempt);
|
|
680
|
+
return;
|
|
681
|
+
}
|
|
682
|
+
// Authenticated retirement also reaches this path for natural idle, where
|
|
683
|
+
// there was no local Stop button to pause the continuously-playing sink.
|
|
684
|
+
// Pause only this current media owner so render drain can be observed.
|
|
685
|
+
if (attempt.media === this.media)
|
|
686
|
+
this.suppressPlayback();
|
|
687
|
+
if (!attempt.generationId || !['active', 'retiring'].includes(attempt.media.status)) {
|
|
688
|
+
attempt.abort.abort();
|
|
689
|
+
attempt.media.close('aborted');
|
|
690
|
+
return;
|
|
691
|
+
}
|
|
692
|
+
attempt.retirement ?? (attempt.retirement = attempt.media.beginRetirement(this.binding(attempt), this.lifetime.signal));
|
|
693
|
+
void attempt.retirement.then(() => this.finishRetirement(attempt)).catch(() => {
|
|
694
|
+
attempt.media.close('aborted');
|
|
695
|
+
});
|
|
696
|
+
}
|
|
697
|
+
finishRetirement(attempt) {
|
|
698
|
+
if (this.closed || !attempt.terminal || attempt.retiredSent)
|
|
699
|
+
return;
|
|
700
|
+
if (attempt.localClosed) {
|
|
701
|
+
this.ackRetired(attempt);
|
|
702
|
+
return;
|
|
703
|
+
}
|
|
704
|
+
if (attempt.finishing)
|
|
705
|
+
return;
|
|
706
|
+
if (!attempt.retirement)
|
|
707
|
+
return;
|
|
708
|
+
attempt.finishing = true;
|
|
709
|
+
const deadline = Math.min(this.now() + 1000, this.deadline);
|
|
710
|
+
const drain = () => {
|
|
711
|
+
if (this.closed || attempt.retiredSent)
|
|
712
|
+
return;
|
|
713
|
+
try {
|
|
714
|
+
if (!this.options.media.dependencies.isPlaybackDrained(this.binding(attempt), this.options.media.audioElement)) {
|
|
715
|
+
if (this.now() >= deadline) {
|
|
716
|
+
attempt.media.close('aborted');
|
|
717
|
+
return;
|
|
718
|
+
}
|
|
719
|
+
this.clock.schedule(drain, 25);
|
|
720
|
+
return;
|
|
721
|
+
}
|
|
722
|
+
void attempt.media.retireToLocal({ binding: this.binding(attempt), terminalReceipt: attempt.terminal }, this.lifetime.signal)
|
|
723
|
+
.catch(() => attempt.media.close('aborted'));
|
|
724
|
+
}
|
|
725
|
+
catch {
|
|
726
|
+
attempt.media.close('aborted');
|
|
727
|
+
}
|
|
728
|
+
};
|
|
729
|
+
void attempt.retirement.then(drain).catch(() => attempt.media.close('aborted'));
|
|
730
|
+
}
|
|
731
|
+
ackRetired(attempt) {
|
|
732
|
+
if (attempt.retiredSent || !attempt.terminal || !attempt.generationId || this.closed)
|
|
733
|
+
return;
|
|
734
|
+
if (!attempt.localClosed && attempt.media.status !== 'local')
|
|
735
|
+
throw unavailable();
|
|
736
|
+
attempt.retiredSent = true;
|
|
737
|
+
this.clock.cancel(attempt.timer);
|
|
738
|
+
this.command('media.retired', { generationId: attempt.generationId, operationId: attempt.operationId, captureEpoch: attempt.captureEpoch });
|
|
739
|
+
this.cleanups.delete(attempt);
|
|
740
|
+
if (this.attempt === attempt) {
|
|
741
|
+
this.attempt = this.pendingWake;
|
|
742
|
+
this.pendingWake = null;
|
|
743
|
+
if (this.attempt)
|
|
744
|
+
this.offer(this.attempt);
|
|
745
|
+
}
|
|
746
|
+
else if (this.pendingWake === attempt)
|
|
747
|
+
this.pendingWake = null;
|
|
748
|
+
}
|
|
749
|
+
dropUnpaid(attempt) {
|
|
750
|
+
// No rtc.offer was sent, therefore this channel never exposed SDP to the
|
|
751
|
+
// server's sole provider-create path. This is not a financial terminal ACK.
|
|
752
|
+
if (attempt.offered || attempt.generationId)
|
|
753
|
+
return;
|
|
754
|
+
this.cleanups.delete(attempt);
|
|
755
|
+
if (this.attempt === attempt) {
|
|
756
|
+
this.attempt = this.pendingWake;
|
|
757
|
+
this.pendingWake = null;
|
|
758
|
+
}
|
|
759
|
+
else if (this.pendingWake === attempt)
|
|
760
|
+
this.pendingWake = null;
|
|
761
|
+
}
|
|
762
|
+
mediaClosed(media) {
|
|
763
|
+
this.requiresGesture = true;
|
|
764
|
+
this.voicePrepared = false;
|
|
765
|
+
for (const attempt of this.attempts()) {
|
|
766
|
+
if (attempt.media !== media)
|
|
767
|
+
continue;
|
|
768
|
+
attempt.localClosed = true;
|
|
769
|
+
attempt.stopped = true;
|
|
770
|
+
attempt.abort.abort();
|
|
771
|
+
this.clock.cancel(attempt.timer);
|
|
772
|
+
this.cleanups.add(attempt);
|
|
773
|
+
this.finishRetirement(attempt);
|
|
774
|
+
if (!attempt.offered)
|
|
775
|
+
this.dropUnpaid(attempt);
|
|
776
|
+
}
|
|
777
|
+
if (!this.closed && !this.hardFencedMedia.has(media)) {
|
|
778
|
+
this.hardFencedMedia.add(media);
|
|
779
|
+
this.fence('pause');
|
|
780
|
+
}
|
|
781
|
+
}
|
|
782
|
+
failAttempt(attempt) { if (!this.closed) {
|
|
783
|
+
this.stop();
|
|
784
|
+
if (!attempt.stopped)
|
|
785
|
+
this.stopAttempt(attempt);
|
|
786
|
+
} }
|
|
787
|
+
suppressPlayback() { try {
|
|
788
|
+
this.options.media.audioElement.pause();
|
|
789
|
+
}
|
|
790
|
+
catch {
|
|
791
|
+
this.close('media');
|
|
792
|
+
} }
|
|
793
|
+
close(reason) {
|
|
794
|
+
if (this.closed)
|
|
795
|
+
return;
|
|
796
|
+
this.closed = true;
|
|
797
|
+
this.credential = null;
|
|
798
|
+
this.lifetime.abort();
|
|
799
|
+
this.detachExternal?.();
|
|
800
|
+
this.detachExternal = null;
|
|
801
|
+
this.clock.cancel(this.connectionTimer);
|
|
802
|
+
this.clock.cancel(this.expiryTimer);
|
|
803
|
+
for (const item of this.outbound.values())
|
|
804
|
+
this.clock.cancel(item.timer);
|
|
805
|
+
for (const attempt of this.attempts()) {
|
|
806
|
+
attempt.abort.abort();
|
|
807
|
+
this.clock.cancel(attempt.timer);
|
|
808
|
+
}
|
|
809
|
+
this.pendingCommands = [];
|
|
810
|
+
this.barriers.clear();
|
|
811
|
+
this.suppressPlayback();
|
|
812
|
+
this.media?.close('ended');
|
|
813
|
+
try {
|
|
814
|
+
this.socket?.close(1000, 'AI Guide connection closed.');
|
|
815
|
+
}
|
|
816
|
+
catch { /* Already disconnected. */ }
|
|
817
|
+
this.connectReject?.(unavailable());
|
|
818
|
+
this.connectReject = null;
|
|
819
|
+
this.connectResolve = null;
|
|
820
|
+
try {
|
|
821
|
+
this.options.onClose(reason);
|
|
822
|
+
}
|
|
823
|
+
catch { /* The local authority is already retired. */ }
|
|
824
|
+
}
|
|
825
|
+
}
|