@pyai/sdk 0.9.2 → 0.11.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 (49) hide show
  1. package/CLI.schema.json +11 -0
  2. package/README.md +131 -3
  3. package/dist/cli-omni-template.d.ts +2 -2
  4. package/dist/cli-omni-template.js +2 -2
  5. package/dist/cli.js +39 -4
  6. package/dist/dialer/appServer.d.ts +21 -0
  7. package/dist/dialer/appServer.js +195 -0
  8. package/dist/dialer/dialerElement.d.ts +23 -0
  9. package/dist/dialer/dialerElement.js +108 -0
  10. package/dist/dialer/dialingQueue.d.ts +31 -0
  11. package/dist/dialer/dialingQueue.js +78 -0
  12. package/dist/dialer/index.d.ts +6 -0
  13. package/dist/dialer/index.js +6 -0
  14. package/dist/dialer/indexedDbJournal.d.ts +11 -0
  15. package/dist/dialer/indexedDbJournal.js +62 -0
  16. package/dist/dialer/managedDialer.d.ts +65 -0
  17. package/dist/dialer/managedDialer.js +217 -0
  18. package/dist/dialer/meetingRecorder.d.ts +83 -0
  19. package/dist/dialer/meetingRecorder.js +261 -0
  20. package/dist/dialer/meetingRecorderElement.d.ts +20 -0
  21. package/dist/dialer/meetingRecorderElement.js +138 -0
  22. package/dist/dialer/meetingRecordingStore.d.ts +17 -0
  23. package/dist/dialer/meetingRecordingStore.js +129 -0
  24. package/dist/dialer/serverBroker.d.ts +3 -0
  25. package/dist/dialer/serverBroker.js +23 -0
  26. package/dist/dialer/voiceSdkAudio.d.ts +33 -0
  27. package/dist/dialer/voiceSdkAudio.js +66 -0
  28. package/dist/index.d.ts +238 -6
  29. package/dist/index.js +67 -3
  30. package/package.json +24 -1
  31. package/src/cli-omni-template.ts +2 -2
  32. package/src/cli.ts +25 -4
  33. package/src/dialer/app/app.css +1 -0
  34. package/src/dialer/app/app.html +7 -0
  35. package/src/dialer/app/app.js +88 -0
  36. package/src/dialer/app/icon.svg +1 -0
  37. package/src/dialer/app/manifest.webmanifest +1 -0
  38. package/src/dialer/appServer.ts +151 -0
  39. package/src/dialer/dialerElement.ts +80 -0
  40. package/src/dialer/dialingQueue.ts +65 -0
  41. package/src/dialer/index.ts +6 -0
  42. package/src/dialer/indexedDbJournal.ts +56 -0
  43. package/src/dialer/managedDialer.ts +187 -0
  44. package/src/dialer/meetingRecorder.ts +220 -0
  45. package/src/dialer/meetingRecorderElement.ts +99 -0
  46. package/src/dialer/meetingRecordingStore.ts +99 -0
  47. package/src/dialer/serverBroker.ts +23 -0
  48. package/src/dialer/voiceSdkAudio.ts +61 -0
  49. package/src/index.ts +174 -5
@@ -0,0 +1,217 @@
1
+ const terminal = (call) => ["completed", "failed", "canceled"].includes(call.status);
2
+ /** One immutable workspace/user scope per instance. Setup and stop retain the
3
+ * original intent through lost acknowledgments, reloads and audio failures. */
4
+ export class ManagedDialer {
5
+ intent = null;
6
+ snapshot = { state: "idle", callId: null, call: null, muted: false, error: null };
7
+ listeners = new Set();
8
+ operation = null;
9
+ initialized = false;
10
+ scope;
11
+ broker;
12
+ journal;
13
+ audio;
14
+ newKey;
15
+ now;
16
+ constructor(scope, broker, journal, audio, newKey = () => crypto.randomUUID(), now = Date.now) {
17
+ if (!scope.trim())
18
+ throw new Error("An authenticated workspace/user scope is required.");
19
+ this.scope = scope;
20
+ this.broker = broker;
21
+ this.journal = journal;
22
+ this.audio = audio;
23
+ this.newKey = newKey;
24
+ this.now = now;
25
+ }
26
+ get current() { return structuredClone(this.snapshot); }
27
+ subscribe(listener) {
28
+ this.listeners.add(listener);
29
+ listener(this.current);
30
+ return () => { this.listeners.delete(listener); };
31
+ }
32
+ update(patch) {
33
+ this.snapshot = { ...this.snapshot, ...patch };
34
+ for (const listener of this.listeners) {
35
+ try {
36
+ listener(this.current);
37
+ }
38
+ catch { /* UI observers cannot interrupt cleanup. */ }
39
+ }
40
+ }
41
+ async exclusive(action) {
42
+ if (this.operation)
43
+ throw new Error("Calling operation is already in progress.");
44
+ const operation = action();
45
+ this.operation = operation;
46
+ try {
47
+ await operation;
48
+ }
49
+ finally {
50
+ if (this.operation === operation)
51
+ this.operation = null;
52
+ }
53
+ }
54
+ async restore() {
55
+ return this.exclusive(async () => {
56
+ if (this.initialized)
57
+ return;
58
+ const saved = await this.journal.read(this.scope);
59
+ if (saved && saved.scope !== this.scope)
60
+ throw new Error("Saved call belongs to another workspace.");
61
+ this.intent = saved ? structuredClone(saved) : null;
62
+ this.initialized = true;
63
+ if (saved) {
64
+ this.update({ state: "unconfirmed", callId: saved.callId ?? null, error: "Recover the previous call before starting another." });
65
+ // Reload never consumes a new browser capability automatically.
66
+ if (saved.callId)
67
+ await this.readStatus();
68
+ }
69
+ });
70
+ }
71
+ async start(input) {
72
+ if (!this.initialized)
73
+ throw new Error("Restore the calling journal before dialing.");
74
+ if (this.intent)
75
+ throw new Error("The previous call must finish and be wrapped up first.");
76
+ if (!/^\+[1-9]\d{6,14}$/.test(input.to))
77
+ throw new Error("Enter the full destination with its country code.");
78
+ return this.exclusive(async () => {
79
+ const intent = { scope: this.scope, key: this.newKey(), input: structuredClone(input), stopping: false };
80
+ // Persist before the first network request. A storage failure cannot dial.
81
+ await this.journal.write(structuredClone(intent));
82
+ this.intent = intent;
83
+ await this.setup();
84
+ });
85
+ }
86
+ async retrySetup() {
87
+ if (!this.intent)
88
+ throw new Error("No call to recover.");
89
+ return this.exclusive(async () => {
90
+ if (this.intent.callId) {
91
+ await this.readStatus();
92
+ return;
93
+ }
94
+ await this.setup();
95
+ });
96
+ }
97
+ async setup() {
98
+ const intent = this.intent;
99
+ this.update({ state: intent.stopping ? "stopping" : "preparing", error: null });
100
+ try {
101
+ const session = await this.broker.create(structuredClone(intent.input), intent.key);
102
+ if (session.id !== session.call_id || session.call.id !== session.call_id || session.connect_params.session_id !== session.call_id ||
103
+ session.transport !== "voice-sdk" || (intent.callId && intent.callId !== session.call_id))
104
+ throw new Error("Calling session identity changed.");
105
+ intent.callId = session.call_id;
106
+ await this.journal.write(structuredClone(intent));
107
+ const saved = await this.journal.read(this.scope);
108
+ if (!saved || saved.key !== intent.key || saved.callId !== intent.callId)
109
+ throw new Error("Calling recovery intent changed.");
110
+ if (saved.stopping)
111
+ intent.stopping = true;
112
+ this.update({ callId: session.call_id, call: session.call });
113
+ if (terminal(session.call)) {
114
+ await this.acceptStatus(session.call);
115
+ return;
116
+ }
117
+ if (intent.stopping) {
118
+ await this.stopKnown();
119
+ return;
120
+ }
121
+ if (!session.access_token || session.expires_at <= this.now() || session.call.stop_requested) {
122
+ this.update({ state: "unconfirmed", error: "This session was consumed, stopped or expired. End or recover the original call." });
123
+ return;
124
+ }
125
+ await this.audio.connect(session, state => {
126
+ if (this.intent !== intent || intent.stopping || this.snapshot.state === "wrapup")
127
+ return;
128
+ if (state === "disconnected") {
129
+ this.audio.disconnect();
130
+ this.update({ state: "unconfirmed", error: "Audio disconnected. Check the original call before dialing again." });
131
+ }
132
+ else
133
+ this.update({ state, error: null });
134
+ });
135
+ }
136
+ catch {
137
+ this.audio.disconnect();
138
+ this.update({ state: "unconfirmed", error: "Call setup is unconfirmed. Recover or end this same attempt." });
139
+ }
140
+ }
141
+ async refresh() {
142
+ if (this.operation)
143
+ await this.operation;
144
+ return this.exclusive(() => this.readStatus());
145
+ }
146
+ async readStatus() {
147
+ if (!this.intent?.callId)
148
+ return;
149
+ try {
150
+ await this.acceptStatus(await this.broker.get(this.intent.callId));
151
+ }
152
+ catch {
153
+ this.update({ error: "Call status is unavailable. The original call is still retained." });
154
+ }
155
+ }
156
+ async acceptStatus(call) {
157
+ if (!this.intent || call.id !== this.intent.callId)
158
+ throw new Error("Calling status identity changed.");
159
+ if (this.snapshot.call && call.version < this.snapshot.call.version)
160
+ return;
161
+ if (terminal(call)) {
162
+ this.audio.disconnect();
163
+ this.update({ call, state: "wrapup", muted: false, error: null });
164
+ }
165
+ else
166
+ this.update({ call });
167
+ }
168
+ async stop() {
169
+ if (!this.intent)
170
+ return;
171
+ // Mark immediately so a late create acknowledgment cannot connect audio.
172
+ this.intent.stopping = true;
173
+ this.audio.disconnect();
174
+ this.update({ state: "stopping", muted: false });
175
+ // Await in-flight setup; never issue an independent replacement create.
176
+ if (this.operation)
177
+ await this.operation;
178
+ return this.exclusive(async () => {
179
+ await this.journal.write(structuredClone(this.intent));
180
+ if (!this.intent.callId)
181
+ await this.setup();
182
+ else
183
+ await this.stopKnown();
184
+ });
185
+ }
186
+ async stopKnown() {
187
+ try {
188
+ const call = await this.broker.hangup(this.intent.callId);
189
+ await this.acceptStatus(call);
190
+ if (!terminal(call))
191
+ this.update({ state: "stopping", error: null });
192
+ }
193
+ catch {
194
+ this.update({ state: "unconfirmed", error: "Stop is unconfirmed. Retry ending the same call." });
195
+ }
196
+ }
197
+ async finishWrapup() {
198
+ return this.exclusive(async () => {
199
+ if (!this.intent || this.snapshot.state !== "wrapup" || !this.snapshot.call || !terminal(this.snapshot.call))
200
+ throw new Error("Confirmed call completion is required.");
201
+ await this.journal.clear(this.scope, this.intent.key);
202
+ this.intent = null;
203
+ this.update({ state: "idle", callId: null, call: null, muted: false, error: null });
204
+ });
205
+ }
206
+ mute(value) {
207
+ if (this.snapshot.state !== "active")
208
+ throw new Error("No active audio call.");
209
+ this.audio.mute(value);
210
+ this.update({ muted: value });
211
+ }
212
+ sendDigits(digits) {
213
+ if (this.snapshot.state !== "active" || !/^[0-9*#w]{1,32}$/.test(digits))
214
+ throw new Error("Enter up to 32 keypad digits on an active call.");
215
+ this.audio.sendDigits(digits);
216
+ }
217
+ }
@@ -0,0 +1,83 @@
1
+ /** Permission-based, audio-only meeting capture. The user selects a source on
2
+ * every start; video is requested for the browser picker but is never recorded. */
3
+ export interface MeetingRecording {
4
+ id: string;
5
+ scope: string;
6
+ state: "recording" | "ready" | "incomplete";
7
+ mimeType: string;
8
+ sources: Array<"shared_audio" | "microphone">;
9
+ createdAt: number;
10
+ endedAt: number | null;
11
+ bytes: number;
12
+ chunks: number;
13
+ maxBytes: number;
14
+ signalObserved: {
15
+ shared_audio: boolean;
16
+ microphone: boolean;
17
+ };
18
+ error: string | null;
19
+ }
20
+ export interface MeetingRecordingStore {
21
+ /** Held for the entire capture; recovery must use the same exclusive lease. */
22
+ acquire(scope: string, id: string): Promise<() => void>;
23
+ create(recording: MeetingRecording): Promise<void>;
24
+ append(scope: string, id: string, sequence: number, bytes: Blob): Promise<void>;
25
+ finish(scope: string, id: string, state: "ready" | "incomplete", endedAt: number, error: string | null, signalObserved?: MeetingRecording["signalObserved"]): Promise<MeetingRecording>;
26
+ get(scope: string, id: string): Promise<MeetingRecording | null>;
27
+ list(scope: string): Promise<MeetingRecording[]>;
28
+ recover(scope: string, id: string): Promise<MeetingRecording>;
29
+ audio(scope: string, id: string): Promise<Blob>;
30
+ }
31
+ export interface MeetingCaptureOptions {
32
+ /** The host must display a recording notice before this foreground action. */
33
+ noticeAccepted: boolean;
34
+ microphone: boolean;
35
+ maxDurationSeconds?: number;
36
+ maxBytes?: number;
37
+ }
38
+ export interface MeetingCaptureEnvironment {
39
+ sharedAudio(): Promise<MediaStream>;
40
+ microphone(): Promise<MediaStream>;
41
+ audioContext(): AudioContext;
42
+ recorder(stream: MediaStream): MediaRecorder;
43
+ newId(): string;
44
+ now(): number;
45
+ }
46
+ export interface MeetingCaptureSnapshot {
47
+ state: "idle" | "starting" | "recording" | "paused" | "stopping" | "ready" | "error";
48
+ recording: MeetingRecording | null;
49
+ error: string | null;
50
+ }
51
+ export declare class MeetingRecorder {
52
+ private readonly scope;
53
+ private readonly store;
54
+ private readonly environment;
55
+ private streams;
56
+ private context;
57
+ private recorder;
58
+ private listeners;
59
+ private snapshot;
60
+ private pendingWrites;
61
+ private writeError;
62
+ private sequence;
63
+ private generation;
64
+ private starting;
65
+ private stopping;
66
+ private timer;
67
+ private watchdog;
68
+ private analysers;
69
+ private signalObserved;
70
+ private releaseStorage;
71
+ constructor(scope: string, store: MeetingRecordingStore, environment?: MeetingCaptureEnvironment);
72
+ get current(): MeetingCaptureSnapshot;
73
+ get recordingScope(): string;
74
+ subscribe(listener: (snapshot: MeetingCaptureSnapshot) => void): () => void;
75
+ private update;
76
+ start(options: MeetingCaptureOptions): Promise<void>;
77
+ private prepare;
78
+ pause(): void;
79
+ resume(): void;
80
+ stop(): Promise<void>;
81
+ private finish;
82
+ private release;
83
+ }
@@ -0,0 +1,261 @@
1
+ const defaultEnvironment = {
2
+ // Do not narrow the source picker to an app selected by the host. Audio can
3
+ // cover a wider surface than video; the browser/OS must obtain real consent.
4
+ sharedAudio: () => navigator.mediaDevices.getDisplayMedia({ video: true, audio: true }),
5
+ microphone: () => navigator.mediaDevices.getUserMedia({ audio: { echoCancellation: true, noiseSuppression: true }, video: false }),
6
+ audioContext: () => new AudioContext(),
7
+ recorder: stream => {
8
+ const mimeType = ["audio/webm;codecs=opus", "audio/mp4"].find(type => MediaRecorder.isTypeSupported(type));
9
+ return new MediaRecorder(stream, { ...(mimeType ? { mimeType } : {}), audioBitsPerSecond: 64000 });
10
+ },
11
+ newId: () => crypto.randomUUID(), now: Date.now,
12
+ };
13
+ export class MeetingRecorder {
14
+ scope;
15
+ store;
16
+ environment;
17
+ streams = [];
18
+ context = null;
19
+ recorder = null;
20
+ listeners = new Set();
21
+ snapshot = { state: "idle", recording: null, error: null };
22
+ pendingWrites = Promise.resolve();
23
+ writeError = null;
24
+ sequence = 0;
25
+ generation = 0;
26
+ starting = null;
27
+ stopping = null;
28
+ timer = null;
29
+ watchdog = null;
30
+ analysers = [];
31
+ signalObserved = { shared_audio: false, microphone: false };
32
+ releaseStorage = null;
33
+ constructor(scope, store, environment = defaultEnvironment) {
34
+ if (!scope.trim())
35
+ throw new Error("A workspace/user recording scope is required.");
36
+ this.scope = scope;
37
+ this.store = store;
38
+ this.environment = environment;
39
+ }
40
+ get current() { return structuredClone(this.snapshot); }
41
+ get recordingScope() { return this.scope; }
42
+ subscribe(listener) {
43
+ this.listeners.add(listener);
44
+ listener(this.current);
45
+ return () => { this.listeners.delete(listener); };
46
+ }
47
+ update(patch) {
48
+ this.snapshot = { ...this.snapshot, ...patch };
49
+ for (const listener of this.listeners) {
50
+ try {
51
+ listener(this.current);
52
+ }
53
+ catch { /* UI cannot prevent capture cleanup. */ }
54
+ }
55
+ }
56
+ async start(options) {
57
+ if (this.starting || this.stopping || ["recording", "paused", "starting", "stopping"].includes(this.snapshot.state))
58
+ throw new Error("Finish the current recording first.");
59
+ if (!options.noticeAccepted)
60
+ throw new Error("Confirm the recording notice before starting.");
61
+ const duration = options.maxDurationSeconds ?? 7200, maxBytes = options.maxBytes ?? 128 * 1024 * 1024;
62
+ if (!Number.isInteger(duration) || duration < 1 || duration > 7200 || !Number.isSafeInteger(maxBytes) || maxBytes < 65536 || maxBytes > 256 * 1024 * 1024)
63
+ throw new Error("Recording limits must be 1–7200 seconds and 64 KiB–256 MiB.");
64
+ const generation = ++this.generation;
65
+ this.pendingWrites = Promise.resolve();
66
+ this.writeError = null;
67
+ this.sequence = 0;
68
+ this.signalObserved = { shared_audio: false, microphone: false };
69
+ this.update({ state: "starting", recording: null, error: null });
70
+ const prepare = this.prepare(options, generation, duration, maxBytes);
71
+ this.starting = prepare;
72
+ try {
73
+ await prepare;
74
+ }
75
+ finally {
76
+ if (this.starting === prepare)
77
+ this.starting = null;
78
+ }
79
+ }
80
+ async prepare(options, generation, duration, maxBytes) {
81
+ try {
82
+ const shared = await this.environment.sharedAudio();
83
+ this.streams.push(shared);
84
+ if (generation !== this.generation) {
85
+ await this.release();
86
+ return;
87
+ }
88
+ if (!shared.getAudioTracks().some(track => track.readyState === "live" && track.enabled))
89
+ throw new Error("The selected source has no shared audio. Enable sharing audio or choose a supported tab or system source.");
90
+ const sources = ["shared_audio"];
91
+ if (options.microphone) {
92
+ const mic = await this.environment.microphone();
93
+ this.streams.push(mic);
94
+ if (generation !== this.generation) {
95
+ await this.release();
96
+ return;
97
+ }
98
+ if (!mic.getAudioTracks().some(track => track.readyState === "live" && track.enabled))
99
+ throw new Error("The microphone is unavailable.");
100
+ sources.push("microphone");
101
+ }
102
+ const context = this.environment.audioContext();
103
+ this.context = context;
104
+ await context.resume();
105
+ if (generation !== this.generation) {
106
+ await this.release();
107
+ return;
108
+ }
109
+ const destination = context.createMediaStreamDestination();
110
+ for (const [index, stream] of this.streams.entries()) {
111
+ const audio = new MediaStream(stream.getAudioTracks());
112
+ const gain = context.createGain();
113
+ gain.gain.value = this.streams.length > 1 ? 0.5 : 1;
114
+ const analyser = context.createAnalyser();
115
+ analyser.fftSize = 512;
116
+ context.createMediaStreamSource(audio).connect(analyser).connect(gain).connect(destination);
117
+ this.analysers.push({ source: index === 0 ? "shared_audio" : "microphone", node: analyser, samples: new Float32Array(512) });
118
+ }
119
+ const recorder = this.environment.recorder(destination.stream);
120
+ this.recorder = recorder;
121
+ const recording = { id: this.environment.newId(), scope: this.scope, state: "recording", mimeType: recorder.mimeType,
122
+ sources, createdAt: this.environment.now(), endedAt: null, bytes: 0, chunks: 0, maxBytes, signalObserved: { ...this.signalObserved }, error: null };
123
+ this.releaseStorage = await this.store.acquire(this.scope, recording.id);
124
+ await this.store.create(recording);
125
+ if (generation !== this.generation) {
126
+ await this.store.finish(this.scope, recording.id, "incomplete", this.environment.now(), "Capture was cancelled before audio started.");
127
+ await this.release();
128
+ return;
129
+ }
130
+ this.update({ recording, state: "recording" });
131
+ recorder.ondataavailable = event => {
132
+ if (!event.data.size)
133
+ return;
134
+ const sequence = this.sequence++;
135
+ this.pendingWrites = this.pendingWrites.then(async () => {
136
+ if (this.writeError)
137
+ return;
138
+ await this.store.append(this.scope, recording.id, sequence, event.data);
139
+ const stored = await this.store.get(this.scope, recording.id);
140
+ if (stored)
141
+ this.update({ recording: stored });
142
+ }).catch(error => {
143
+ this.writeError = error instanceof Error ? error : new Error("Recording storage failed.");
144
+ void this.stop();
145
+ });
146
+ };
147
+ recorder.onerror = () => { this.writeError = new Error("Audio capture failed; the saved recording may be incomplete."); void this.stop(); };
148
+ // A stop from the browser/OS source chooser must also release the mic.
149
+ for (const stream of this.streams)
150
+ for (const track of stream.getTracks())
151
+ track.addEventListener("ended", () => void this.stop(), { once: true });
152
+ recorder.start(1000);
153
+ this.timer = setTimeout(() => void this.stop(), duration * 1000);
154
+ this.watchdog = setInterval(() => {
155
+ if (this.snapshot.state === "recording")
156
+ for (const analyser of this.analysers) {
157
+ analyser.node.getFloatTimeDomainData(analyser.samples);
158
+ if (analyser.samples.some(sample => Math.abs(sample) > 0.00001))
159
+ this.signalObserved[analyser.source] = true;
160
+ }
161
+ if (this.streams.some(stream => stream.getAudioTracks().some(track => track.readyState !== "live" || !track.enabled))) {
162
+ this.writeError = new Error("An audio source stopped; the saved recording may be incomplete.");
163
+ void this.stop();
164
+ }
165
+ }, 250);
166
+ }
167
+ catch (error) {
168
+ await this.release();
169
+ if (generation === this.generation)
170
+ this.update({ state: "error", error: error instanceof Error ? error.message : "Meeting capture could not start." });
171
+ throw error;
172
+ }
173
+ }
174
+ pause() {
175
+ if (this.snapshot.state !== "recording" || !this.recorder)
176
+ throw new Error("No recording to pause.");
177
+ this.recorder.pause();
178
+ this.update({ state: "paused" });
179
+ }
180
+ resume() {
181
+ if (this.snapshot.state !== "paused" || !this.recorder)
182
+ throw new Error("No paused recording.");
183
+ this.recorder.resume();
184
+ this.update({ state: "recording" });
185
+ }
186
+ async stop() {
187
+ if (this.stopping)
188
+ return this.stopping;
189
+ ++this.generation;
190
+ const finish = this.finish();
191
+ this.stopping = finish;
192
+ try {
193
+ await finish;
194
+ }
195
+ finally {
196
+ if (this.stopping === finish)
197
+ this.stopping = null;
198
+ }
199
+ }
200
+ async finish() {
201
+ this.update({ state: "stopping" });
202
+ if (this.starting)
203
+ await this.starting.catch(() => { });
204
+ const recorder = this.recorder, recording = this.snapshot.recording;
205
+ try {
206
+ if (recorder && recorder.state !== "inactive") {
207
+ await new Promise(resolve => {
208
+ const timeout = setTimeout(() => { this.writeError = new Error("Audio finalization was not acknowledged."); resolve(); }, 5000);
209
+ recorder.addEventListener("stop", () => { clearTimeout(timeout); resolve(); }, { once: true });
210
+ try {
211
+ recorder.stop();
212
+ }
213
+ catch {
214
+ clearTimeout(timeout);
215
+ this.writeError = new Error("Audio finalization failed.");
216
+ resolve();
217
+ }
218
+ });
219
+ }
220
+ await this.pendingWrites;
221
+ if (recording) {
222
+ const stored = await this.store.get(this.scope, recording.id);
223
+ const error = this.writeError?.message ?? (!stored?.bytes ? "No audio was saved." : !this.signalObserved.shared_audio ? "No sound was detected from the shared source. Check this recording before using it." : null);
224
+ const final = await this.store.finish(this.scope, recording.id, error ? "incomplete" : "ready", this.environment.now(), error, { ...this.signalObserved });
225
+ this.update({ state: error ? "error" : "ready", recording: final, error });
226
+ }
227
+ else
228
+ this.update({ state: "idle", error: null });
229
+ }
230
+ catch (error) {
231
+ this.update({ state: "error", error: error instanceof Error ? error.message : "Recording finalization failed; saved chunks remain recoverable." });
232
+ }
233
+ finally {
234
+ await this.release();
235
+ }
236
+ }
237
+ async release() {
238
+ if (this.timer)
239
+ clearTimeout(this.timer);
240
+ if (this.watchdog)
241
+ clearInterval(this.watchdog);
242
+ this.timer = null;
243
+ this.watchdog = null;
244
+ for (const stream of this.streams)
245
+ for (const track of stream.getTracks()) {
246
+ try {
247
+ track.stop();
248
+ }
249
+ catch { /* Release the remaining sources. */ }
250
+ }
251
+ this.streams = [];
252
+ this.recorder = null;
253
+ this.releaseStorage?.();
254
+ this.releaseStorage = null;
255
+ this.analysers = [];
256
+ const context = this.context;
257
+ this.context = null;
258
+ if (context && context.state !== "closed")
259
+ await context.close().catch(() => { });
260
+ }
261
+ }
@@ -0,0 +1,20 @@
1
+ import type { MeetingRecorder } from "./meetingRecorder.ts";
2
+ import type { MeetingRecordingStore } from "./meetingRecorder.ts";
3
+ /** Foreground capture controls. The native browser/OS picker is always shown;
4
+ * the application never silently chooses a user's window or microphone. */
5
+ export declare class PyaiMeetingRecorderElement extends HTMLElement {
6
+ private root;
7
+ private recorder;
8
+ private store;
9
+ private unsubscribe;
10
+ private historyGeneration;
11
+ constructor();
12
+ bind(recorder: MeetingRecorder, store: MeetingRecordingStore): void;
13
+ connectedCallback(): void;
14
+ disconnectedCallback(): void;
15
+ private render;
16
+ private refreshHistory;
17
+ private download;
18
+ private showError;
19
+ private run;
20
+ }