@absolutejs/voice 0.0.22-beta.319 → 0.0.22-beta.320

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.
@@ -3357,6 +3357,412 @@ var serverMessageToAction = (message) => {
3357
3357
  }
3358
3358
  };
3359
3359
 
3360
+ // node_modules/@absolutejs/media/dist/index.js
3361
+ var formatLabel = (format) => `${format.container}/${format.encoding}/${String(format.sampleRateHz)}hz/${String(format.channels)}ch`;
3362
+ var formatMatches = (actual, expected) => actual.container === expected.container && actual.encoding === expected.encoding && actual.sampleRateHz === expected.sampleRateHz && actual.channels === expected.channels;
3363
+ var pushIssue = (issues, severity, code, message) => {
3364
+ issues.push({ code, message, severity });
3365
+ };
3366
+ var numericMetadata = (frame, key) => {
3367
+ const value = frame.metadata?.[key];
3368
+ return typeof value === "number" && Number.isFinite(value) ? value : undefined;
3369
+ };
3370
+ var average = (values) => values.length === 0 ? undefined : values.reduce((total, value) => total + value, 0) / values.length;
3371
+ var max = (values) => values.length === 0 ? undefined : Math.max(...values);
3372
+ var min = (values) => values.length === 0 ? undefined : Math.min(...values);
3373
+ var numericStat = (stat, key) => {
3374
+ const value = stat[key];
3375
+ return typeof value === "number" && Number.isFinite(value) ? value : undefined;
3376
+ };
3377
+ var booleanStat = (stat, key) => {
3378
+ const value = stat[key];
3379
+ return typeof value === "boolean" ? value : undefined;
3380
+ };
3381
+ var stringStat = (stat, key) => {
3382
+ const value = stat[key];
3383
+ return typeof value === "string" ? value : undefined;
3384
+ };
3385
+ var secondsToMs = (value) => value === undefined ? undefined : value * 1000;
3386
+ var normalizeWebRTCStat = (stat) => {
3387
+ const sample = {};
3388
+ for (const [key, value] of Object.entries(stat)) {
3389
+ if (value === null || typeof value === "boolean" || typeof value === "number" || typeof value === "string") {
3390
+ sample[key] = value;
3391
+ }
3392
+ }
3393
+ return sample;
3394
+ };
3395
+ var buildMediaResamplingPlan = (input) => {
3396
+ const required = !formatMatches(input.inputFormat, input.outputFormat);
3397
+ return {
3398
+ inputFormat: input.inputFormat,
3399
+ outputFormat: input.outputFormat,
3400
+ ratio: input.outputFormat.sampleRateHz / input.inputFormat.sampleRateHz,
3401
+ required,
3402
+ status: input.inputFormat.container === input.outputFormat.container && input.inputFormat.encoding === input.outputFormat.encoding && input.inputFormat.channels === input.outputFormat.channels ? "pass" : "warn"
3403
+ };
3404
+ };
3405
+ var speechProbability = (frame) => {
3406
+ if (frame.metadata?.isSpeech === true) {
3407
+ return 1;
3408
+ }
3409
+ if (frame.metadata?.isSpeech === false) {
3410
+ return 0;
3411
+ }
3412
+ for (const key of ["speechProbability", "voiceProbability", "rms", "energy"]) {
3413
+ const value = numericMetadata(frame, key);
3414
+ if (value !== undefined) {
3415
+ return value;
3416
+ }
3417
+ }
3418
+ return 0;
3419
+ };
3420
+ var buildMediaVadReport = (input = {}) => {
3421
+ const frames = (input.frames ?? []).filter((frame) => frame.kind === "input-audio");
3422
+ const speechStartThreshold = input.speechStartThreshold ?? 0.6;
3423
+ const speechEndThreshold = input.speechEndThreshold ?? 0.35;
3424
+ const minSpeechFrames = input.minSpeechFrames ?? 1;
3425
+ const maxSilenceFrames = input.maxSilenceFrames ?? 1;
3426
+ const segments = [];
3427
+ let activeFrames = [];
3428
+ let silenceFrames = 0;
3429
+ const closeSegment = () => {
3430
+ if (activeFrames.length < minSpeechFrames) {
3431
+ activeFrames = [];
3432
+ silenceFrames = 0;
3433
+ return;
3434
+ }
3435
+ const first = activeFrames[0];
3436
+ const last = activeFrames.at(-1);
3437
+ if (!first) {
3438
+ return;
3439
+ }
3440
+ segments.push({
3441
+ durationMs: first.at !== undefined && last?.at !== undefined ? last.at - first.at + (last.durationMs ?? 0) : undefined,
3442
+ endAt: last?.at !== undefined ? last.at + (last.durationMs ?? 0) : undefined,
3443
+ frameCount: activeFrames.length,
3444
+ segmentId: `vad:${String(segments.length + 1)}`,
3445
+ sessionId: first.sessionId,
3446
+ startAt: first.at,
3447
+ turnId: first.turnId
3448
+ });
3449
+ activeFrames = [];
3450
+ silenceFrames = 0;
3451
+ };
3452
+ for (const frame of frames) {
3453
+ const probability = speechProbability(frame);
3454
+ if (activeFrames.length === 0) {
3455
+ if (probability >= speechStartThreshold) {
3456
+ activeFrames.push(frame);
3457
+ }
3458
+ continue;
3459
+ }
3460
+ activeFrames.push(frame);
3461
+ if (probability <= speechEndThreshold) {
3462
+ silenceFrames += 1;
3463
+ } else {
3464
+ silenceFrames = 0;
3465
+ }
3466
+ if (silenceFrames > maxSilenceFrames) {
3467
+ closeSegment();
3468
+ }
3469
+ }
3470
+ closeSegment();
3471
+ return {
3472
+ checkedAt: Date.now(),
3473
+ inputAudioFrames: frames.length,
3474
+ segments,
3475
+ status: frames.length === 0 ? "warn" : "pass"
3476
+ };
3477
+ };
3478
+ var buildMediaInterruptionReport = (input = {}) => {
3479
+ const issues = [];
3480
+ const interruptionFrames = (input.frames ?? []).filter((frame) => frame.kind === "interruption");
3481
+ const latenciesMs = interruptionFrames.map((frame) => frame.latencyMs).filter((latency) => typeof latency === "number");
3482
+ const maxInterruptionLatencyMs = input.maxInterruptionLatencyMs;
3483
+ if (interruptionFrames.length === 0) {
3484
+ pushIssue(issues, "warning", "media.interruption_missing", "No interruption frame was observed.");
3485
+ }
3486
+ if (maxInterruptionLatencyMs !== undefined && latenciesMs.some((latency) => latency > maxInterruptionLatencyMs)) {
3487
+ pushIssue(issues, "error", "media.interruption_latency", `Interruption latency exceeded ${String(maxInterruptionLatencyMs)}ms.`);
3488
+ }
3489
+ return {
3490
+ checkedAt: Date.now(),
3491
+ interruptionFrames: interruptionFrames.length,
3492
+ issues,
3493
+ latenciesMs,
3494
+ status: issues.some((issue) => issue.severity === "error") ? "fail" : issues.length > 0 ? "warn" : "pass"
3495
+ };
3496
+ };
3497
+ var buildMediaQualityReport = (input = {}) => {
3498
+ const frames = [...input.frames ?? []].sort((a, b) => (a.at ?? 0) - (b.at ?? 0));
3499
+ const audioFrames = frames.filter((frame) => frame.kind === "input-audio" || frame.kind === "assistant-audio");
3500
+ const inputAudioFrames = frames.filter((frame) => frame.kind === "input-audio");
3501
+ const assistantAudioFrames = frames.filter((frame) => frame.kind === "assistant-audio");
3502
+ const issues = [];
3503
+ const gapsMs = [];
3504
+ for (const [index, frame] of audioFrames.entries()) {
3505
+ const previous = audioFrames[index - 1];
3506
+ if (previous?.at === undefined || frame.at === undefined || previous.durationMs === undefined) {
3507
+ continue;
3508
+ }
3509
+ const gap = frame.at - (previous.at + previous.durationMs);
3510
+ if (gap > 0) {
3511
+ gapsMs.push(gap);
3512
+ }
3513
+ }
3514
+ const jitterMs = audioFrames.map((frame) => numericMetadata(frame, "jitterMs")).filter((value) => value !== undefined).at(-1) ?? max(gapsMs);
3515
+ const first = audioFrames.find((frame) => frame.at !== undefined);
3516
+ const last = audioFrames.toReversed().find((frame) => frame.at !== undefined);
3517
+ const durationMs = first?.at !== undefined && last?.at !== undefined ? last.at - first.at + (last.durationMs ?? 0) : undefined;
3518
+ const expectedDurationMs = audioFrames.length > 0 ? audioFrames.reduce((total, frame) => total + (frame.durationMs ?? 0), 0) : undefined;
3519
+ const timestampDriftMs = durationMs !== undefined && expectedDurationMs !== undefined ? Math.max(0, durationMs - expectedDurationMs) : undefined;
3520
+ const speechScores = inputAudioFrames.map(speechProbability);
3521
+ const speechFrames = speechScores.filter((score) => score >= 0.6).length;
3522
+ const silenceFrames = speechScores.filter((score) => score <= 0.35).length;
3523
+ const unknownSpeechFrames = Math.max(0, inputAudioFrames.length - speechFrames - silenceFrames);
3524
+ const speechRatio = inputAudioFrames.length === 0 ? 0 : speechFrames / inputAudioFrames.length;
3525
+ const silenceRatio = inputAudioFrames.length === 0 ? 0 : silenceFrames / inputAudioFrames.length;
3526
+ const levels = audioFrames.map((frame) => numericMetadata(frame, "level") ?? numericMetadata(frame, "rms") ?? numericMetadata(frame, "energy")).filter((value) => value !== undefined);
3527
+ const backpressureEvents = input.transport?.backpressureEvents ?? 0;
3528
+ const maxGapMs = input.maxGapMs;
3529
+ if (maxGapMs !== undefined && gapsMs.some((gap) => gap > maxGapMs)) {
3530
+ pushIssue(issues, "warning", "media.quality_gap", `Observed media gap above ${String(maxGapMs)}ms.`);
3531
+ }
3532
+ if (input.maxJitterMs !== undefined && jitterMs !== undefined && jitterMs > input.maxJitterMs) {
3533
+ pushIssue(issues, "warning", "media.quality_jitter", `Observed jitter ${String(jitterMs)}ms above ${String(input.maxJitterMs)}ms.`);
3534
+ }
3535
+ if (input.maxTimestampDriftMs !== undefined && timestampDriftMs !== undefined && timestampDriftMs > input.maxTimestampDriftMs) {
3536
+ pushIssue(issues, "warning", "media.quality_timestamp_drift", `Observed timestamp drift ${String(timestampDriftMs)}ms above ${String(input.maxTimestampDriftMs)}ms.`);
3537
+ }
3538
+ if (input.minSpeechRatio !== undefined && inputAudioFrames.length > 0 && speechRatio < input.minSpeechRatio) {
3539
+ pushIssue(issues, "warning", "media.quality_speech_ratio", `Observed speech ratio ${String(speechRatio)} below ${String(input.minSpeechRatio)}.`);
3540
+ }
3541
+ if (input.maxBackpressureEvents !== undefined && backpressureEvents > input.maxBackpressureEvents) {
3542
+ pushIssue(issues, "warning", "media.quality_backpressure", `Observed ${String(backpressureEvents)} backpressure event(s), above ${String(input.maxBackpressureEvents)}.`);
3543
+ }
3544
+ return {
3545
+ assistantAudioFrames: assistantAudioFrames.length,
3546
+ backpressureEvents,
3547
+ checkedAt: Date.now(),
3548
+ durationMs,
3549
+ gapCount: gapsMs.length,
3550
+ gapsMs,
3551
+ inputAudioFrames: inputAudioFrames.length,
3552
+ issues,
3553
+ jitterMs,
3554
+ levelAverage: average(levels),
3555
+ levelMax: max(levels),
3556
+ levelMin: min(levels),
3557
+ silenceFrames,
3558
+ silenceRatio,
3559
+ speechFrames,
3560
+ speechRatio,
3561
+ status: issues.some((issue) => issue.severity === "error") ? "fail" : issues.length > 0 ? "warn" : "pass",
3562
+ timestampDriftMs,
3563
+ totalFrames: frames.length,
3564
+ unknownSpeechFrames
3565
+ };
3566
+ };
3567
+ var buildMediaWebRTCStatsReport = (input = {}) => {
3568
+ const stats = input.stats ?? [];
3569
+ const issues = [];
3570
+ const inbound = stats.filter((stat) => stat.type === "inbound-rtp" && stringStat(stat, "kind") !== "video");
3571
+ const outbound = stats.filter((stat) => stat.type === "outbound-rtp" && stringStat(stat, "kind") !== "video");
3572
+ const candidatePairs = stats.filter((stat) => stat.type === "candidate-pair");
3573
+ const audioTracks = stats.filter((stat) => (stat.type === "track" || stat.type === "media-source") && stringStat(stat, "kind") === "audio");
3574
+ const activeCandidatePairs = candidatePairs.filter((stat) => booleanStat(stat, "selected") === true || booleanStat(stat, "nominated") === true || stringStat(stat, "state") === "succeeded").length;
3575
+ const liveAudioTracks = audioTracks.filter((stat) => stringStat(stat, "readyState") !== "ended" && stringStat(stat, "trackState") !== "ended" && booleanStat(stat, "ended") !== true).length;
3576
+ const endedAudioTracks = audioTracks.filter((stat) => stringStat(stat, "readyState") === "ended" || stringStat(stat, "trackState") === "ended" || booleanStat(stat, "ended") === true).length;
3577
+ const inboundPackets = inbound.reduce((total, stat) => total + (numericStat(stat, "packetsReceived") ?? 0), 0);
3578
+ const outboundPackets = outbound.reduce((total, stat) => total + (numericStat(stat, "packetsSent") ?? 0), 0);
3579
+ const packetsLost = [...inbound, ...outbound].reduce((total, stat) => total + Math.max(0, numericStat(stat, "packetsLost") ?? 0), 0);
3580
+ const packetLossDenominator = inboundPackets + packetsLost;
3581
+ const packetLossRatio = packetLossDenominator === 0 ? 0 : packetsLost / packetLossDenominator;
3582
+ const bytesReceived = inbound.reduce((total, stat) => total + (numericStat(stat, "bytesReceived") ?? 0), 0);
3583
+ const bytesSent = outbound.reduce((total, stat) => total + (numericStat(stat, "bytesSent") ?? 0), 0);
3584
+ const roundTripTimeMs = max(candidatePairs.map((stat) => secondsToMs(numericStat(stat, "currentRoundTripTime") ?? numericStat(stat, "roundTripTime"))).filter((value) => value !== undefined));
3585
+ const jitterMs = max([...inbound, ...outbound].map((stat) => secondsToMs(numericStat(stat, "jitter"))).filter((value) => value !== undefined));
3586
+ const jitterBufferDelayMs = max(inbound.map((stat) => {
3587
+ const delay = numericStat(stat, "jitterBufferDelay");
3588
+ const emitted = numericStat(stat, "jitterBufferEmittedCount");
3589
+ return delay !== undefined && emitted !== undefined && emitted > 0 ? delay / emitted * 1000 : undefined;
3590
+ }).filter((value) => value !== undefined));
3591
+ const audioLevels = audioTracks.map((stat) => numericStat(stat, "audioLevel")).filter((value) => value !== undefined);
3592
+ if (input.requireConnectedCandidatePair && candidatePairs.length > 0 && activeCandidatePairs === 0) {
3593
+ pushIssue(issues, "error", "media.webrtc_candidate_pair_missing", "No active WebRTC candidate pair was observed.");
3594
+ }
3595
+ if (input.requireLiveAudioTrack && liveAudioTracks === 0) {
3596
+ pushIssue(issues, "error", "media.webrtc_audio_track_missing", "No live WebRTC audio track was observed.");
3597
+ }
3598
+ if (input.maxPacketLossRatio !== undefined && packetLossRatio > input.maxPacketLossRatio) {
3599
+ pushIssue(issues, "warning", "media.webrtc_packet_loss", `Observed WebRTC packet loss ratio ${String(packetLossRatio)} above ${String(input.maxPacketLossRatio)}.`);
3600
+ }
3601
+ if (input.maxRoundTripTimeMs !== undefined && roundTripTimeMs !== undefined && roundTripTimeMs > input.maxRoundTripTimeMs) {
3602
+ pushIssue(issues, "warning", "media.webrtc_round_trip_time", `Observed WebRTC RTT ${String(roundTripTimeMs)}ms above ${String(input.maxRoundTripTimeMs)}ms.`);
3603
+ }
3604
+ if (input.maxJitterMs !== undefined && jitterMs !== undefined && jitterMs > input.maxJitterMs) {
3605
+ pushIssue(issues, "warning", "media.webrtc_jitter", `Observed WebRTC jitter ${String(jitterMs)}ms above ${String(input.maxJitterMs)}ms.`);
3606
+ }
3607
+ return {
3608
+ activeCandidatePairs,
3609
+ audioLevelAverage: average(audioLevels),
3610
+ bytesReceived,
3611
+ bytesSent,
3612
+ checkedAt: Date.now(),
3613
+ endedAudioTracks,
3614
+ inboundPackets,
3615
+ issues,
3616
+ jitterBufferDelayMs,
3617
+ jitterMs,
3618
+ liveAudioTracks,
3619
+ outboundPackets,
3620
+ packetLossRatio,
3621
+ packetsLost,
3622
+ roundTripTimeMs,
3623
+ status: issues.some((issue) => issue.severity === "error") ? "fail" : issues.length > 0 ? "warn" : "pass",
3624
+ totalStats: stats.length
3625
+ };
3626
+ };
3627
+ var collectMediaWebRTCStats = async (input) => {
3628
+ const report = await input.peerConnection.getStats(input.selector ?? null);
3629
+ return [...report.values()].map(normalizeWebRTCStat);
3630
+ };
3631
+ var collectMediaWebRTCStatsReport = async (input) => {
3632
+ const stats = await collectMediaWebRTCStats(input);
3633
+ return buildMediaWebRTCStatsReport({
3634
+ ...input,
3635
+ stats
3636
+ });
3637
+ };
3638
+ var buildMediaPipelineCalibrationReport = (input = {}) => {
3639
+ const frames = input.frames ?? [];
3640
+ const issues = [];
3641
+ const inputFrames = frames.filter((frame) => frame.kind === "input-audio");
3642
+ const assistantFrames = frames.filter((frame) => frame.kind === "assistant-audio");
3643
+ const turnCommitFrames = frames.filter((frame) => frame.kind === "turn-commit");
3644
+ const interruptionFrameRecords = frames.filter((frame) => frame.kind === "interruption");
3645
+ const traceLinkedFrames = frames.filter((frame) => frame.traceEventId).length;
3646
+ const backpressureFrames = frames.filter((frame) => Boolean(frame.metadata?.backpressure)).length;
3647
+ const audioLatencies = assistantFrames.map((frame) => frame.latencyMs).filter((latency) => typeof latency === "number");
3648
+ const firstAudioLatencyMs = audioLatencies.length > 0 ? Math.min(...audioLatencies) : undefined;
3649
+ const jitterValues = frames.map((frame) => numericMetadata(frame, "jitterMs")).filter((value) => value !== undefined);
3650
+ const jitterMs = jitterValues.length > 0 ? Math.max(...jitterValues) : undefined;
3651
+ const inputFormat = input.inputFormat ?? inputFrames.find((frame) => frame.format)?.format;
3652
+ const outputFormat = input.outputFormat ?? assistantFrames.find((frame) => frame.format)?.format;
3653
+ const resamplingRequired = Boolean(input.expectedInputFormat && inputFormat && inputFormat.sampleRateHz !== input.expectedInputFormat.sampleRateHz) || Boolean(input.expectedOutputFormat && outputFormat && outputFormat.sampleRateHz !== input.expectedOutputFormat.sampleRateHz);
3654
+ const resamplingTargetHz = resamplingRequired && input.expectedInputFormat ? input.expectedInputFormat.sampleRateHz : resamplingRequired ? input.expectedOutputFormat?.sampleRateHz : undefined;
3655
+ if (inputFrames.length === 0) {
3656
+ pushIssue(issues, "warning", "media.input_audio_missing", "No input audio frames were observed.");
3657
+ }
3658
+ if (assistantFrames.length === 0) {
3659
+ pushIssue(issues, "warning", "media.assistant_audio_missing", "No assistant audio frames were observed.");
3660
+ }
3661
+ if (input.expectedInputFormat && inputFormat && !formatMatches(inputFormat, input.expectedInputFormat)) {
3662
+ pushIssue(issues, inputFormat.sampleRateHz === input.expectedInputFormat.sampleRateHz ? "warning" : "error", "media.input_format_mismatch", `Input format ${formatLabel(inputFormat)} does not match expected ${formatLabel(input.expectedInputFormat)}.`);
3663
+ }
3664
+ if (input.expectedOutputFormat && outputFormat && !formatMatches(outputFormat, input.expectedOutputFormat)) {
3665
+ pushIssue(issues, outputFormat.sampleRateHz === input.expectedOutputFormat.sampleRateHz ? "warning" : "error", "media.output_format_mismatch", `Output format ${formatLabel(outputFormat)} does not match expected ${formatLabel(input.expectedOutputFormat)}.`);
3666
+ }
3667
+ if (firstAudioLatencyMs !== undefined && input.maxFirstAudioLatencyMs !== undefined && firstAudioLatencyMs > input.maxFirstAudioLatencyMs) {
3668
+ pushIssue(issues, "error", "media.first_audio_latency", `First audio latency ${String(firstAudioLatencyMs)}ms exceeds budget ${String(input.maxFirstAudioLatencyMs)}ms.`);
3669
+ }
3670
+ if (jitterMs !== undefined && input.maxJitterMs !== undefined && jitterMs > input.maxJitterMs) {
3671
+ pushIssue(issues, "warning", "media.jitter", `Media jitter ${String(jitterMs)}ms exceeds budget ${String(input.maxJitterMs)}ms.`);
3672
+ }
3673
+ if (input.maxBackpressureFrames !== undefined && backpressureFrames > input.maxBackpressureFrames) {
3674
+ pushIssue(issues, "warning", "media.backpressure", `Backpressure frame count ${String(backpressureFrames)} exceeds budget ${String(input.maxBackpressureFrames)}.`);
3675
+ }
3676
+ if (input.requireInterruptionFrame && interruptionFrameRecords.length === 0) {
3677
+ pushIssue(issues, "warning", "media.interruption_missing", "No interruption frame was observed.");
3678
+ }
3679
+ if (input.requireTraceEvidence && traceLinkedFrames === 0) {
3680
+ pushIssue(issues, "warning", "media.trace_evidence_missing", "No media frames were linked to trace evidence.");
3681
+ }
3682
+ return {
3683
+ assistantAudioFrames: assistantFrames.length,
3684
+ backpressureFrames,
3685
+ checkedAt: Date.now(),
3686
+ firstAudioLatencyMs,
3687
+ inputAudioFrames: inputFrames.length,
3688
+ inputFormat,
3689
+ interruptionFrames: interruptionFrameRecords.length,
3690
+ issues,
3691
+ jitterMs,
3692
+ outputFormat,
3693
+ resamplingRequired,
3694
+ resamplingTargetHz,
3695
+ status: issues.some((issue) => issue.severity === "error") ? "fail" : issues.length > 0 ? "warn" : "pass",
3696
+ surface: input.surface ?? "media-pipeline",
3697
+ traceLinkedFrames,
3698
+ turnCommitFrames: turnCommitFrames.length
3699
+ };
3700
+ };
3701
+
3702
+ // src/client/browserMedia.ts
3703
+ var DEFAULT_BROWSER_MEDIA_PATH = "/api/voice/browser-media";
3704
+ var DEFAULT_BROWSER_MEDIA_INTERVAL_MS = 5000;
3705
+ var resolvePeerConnection = async (options) => options.peerConnection ?? await options.getPeerConnection?.() ?? null;
3706
+ var postBrowserMediaReport = async (payload, options) => {
3707
+ const requestFetch = options.fetch ?? globalThis.fetch;
3708
+ if (!requestFetch) {
3709
+ return;
3710
+ }
3711
+ await requestFetch(options.path ?? DEFAULT_BROWSER_MEDIA_PATH, {
3712
+ body: JSON.stringify(payload),
3713
+ headers: {
3714
+ "Content-Type": "application/json"
3715
+ },
3716
+ keepalive: true,
3717
+ method: "POST"
3718
+ });
3719
+ };
3720
+ var createVoiceBrowserMediaReporter = (options) => {
3721
+ let interval = null;
3722
+ const reportOnce = async () => {
3723
+ const peerConnection = await resolvePeerConnection(options);
3724
+ if (!peerConnection) {
3725
+ return;
3726
+ }
3727
+ const report = await collectMediaWebRTCStatsReport({
3728
+ ...options,
3729
+ peerConnection
3730
+ });
3731
+ const payload = {
3732
+ at: Date.now(),
3733
+ report,
3734
+ scenarioId: options.getScenarioId?.() ?? null,
3735
+ sessionId: options.getSessionId?.() ?? null
3736
+ };
3737
+ options.onReport?.(payload);
3738
+ await postBrowserMediaReport(payload, options);
3739
+ return payload;
3740
+ };
3741
+ const run = () => {
3742
+ reportOnce().catch((error) => {
3743
+ options.onError?.(error);
3744
+ });
3745
+ };
3746
+ const stop = () => {
3747
+ if (interval) {
3748
+ clearInterval(interval);
3749
+ interval = null;
3750
+ }
3751
+ };
3752
+ return {
3753
+ close: stop,
3754
+ reportOnce,
3755
+ start: () => {
3756
+ if (interval) {
3757
+ return;
3758
+ }
3759
+ run();
3760
+ interval = setInterval(run, options.intervalMs ?? DEFAULT_BROWSER_MEDIA_INTERVAL_MS);
3761
+ },
3762
+ stop
3763
+ };
3764
+ };
3765
+
3360
3766
  // src/client/connection.ts
3361
3767
  var WS_OPEN = 1;
3362
3768
  var WS_CLOSED = 3;
@@ -3789,12 +4195,18 @@ var createVoiceStreamStore = () => {
3789
4195
  var createVoiceStream = (path, options = {}) => {
3790
4196
  const connection = createVoiceConnection(path, options);
3791
4197
  const store = createVoiceStreamStore();
4198
+ const browserMediaReporter = options.browserMedia && typeof window !== "undefined" ? createVoiceBrowserMediaReporter({
4199
+ ...options.browserMedia,
4200
+ getScenarioId: () => options.browserMedia ? options.browserMedia.getScenarioId?.() ?? connection.getScenarioId() : connection.getScenarioId(),
4201
+ getSessionId: () => options.browserMedia ? options.browserMedia.getSessionId?.() ?? connection.getSessionId() : connection.getSessionId()
4202
+ }) : null;
3792
4203
  const subscribers = new Set;
3793
4204
  const start = (input) => Promise.resolve().then(() => {
3794
4205
  if (!input?.sessionId && !input?.scenarioId) {
3795
4206
  return;
3796
4207
  }
3797
4208
  connection.start(input);
4209
+ browserMediaReporter?.start();
3798
4210
  });
3799
4211
  const notify = () => {
3800
4212
  subscribers.forEach((subscriber) => subscriber());
@@ -3836,6 +4248,7 @@ var createVoiceStream = (path, options = {}) => {
3836
4248
  },
3837
4249
  close() {
3838
4250
  unsubscribeConnection();
4251
+ browserMediaReporter?.close();
3839
4252
  connection.close();
3840
4253
  store.dispatch({ type: "disconnected" });
3841
4254
  notify();