@absolutejs/voice 0.0.22-beta.464 → 0.0.22-beta.465

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.
@@ -4261,934 +4261,12 @@ var serverMessageToAction = (message) => {
4261
4261
  }
4262
4262
  };
4263
4263
 
4264
- // node_modules/@absolutejs/media/dist/index.js
4265
- import { mkdir, writeFile } from "fs/promises";
4266
- import { join } from "path";
4267
- var formatLabel = (format) => `${format.container}/${format.encoding}/${String(format.sampleRateHz)}hz/${String(format.channels)}ch`;
4268
- var formatMatches = (actual, expected) => actual.container === expected.container && actual.encoding === expected.encoding && actual.sampleRateHz === expected.sampleRateHz && actual.channels === expected.channels;
4269
- var pushIssue = (issues, severity, code, message) => {
4270
- issues.push({ code, message, severity });
4271
- };
4272
- var numericMetadata = (frame, key) => {
4273
- const value = frame.metadata?.[key];
4274
- return typeof value === "number" && Number.isFinite(value) ? value : undefined;
4275
- };
4276
- var average = (values) => values.length === 0 ? undefined : values.reduce((total, value) => total + value, 0) / values.length;
4277
- var max = (values) => values.length === 0 ? undefined : Math.max(...values);
4278
- var min = (values) => values.length === 0 ? undefined : Math.min(...values);
4279
- var numericStat = (stat, key) => {
4280
- const value = stat[key];
4281
- return typeof value === "number" && Number.isFinite(value) ? value : undefined;
4282
- };
4283
- var booleanStat = (stat, key) => {
4284
- const value = stat[key];
4285
- return typeof value === "boolean" ? value : undefined;
4286
- };
4287
- var stringStat = (stat, key) => {
4288
- const value = stat[key];
4289
- return typeof value === "string" ? value : undefined;
4290
- };
4291
- var statKey = (stat) => String(stat.id ?? stringStat(stat, "ssrc") ?? numericStat(stat, "ssrc") ?? stringStat(stat, "trackIdentifier") ?? stringStat(stat, "mid") ?? "unknown");
4292
- var secondsToMs = (value) => value === undefined ? undefined : value * 1000;
4293
- var DEFAULT_TELEPHONY_FORMAT = {
4294
- channels: 1,
4295
- container: "raw",
4296
- encoding: "mulaw",
4297
- sampleRateHz: 8000
4298
- };
4299
- var bytesToBase64 = (audio) => {
4300
- const bytes = audio instanceof ArrayBuffer ? new Uint8Array(audio) : new Uint8Array(audio.buffer, audio.byteOffset, audio.byteLength);
4301
- return Buffer.from(bytes).toString("base64");
4302
- };
4303
- var base64ToBytes = (value) => new Uint8Array(Buffer.from(value, "base64"));
4304
- var unknownRecord = (value) => value && typeof value === "object" ? value : {};
4305
- var firstString = (records, keys) => {
4306
- for (const record of records) {
4307
- for (const key of keys) {
4308
- const value = record[key];
4309
- if (typeof value === "string" && value.length > 0) {
4310
- return value;
4311
- }
4312
- if (typeof value === "number" && Number.isFinite(value)) {
4313
- return String(value);
4314
- }
4315
- }
4316
- }
4317
- return;
4318
- };
4319
- var firstNumber = (records, keys) => {
4320
- for (const record of records) {
4321
- for (const key of keys) {
4322
- const value = record[key];
4323
- if (typeof value === "number" && Number.isFinite(value)) {
4324
- return value;
4325
- }
4326
- if (typeof value === "string") {
4327
- const parsed = Number(value);
4328
- if (Number.isFinite(parsed)) {
4329
- return parsed;
4330
- }
4331
- }
4332
- }
4333
- }
4334
- return;
4335
- };
4336
- var telephonyDirection = (track) => {
4337
- const normalized = track?.toLowerCase();
4338
- if (!normalized) {
4339
- return "unknown";
4340
- }
4341
- if (normalized.includes("inbound") || normalized.includes("caller") || normalized.includes("in")) {
4342
- return "inbound";
4343
- }
4344
- if (normalized.includes("outbound") || normalized.includes("assistant") || normalized.includes("out")) {
4345
- return "outbound";
4346
- }
4347
- return "unknown";
4348
- };
4349
- var telephonyFrameKind = (direction) => direction === "outbound" ? "assistant-audio" : "input-audio";
4350
- var telephonyEventKind = (envelope) => {
4351
- const raw = firstString([envelope], ["event", "type", "eventType"]) ?? firstString([unknownRecord(envelope.message)], ["event", "type"]);
4352
- const normalized = raw?.toLowerCase().replace(/[_\s-]+/g, "-");
4353
- if (!normalized) {
4354
- return "unknown";
4355
- }
4356
- if (normalized.includes("connected")) {
4357
- return "connected";
4358
- }
4359
- if (normalized.includes("start")) {
4360
- return "start";
4361
- }
4362
- if (normalized.includes("media")) {
4363
- return "media";
4364
- }
4365
- if (normalized.includes("stop") || normalized.includes("closed")) {
4366
- return "stop";
4367
- }
4368
- if (normalized.includes("error") || normalized.includes("failed")) {
4369
- return "error";
4370
- }
4371
- return "unknown";
4372
- };
4373
- var normalizeWebRTCStat = (stat) => {
4374
- const sample = {};
4375
- for (const [key, value] of Object.entries(stat)) {
4376
- if (value === null || typeof value === "boolean" || typeof value === "number" || typeof value === "string") {
4377
- sample[key] = value;
4378
- }
4379
- }
4380
- return sample;
4381
- };
4382
- var parseTelephonyMediaFrame = (input) => {
4383
- const envelope = input.envelope;
4384
- const media = unknownRecord(envelope.media);
4385
- const payload = firstString([media, envelope], ["payload", "audio", "data"]) ?? firstString([unknownRecord(envelope.message)], ["payload"]);
4386
- if (!payload) {
4387
- return;
4388
- }
4389
- const carrier = input.carrier ?? firstString([envelope], ["provider"]) ?? "telephony";
4390
- const streamId = firstString([media, envelope], ["streamSid", "stream_id", "streamId", "streamId", "callSid", "call_id"]);
4391
- const sequenceNumber = firstString([media, envelope], ["sequenceNumber", "sequence_number", "chunk"]);
4392
- const track = firstString([media, envelope], ["track", "direction"]);
4393
- const direction = telephonyDirection(track);
4394
- const timestamp = firstNumber([media, envelope], ["timestamp", "time", "startedAt"]);
4395
- return {
4396
- at: timestamp,
4397
- audio: base64ToBytes(payload),
4398
- format: input.format ?? DEFAULT_TELEPHONY_FORMAT,
4399
- id: [
4400
- carrier,
4401
- streamId ?? input.sessionId ?? "stream",
4402
- sequenceNumber ?? timestamp ?? Date.now()
4403
- ].join(":"),
4404
- kind: telephonyFrameKind(direction),
4405
- metadata: {
4406
- carrier,
4407
- direction,
4408
- event: firstString([envelope], ["event", "type"]),
4409
- sequenceNumber,
4410
- streamId,
4411
- track
4412
- },
4413
- sessionId: input.sessionId ?? streamId,
4414
- source: "telephony"
4415
- };
4416
- };
4417
- var serializeTelephonyMediaFrame = (input) => {
4418
- const carrier = input.carrier ?? input.frame.metadata?.carrier ?? "telephony";
4419
- const streamId = input.streamId ?? (typeof input.frame.metadata?.streamId === "string" ? input.frame.metadata.streamId : input.frame.sessionId);
4420
- const sequenceNumber = input.sequenceNumber ?? (typeof input.frame.metadata?.sequenceNumber === "string" || typeof input.frame.metadata?.sequenceNumber === "number" ? input.frame.metadata.sequenceNumber : undefined);
4421
- const direction = input.frame.kind === "assistant-audio" ? "outbound" : "inbound";
4422
- const payload = input.frame.audio ? bytesToBase64(input.frame.audio) : "";
4423
- if (carrier === "twilio") {
4424
- return {
4425
- event: "media",
4426
- sequenceNumber,
4427
- streamSid: streamId,
4428
- media: {
4429
- payload,
4430
- timestamp: input.frame.at,
4431
- track: direction
4432
- }
4433
- };
4434
- }
4435
- if (carrier === "telnyx") {
4436
- return {
4437
- event: "media",
4438
- stream_id: streamId,
4439
- sequence_number: sequenceNumber,
4440
- media: {
4441
- payload,
4442
- timestamp: input.frame.at,
4443
- track: direction
4444
- }
4445
- };
4446
- }
4447
- if (carrier === "plivo") {
4448
- return {
4449
- event: "media",
4450
- streamId,
4451
- sequenceNumber,
4452
- media: {
4453
- payload,
4454
- timestamp: input.frame.at,
4455
- track: direction
4456
- }
4457
- };
4458
- }
4459
- return {
4460
- event: "media",
4461
- provider: carrier,
4462
- sequenceNumber,
4463
- streamId,
4464
- media: {
4465
- payload,
4466
- timestamp: input.frame.at,
4467
- track: direction
4468
- }
4469
- };
4470
- };
4471
- var createTelephonyMediaSerializer = (input) => {
4472
- const format = input.format ?? DEFAULT_TELEPHONY_FORMAT;
4473
- return {
4474
- carrier: input.carrier,
4475
- format,
4476
- parse: (envelope) => parseTelephonyMediaFrame({
4477
- carrier: input.carrier,
4478
- envelope,
4479
- format,
4480
- sessionId: input.sessionId ?? input.streamId
4481
- }),
4482
- serialize: (frame) => serializeTelephonyMediaFrame({
4483
- carrier: input.carrier,
4484
- frame,
4485
- streamId: input.streamId
4486
- })
4487
- };
4488
- };
4489
- var parseTelephonyStreamEvent = (input) => {
4490
- const envelope = input.envelope;
4491
- const media = unknownRecord(envelope.media);
4492
- const start = unknownRecord(envelope.start);
4493
- const stop = unknownRecord(envelope.stop);
4494
- const errorRecord = unknownRecord(envelope.error);
4495
- const kind = telephonyEventKind(envelope);
4496
- const carrier = input.carrier ?? firstString([envelope], ["provider", "carrier"]) ?? "telephony";
4497
- const frame = kind === "media" ? parseTelephonyMediaFrame({
4498
- carrier,
4499
- envelope,
4500
- format: input.format,
4501
- sessionId: input.sessionId
4502
- }) : undefined;
4503
- const streamId = firstString([media, start, stop, envelope], ["streamSid", "stream_id", "streamId", "callSid", "call_id"]) ?? input.sessionId;
4504
- const sequenceNumber = firstString([media, envelope], ["sequenceNumber", "sequence_number", "chunk"]);
4505
- const track = firstString([media, envelope], ["track", "direction"]);
4506
- return {
4507
- audioBytes: frame?.audio ? frame.audio instanceof ArrayBuffer ? frame.audio.byteLength : frame.audio.byteLength : 0,
4508
- at: frame?.at ?? firstNumber([media, start, stop, envelope], ["timestamp", "time", "startedAt"]),
4509
- carrier,
4510
- direction: telephonyDirection(track),
4511
- error: firstString([errorRecord, envelope], ["message", "error", "reason"]),
4512
- kind,
4513
- sequenceNumber,
4514
- streamId
4515
- };
4516
- };
4517
- var buildMediaTelephonyStreamLifecycleReport = (input = {}) => {
4518
- const envelopes = input.envelopes ?? [];
4519
- const events = envelopes.map((envelope) => parseTelephonyStreamEvent({
4520
- carrier: input.carrier,
4521
- envelope
4522
- }));
4523
- const issues = [];
4524
- const startedIndex = events.findIndex((event) => event.kind === "start");
4525
- const firstMediaIndex = events.findIndex((event) => event.kind === "media");
4526
- const stoppedIndex = events.findIndex((event) => event.kind === "stop");
4527
- const started = startedIndex >= 0;
4528
- const stopped = stoppedIndex >= 0;
4529
- const mediaEvents = events.filter((event) => event.kind === "media");
4530
- const audioBytes = events.reduce((total, event) => total + event.audioBytes, 0);
4531
- const minAudioBytes = input.minAudioBytes ?? 1;
4532
- const streamIds = Array.from(new Set(events.map((event) => event.streamId).filter(Boolean)));
4533
- if ((input.requireStart ?? true) && !started) {
4534
- pushIssue(issues, "error", "media.telephony_missing_start", "Telephony media stream did not include a start event.");
4535
- }
4536
- if ((input.requireMedia ?? true) && mediaEvents.length === 0) {
4537
- pushIssue(issues, "error", "media.telephony_missing_media", "Telephony media stream did not include media payload events.");
4538
- }
4539
- if ((input.requireStop ?? true) && !stopped) {
4540
- pushIssue(issues, input.maxMissingStop === false ? "warning" : "error", "media.telephony_missing_stop", "Telephony media stream did not include a stop event.");
4541
- }
4542
- if (started && firstMediaIndex >= 0 && firstMediaIndex < startedIndex) {
4543
- pushIssue(issues, "error", "media.telephony_media_before_start", "Telephony media payload arrived before the stream start event.");
4544
- }
4545
- if (stopped && firstMediaIndex >= 0 && stoppedIndex < firstMediaIndex) {
4546
- pushIssue(issues, "error", "media.telephony_stop_before_media", "Telephony media stream stopped before any media payload arrived.");
4547
- }
4548
- if (mediaEvents.length > 0 && audioBytes < minAudioBytes) {
4549
- pushIssue(issues, "error", "media.telephony_no_audio_bytes", `Telephony media stream parsed ${String(audioBytes)} audio byte(s), below required ${String(minAudioBytes)}.`);
4550
- }
4551
- for (const event of events) {
4552
- if (event.kind === "error") {
4553
- pushIssue(issues, "error", "media.telephony_stream_error", event.error ?? "Telephony media stream emitted an error event.");
4554
- }
4555
- }
4556
- return {
4557
- audioBytes,
4558
- carrier: input.carrier,
4559
- checkedAt: Date.now(),
4560
- events,
4561
- issues,
4562
- mediaEvents: mediaEvents.length,
4563
- started,
4564
- status: issues.some((issue) => issue.severity === "error") ? "fail" : issues.length > 0 ? "warn" : "pass",
4565
- stopped,
4566
- streamIds
4567
- };
4568
- };
4569
- var buildMediaResamplingPlan = (input) => {
4570
- const required = !formatMatches(input.inputFormat, input.outputFormat);
4571
- return {
4572
- inputFormat: input.inputFormat,
4573
- outputFormat: input.outputFormat,
4574
- ratio: input.outputFormat.sampleRateHz / input.inputFormat.sampleRateHz,
4575
- required,
4576
- status: input.inputFormat.container === input.outputFormat.container && input.inputFormat.encoding === input.outputFormat.encoding && input.inputFormat.channels === input.outputFormat.channels ? "pass" : "warn"
4577
- };
4578
- };
4579
- var speechProbability = (frame) => {
4580
- if (frame.metadata?.isSpeech === true) {
4581
- return 1;
4582
- }
4583
- if (frame.metadata?.isSpeech === false) {
4584
- return 0;
4585
- }
4586
- for (const key of ["speechProbability", "voiceProbability", "rms", "energy"]) {
4587
- const value = numericMetadata(frame, key);
4588
- if (value !== undefined) {
4589
- return value;
4590
- }
4591
- }
4592
- return 0;
4593
- };
4594
- var buildMediaVadReport = (input = {}) => {
4595
- const frames = (input.frames ?? []).filter((frame) => frame.kind === "input-audio");
4596
- const speechStartThreshold = input.speechStartThreshold ?? 0.6;
4597
- const speechEndThreshold = input.speechEndThreshold ?? 0.35;
4598
- const minSpeechFrames = input.minSpeechFrames ?? 1;
4599
- const maxSilenceFrames = input.maxSilenceFrames ?? 1;
4600
- const segments = [];
4601
- let activeFrames = [];
4602
- let silenceFrames = 0;
4603
- const closeSegment = () => {
4604
- if (activeFrames.length < minSpeechFrames) {
4605
- activeFrames = [];
4606
- silenceFrames = 0;
4607
- return;
4608
- }
4609
- const first = activeFrames[0];
4610
- const last = activeFrames.at(-1);
4611
- if (!first) {
4612
- return;
4613
- }
4614
- segments.push({
4615
- durationMs: first.at !== undefined && last?.at !== undefined ? last.at - first.at + (last.durationMs ?? 0) : undefined,
4616
- endAt: last?.at !== undefined ? last.at + (last.durationMs ?? 0) : undefined,
4617
- frameCount: activeFrames.length,
4618
- segmentId: `vad:${String(segments.length + 1)}`,
4619
- sessionId: first.sessionId,
4620
- startAt: first.at,
4621
- turnId: first.turnId
4622
- });
4623
- activeFrames = [];
4624
- silenceFrames = 0;
4625
- };
4626
- for (const frame of frames) {
4627
- const probability = speechProbability(frame);
4628
- if (activeFrames.length === 0) {
4629
- if (probability >= speechStartThreshold) {
4630
- activeFrames.push(frame);
4631
- }
4632
- continue;
4633
- }
4634
- activeFrames.push(frame);
4635
- if (probability <= speechEndThreshold) {
4636
- silenceFrames += 1;
4637
- } else {
4638
- silenceFrames = 0;
4639
- }
4640
- if (silenceFrames > maxSilenceFrames) {
4641
- closeSegment();
4642
- }
4643
- }
4644
- closeSegment();
4645
- return {
4646
- checkedAt: Date.now(),
4647
- inputAudioFrames: frames.length,
4648
- segments,
4649
- status: frames.length === 0 ? "warn" : "pass"
4650
- };
4651
- };
4652
- var buildMediaInterruptionReport = (input = {}) => {
4653
- const issues = [];
4654
- const interruptionFrames = (input.frames ?? []).filter((frame) => frame.kind === "interruption");
4655
- const latenciesMs = interruptionFrames.map((frame) => frame.latencyMs).filter((latency) => typeof latency === "number");
4656
- const maxInterruptionLatencyMs = input.maxInterruptionLatencyMs;
4657
- if (interruptionFrames.length === 0) {
4658
- pushIssue(issues, "warning", "media.interruption_missing", "No interruption frame was observed.");
4659
- }
4660
- if (maxInterruptionLatencyMs !== undefined && latenciesMs.some((latency) => latency > maxInterruptionLatencyMs)) {
4661
- pushIssue(issues, "error", "media.interruption_latency", `Interruption latency exceeded ${String(maxInterruptionLatencyMs)}ms.`);
4662
- }
4663
- return {
4664
- checkedAt: Date.now(),
4665
- interruptionFrames: interruptionFrames.length,
4666
- issues,
4667
- latenciesMs,
4668
- status: issues.some((issue) => issue.severity === "error") ? "fail" : issues.length > 0 ? "warn" : "pass"
4669
- };
4670
- };
4671
- var buildMediaQualityReport = (input = {}) => {
4672
- const frames = [...input.frames ?? []].sort((a, b) => (a.at ?? 0) - (b.at ?? 0));
4673
- const audioFrames = frames.filter((frame) => frame.kind === "input-audio" || frame.kind === "assistant-audio");
4674
- const inputAudioFrames = frames.filter((frame) => frame.kind === "input-audio");
4675
- const assistantAudioFrames = frames.filter((frame) => frame.kind === "assistant-audio");
4676
- const issues = [];
4677
- const gapsMs = [];
4678
- for (const [index, frame] of audioFrames.entries()) {
4679
- const previous = audioFrames[index - 1];
4680
- if (previous?.at === undefined || frame.at === undefined || previous.durationMs === undefined) {
4681
- continue;
4682
- }
4683
- const gap = frame.at - (previous.at + previous.durationMs);
4684
- if (gap > 0) {
4685
- gapsMs.push(gap);
4686
- }
4687
- }
4688
- const jitterMs = audioFrames.map((frame) => numericMetadata(frame, "jitterMs")).filter((value) => value !== undefined).at(-1) ?? max(gapsMs);
4689
- const first = audioFrames.find((frame) => frame.at !== undefined);
4690
- const last = audioFrames.toReversed().find((frame) => frame.at !== undefined);
4691
- const durationMs = first?.at !== undefined && last?.at !== undefined ? last.at - first.at + (last.durationMs ?? 0) : undefined;
4692
- const expectedDurationMs = audioFrames.length > 0 ? audioFrames.reduce((total, frame) => total + (frame.durationMs ?? 0), 0) : undefined;
4693
- const timestampDriftMs = durationMs !== undefined && expectedDurationMs !== undefined ? Math.max(0, durationMs - expectedDurationMs) : undefined;
4694
- const speechScores = inputAudioFrames.map(speechProbability);
4695
- const speechFrames = speechScores.filter((score) => score >= 0.6).length;
4696
- const silenceFrames = speechScores.filter((score) => score <= 0.35).length;
4697
- const unknownSpeechFrames = Math.max(0, inputAudioFrames.length - speechFrames - silenceFrames);
4698
- const speechRatio = inputAudioFrames.length === 0 ? 0 : speechFrames / inputAudioFrames.length;
4699
- const silenceRatio = inputAudioFrames.length === 0 ? 0 : silenceFrames / inputAudioFrames.length;
4700
- const levels = audioFrames.map((frame) => numericMetadata(frame, "level") ?? numericMetadata(frame, "rms") ?? numericMetadata(frame, "energy")).filter((value) => value !== undefined);
4701
- const backpressureEvents = input.transport?.backpressureEvents ?? 0;
4702
- const maxGapMs = input.maxGapMs;
4703
- if (maxGapMs !== undefined && gapsMs.some((gap) => gap > maxGapMs)) {
4704
- pushIssue(issues, "warning", "media.quality_gap", `Observed media gap above ${String(maxGapMs)}ms.`);
4705
- }
4706
- if (input.maxJitterMs !== undefined && jitterMs !== undefined && jitterMs > input.maxJitterMs) {
4707
- pushIssue(issues, "warning", "media.quality_jitter", `Observed jitter ${String(jitterMs)}ms above ${String(input.maxJitterMs)}ms.`);
4708
- }
4709
- if (input.maxTimestampDriftMs !== undefined && timestampDriftMs !== undefined && timestampDriftMs > input.maxTimestampDriftMs) {
4710
- pushIssue(issues, "warning", "media.quality_timestamp_drift", `Observed timestamp drift ${String(timestampDriftMs)}ms above ${String(input.maxTimestampDriftMs)}ms.`);
4711
- }
4712
- if (input.minSpeechRatio !== undefined && inputAudioFrames.length > 0 && speechRatio < input.minSpeechRatio) {
4713
- pushIssue(issues, "warning", "media.quality_speech_ratio", `Observed speech ratio ${String(speechRatio)} below ${String(input.minSpeechRatio)}.`);
4714
- }
4715
- if (input.maxBackpressureEvents !== undefined && backpressureEvents > input.maxBackpressureEvents) {
4716
- pushIssue(issues, "warning", "media.quality_backpressure", `Observed ${String(backpressureEvents)} backpressure event(s), above ${String(input.maxBackpressureEvents)}.`);
4717
- }
4718
- return {
4719
- assistantAudioFrames: assistantAudioFrames.length,
4720
- backpressureEvents,
4721
- checkedAt: Date.now(),
4722
- durationMs,
4723
- gapCount: gapsMs.length,
4724
- gapsMs,
4725
- inputAudioFrames: inputAudioFrames.length,
4726
- issues,
4727
- jitterMs,
4728
- levelAverage: average(levels),
4729
- levelMax: max(levels),
4730
- levelMin: min(levels),
4731
- silenceFrames,
4732
- silenceRatio,
4733
- speechFrames,
4734
- speechRatio,
4735
- status: issues.some((issue) => issue.severity === "error") ? "fail" : issues.length > 0 ? "warn" : "pass",
4736
- timestampDriftMs,
4737
- totalFrames: frames.length,
4738
- unknownSpeechFrames
4739
- };
4740
- };
4741
- var buildMediaWebRTCStatsReport = (input = {}) => {
4742
- const stats = input.stats ?? [];
4743
- const issues = [];
4744
- const inbound = stats.filter((stat) => stat.type === "inbound-rtp" && stringStat(stat, "kind") !== "video");
4745
- const outbound = stats.filter((stat) => stat.type === "outbound-rtp" && stringStat(stat, "kind") !== "video");
4746
- const candidatePairs = stats.filter((stat) => stat.type === "candidate-pair");
4747
- const audioTracks = stats.filter((stat) => (stat.type === "track" || stat.type === "media-source") && stringStat(stat, "kind") === "audio");
4748
- const activeCandidatePairs = candidatePairs.filter((stat) => booleanStat(stat, "selected") === true || booleanStat(stat, "nominated") === true || stringStat(stat, "state") === "succeeded").length;
4749
- const liveAudioTracks = audioTracks.filter((stat) => stringStat(stat, "readyState") !== "ended" && stringStat(stat, "trackState") !== "ended" && booleanStat(stat, "ended") !== true).length;
4750
- const endedAudioTracks = audioTracks.filter((stat) => stringStat(stat, "readyState") === "ended" || stringStat(stat, "trackState") === "ended" || booleanStat(stat, "ended") === true).length;
4751
- const inboundPackets = inbound.reduce((total, stat) => total + (numericStat(stat, "packetsReceived") ?? 0), 0);
4752
- const outboundPackets = outbound.reduce((total, stat) => total + (numericStat(stat, "packetsSent") ?? 0), 0);
4753
- const packetsLost = [...inbound, ...outbound].reduce((total, stat) => total + Math.max(0, numericStat(stat, "packetsLost") ?? 0), 0);
4754
- const packetLossDenominator = inboundPackets + packetsLost;
4755
- const packetLossRatio = packetLossDenominator === 0 ? 0 : packetsLost / packetLossDenominator;
4756
- const bytesReceived = inbound.reduce((total, stat) => total + (numericStat(stat, "bytesReceived") ?? 0), 0);
4757
- const bytesSent = outbound.reduce((total, stat) => total + (numericStat(stat, "bytesSent") ?? 0), 0);
4758
- const roundTripTimeMs = max(candidatePairs.map((stat) => secondsToMs(numericStat(stat, "currentRoundTripTime") ?? numericStat(stat, "roundTripTime"))).filter((value) => value !== undefined));
4759
- const jitterMs = max([...inbound, ...outbound].map((stat) => secondsToMs(numericStat(stat, "jitter"))).filter((value) => value !== undefined));
4760
- const jitterBufferDelayMs = max(inbound.map((stat) => {
4761
- const delay = numericStat(stat, "jitterBufferDelay");
4762
- const emitted = numericStat(stat, "jitterBufferEmittedCount");
4763
- return delay !== undefined && emitted !== undefined && emitted > 0 ? delay / emitted * 1000 : undefined;
4764
- }).filter((value) => value !== undefined));
4765
- const audioLevels = audioTracks.map((stat) => numericStat(stat, "audioLevel")).filter((value) => value !== undefined);
4766
- if (input.requireConnectedCandidatePair && candidatePairs.length > 0 && activeCandidatePairs === 0) {
4767
- pushIssue(issues, "error", "media.webrtc_candidate_pair_missing", "No active WebRTC candidate pair was observed.");
4768
- }
4769
- if (input.requireLiveAudioTrack && liveAudioTracks === 0) {
4770
- pushIssue(issues, "error", "media.webrtc_audio_track_missing", "No live WebRTC audio track was observed.");
4771
- }
4772
- if (input.maxPacketLossRatio !== undefined && packetLossRatio > input.maxPacketLossRatio) {
4773
- pushIssue(issues, "warning", "media.webrtc_packet_loss", `Observed WebRTC packet loss ratio ${String(packetLossRatio)} above ${String(input.maxPacketLossRatio)}.`);
4774
- }
4775
- if (input.maxRoundTripTimeMs !== undefined && roundTripTimeMs !== undefined && roundTripTimeMs > input.maxRoundTripTimeMs) {
4776
- pushIssue(issues, "warning", "media.webrtc_round_trip_time", `Observed WebRTC RTT ${String(roundTripTimeMs)}ms above ${String(input.maxRoundTripTimeMs)}ms.`);
4777
- }
4778
- if (input.maxJitterMs !== undefined && jitterMs !== undefined && jitterMs > input.maxJitterMs) {
4779
- pushIssue(issues, "warning", "media.webrtc_jitter", `Observed WebRTC jitter ${String(jitterMs)}ms above ${String(input.maxJitterMs)}ms.`);
4780
- }
4781
- return {
4782
- activeCandidatePairs,
4783
- audioLevelAverage: average(audioLevels),
4784
- bytesReceived,
4785
- bytesSent,
4786
- checkedAt: Date.now(),
4787
- endedAudioTracks,
4788
- inboundPackets,
4789
- issues,
4790
- jitterBufferDelayMs,
4791
- jitterMs,
4792
- liveAudioTracks,
4793
- outboundPackets,
4794
- packetLossRatio,
4795
- packetsLost,
4796
- roundTripTimeMs,
4797
- status: issues.some((issue) => issue.severity === "error") ? "fail" : issues.length > 0 ? "warn" : "pass",
4798
- totalStats: stats.length
4799
- };
4800
- };
4801
- var collectMediaWebRTCStats = async (input) => {
4802
- const report = await input.peerConnection.getStats(input.selector ?? null);
4803
- return [...report.values()].map(normalizeWebRTCStat);
4804
- };
4805
- var buildMediaWebRTCStreamContinuityReport = (input = {}) => {
4806
- const stats = input.stats ?? [];
4807
- const previousStats = input.previousStats ?? [];
4808
- const issues = [];
4809
- const previousByKey = new Map(previousStats.map((stat) => [statKey(stat), stat]));
4810
- const audioRtp = stats.filter((stat) => (stat.type === "inbound-rtp" || stat.type === "outbound-rtp") && stringStat(stat, "kind") !== "video" && stringStat(stat, "mediaType") !== "video");
4811
- const streams = audioRtp.map((stat) => {
4812
- const direction = stat.type === "outbound-rtp" ? "outbound" : "inbound";
4813
- const packetsKey = direction === "outbound" ? "packetsSent" : "packetsReceived";
4814
- const bytesKey = direction === "outbound" ? "bytesSent" : "bytesReceived";
4815
- const previous = previousByKey.get(statKey(stat));
4816
- const currentPackets = numericStat(stat, packetsKey);
4817
- const previousPackets = previous ? numericStat(previous, packetsKey) : undefined;
4818
- const currentBytes = numericStat(stat, bytesKey);
4819
- const previousBytes = previous ? numericStat(previous, bytesKey) : undefined;
4820
- const timeDeltaMs = stat.timestamp !== undefined && previous?.timestamp !== undefined ? stat.timestamp - previous.timestamp : undefined;
4821
- return {
4822
- bytesDelta: currentBytes !== undefined && previousBytes !== undefined ? currentBytes - previousBytes : undefined,
4823
- currentPackets,
4824
- direction,
4825
- id: statKey(stat),
4826
- packetDelta: currentPackets !== undefined && previousPackets !== undefined ? currentPackets - previousPackets : undefined,
4827
- previousPackets,
4828
- timeDeltaMs
4829
- };
4830
- });
4831
- const inbound = streams.filter((stream) => stream.direction === "inbound");
4832
- const outbound = streams.filter((stream) => stream.direction === "outbound");
4833
- const maxObservedGapMs = max(streams.map((stream) => stream.timeDeltaMs).filter((value) => value !== undefined));
4834
- const stalledInboundStreams = inbound.filter((stream) => input.maxInboundPacketStallMs !== undefined && stream.timeDeltaMs !== undefined && stream.timeDeltaMs >= input.maxInboundPacketStallMs && stream.packetDelta !== undefined && stream.packetDelta <= 0).length;
4835
- const stalledOutboundStreams = outbound.filter((stream) => input.maxOutboundPacketStallMs !== undefined && stream.timeDeltaMs !== undefined && stream.timeDeltaMs >= input.maxOutboundPacketStallMs && stream.packetDelta !== undefined && stream.packetDelta <= 0).length;
4836
- if (input.requireInboundAudio && inbound.length === 0) {
4837
- pushIssue(issues, "error", "media.webrtc_inbound_audio_missing", "No inbound WebRTC audio RTP stream was observed.");
4838
- }
4839
- if (input.requireOutboundAudio && outbound.length === 0) {
4840
- pushIssue(issues, "error", "media.webrtc_outbound_audio_missing", "No outbound WebRTC audio RTP stream was observed.");
4841
- }
4842
- if (input.maxGapMs !== undefined && maxObservedGapMs !== undefined && maxObservedGapMs > input.maxGapMs) {
4843
- pushIssue(issues, "warning", "media.webrtc_stream_gap", `Observed WebRTC stream sample gap ${String(maxObservedGapMs)}ms above ${String(input.maxGapMs)}ms.`);
4844
- }
4845
- if (stalledInboundStreams > 0) {
4846
- pushIssue(issues, "error", "media.webrtc_inbound_stalled", `${String(stalledInboundStreams)} inbound WebRTC audio stream(s) stopped receiving packets.`);
4847
- }
4848
- if (stalledOutboundStreams > 0) {
4849
- pushIssue(issues, "error", "media.webrtc_outbound_stalled", `${String(stalledOutboundStreams)} outbound WebRTC audio stream(s) stopped sending packets.`);
4850
- }
4851
- return {
4852
- checkedAt: Date.now(),
4853
- inboundAudioStreams: inbound.length,
4854
- issues,
4855
- maxObservedGapMs,
4856
- outboundAudioStreams: outbound.length,
4857
- stalledInboundStreams,
4858
- stalledOutboundStreams,
4859
- status: issues.some((issue) => issue.severity === "error") ? "fail" : issues.length > 0 ? "warn" : "pass",
4860
- streams,
4861
- totalStats: stats.length
4862
- };
4863
- };
4864
- var buildMediaPipelineCalibrationReport = (input = {}) => {
4865
- const frames = input.frames ?? [];
4866
- const issues = [];
4867
- const inputFrames = frames.filter((frame) => frame.kind === "input-audio");
4868
- const assistantFrames = frames.filter((frame) => frame.kind === "assistant-audio");
4869
- const turnCommitFrames = frames.filter((frame) => frame.kind === "turn-commit");
4870
- const interruptionFrameRecords = frames.filter((frame) => frame.kind === "interruption");
4871
- const traceLinkedFrames = frames.filter((frame) => frame.traceEventId).length;
4872
- const backpressureFrames = frames.filter((frame) => Boolean(frame.metadata?.backpressure)).length;
4873
- const audioLatencies = assistantFrames.map((frame) => frame.latencyMs).filter((latency) => typeof latency === "number");
4874
- const firstAudioLatencyMs = audioLatencies.length > 0 ? Math.min(...audioLatencies) : undefined;
4875
- const jitterValues = frames.map((frame) => numericMetadata(frame, "jitterMs")).filter((value) => value !== undefined);
4876
- const jitterMs = jitterValues.length > 0 ? Math.max(...jitterValues) : undefined;
4877
- const inputFormat = input.inputFormat ?? inputFrames.find((frame) => frame.format)?.format;
4878
- const outputFormat = input.outputFormat ?? assistantFrames.find((frame) => frame.format)?.format;
4879
- const resamplingRequired = Boolean(input.expectedInputFormat && inputFormat && inputFormat.sampleRateHz !== input.expectedInputFormat.sampleRateHz) || Boolean(input.expectedOutputFormat && outputFormat && outputFormat.sampleRateHz !== input.expectedOutputFormat.sampleRateHz);
4880
- const resamplingTargetHz = resamplingRequired && input.expectedInputFormat ? input.expectedInputFormat.sampleRateHz : resamplingRequired ? input.expectedOutputFormat?.sampleRateHz : undefined;
4881
- if (inputFrames.length === 0) {
4882
- pushIssue(issues, "warning", "media.input_audio_missing", "No input audio frames were observed.");
4883
- }
4884
- if (assistantFrames.length === 0) {
4885
- pushIssue(issues, "warning", "media.assistant_audio_missing", "No assistant audio frames were observed.");
4886
- }
4887
- if (input.expectedInputFormat && inputFormat && !formatMatches(inputFormat, input.expectedInputFormat)) {
4888
- pushIssue(issues, inputFormat.sampleRateHz === input.expectedInputFormat.sampleRateHz ? "warning" : "error", "media.input_format_mismatch", `Input format ${formatLabel(inputFormat)} does not match expected ${formatLabel(input.expectedInputFormat)}.`);
4889
- }
4890
- if (input.expectedOutputFormat && outputFormat && !formatMatches(outputFormat, input.expectedOutputFormat)) {
4891
- pushIssue(issues, outputFormat.sampleRateHz === input.expectedOutputFormat.sampleRateHz ? "warning" : "error", "media.output_format_mismatch", `Output format ${formatLabel(outputFormat)} does not match expected ${formatLabel(input.expectedOutputFormat)}.`);
4892
- }
4893
- if (firstAudioLatencyMs !== undefined && input.maxFirstAudioLatencyMs !== undefined && firstAudioLatencyMs > input.maxFirstAudioLatencyMs) {
4894
- pushIssue(issues, "error", "media.first_audio_latency", `First audio latency ${String(firstAudioLatencyMs)}ms exceeds budget ${String(input.maxFirstAudioLatencyMs)}ms.`);
4895
- }
4896
- if (jitterMs !== undefined && input.maxJitterMs !== undefined && jitterMs > input.maxJitterMs) {
4897
- pushIssue(issues, "warning", "media.jitter", `Media jitter ${String(jitterMs)}ms exceeds budget ${String(input.maxJitterMs)}ms.`);
4898
- }
4899
- if (input.maxBackpressureFrames !== undefined && backpressureFrames > input.maxBackpressureFrames) {
4900
- pushIssue(issues, "warning", "media.backpressure", `Backpressure frame count ${String(backpressureFrames)} exceeds budget ${String(input.maxBackpressureFrames)}.`);
4901
- }
4902
- if (input.requireInterruptionFrame && interruptionFrameRecords.length === 0) {
4903
- pushIssue(issues, "warning", "media.interruption_missing", "No interruption frame was observed.");
4904
- }
4905
- if (input.requireTraceEvidence && traceLinkedFrames === 0) {
4906
- pushIssue(issues, "warning", "media.trace_evidence_missing", "No media frames were linked to trace evidence.");
4907
- }
4908
- return {
4909
- assistantAudioFrames: assistantFrames.length,
4910
- backpressureFrames,
4911
- checkedAt: Date.now(),
4912
- firstAudioLatencyMs,
4913
- inputAudioFrames: inputFrames.length,
4914
- inputFormat,
4915
- interruptionFrames: interruptionFrameRecords.length,
4916
- issues,
4917
- jitterMs,
4918
- outputFormat,
4919
- resamplingRequired,
4920
- resamplingTargetHz,
4921
- status: issues.some((issue) => issue.severity === "error") ? "fail" : issues.length > 0 ? "warn" : "pass",
4922
- surface: input.surface ?? "media-pipeline",
4923
- traceLinkedFrames,
4924
- turnCommitFrames: turnCommitFrames.length
4925
- };
4926
- };
4927
- var DEFAULT_METADATA_DENY = [
4928
- "audioPayload",
4929
- "auth",
4930
- "authorization",
4931
- "cookie",
4932
- "email",
4933
- "phone",
4934
- "phoneNumber",
4935
- "rawPayload",
4936
- "secret",
4937
- "token",
4938
- "transcript",
4939
- "utterance"
4940
- ];
4941
- var DEFAULT_TRUNCATE = 8;
4942
- var issueCodes = (issues) => Array.from(new Set(issues.map((issue) => issue.code)));
4943
- var lastEventKind = (events) => events[events.length - 1]?.kind;
4944
- var formatOptionalMs = (value) => value === undefined ? "n/a" : `${String(Math.round(value))}ms`;
4945
- var formatRatio = (value) => `${(value * 100).toFixed(1)}%`;
4946
- var escapeMarkdownCell = (value) => value.replace(/\|/g, "\\|").replace(/\n/g, " ");
4947
- var renderIssuesTable = (issues) => {
4948
- if (issues.length === 0) {
4949
- return `- No issues.
4950
- `;
4951
- }
4952
- const rows = issues.map((issue) => `| ${issue.severity} | ${escapeMarkdownCell(issue.code)} | ${escapeMarkdownCell(issue.message)} |`).join(`
4953
- `);
4954
- return `| Severity | Code | Message |
4955
- | --- | --- | --- |
4956
- ${rows}
4957
- `;
4958
- };
4959
- var summarizeMediaQualityReport = (report) => ({
4960
- backpressureEvents: report.backpressureEvents,
4961
- description: `${report.totalFrames} frame(s), ${report.gapCount} gap(s), speech ${formatRatio(report.speechRatio)}, status ${report.status}.`,
4962
- driftMs: report.timestampDriftMs,
4963
- frameCount: report.totalFrames,
4964
- gapCount: report.gapCount,
4965
- issueCodes: issueCodes(report.issues),
4966
- issueCount: report.issues.length,
4967
- jitterMs: report.jitterMs,
4968
- silenceRatio: report.silenceRatio,
4969
- speechRatio: report.speechRatio,
4970
- status: report.status
4971
- });
4972
- var summarizeMediaTransportReport = (report) => ({
4973
- backpressureEvents: report.backpressureEvents,
4974
- description: `${report.name}: ${report.state}, in ${report.inputFrames}, out ${report.outputFrames}, backpressure ${report.backpressureEvents}.`,
4975
- errors: report.events.filter((event) => event.kind === "error").length,
4976
- inputFrames: report.inputFrames,
4977
- lastEventKind: lastEventKind(report.events),
4978
- name: report.name,
4979
- outputFrames: report.outputFrames,
4980
- state: report.state,
4981
- status: report.status
4982
- });
4983
- var summarizeMediaProcessorGraphReport = (report) => {
4984
- const errorIssueCodes = Array.from(new Set(report.errors.map((event) => event.kind)));
4985
- return {
4986
- backpressureEvents: report.backpressure.events.length,
4987
- description: `${report.name}: ${report.state}, ${report.nodes.length} node(s), in ${report.inputFrames}, out ${report.emittedFrames}, dropped ${report.droppedFrames}.`,
4988
- droppedFrames: report.droppedFrames,
4989
- edgeCount: report.edges.length,
4990
- edgeEventCount: report.edgeEvents.length,
4991
- emittedFrames: report.emittedFrames,
4992
- errorCount: report.errors.length,
4993
- inputFrames: report.inputFrames,
4994
- issueCodes: errorIssueCodes,
4995
- lifecycleEventCount: report.lifecycleEvents.length,
4996
- name: report.name,
4997
- nodeCount: report.nodes.length,
4998
- state: report.state,
4999
- status: report.status,
5000
- timingMaxMs: report.timing.maxNodeMs
5001
- };
5002
- };
5003
- var renderMediaQualityMarkdown = (report, options = {}) => {
5004
- const title = options.title ?? "Media Quality Report";
5005
- const lines = [
5006
- `# ${title}`,
5007
- "",
5008
- `Status: **${report.status}**`,
5009
- "",
5010
- "| Metric | Value |",
5011
- "| --- | ---: |",
5012
- `| Total frames | ${report.totalFrames} |`,
5013
- `| Input audio | ${report.inputAudioFrames} |`,
5014
- `| Assistant audio | ${report.assistantAudioFrames} |`,
5015
- `| Gaps | ${report.gapCount} |`,
5016
- `| Jitter | ${formatOptionalMs(report.jitterMs)} |`,
5017
- `| Timestamp drift | ${formatOptionalMs(report.timestampDriftMs)} |`,
5018
- `| Speech ratio | ${formatRatio(report.speechRatio)} |`,
5019
- `| Silence ratio | ${formatRatio(report.silenceRatio)} |`,
5020
- `| Backpressure events | ${report.backpressureEvents} |`,
5021
- "",
5022
- "## Issues",
5023
- "",
5024
- renderIssuesTable(report.issues).trimEnd()
5025
- ];
5026
- return `${lines.join(`
5027
- `)}
5028
- `;
5029
- };
5030
- var renderMediaTransportMarkdown = (report, options = {}) => {
5031
- const title = options.title ?? `Media Transport: ${report.name}`;
5032
- const limit = options.redact?.truncateArraysAt ?? DEFAULT_TRUNCATE;
5033
- const events = report.events.slice(-limit);
5034
- const eventRows = events.length === 0 ? "- No transport events recorded." : ["| At | Kind | State | Buffered | Error |", "| --- | --- | --- | ---: | --- |"].concat(events.map((event) => `| ${event.at} | ${event.kind} | ${event.state} | ${event.bufferedFrames ?? ""} | ${escapeMarkdownCell(event.error ?? "")} |`)).join(`
5035
- `);
5036
- const lines = [
5037
- `# ${title}`,
5038
- "",
5039
- `Status: **${report.status}** \xB7 State: **${report.state}**`,
5040
- "",
5041
- "| Metric | Value |",
5042
- "| --- | ---: |",
5043
- `| Input frames | ${report.inputFrames} |`,
5044
- `| Output frames | ${report.outputFrames} |`,
5045
- `| Backpressure events | ${report.backpressureEvents} |`,
5046
- `| Connected | ${report.connected ? "yes" : "no"} |`,
5047
- `| Closed | ${report.closed ? "yes" : "no"} |`,
5048
- `| Failed | ${report.failed ? "yes" : "no"} |`,
5049
- "",
5050
- `## Last ${events.length} event(s)`,
5051
- "",
5052
- eventRows
5053
- ];
5054
- return `${lines.join(`
5055
- `)}
5056
- `;
5057
- };
5058
- var renderMediaProcessorGraphMarkdown = (report, options = {}) => {
5059
- const title = options.title ?? `Media Processor Graph: ${report.name}`;
5060
- const limit = options.redact?.truncateArraysAt ?? DEFAULT_TRUNCATE;
5061
- const nodeRows = report.nodes.map((node) => `| ${escapeMarkdownCell(node.name)} | ${node.kind} | ${node.status} | ${node.inputFrames} | ${node.emittedFrames} | ${node.droppedFrames} | ${node.errors.length} |`).join(`
5062
- `);
5063
- const edgeRows = report.edges.slice(0, limit).map((edge) => `| ${escapeMarkdownCell(edge.from)} | ${escapeMarkdownCell(edge.to)} | ${edge.status} | ${edge.emittedFrames} |`).join(`
5064
- `);
5065
- const issues = report.errors.map((event) => ({
5066
- code: event.kind,
5067
- message: event.error ?? `Processor graph ${event.kind} (state ${event.state}).`,
5068
- severity: "error"
5069
- }));
5070
- const lines = [
5071
- `# ${title}`,
5072
- "",
5073
- `Status: **${report.status}** \xB7 State: **${report.state}**`,
5074
- "",
5075
- "| Metric | Value |",
5076
- "| --- | ---: |",
5077
- `| Nodes | ${report.nodes.length} |`,
5078
- `| Input frames | ${report.inputFrames} |`,
5079
- `| Emitted frames | ${report.emittedFrames} |`,
5080
- `| Dropped frames | ${report.droppedFrames} |`,
5081
- `| Lifecycle events | ${report.lifecycleEvents.length} |`,
5082
- `| Edge events | ${report.edgeEvents.length} |`,
5083
- `| Backpressure events | ${report.backpressure.events.length} |`,
5084
- `| Timing max | ${formatOptionalMs(report.timing.maxNodeMs)} |`,
5085
- `| Timing average | ${formatOptionalMs(report.timing.averageNodeMs)} |`,
5086
- "",
5087
- "## Nodes",
5088
- "",
5089
- nodeRows ? `| Node | Kind | Status | In | Out | Dropped | Errors |
5090
- | --- | --- | --- | ---: | ---: | ---: | ---: |
5091
- ${nodeRows}` : "- No nodes.",
5092
- "",
5093
- `## Edges (showing up to ${limit})`,
5094
- "",
5095
- edgeRows ? `| From | To | Status | Frames |
5096
- | --- | --- | --- | ---: |
5097
- ${edgeRows}` : "- No edges.",
5098
- "",
5099
- "## Errors",
5100
- "",
5101
- renderIssuesTable(issues).trimEnd()
5102
- ];
5103
- return `${lines.join(`
5104
- `)}
5105
- `;
5106
- };
5107
- var truncateArrays = (value, limit, seen) => {
5108
- if (Array.isArray(value)) {
5109
- const head = value.slice(0, limit).map((entry) => truncateArrays(entry, limit, seen));
5110
- if (value.length > limit) {
5111
- return [...head, { truncated: value.length - limit }];
5112
- }
5113
- return head;
5114
- }
5115
- if (value && typeof value === "object") {
5116
- if (seen.has(value))
5117
- return value;
5118
- seen.add(value);
5119
- const next = {};
5120
- for (const [key, entry] of Object.entries(value)) {
5121
- next[key] = truncateArrays(entry, limit, seen);
5122
- }
5123
- return next;
5124
- }
5125
- return value;
5126
- };
5127
- var applyRedaction = (value, options, seen) => {
5128
- const mode = options.mode ?? "omit";
5129
- const maskValue = options.maskValue ?? "[redacted]";
5130
- const allow = new Set(options.metadataAllow ?? []);
5131
- const deny = new Set(options.metadataDeny ?? DEFAULT_METADATA_DENY);
5132
- const walk = (input) => {
5133
- if (Array.isArray(input)) {
5134
- return input.map((entry) => walk(entry));
5135
- }
5136
- if (input && typeof input === "object") {
5137
- if (seen.has(input))
5138
- return input;
5139
- seen.add(input);
5140
- const next = {};
5141
- for (const [key, entry] of Object.entries(input)) {
5142
- if (allow.has(key)) {
5143
- next[key] = entry;
5144
- continue;
5145
- }
5146
- if (deny.has(key)) {
5147
- if (mode === "mask")
5148
- next[key] = maskValue;
5149
- continue;
5150
- }
5151
- next[key] = walk(entry);
5152
- }
5153
- return next;
5154
- }
5155
- return input;
5156
- };
5157
- return walk(value);
5158
- };
5159
- var redactMediaReport = (report, options = {}) => {
5160
- const limit = options.truncateArraysAt ?? DEFAULT_TRUNCATE;
5161
- const truncated = truncateArrays(report, limit, new WeakSet);
5162
- return applyRedaction(truncated, options, new WeakSet);
5163
- };
5164
- var buildArtifactPair = (report, summary, markdown, options) => {
5165
- const jsonValue = options.redact ? redactMediaReport(report, options.redact) : report;
5166
- return {
5167
- json: JSON.stringify(jsonValue, null, 2),
5168
- jsonValue,
5169
- markdown,
5170
- summary
5171
- };
5172
- };
5173
- var buildMediaQualityArtifact = (report, options = {}) => buildArtifactPair(report, summarizeMediaQualityReport(report), renderMediaQualityMarkdown(report, options), options);
5174
- var buildMediaTransportArtifact = (report, options = {}) => buildArtifactPair(report, summarizeMediaTransportReport(report), renderMediaTransportMarkdown(report, options), options);
5175
- var buildMediaProcessorGraphArtifact = (report, options = {}) => buildArtifactPair(report, summarizeMediaProcessorGraphReport(report), renderMediaProcessorGraphMarkdown(report, options), options);
5176
- var writeMediaArtifact = async (input) => {
5177
- await mkdir(input.dir, { recursive: true });
5178
- const jsonPath = join(input.dir, `${input.slug}.json`);
5179
- const markdownPath = join(input.dir, `${input.slug}.md`);
5180
- await Promise.all([
5181
- writeFile(jsonPath, input.json, "utf8"),
5182
- writeFile(markdownPath, input.markdown, "utf8")
5183
- ]);
5184
- return {
5185
- jsonPath,
5186
- markdownPath,
5187
- summary: input.summary
5188
- };
5189
- };
5190
-
5191
4264
  // src/client/browserMedia.ts
4265
+ import {
4266
+ buildMediaWebRTCStatsReport,
4267
+ buildMediaWebRTCStreamContinuityReport,
4268
+ collectMediaWebRTCStats
4269
+ } from "@absolutejs/media";
5192
4270
  var DEFAULT_BROWSER_MEDIA_PATH = "/api/voice/browser-media";
5193
4271
  var DEFAULT_BROWSER_MEDIA_INTERVAL_MS = 5000;
5194
4272
  var resolvePeerConnection = async (options) => options.peerConnection ?? await options.getPeerConnection?.() ?? null;