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

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.
@@ -790,934 +790,12 @@ var serverMessageToAction = (message) => {
790
790
  }
791
791
  };
792
792
 
793
- // node_modules/@absolutejs/media/dist/index.js
794
- import { mkdir, writeFile } from "fs/promises";
795
- import { join } from "path";
796
- var formatLabel = (format) => `${format.container}/${format.encoding}/${String(format.sampleRateHz)}hz/${String(format.channels)}ch`;
797
- var formatMatches = (actual, expected) => actual.container === expected.container && actual.encoding === expected.encoding && actual.sampleRateHz === expected.sampleRateHz && actual.channels === expected.channels;
798
- var pushIssue = (issues, severity, code, message) => {
799
- issues.push({ code, message, severity });
800
- };
801
- var numericMetadata = (frame, key) => {
802
- const value = frame.metadata?.[key];
803
- return typeof value === "number" && Number.isFinite(value) ? value : undefined;
804
- };
805
- var average = (values) => values.length === 0 ? undefined : values.reduce((total, value) => total + value, 0) / values.length;
806
- var max = (values) => values.length === 0 ? undefined : Math.max(...values);
807
- var min = (values) => values.length === 0 ? undefined : Math.min(...values);
808
- var numericStat = (stat, key) => {
809
- const value = stat[key];
810
- return typeof value === "number" && Number.isFinite(value) ? value : undefined;
811
- };
812
- var booleanStat = (stat, key) => {
813
- const value = stat[key];
814
- return typeof value === "boolean" ? value : undefined;
815
- };
816
- var stringStat = (stat, key) => {
817
- const value = stat[key];
818
- return typeof value === "string" ? value : undefined;
819
- };
820
- var statKey = (stat) => String(stat.id ?? stringStat(stat, "ssrc") ?? numericStat(stat, "ssrc") ?? stringStat(stat, "trackIdentifier") ?? stringStat(stat, "mid") ?? "unknown");
821
- var secondsToMs = (value) => value === undefined ? undefined : value * 1000;
822
- var DEFAULT_TELEPHONY_FORMAT = {
823
- channels: 1,
824
- container: "raw",
825
- encoding: "mulaw",
826
- sampleRateHz: 8000
827
- };
828
- var bytesToBase64 = (audio) => {
829
- const bytes = audio instanceof ArrayBuffer ? new Uint8Array(audio) : new Uint8Array(audio.buffer, audio.byteOffset, audio.byteLength);
830
- return Buffer.from(bytes).toString("base64");
831
- };
832
- var base64ToBytes = (value) => new Uint8Array(Buffer.from(value, "base64"));
833
- var unknownRecord = (value) => value && typeof value === "object" ? value : {};
834
- var firstString = (records, keys) => {
835
- for (const record of records) {
836
- for (const key of keys) {
837
- const value = record[key];
838
- if (typeof value === "string" && value.length > 0) {
839
- return value;
840
- }
841
- if (typeof value === "number" && Number.isFinite(value)) {
842
- return String(value);
843
- }
844
- }
845
- }
846
- return;
847
- };
848
- var firstNumber = (records, keys) => {
849
- for (const record of records) {
850
- for (const key of keys) {
851
- const value = record[key];
852
- if (typeof value === "number" && Number.isFinite(value)) {
853
- return value;
854
- }
855
- if (typeof value === "string") {
856
- const parsed = Number(value);
857
- if (Number.isFinite(parsed)) {
858
- return parsed;
859
- }
860
- }
861
- }
862
- }
863
- return;
864
- };
865
- var telephonyDirection = (track) => {
866
- const normalized = track?.toLowerCase();
867
- if (!normalized) {
868
- return "unknown";
869
- }
870
- if (normalized.includes("inbound") || normalized.includes("caller") || normalized.includes("in")) {
871
- return "inbound";
872
- }
873
- if (normalized.includes("outbound") || normalized.includes("assistant") || normalized.includes("out")) {
874
- return "outbound";
875
- }
876
- return "unknown";
877
- };
878
- var telephonyFrameKind = (direction) => direction === "outbound" ? "assistant-audio" : "input-audio";
879
- var telephonyEventKind = (envelope) => {
880
- const raw = firstString([envelope], ["event", "type", "eventType"]) ?? firstString([unknownRecord(envelope.message)], ["event", "type"]);
881
- const normalized = raw?.toLowerCase().replace(/[_\s-]+/g, "-");
882
- if (!normalized) {
883
- return "unknown";
884
- }
885
- if (normalized.includes("connected")) {
886
- return "connected";
887
- }
888
- if (normalized.includes("start")) {
889
- return "start";
890
- }
891
- if (normalized.includes("media")) {
892
- return "media";
893
- }
894
- if (normalized.includes("stop") || normalized.includes("closed")) {
895
- return "stop";
896
- }
897
- if (normalized.includes("error") || normalized.includes("failed")) {
898
- return "error";
899
- }
900
- return "unknown";
901
- };
902
- var normalizeWebRTCStat = (stat) => {
903
- const sample = {};
904
- for (const [key, value] of Object.entries(stat)) {
905
- if (value === null || typeof value === "boolean" || typeof value === "number" || typeof value === "string") {
906
- sample[key] = value;
907
- }
908
- }
909
- return sample;
910
- };
911
- var parseTelephonyMediaFrame = (input) => {
912
- const envelope = input.envelope;
913
- const media = unknownRecord(envelope.media);
914
- const payload = firstString([media, envelope], ["payload", "audio", "data"]) ?? firstString([unknownRecord(envelope.message)], ["payload"]);
915
- if (!payload) {
916
- return;
917
- }
918
- const carrier = input.carrier ?? firstString([envelope], ["provider"]) ?? "telephony";
919
- const streamId = firstString([media, envelope], ["streamSid", "stream_id", "streamId", "streamId", "callSid", "call_id"]);
920
- const sequenceNumber = firstString([media, envelope], ["sequenceNumber", "sequence_number", "chunk"]);
921
- const track = firstString([media, envelope], ["track", "direction"]);
922
- const direction = telephonyDirection(track);
923
- const timestamp = firstNumber([media, envelope], ["timestamp", "time", "startedAt"]);
924
- return {
925
- at: timestamp,
926
- audio: base64ToBytes(payload),
927
- format: input.format ?? DEFAULT_TELEPHONY_FORMAT,
928
- id: [
929
- carrier,
930
- streamId ?? input.sessionId ?? "stream",
931
- sequenceNumber ?? timestamp ?? Date.now()
932
- ].join(":"),
933
- kind: telephonyFrameKind(direction),
934
- metadata: {
935
- carrier,
936
- direction,
937
- event: firstString([envelope], ["event", "type"]),
938
- sequenceNumber,
939
- streamId,
940
- track
941
- },
942
- sessionId: input.sessionId ?? streamId,
943
- source: "telephony"
944
- };
945
- };
946
- var serializeTelephonyMediaFrame = (input) => {
947
- const carrier = input.carrier ?? input.frame.metadata?.carrier ?? "telephony";
948
- const streamId = input.streamId ?? (typeof input.frame.metadata?.streamId === "string" ? input.frame.metadata.streamId : input.frame.sessionId);
949
- const sequenceNumber = input.sequenceNumber ?? (typeof input.frame.metadata?.sequenceNumber === "string" || typeof input.frame.metadata?.sequenceNumber === "number" ? input.frame.metadata.sequenceNumber : undefined);
950
- const direction = input.frame.kind === "assistant-audio" ? "outbound" : "inbound";
951
- const payload = input.frame.audio ? bytesToBase64(input.frame.audio) : "";
952
- if (carrier === "twilio") {
953
- return {
954
- event: "media",
955
- sequenceNumber,
956
- streamSid: streamId,
957
- media: {
958
- payload,
959
- timestamp: input.frame.at,
960
- track: direction
961
- }
962
- };
963
- }
964
- if (carrier === "telnyx") {
965
- return {
966
- event: "media",
967
- stream_id: streamId,
968
- sequence_number: sequenceNumber,
969
- media: {
970
- payload,
971
- timestamp: input.frame.at,
972
- track: direction
973
- }
974
- };
975
- }
976
- if (carrier === "plivo") {
977
- return {
978
- event: "media",
979
- streamId,
980
- sequenceNumber,
981
- media: {
982
- payload,
983
- timestamp: input.frame.at,
984
- track: direction
985
- }
986
- };
987
- }
988
- return {
989
- event: "media",
990
- provider: carrier,
991
- sequenceNumber,
992
- streamId,
993
- media: {
994
- payload,
995
- timestamp: input.frame.at,
996
- track: direction
997
- }
998
- };
999
- };
1000
- var createTelephonyMediaSerializer = (input) => {
1001
- const format = input.format ?? DEFAULT_TELEPHONY_FORMAT;
1002
- return {
1003
- carrier: input.carrier,
1004
- format,
1005
- parse: (envelope) => parseTelephonyMediaFrame({
1006
- carrier: input.carrier,
1007
- envelope,
1008
- format,
1009
- sessionId: input.sessionId ?? input.streamId
1010
- }),
1011
- serialize: (frame) => serializeTelephonyMediaFrame({
1012
- carrier: input.carrier,
1013
- frame,
1014
- streamId: input.streamId
1015
- })
1016
- };
1017
- };
1018
- var parseTelephonyStreamEvent = (input) => {
1019
- const envelope = input.envelope;
1020
- const media = unknownRecord(envelope.media);
1021
- const start = unknownRecord(envelope.start);
1022
- const stop = unknownRecord(envelope.stop);
1023
- const errorRecord = unknownRecord(envelope.error);
1024
- const kind = telephonyEventKind(envelope);
1025
- const carrier = input.carrier ?? firstString([envelope], ["provider", "carrier"]) ?? "telephony";
1026
- const frame = kind === "media" ? parseTelephonyMediaFrame({
1027
- carrier,
1028
- envelope,
1029
- format: input.format,
1030
- sessionId: input.sessionId
1031
- }) : undefined;
1032
- const streamId = firstString([media, start, stop, envelope], ["streamSid", "stream_id", "streamId", "callSid", "call_id"]) ?? input.sessionId;
1033
- const sequenceNumber = firstString([media, envelope], ["sequenceNumber", "sequence_number", "chunk"]);
1034
- const track = firstString([media, envelope], ["track", "direction"]);
1035
- return {
1036
- audioBytes: frame?.audio ? frame.audio instanceof ArrayBuffer ? frame.audio.byteLength : frame.audio.byteLength : 0,
1037
- at: frame?.at ?? firstNumber([media, start, stop, envelope], ["timestamp", "time", "startedAt"]),
1038
- carrier,
1039
- direction: telephonyDirection(track),
1040
- error: firstString([errorRecord, envelope], ["message", "error", "reason"]),
1041
- kind,
1042
- sequenceNumber,
1043
- streamId
1044
- };
1045
- };
1046
- var buildMediaTelephonyStreamLifecycleReport = (input = {}) => {
1047
- const envelopes = input.envelopes ?? [];
1048
- const events = envelopes.map((envelope) => parseTelephonyStreamEvent({
1049
- carrier: input.carrier,
1050
- envelope
1051
- }));
1052
- const issues = [];
1053
- const startedIndex = events.findIndex((event) => event.kind === "start");
1054
- const firstMediaIndex = events.findIndex((event) => event.kind === "media");
1055
- const stoppedIndex = events.findIndex((event) => event.kind === "stop");
1056
- const started = startedIndex >= 0;
1057
- const stopped = stoppedIndex >= 0;
1058
- const mediaEvents = events.filter((event) => event.kind === "media");
1059
- const audioBytes = events.reduce((total, event) => total + event.audioBytes, 0);
1060
- const minAudioBytes = input.minAudioBytes ?? 1;
1061
- const streamIds = Array.from(new Set(events.map((event) => event.streamId).filter(Boolean)));
1062
- if ((input.requireStart ?? true) && !started) {
1063
- pushIssue(issues, "error", "media.telephony_missing_start", "Telephony media stream did not include a start event.");
1064
- }
1065
- if ((input.requireMedia ?? true) && mediaEvents.length === 0) {
1066
- pushIssue(issues, "error", "media.telephony_missing_media", "Telephony media stream did not include media payload events.");
1067
- }
1068
- if ((input.requireStop ?? true) && !stopped) {
1069
- pushIssue(issues, input.maxMissingStop === false ? "warning" : "error", "media.telephony_missing_stop", "Telephony media stream did not include a stop event.");
1070
- }
1071
- if (started && firstMediaIndex >= 0 && firstMediaIndex < startedIndex) {
1072
- pushIssue(issues, "error", "media.telephony_media_before_start", "Telephony media payload arrived before the stream start event.");
1073
- }
1074
- if (stopped && firstMediaIndex >= 0 && stoppedIndex < firstMediaIndex) {
1075
- pushIssue(issues, "error", "media.telephony_stop_before_media", "Telephony media stream stopped before any media payload arrived.");
1076
- }
1077
- if (mediaEvents.length > 0 && audioBytes < minAudioBytes) {
1078
- pushIssue(issues, "error", "media.telephony_no_audio_bytes", `Telephony media stream parsed ${String(audioBytes)} audio byte(s), below required ${String(minAudioBytes)}.`);
1079
- }
1080
- for (const event of events) {
1081
- if (event.kind === "error") {
1082
- pushIssue(issues, "error", "media.telephony_stream_error", event.error ?? "Telephony media stream emitted an error event.");
1083
- }
1084
- }
1085
- return {
1086
- audioBytes,
1087
- carrier: input.carrier,
1088
- checkedAt: Date.now(),
1089
- events,
1090
- issues,
1091
- mediaEvents: mediaEvents.length,
1092
- started,
1093
- status: issues.some((issue) => issue.severity === "error") ? "fail" : issues.length > 0 ? "warn" : "pass",
1094
- stopped,
1095
- streamIds
1096
- };
1097
- };
1098
- var buildMediaResamplingPlan = (input) => {
1099
- const required = !formatMatches(input.inputFormat, input.outputFormat);
1100
- return {
1101
- inputFormat: input.inputFormat,
1102
- outputFormat: input.outputFormat,
1103
- ratio: input.outputFormat.sampleRateHz / input.inputFormat.sampleRateHz,
1104
- required,
1105
- status: input.inputFormat.container === input.outputFormat.container && input.inputFormat.encoding === input.outputFormat.encoding && input.inputFormat.channels === input.outputFormat.channels ? "pass" : "warn"
1106
- };
1107
- };
1108
- var speechProbability = (frame) => {
1109
- if (frame.metadata?.isSpeech === true) {
1110
- return 1;
1111
- }
1112
- if (frame.metadata?.isSpeech === false) {
1113
- return 0;
1114
- }
1115
- for (const key of ["speechProbability", "voiceProbability", "rms", "energy"]) {
1116
- const value = numericMetadata(frame, key);
1117
- if (value !== undefined) {
1118
- return value;
1119
- }
1120
- }
1121
- return 0;
1122
- };
1123
- var buildMediaVadReport = (input = {}) => {
1124
- const frames = (input.frames ?? []).filter((frame) => frame.kind === "input-audio");
1125
- const speechStartThreshold = input.speechStartThreshold ?? 0.6;
1126
- const speechEndThreshold = input.speechEndThreshold ?? 0.35;
1127
- const minSpeechFrames = input.minSpeechFrames ?? 1;
1128
- const maxSilenceFrames = input.maxSilenceFrames ?? 1;
1129
- const segments = [];
1130
- let activeFrames = [];
1131
- let silenceFrames = 0;
1132
- const closeSegment = () => {
1133
- if (activeFrames.length < minSpeechFrames) {
1134
- activeFrames = [];
1135
- silenceFrames = 0;
1136
- return;
1137
- }
1138
- const first = activeFrames[0];
1139
- const last = activeFrames.at(-1);
1140
- if (!first) {
1141
- return;
1142
- }
1143
- segments.push({
1144
- durationMs: first.at !== undefined && last?.at !== undefined ? last.at - first.at + (last.durationMs ?? 0) : undefined,
1145
- endAt: last?.at !== undefined ? last.at + (last.durationMs ?? 0) : undefined,
1146
- frameCount: activeFrames.length,
1147
- segmentId: `vad:${String(segments.length + 1)}`,
1148
- sessionId: first.sessionId,
1149
- startAt: first.at,
1150
- turnId: first.turnId
1151
- });
1152
- activeFrames = [];
1153
- silenceFrames = 0;
1154
- };
1155
- for (const frame of frames) {
1156
- const probability = speechProbability(frame);
1157
- if (activeFrames.length === 0) {
1158
- if (probability >= speechStartThreshold) {
1159
- activeFrames.push(frame);
1160
- }
1161
- continue;
1162
- }
1163
- activeFrames.push(frame);
1164
- if (probability <= speechEndThreshold) {
1165
- silenceFrames += 1;
1166
- } else {
1167
- silenceFrames = 0;
1168
- }
1169
- if (silenceFrames > maxSilenceFrames) {
1170
- closeSegment();
1171
- }
1172
- }
1173
- closeSegment();
1174
- return {
1175
- checkedAt: Date.now(),
1176
- inputAudioFrames: frames.length,
1177
- segments,
1178
- status: frames.length === 0 ? "warn" : "pass"
1179
- };
1180
- };
1181
- var buildMediaInterruptionReport = (input = {}) => {
1182
- const issues = [];
1183
- const interruptionFrames = (input.frames ?? []).filter((frame) => frame.kind === "interruption");
1184
- const latenciesMs = interruptionFrames.map((frame) => frame.latencyMs).filter((latency) => typeof latency === "number");
1185
- const maxInterruptionLatencyMs = input.maxInterruptionLatencyMs;
1186
- if (interruptionFrames.length === 0) {
1187
- pushIssue(issues, "warning", "media.interruption_missing", "No interruption frame was observed.");
1188
- }
1189
- if (maxInterruptionLatencyMs !== undefined && latenciesMs.some((latency) => latency > maxInterruptionLatencyMs)) {
1190
- pushIssue(issues, "error", "media.interruption_latency", `Interruption latency exceeded ${String(maxInterruptionLatencyMs)}ms.`);
1191
- }
1192
- return {
1193
- checkedAt: Date.now(),
1194
- interruptionFrames: interruptionFrames.length,
1195
- issues,
1196
- latenciesMs,
1197
- status: issues.some((issue) => issue.severity === "error") ? "fail" : issues.length > 0 ? "warn" : "pass"
1198
- };
1199
- };
1200
- var buildMediaQualityReport = (input = {}) => {
1201
- const frames = [...input.frames ?? []].sort((a, b) => (a.at ?? 0) - (b.at ?? 0));
1202
- const audioFrames = frames.filter((frame) => frame.kind === "input-audio" || frame.kind === "assistant-audio");
1203
- const inputAudioFrames = frames.filter((frame) => frame.kind === "input-audio");
1204
- const assistantAudioFrames = frames.filter((frame) => frame.kind === "assistant-audio");
1205
- const issues = [];
1206
- const gapsMs = [];
1207
- for (const [index, frame] of audioFrames.entries()) {
1208
- const previous = audioFrames[index - 1];
1209
- if (previous?.at === undefined || frame.at === undefined || previous.durationMs === undefined) {
1210
- continue;
1211
- }
1212
- const gap = frame.at - (previous.at + previous.durationMs);
1213
- if (gap > 0) {
1214
- gapsMs.push(gap);
1215
- }
1216
- }
1217
- const jitterMs = audioFrames.map((frame) => numericMetadata(frame, "jitterMs")).filter((value) => value !== undefined).at(-1) ?? max(gapsMs);
1218
- const first = audioFrames.find((frame) => frame.at !== undefined);
1219
- const last = audioFrames.toReversed().find((frame) => frame.at !== undefined);
1220
- const durationMs = first?.at !== undefined && last?.at !== undefined ? last.at - first.at + (last.durationMs ?? 0) : undefined;
1221
- const expectedDurationMs = audioFrames.length > 0 ? audioFrames.reduce((total, frame) => total + (frame.durationMs ?? 0), 0) : undefined;
1222
- const timestampDriftMs = durationMs !== undefined && expectedDurationMs !== undefined ? Math.max(0, durationMs - expectedDurationMs) : undefined;
1223
- const speechScores = inputAudioFrames.map(speechProbability);
1224
- const speechFrames = speechScores.filter((score) => score >= 0.6).length;
1225
- const silenceFrames = speechScores.filter((score) => score <= 0.35).length;
1226
- const unknownSpeechFrames = Math.max(0, inputAudioFrames.length - speechFrames - silenceFrames);
1227
- const speechRatio = inputAudioFrames.length === 0 ? 0 : speechFrames / inputAudioFrames.length;
1228
- const silenceRatio = inputAudioFrames.length === 0 ? 0 : silenceFrames / inputAudioFrames.length;
1229
- const levels = audioFrames.map((frame) => numericMetadata(frame, "level") ?? numericMetadata(frame, "rms") ?? numericMetadata(frame, "energy")).filter((value) => value !== undefined);
1230
- const backpressureEvents = input.transport?.backpressureEvents ?? 0;
1231
- const maxGapMs = input.maxGapMs;
1232
- if (maxGapMs !== undefined && gapsMs.some((gap) => gap > maxGapMs)) {
1233
- pushIssue(issues, "warning", "media.quality_gap", `Observed media gap above ${String(maxGapMs)}ms.`);
1234
- }
1235
- if (input.maxJitterMs !== undefined && jitterMs !== undefined && jitterMs > input.maxJitterMs) {
1236
- pushIssue(issues, "warning", "media.quality_jitter", `Observed jitter ${String(jitterMs)}ms above ${String(input.maxJitterMs)}ms.`);
1237
- }
1238
- if (input.maxTimestampDriftMs !== undefined && timestampDriftMs !== undefined && timestampDriftMs > input.maxTimestampDriftMs) {
1239
- pushIssue(issues, "warning", "media.quality_timestamp_drift", `Observed timestamp drift ${String(timestampDriftMs)}ms above ${String(input.maxTimestampDriftMs)}ms.`);
1240
- }
1241
- if (input.minSpeechRatio !== undefined && inputAudioFrames.length > 0 && speechRatio < input.minSpeechRatio) {
1242
- pushIssue(issues, "warning", "media.quality_speech_ratio", `Observed speech ratio ${String(speechRatio)} below ${String(input.minSpeechRatio)}.`);
1243
- }
1244
- if (input.maxBackpressureEvents !== undefined && backpressureEvents > input.maxBackpressureEvents) {
1245
- pushIssue(issues, "warning", "media.quality_backpressure", `Observed ${String(backpressureEvents)} backpressure event(s), above ${String(input.maxBackpressureEvents)}.`);
1246
- }
1247
- return {
1248
- assistantAudioFrames: assistantAudioFrames.length,
1249
- backpressureEvents,
1250
- checkedAt: Date.now(),
1251
- durationMs,
1252
- gapCount: gapsMs.length,
1253
- gapsMs,
1254
- inputAudioFrames: inputAudioFrames.length,
1255
- issues,
1256
- jitterMs,
1257
- levelAverage: average(levels),
1258
- levelMax: max(levels),
1259
- levelMin: min(levels),
1260
- silenceFrames,
1261
- silenceRatio,
1262
- speechFrames,
1263
- speechRatio,
1264
- status: issues.some((issue) => issue.severity === "error") ? "fail" : issues.length > 0 ? "warn" : "pass",
1265
- timestampDriftMs,
1266
- totalFrames: frames.length,
1267
- unknownSpeechFrames
1268
- };
1269
- };
1270
- var buildMediaWebRTCStatsReport = (input = {}) => {
1271
- const stats = input.stats ?? [];
1272
- const issues = [];
1273
- const inbound = stats.filter((stat) => stat.type === "inbound-rtp" && stringStat(stat, "kind") !== "video");
1274
- const outbound = stats.filter((stat) => stat.type === "outbound-rtp" && stringStat(stat, "kind") !== "video");
1275
- const candidatePairs = stats.filter((stat) => stat.type === "candidate-pair");
1276
- const audioTracks = stats.filter((stat) => (stat.type === "track" || stat.type === "media-source") && stringStat(stat, "kind") === "audio");
1277
- const activeCandidatePairs = candidatePairs.filter((stat) => booleanStat(stat, "selected") === true || booleanStat(stat, "nominated") === true || stringStat(stat, "state") === "succeeded").length;
1278
- const liveAudioTracks = audioTracks.filter((stat) => stringStat(stat, "readyState") !== "ended" && stringStat(stat, "trackState") !== "ended" && booleanStat(stat, "ended") !== true).length;
1279
- const endedAudioTracks = audioTracks.filter((stat) => stringStat(stat, "readyState") === "ended" || stringStat(stat, "trackState") === "ended" || booleanStat(stat, "ended") === true).length;
1280
- const inboundPackets = inbound.reduce((total, stat) => total + (numericStat(stat, "packetsReceived") ?? 0), 0);
1281
- const outboundPackets = outbound.reduce((total, stat) => total + (numericStat(stat, "packetsSent") ?? 0), 0);
1282
- const packetsLost = [...inbound, ...outbound].reduce((total, stat) => total + Math.max(0, numericStat(stat, "packetsLost") ?? 0), 0);
1283
- const packetLossDenominator = inboundPackets + packetsLost;
1284
- const packetLossRatio = packetLossDenominator === 0 ? 0 : packetsLost / packetLossDenominator;
1285
- const bytesReceived = inbound.reduce((total, stat) => total + (numericStat(stat, "bytesReceived") ?? 0), 0);
1286
- const bytesSent = outbound.reduce((total, stat) => total + (numericStat(stat, "bytesSent") ?? 0), 0);
1287
- const roundTripTimeMs = max(candidatePairs.map((stat) => secondsToMs(numericStat(stat, "currentRoundTripTime") ?? numericStat(stat, "roundTripTime"))).filter((value) => value !== undefined));
1288
- const jitterMs = max([...inbound, ...outbound].map((stat) => secondsToMs(numericStat(stat, "jitter"))).filter((value) => value !== undefined));
1289
- const jitterBufferDelayMs = max(inbound.map((stat) => {
1290
- const delay = numericStat(stat, "jitterBufferDelay");
1291
- const emitted = numericStat(stat, "jitterBufferEmittedCount");
1292
- return delay !== undefined && emitted !== undefined && emitted > 0 ? delay / emitted * 1000 : undefined;
1293
- }).filter((value) => value !== undefined));
1294
- const audioLevels = audioTracks.map((stat) => numericStat(stat, "audioLevel")).filter((value) => value !== undefined);
1295
- if (input.requireConnectedCandidatePair && candidatePairs.length > 0 && activeCandidatePairs === 0) {
1296
- pushIssue(issues, "error", "media.webrtc_candidate_pair_missing", "No active WebRTC candidate pair was observed.");
1297
- }
1298
- if (input.requireLiveAudioTrack && liveAudioTracks === 0) {
1299
- pushIssue(issues, "error", "media.webrtc_audio_track_missing", "No live WebRTC audio track was observed.");
1300
- }
1301
- if (input.maxPacketLossRatio !== undefined && packetLossRatio > input.maxPacketLossRatio) {
1302
- pushIssue(issues, "warning", "media.webrtc_packet_loss", `Observed WebRTC packet loss ratio ${String(packetLossRatio)} above ${String(input.maxPacketLossRatio)}.`);
1303
- }
1304
- if (input.maxRoundTripTimeMs !== undefined && roundTripTimeMs !== undefined && roundTripTimeMs > input.maxRoundTripTimeMs) {
1305
- pushIssue(issues, "warning", "media.webrtc_round_trip_time", `Observed WebRTC RTT ${String(roundTripTimeMs)}ms above ${String(input.maxRoundTripTimeMs)}ms.`);
1306
- }
1307
- if (input.maxJitterMs !== undefined && jitterMs !== undefined && jitterMs > input.maxJitterMs) {
1308
- pushIssue(issues, "warning", "media.webrtc_jitter", `Observed WebRTC jitter ${String(jitterMs)}ms above ${String(input.maxJitterMs)}ms.`);
1309
- }
1310
- return {
1311
- activeCandidatePairs,
1312
- audioLevelAverage: average(audioLevels),
1313
- bytesReceived,
1314
- bytesSent,
1315
- checkedAt: Date.now(),
1316
- endedAudioTracks,
1317
- inboundPackets,
1318
- issues,
1319
- jitterBufferDelayMs,
1320
- jitterMs,
1321
- liveAudioTracks,
1322
- outboundPackets,
1323
- packetLossRatio,
1324
- packetsLost,
1325
- roundTripTimeMs,
1326
- status: issues.some((issue) => issue.severity === "error") ? "fail" : issues.length > 0 ? "warn" : "pass",
1327
- totalStats: stats.length
1328
- };
1329
- };
1330
- var collectMediaWebRTCStats = async (input) => {
1331
- const report = await input.peerConnection.getStats(input.selector ?? null);
1332
- return [...report.values()].map(normalizeWebRTCStat);
1333
- };
1334
- var buildMediaWebRTCStreamContinuityReport = (input = {}) => {
1335
- const stats = input.stats ?? [];
1336
- const previousStats = input.previousStats ?? [];
1337
- const issues = [];
1338
- const previousByKey = new Map(previousStats.map((stat) => [statKey(stat), stat]));
1339
- const audioRtp = stats.filter((stat) => (stat.type === "inbound-rtp" || stat.type === "outbound-rtp") && stringStat(stat, "kind") !== "video" && stringStat(stat, "mediaType") !== "video");
1340
- const streams = audioRtp.map((stat) => {
1341
- const direction = stat.type === "outbound-rtp" ? "outbound" : "inbound";
1342
- const packetsKey = direction === "outbound" ? "packetsSent" : "packetsReceived";
1343
- const bytesKey = direction === "outbound" ? "bytesSent" : "bytesReceived";
1344
- const previous = previousByKey.get(statKey(stat));
1345
- const currentPackets = numericStat(stat, packetsKey);
1346
- const previousPackets = previous ? numericStat(previous, packetsKey) : undefined;
1347
- const currentBytes = numericStat(stat, bytesKey);
1348
- const previousBytes = previous ? numericStat(previous, bytesKey) : undefined;
1349
- const timeDeltaMs = stat.timestamp !== undefined && previous?.timestamp !== undefined ? stat.timestamp - previous.timestamp : undefined;
1350
- return {
1351
- bytesDelta: currentBytes !== undefined && previousBytes !== undefined ? currentBytes - previousBytes : undefined,
1352
- currentPackets,
1353
- direction,
1354
- id: statKey(stat),
1355
- packetDelta: currentPackets !== undefined && previousPackets !== undefined ? currentPackets - previousPackets : undefined,
1356
- previousPackets,
1357
- timeDeltaMs
1358
- };
1359
- });
1360
- const inbound = streams.filter((stream) => stream.direction === "inbound");
1361
- const outbound = streams.filter((stream) => stream.direction === "outbound");
1362
- const maxObservedGapMs = max(streams.map((stream) => stream.timeDeltaMs).filter((value) => value !== undefined));
1363
- const stalledInboundStreams = inbound.filter((stream) => input.maxInboundPacketStallMs !== undefined && stream.timeDeltaMs !== undefined && stream.timeDeltaMs >= input.maxInboundPacketStallMs && stream.packetDelta !== undefined && stream.packetDelta <= 0).length;
1364
- const stalledOutboundStreams = outbound.filter((stream) => input.maxOutboundPacketStallMs !== undefined && stream.timeDeltaMs !== undefined && stream.timeDeltaMs >= input.maxOutboundPacketStallMs && stream.packetDelta !== undefined && stream.packetDelta <= 0).length;
1365
- if (input.requireInboundAudio && inbound.length === 0) {
1366
- pushIssue(issues, "error", "media.webrtc_inbound_audio_missing", "No inbound WebRTC audio RTP stream was observed.");
1367
- }
1368
- if (input.requireOutboundAudio && outbound.length === 0) {
1369
- pushIssue(issues, "error", "media.webrtc_outbound_audio_missing", "No outbound WebRTC audio RTP stream was observed.");
1370
- }
1371
- if (input.maxGapMs !== undefined && maxObservedGapMs !== undefined && maxObservedGapMs > input.maxGapMs) {
1372
- pushIssue(issues, "warning", "media.webrtc_stream_gap", `Observed WebRTC stream sample gap ${String(maxObservedGapMs)}ms above ${String(input.maxGapMs)}ms.`);
1373
- }
1374
- if (stalledInboundStreams > 0) {
1375
- pushIssue(issues, "error", "media.webrtc_inbound_stalled", `${String(stalledInboundStreams)} inbound WebRTC audio stream(s) stopped receiving packets.`);
1376
- }
1377
- if (stalledOutboundStreams > 0) {
1378
- pushIssue(issues, "error", "media.webrtc_outbound_stalled", `${String(stalledOutboundStreams)} outbound WebRTC audio stream(s) stopped sending packets.`);
1379
- }
1380
- return {
1381
- checkedAt: Date.now(),
1382
- inboundAudioStreams: inbound.length,
1383
- issues,
1384
- maxObservedGapMs,
1385
- outboundAudioStreams: outbound.length,
1386
- stalledInboundStreams,
1387
- stalledOutboundStreams,
1388
- status: issues.some((issue) => issue.severity === "error") ? "fail" : issues.length > 0 ? "warn" : "pass",
1389
- streams,
1390
- totalStats: stats.length
1391
- };
1392
- };
1393
- var buildMediaPipelineCalibrationReport = (input = {}) => {
1394
- const frames = input.frames ?? [];
1395
- const issues = [];
1396
- const inputFrames = frames.filter((frame) => frame.kind === "input-audio");
1397
- const assistantFrames = frames.filter((frame) => frame.kind === "assistant-audio");
1398
- const turnCommitFrames = frames.filter((frame) => frame.kind === "turn-commit");
1399
- const interruptionFrameRecords = frames.filter((frame) => frame.kind === "interruption");
1400
- const traceLinkedFrames = frames.filter((frame) => frame.traceEventId).length;
1401
- const backpressureFrames = frames.filter((frame) => Boolean(frame.metadata?.backpressure)).length;
1402
- const audioLatencies = assistantFrames.map((frame) => frame.latencyMs).filter((latency) => typeof latency === "number");
1403
- const firstAudioLatencyMs = audioLatencies.length > 0 ? Math.min(...audioLatencies) : undefined;
1404
- const jitterValues = frames.map((frame) => numericMetadata(frame, "jitterMs")).filter((value) => value !== undefined);
1405
- const jitterMs = jitterValues.length > 0 ? Math.max(...jitterValues) : undefined;
1406
- const inputFormat = input.inputFormat ?? inputFrames.find((frame) => frame.format)?.format;
1407
- const outputFormat = input.outputFormat ?? assistantFrames.find((frame) => frame.format)?.format;
1408
- const resamplingRequired = Boolean(input.expectedInputFormat && inputFormat && inputFormat.sampleRateHz !== input.expectedInputFormat.sampleRateHz) || Boolean(input.expectedOutputFormat && outputFormat && outputFormat.sampleRateHz !== input.expectedOutputFormat.sampleRateHz);
1409
- const resamplingTargetHz = resamplingRequired && input.expectedInputFormat ? input.expectedInputFormat.sampleRateHz : resamplingRequired ? input.expectedOutputFormat?.sampleRateHz : undefined;
1410
- if (inputFrames.length === 0) {
1411
- pushIssue(issues, "warning", "media.input_audio_missing", "No input audio frames were observed.");
1412
- }
1413
- if (assistantFrames.length === 0) {
1414
- pushIssue(issues, "warning", "media.assistant_audio_missing", "No assistant audio frames were observed.");
1415
- }
1416
- if (input.expectedInputFormat && inputFormat && !formatMatches(inputFormat, input.expectedInputFormat)) {
1417
- pushIssue(issues, inputFormat.sampleRateHz === input.expectedInputFormat.sampleRateHz ? "warning" : "error", "media.input_format_mismatch", `Input format ${formatLabel(inputFormat)} does not match expected ${formatLabel(input.expectedInputFormat)}.`);
1418
- }
1419
- if (input.expectedOutputFormat && outputFormat && !formatMatches(outputFormat, input.expectedOutputFormat)) {
1420
- pushIssue(issues, outputFormat.sampleRateHz === input.expectedOutputFormat.sampleRateHz ? "warning" : "error", "media.output_format_mismatch", `Output format ${formatLabel(outputFormat)} does not match expected ${formatLabel(input.expectedOutputFormat)}.`);
1421
- }
1422
- if (firstAudioLatencyMs !== undefined && input.maxFirstAudioLatencyMs !== undefined && firstAudioLatencyMs > input.maxFirstAudioLatencyMs) {
1423
- pushIssue(issues, "error", "media.first_audio_latency", `First audio latency ${String(firstAudioLatencyMs)}ms exceeds budget ${String(input.maxFirstAudioLatencyMs)}ms.`);
1424
- }
1425
- if (jitterMs !== undefined && input.maxJitterMs !== undefined && jitterMs > input.maxJitterMs) {
1426
- pushIssue(issues, "warning", "media.jitter", `Media jitter ${String(jitterMs)}ms exceeds budget ${String(input.maxJitterMs)}ms.`);
1427
- }
1428
- if (input.maxBackpressureFrames !== undefined && backpressureFrames > input.maxBackpressureFrames) {
1429
- pushIssue(issues, "warning", "media.backpressure", `Backpressure frame count ${String(backpressureFrames)} exceeds budget ${String(input.maxBackpressureFrames)}.`);
1430
- }
1431
- if (input.requireInterruptionFrame && interruptionFrameRecords.length === 0) {
1432
- pushIssue(issues, "warning", "media.interruption_missing", "No interruption frame was observed.");
1433
- }
1434
- if (input.requireTraceEvidence && traceLinkedFrames === 0) {
1435
- pushIssue(issues, "warning", "media.trace_evidence_missing", "No media frames were linked to trace evidence.");
1436
- }
1437
- return {
1438
- assistantAudioFrames: assistantFrames.length,
1439
- backpressureFrames,
1440
- checkedAt: Date.now(),
1441
- firstAudioLatencyMs,
1442
- inputAudioFrames: inputFrames.length,
1443
- inputFormat,
1444
- interruptionFrames: interruptionFrameRecords.length,
1445
- issues,
1446
- jitterMs,
1447
- outputFormat,
1448
- resamplingRequired,
1449
- resamplingTargetHz,
1450
- status: issues.some((issue) => issue.severity === "error") ? "fail" : issues.length > 0 ? "warn" : "pass",
1451
- surface: input.surface ?? "media-pipeline",
1452
- traceLinkedFrames,
1453
- turnCommitFrames: turnCommitFrames.length
1454
- };
1455
- };
1456
- var DEFAULT_METADATA_DENY = [
1457
- "audioPayload",
1458
- "auth",
1459
- "authorization",
1460
- "cookie",
1461
- "email",
1462
- "phone",
1463
- "phoneNumber",
1464
- "rawPayload",
1465
- "secret",
1466
- "token",
1467
- "transcript",
1468
- "utterance"
1469
- ];
1470
- var DEFAULT_TRUNCATE = 8;
1471
- var issueCodes = (issues) => Array.from(new Set(issues.map((issue) => issue.code)));
1472
- var lastEventKind = (events) => events[events.length - 1]?.kind;
1473
- var formatOptionalMs = (value) => value === undefined ? "n/a" : `${String(Math.round(value))}ms`;
1474
- var formatRatio = (value) => `${(value * 100).toFixed(1)}%`;
1475
- var escapeMarkdownCell = (value) => value.replace(/\|/g, "\\|").replace(/\n/g, " ");
1476
- var renderIssuesTable = (issues) => {
1477
- if (issues.length === 0) {
1478
- return `- No issues.
1479
- `;
1480
- }
1481
- const rows = issues.map((issue) => `| ${issue.severity} | ${escapeMarkdownCell(issue.code)} | ${escapeMarkdownCell(issue.message)} |`).join(`
1482
- `);
1483
- return `| Severity | Code | Message |
1484
- | --- | --- | --- |
1485
- ${rows}
1486
- `;
1487
- };
1488
- var summarizeMediaQualityReport = (report) => ({
1489
- backpressureEvents: report.backpressureEvents,
1490
- description: `${report.totalFrames} frame(s), ${report.gapCount} gap(s), speech ${formatRatio(report.speechRatio)}, status ${report.status}.`,
1491
- driftMs: report.timestampDriftMs,
1492
- frameCount: report.totalFrames,
1493
- gapCount: report.gapCount,
1494
- issueCodes: issueCodes(report.issues),
1495
- issueCount: report.issues.length,
1496
- jitterMs: report.jitterMs,
1497
- silenceRatio: report.silenceRatio,
1498
- speechRatio: report.speechRatio,
1499
- status: report.status
1500
- });
1501
- var summarizeMediaTransportReport = (report) => ({
1502
- backpressureEvents: report.backpressureEvents,
1503
- description: `${report.name}: ${report.state}, in ${report.inputFrames}, out ${report.outputFrames}, backpressure ${report.backpressureEvents}.`,
1504
- errors: report.events.filter((event) => event.kind === "error").length,
1505
- inputFrames: report.inputFrames,
1506
- lastEventKind: lastEventKind(report.events),
1507
- name: report.name,
1508
- outputFrames: report.outputFrames,
1509
- state: report.state,
1510
- status: report.status
1511
- });
1512
- var summarizeMediaProcessorGraphReport = (report) => {
1513
- const errorIssueCodes = Array.from(new Set(report.errors.map((event) => event.kind)));
1514
- return {
1515
- backpressureEvents: report.backpressure.events.length,
1516
- description: `${report.name}: ${report.state}, ${report.nodes.length} node(s), in ${report.inputFrames}, out ${report.emittedFrames}, dropped ${report.droppedFrames}.`,
1517
- droppedFrames: report.droppedFrames,
1518
- edgeCount: report.edges.length,
1519
- edgeEventCount: report.edgeEvents.length,
1520
- emittedFrames: report.emittedFrames,
1521
- errorCount: report.errors.length,
1522
- inputFrames: report.inputFrames,
1523
- issueCodes: errorIssueCodes,
1524
- lifecycleEventCount: report.lifecycleEvents.length,
1525
- name: report.name,
1526
- nodeCount: report.nodes.length,
1527
- state: report.state,
1528
- status: report.status,
1529
- timingMaxMs: report.timing.maxNodeMs
1530
- };
1531
- };
1532
- var renderMediaQualityMarkdown = (report, options = {}) => {
1533
- const title = options.title ?? "Media Quality Report";
1534
- const lines = [
1535
- `# ${title}`,
1536
- "",
1537
- `Status: **${report.status}**`,
1538
- "",
1539
- "| Metric | Value |",
1540
- "| --- | ---: |",
1541
- `| Total frames | ${report.totalFrames} |`,
1542
- `| Input audio | ${report.inputAudioFrames} |`,
1543
- `| Assistant audio | ${report.assistantAudioFrames} |`,
1544
- `| Gaps | ${report.gapCount} |`,
1545
- `| Jitter | ${formatOptionalMs(report.jitterMs)} |`,
1546
- `| Timestamp drift | ${formatOptionalMs(report.timestampDriftMs)} |`,
1547
- `| Speech ratio | ${formatRatio(report.speechRatio)} |`,
1548
- `| Silence ratio | ${formatRatio(report.silenceRatio)} |`,
1549
- `| Backpressure events | ${report.backpressureEvents} |`,
1550
- "",
1551
- "## Issues",
1552
- "",
1553
- renderIssuesTable(report.issues).trimEnd()
1554
- ];
1555
- return `${lines.join(`
1556
- `)}
1557
- `;
1558
- };
1559
- var renderMediaTransportMarkdown = (report, options = {}) => {
1560
- const title = options.title ?? `Media Transport: ${report.name}`;
1561
- const limit = options.redact?.truncateArraysAt ?? DEFAULT_TRUNCATE;
1562
- const events = report.events.slice(-limit);
1563
- 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(`
1564
- `);
1565
- const lines = [
1566
- `# ${title}`,
1567
- "",
1568
- `Status: **${report.status}** \xB7 State: **${report.state}**`,
1569
- "",
1570
- "| Metric | Value |",
1571
- "| --- | ---: |",
1572
- `| Input frames | ${report.inputFrames} |`,
1573
- `| Output frames | ${report.outputFrames} |`,
1574
- `| Backpressure events | ${report.backpressureEvents} |`,
1575
- `| Connected | ${report.connected ? "yes" : "no"} |`,
1576
- `| Closed | ${report.closed ? "yes" : "no"} |`,
1577
- `| Failed | ${report.failed ? "yes" : "no"} |`,
1578
- "",
1579
- `## Last ${events.length} event(s)`,
1580
- "",
1581
- eventRows
1582
- ];
1583
- return `${lines.join(`
1584
- `)}
1585
- `;
1586
- };
1587
- var renderMediaProcessorGraphMarkdown = (report, options = {}) => {
1588
- const title = options.title ?? `Media Processor Graph: ${report.name}`;
1589
- const limit = options.redact?.truncateArraysAt ?? DEFAULT_TRUNCATE;
1590
- const nodeRows = report.nodes.map((node) => `| ${escapeMarkdownCell(node.name)} | ${node.kind} | ${node.status} | ${node.inputFrames} | ${node.emittedFrames} | ${node.droppedFrames} | ${node.errors.length} |`).join(`
1591
- `);
1592
- const edgeRows = report.edges.slice(0, limit).map((edge) => `| ${escapeMarkdownCell(edge.from)} | ${escapeMarkdownCell(edge.to)} | ${edge.status} | ${edge.emittedFrames} |`).join(`
1593
- `);
1594
- const issues = report.errors.map((event) => ({
1595
- code: event.kind,
1596
- message: event.error ?? `Processor graph ${event.kind} (state ${event.state}).`,
1597
- severity: "error"
1598
- }));
1599
- const lines = [
1600
- `# ${title}`,
1601
- "",
1602
- `Status: **${report.status}** \xB7 State: **${report.state}**`,
1603
- "",
1604
- "| Metric | Value |",
1605
- "| --- | ---: |",
1606
- `| Nodes | ${report.nodes.length} |`,
1607
- `| Input frames | ${report.inputFrames} |`,
1608
- `| Emitted frames | ${report.emittedFrames} |`,
1609
- `| Dropped frames | ${report.droppedFrames} |`,
1610
- `| Lifecycle events | ${report.lifecycleEvents.length} |`,
1611
- `| Edge events | ${report.edgeEvents.length} |`,
1612
- `| Backpressure events | ${report.backpressure.events.length} |`,
1613
- `| Timing max | ${formatOptionalMs(report.timing.maxNodeMs)} |`,
1614
- `| Timing average | ${formatOptionalMs(report.timing.averageNodeMs)} |`,
1615
- "",
1616
- "## Nodes",
1617
- "",
1618
- nodeRows ? `| Node | Kind | Status | In | Out | Dropped | Errors |
1619
- | --- | --- | --- | ---: | ---: | ---: | ---: |
1620
- ${nodeRows}` : "- No nodes.",
1621
- "",
1622
- `## Edges (showing up to ${limit})`,
1623
- "",
1624
- edgeRows ? `| From | To | Status | Frames |
1625
- | --- | --- | --- | ---: |
1626
- ${edgeRows}` : "- No edges.",
1627
- "",
1628
- "## Errors",
1629
- "",
1630
- renderIssuesTable(issues).trimEnd()
1631
- ];
1632
- return `${lines.join(`
1633
- `)}
1634
- `;
1635
- };
1636
- var truncateArrays = (value, limit, seen) => {
1637
- if (Array.isArray(value)) {
1638
- const head = value.slice(0, limit).map((entry) => truncateArrays(entry, limit, seen));
1639
- if (value.length > limit) {
1640
- return [...head, { truncated: value.length - limit }];
1641
- }
1642
- return head;
1643
- }
1644
- if (value && typeof value === "object") {
1645
- if (seen.has(value))
1646
- return value;
1647
- seen.add(value);
1648
- const next = {};
1649
- for (const [key, entry] of Object.entries(value)) {
1650
- next[key] = truncateArrays(entry, limit, seen);
1651
- }
1652
- return next;
1653
- }
1654
- return value;
1655
- };
1656
- var applyRedaction = (value, options, seen) => {
1657
- const mode = options.mode ?? "omit";
1658
- const maskValue = options.maskValue ?? "[redacted]";
1659
- const allow = new Set(options.metadataAllow ?? []);
1660
- const deny = new Set(options.metadataDeny ?? DEFAULT_METADATA_DENY);
1661
- const walk = (input) => {
1662
- if (Array.isArray(input)) {
1663
- return input.map((entry) => walk(entry));
1664
- }
1665
- if (input && typeof input === "object") {
1666
- if (seen.has(input))
1667
- return input;
1668
- seen.add(input);
1669
- const next = {};
1670
- for (const [key, entry] of Object.entries(input)) {
1671
- if (allow.has(key)) {
1672
- next[key] = entry;
1673
- continue;
1674
- }
1675
- if (deny.has(key)) {
1676
- if (mode === "mask")
1677
- next[key] = maskValue;
1678
- continue;
1679
- }
1680
- next[key] = walk(entry);
1681
- }
1682
- return next;
1683
- }
1684
- return input;
1685
- };
1686
- return walk(value);
1687
- };
1688
- var redactMediaReport = (report, options = {}) => {
1689
- const limit = options.truncateArraysAt ?? DEFAULT_TRUNCATE;
1690
- const truncated = truncateArrays(report, limit, new WeakSet);
1691
- return applyRedaction(truncated, options, new WeakSet);
1692
- };
1693
- var buildArtifactPair = (report, summary, markdown, options) => {
1694
- const jsonValue = options.redact ? redactMediaReport(report, options.redact) : report;
1695
- return {
1696
- json: JSON.stringify(jsonValue, null, 2),
1697
- jsonValue,
1698
- markdown,
1699
- summary
1700
- };
1701
- };
1702
- var buildMediaQualityArtifact = (report, options = {}) => buildArtifactPair(report, summarizeMediaQualityReport(report), renderMediaQualityMarkdown(report, options), options);
1703
- var buildMediaTransportArtifact = (report, options = {}) => buildArtifactPair(report, summarizeMediaTransportReport(report), renderMediaTransportMarkdown(report, options), options);
1704
- var buildMediaProcessorGraphArtifact = (report, options = {}) => buildArtifactPair(report, summarizeMediaProcessorGraphReport(report), renderMediaProcessorGraphMarkdown(report, options), options);
1705
- var writeMediaArtifact = async (input) => {
1706
- await mkdir(input.dir, { recursive: true });
1707
- const jsonPath = join(input.dir, `${input.slug}.json`);
1708
- const markdownPath = join(input.dir, `${input.slug}.md`);
1709
- await Promise.all([
1710
- writeFile(jsonPath, input.json, "utf8"),
1711
- writeFile(markdownPath, input.markdown, "utf8")
1712
- ]);
1713
- return {
1714
- jsonPath,
1715
- markdownPath,
1716
- summary: input.summary
1717
- };
1718
- };
1719
-
1720
793
  // src/client/browserMedia.ts
794
+ import {
795
+ buildMediaWebRTCStatsReport,
796
+ buildMediaWebRTCStreamContinuityReport,
797
+ collectMediaWebRTCStats
798
+ } from "@absolutejs/media";
1721
799
  var DEFAULT_BROWSER_MEDIA_PATH = "/api/voice/browser-media";
1722
800
  var DEFAULT_BROWSER_MEDIA_INTERVAL_MS = 5000;
1723
801
  var resolvePeerConnection = async (options) => options.peerConnection ?? await options.getPeerConnection?.() ?? null;