realtime-avatar 0.35.0 → 0.37.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -832,6 +832,134 @@ var liveKitSessionReleaseReasonSchema = z.enum([
832
832
  "manual",
833
833
  "idle_timeout"
834
834
  ]);
835
+ var schema08 = z.string().min(1).max(2e3);
836
+ var schema117 = z.enum(["mp3", "wav"]);
837
+ var schema212 = z.number().min(0.5).max(2);
838
+ var schema37 = z.string().regex(new RegExp("^[A-Za-z0-9-]+$")).min(2).max(16);
839
+ var schema47 = z.strictObject({
840
+ "text": z.string().trim().pipe(schema08),
841
+ "format": schema117.optional(),
842
+ "speed": schema212.optional(),
843
+ "language": schema37.optional()
844
+ });
845
+ var schema56 = z.string().regex(new RegExp("^(vce|voice)_"));
846
+ var schema64 = z.number().min(0);
847
+ var schema74 = z.int().min(1);
848
+ var schema84 = z.strictObject({
849
+ "text": z.string().trim().pipe(schema08),
850
+ "speed": schema212.optional(),
851
+ "language": schema37.optional()
852
+ });
853
+ var schema94 = z.string().max(4096);
854
+ var schema104 = z.number().min(0).max(180);
855
+ var schema118 = z.strictObject({
856
+ "text": schema94,
857
+ "start": schema104,
858
+ "end": schema104
859
+ });
860
+ var speechAlignedTextSchema = schema118.refine((segment) => segment.end >= segment.start);
861
+ var schema134 = z.uuid().regex(new RegExp("^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"));
862
+ var schema144 = z.literal("started");
863
+ var schema154 = z.literal("pcm_s16le");
864
+ var schema163 = z.literal(24e3);
865
+ var schema173 = z.literal(1);
866
+ var schema183 = z.strictObject({
867
+ "requestId": schema134,
868
+ "type": schema144,
869
+ "encoding": schema154,
870
+ "sampleRate": schema163,
871
+ "channels": schema173
872
+ });
873
+ var schema193 = z.literal("audio");
874
+ var schema202 = z.int().min(0).max(9007199254740991);
875
+ var schema213 = z.int().min(0).max(432e4);
876
+ var schema222 = z.base64().regex(new RegExp("^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$")).min(4).max(21848);
877
+ var schema232 = z.strictObject({
878
+ "requestId": schema134,
879
+ "type": schema193,
880
+ "sequence": schema202,
881
+ "sampleOffset": schema213,
882
+ "audioBase64": schema222
883
+ });
884
+ var schema242 = z.literal("alignment");
885
+ var schema252 = z.int().min(0).max(127);
886
+ var schema262 = z.array(speechAlignedTextSchema).max(2048);
887
+ var schema272 = z.strictObject({
888
+ "requestId": schema134,
889
+ "type": schema242,
890
+ "chunkSeq": schema252,
891
+ "segments": schema262
892
+ });
893
+ var schema282 = z.literal("completed");
894
+ var schema292 = z.int().max(432e4).gt(0);
895
+ var schema30 = z.int().max(9007199254740991).gt(0);
896
+ var schema31 = z.strictObject({
897
+ "requestId": schema134,
898
+ "type": schema282,
899
+ "totalSamples": schema292,
900
+ "billedCredits": schema64,
901
+ "billedBytes": schema30
902
+ });
903
+ var schema322 = z.literal("failed");
904
+ var schema332 = z.string();
905
+ var schema342 = z.int().min(-9007199254740991).max(9007199254740991);
906
+ var schema352 = z.string();
907
+ var schema362 = z.url();
908
+ var schema372 = z.boolean();
909
+ var schema38 = z.uuid().regex(new RegExp("^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"));
910
+ var schema39 = z.enum(["*", "api_keys:write", "credits:read", "avatars:read", "avatars:write", "realtime:write", "usage:read", "recordings:read", "usage:write", "speech:write", "renders:read", "renders:write"]);
911
+ var schema40 = z.enum(["*", "api_keys:write", "credits:read", "avatars:read", "avatars:write", "realtime:write", "usage:read", "recordings:read", "usage:write", "speech:write", "renders:read", "renders:write"]);
912
+ var schema41 = z.array(schema40);
913
+ var schema422 = z.string();
914
+ var schema432 = z.int().max(9007199254740991).gt(0);
915
+ var schema442 = z.int().min(0).max(9007199254740991);
916
+ var schema452 = z.int().min(0).max(9007199254740991);
917
+ var schema462 = z.int().min(0).max(9007199254740991);
918
+ var schema472 = z.int().min(0).max(9007199254740991);
919
+ var schema48 = z.looseObject({
920
+ "error": schema332,
921
+ "status": schema342,
922
+ "code": schema352,
923
+ "documentation": schema362,
924
+ "retryable": schema372.optional(),
925
+ "requestId": schema38.optional(),
926
+ "requiredScope": schema39.optional(),
927
+ "grantedScopes": schema41.optional(),
928
+ "billingUrl": schema422.optional(),
929
+ "maxConcurrentSessions": schema432.optional(),
930
+ "liveSessions": schema442.optional(),
931
+ "activeSessions": schema452.optional(),
932
+ "connectingSessions": schema462.optional(),
933
+ "pendingSessions": schema472.optional()
934
+ });
935
+ var schema49 = z.strictObject({
936
+ "requestId": schema134,
937
+ "type": schema322,
938
+ "error": schema48
939
+ });
940
+ var schema50 = z.union([schema183, schema232, schema272, schema31, schema49]);
941
+ var createSpeechRequestSchema = schema47.extend({
942
+ format: schema47.shape.format.unwrap().default("mp3")
943
+ });
944
+ var createSpeechStreamRequestSchema = schema84;
945
+ var speechStreamEventSchema = schema50;
946
+ var SPEECH_STREAM_CONTRACT = { "maxAudioEventBytes": 16384, "maxSamples": 432e4};
947
+ var speechVoiceIdSchema = schema56;
948
+ var speechContentTypeSchema = z.enum(["audio/mpeg", "audio/wav"]);
949
+ var speechResponseHeadersSchema = z.strictObject({
950
+ "X-RTA-Billed-Credits": z.string().regex(/^(?:0|[1-9][0-9]*)(?:\.[0-9]+)?$/).transform(Number).pipe(schema64).nullable(),
951
+ "X-RTA-Billed-Bytes": z.string().regex(/^(?:0|[1-9][0-9]*)(?:\.[0-9]+)?$/).transform(Number).pipe(schema74).nullable()
952
+ });
953
+ function readSpeechHeaders(headers) {
954
+ const parsed = speechResponseHeadersSchema.parse({
955
+ "X-RTA-Billed-Credits": headers.get("X-RTA-Billed-Credits"),
956
+ "X-RTA-Billed-Bytes": headers.get("X-RTA-Billed-Bytes")
957
+ });
958
+ return {
959
+ billedCredits: parsed["X-RTA-Billed-Credits"],
960
+ billedBytes: parsed["X-RTA-Billed-Bytes"]
961
+ };
962
+ }
835
963
 
836
964
  // ../http-client/src/retry.ts
837
965
  var RETRYABLE_STATUS = /* @__PURE__ */ new Set([408, 500, 502, 503, 504]);
@@ -864,119 +992,442 @@ function isTransient(cause) {
864
992
  const name = cause?.name;
865
993
  return name === "TimeoutError" || name === "TypeError" || name === "FetchError";
866
994
  }
867
- var schema08 = z.string().min(1).max(160);
868
- var schema117 = z.custom((value) => typeof value === "object" && value !== null && !Array.isArray(value));
869
- var schema212 = z.enum(["cartesia", "fish"]);
870
- var schema37 = z.string().min(1).max(240);
871
- var schema47 = z.string().min(1).max(120);
872
- var schema56 = z.number().min(0.5).max(2);
873
- var schema64 = z.null();
874
- var schema74 = z.union([schema56, schema64]);
875
- var schema84 = z.string().min(1).max(80);
876
- var schema94 = z.union([schema84, schema64]);
877
- var schema104 = z.string().min(2).max(16);
878
- var schema118 = z.union([schema104, schema64]);
995
+ var schema09 = z.string().min(1).max(160);
996
+ var schema119 = z.custom((value) => typeof value === "object" && value !== null && !Array.isArray(value));
997
+ var schema214 = z.enum(["cartesia", "fish"]);
998
+ var schema310 = z.string().min(1).max(240);
999
+ var schema410 = z.string().min(1).max(120);
1000
+ var schema57 = z.number().min(0.5).max(2);
1001
+ var schema65 = z.null();
1002
+ var schema75 = z.union([schema57, schema65]);
1003
+ var schema85 = z.string().min(1).max(80);
1004
+ var schema95 = z.union([schema85, schema65]);
1005
+ var schema105 = z.string().min(2).max(16);
1006
+ var schema1110 = z.union([schema105, schema65]);
879
1007
  var schema124 = z.strictObject({
880
- "provider": schema212,
881
- "voice_id": schema37,
882
- "model": schema47.optional(),
883
- "speed": schema74.optional(),
884
- "emotion": schema94.optional(),
885
- "language": schema118.optional()
886
- });
887
- var schema134 = z.string().min(8).max(80);
888
- var schema144 = z.string();
889
- var schema154 = z.enum(["video", "live2d"]);
890
- var schema163 = z.enum(["image", "video"]);
891
- var schema173 = z.enum(["realtime-avatar-live-v1", "realtime-avatar-video-v1"]);
892
- var schema183 = z.union([schema134, schema64]);
893
- var schema193 = z.enum(["draft", "preprocessing", "ready", "failed", "disabled", "deleted"]);
894
- var schema202 = z.union([schema144, schema64]);
895
- var schema213 = z.enum(["none", "queued", "generating", "ready", "failed"]);
896
- var schema222 = z.enum(["local", "gemini", "openai"]);
897
- var schema232 = z.string().max(200);
898
- var schema242 = z.union([schema232, schema64]);
899
- var schema252 = z.strictObject({
900
- "provider": schema222,
901
- "model": schema242.optional()
902
- });
903
- var schema262 = z.union([schema252, schema64]);
904
- var schema272 = z.strictObject({
905
- "id": schema134,
906
- "tenantId": schema134,
907
- "displayName": schema144,
908
- "renderer": schema154,
909
- "sourceKind": schema163,
910
- "modelId": schema173,
911
- "sourceAssetId": schema183,
912
- "status": schema193,
913
- "error": schema202,
914
- "idleVideoStatus": schema213,
915
- "defaultVoiceId": schema202,
916
- "llm": schema262,
917
- "createdAt": schema144,
918
- "updatedAt": schema144
1008
+ "provider": schema214,
1009
+ "voice_id": schema310,
1010
+ "model": schema410.optional(),
1011
+ "speed": schema75.optional(),
1012
+ "emotion": schema95.optional(),
1013
+ "language": schema1110.optional()
1014
+ });
1015
+ var schema135 = z.string().min(8).max(80);
1016
+ var schema145 = z.string();
1017
+ var schema155 = z.enum(["video", "live2d"]);
1018
+ var schema164 = z.enum(["image", "video"]);
1019
+ var schema174 = z.enum(["realtime-avatar-live-v1", "realtime-avatar-video-v1"]);
1020
+ var schema184 = z.union([schema135, schema65]);
1021
+ var schema194 = z.enum(["draft", "preprocessing", "ready", "failed", "disabled", "deleted"]);
1022
+ var schema203 = z.union([schema145, schema65]);
1023
+ var schema215 = z.enum(["none", "queued", "generating", "ready", "failed"]);
1024
+ var schema223 = z.enum(["local", "gemini", "openai"]);
1025
+ var schema233 = z.string().max(200);
1026
+ var schema243 = z.union([schema233, schema65]);
1027
+ var schema253 = z.strictObject({
1028
+ "provider": schema223,
1029
+ "model": schema243.optional()
1030
+ });
1031
+ var schema263 = z.union([schema253, schema65]);
1032
+ var schema273 = z.strictObject({
1033
+ "id": schema135,
1034
+ "tenantId": schema135,
1035
+ "displayName": schema145,
1036
+ "renderer": schema155,
1037
+ "sourceKind": schema164,
1038
+ "modelId": schema174,
1039
+ "sourceAssetId": schema184,
1040
+ "status": schema194,
1041
+ "error": schema203,
1042
+ "idleVideoStatus": schema215,
1043
+ "defaultVoiceId": schema203,
1044
+ "llm": schema263,
1045
+ "createdAt": schema145,
1046
+ "updatedAt": schema145
919
1047
  });
920
1048
  var createLive2dAvatarInputSchema = z.strictObject({
921
- displayName: schema08,
922
- settings: schema117.optional(),
923
- metadata: schema117.optional(),
1049
+ displayName: schema09,
1050
+ settings: schema119.optional(),
1051
+ metadata: schema119.optional(),
924
1052
  voice: schema124
925
1053
  });
926
- var avatarResponseSchema = schema272;
927
- var schema09 = z.url().regex(new RegExp("^https:\\/\\/")).max(500);
928
- var schema119 = z.string().min(16).max(200);
929
- var schema214 = z.string().min(1).max(200);
930
- var schema38 = z.string().min(2).max(35);
931
- var schema48 = z.literal([8e3, 16e3, 22050, 24e3, 44100, 48e3]);
932
- var schema57 = z.int().min(1e3).max(15e3);
933
- var schema65 = z.strictObject({
934
- "url": schema09,
935
- "secret": schema119,
936
- "voice_id": schema214.optional(),
937
- "language": schema38.optional(),
938
- "sample_rate": schema48.optional(),
939
- "timeout_ms": schema57.optional()
940
- });
941
- var schema75 = z.literal("voice.synthesize");
942
- var schema85 = z.literal(1);
943
- var schema95 = z.string().min(1).max(200);
944
- var schema105 = z.string().min(1).max(200);
945
- var schema1110 = z.object({
946
- "generation_id": schema95,
947
- "utterance_id": schema105
1054
+ var avatarResponseSchema = schema273;
1055
+
1056
+ // ../../node_modules/eventsource-parser/dist/index.js
1057
+ var ParseError = class extends Error {
1058
+ constructor(message, options) {
1059
+ super(message), this.name = "ParseError", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line;
1060
+ }
1061
+ };
1062
+ var LF = 10;
1063
+ var CR = 13;
1064
+ var SPACE = 32;
1065
+ function noop(_arg) {
1066
+ }
1067
+ function createParser(config) {
1068
+ if (typeof config == "function")
1069
+ throw new TypeError(
1070
+ "`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?"
1071
+ );
1072
+ const { onEvent = noop, onError = noop, onRetry = noop, onComment, maxBufferSize } = config, pendingFragments = [];
1073
+ let pendingFragmentsLength = 0, isFirstChunk = true, id, data = "", dataLines = 0, eventType, terminated = false;
1074
+ function feed(chunk) {
1075
+ if (terminated)
1076
+ throw new Error(
1077
+ "Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing."
1078
+ );
1079
+ if (isFirstChunk && (isFirstChunk = false, chunk.charCodeAt(0) === 239 && chunk.charCodeAt(1) === 187 && chunk.charCodeAt(2) === 191 && (chunk = chunk.slice(3))), pendingFragments.length === 0) {
1080
+ const trailing2 = processLines(chunk);
1081
+ trailing2 !== "" && (pendingFragments.push(trailing2), pendingFragmentsLength = trailing2.length), checkBufferSize();
1082
+ return;
1083
+ }
1084
+ if (chunk.indexOf(`
1085
+ `) === -1 && chunk.indexOf("\r") === -1) {
1086
+ pendingFragments.push(chunk), pendingFragmentsLength += chunk.length, checkBufferSize();
1087
+ return;
1088
+ }
1089
+ pendingFragments.push(chunk);
1090
+ const input = pendingFragments.join("");
1091
+ pendingFragments.length = 0, pendingFragmentsLength = 0;
1092
+ const trailing = processLines(input);
1093
+ trailing !== "" && (pendingFragments.push(trailing), pendingFragmentsLength = trailing.length), checkBufferSize();
1094
+ }
1095
+ function checkBufferSize() {
1096
+ maxBufferSize !== void 0 && (pendingFragmentsLength + data.length <= maxBufferSize || (terminated = true, pendingFragments.length = 0, pendingFragmentsLength = 0, id = void 0, data = "", dataLines = 0, eventType = void 0, onError(
1097
+ new ParseError(`Buffered data exceeded max buffer size of ${maxBufferSize} characters`, {
1098
+ type: "max-buffer-size-exceeded"
1099
+ })
1100
+ )));
1101
+ }
1102
+ function processLines(chunk) {
1103
+ let searchIndex = 0;
1104
+ if (chunk.indexOf("\r") === -1) {
1105
+ let lfIndex = chunk.indexOf(`
1106
+ `, searchIndex);
1107
+ for (; lfIndex !== -1; ) {
1108
+ if (searchIndex === lfIndex) {
1109
+ dataLines > 0 && onEvent({ id, event: eventType, data }), id = void 0, data = "", dataLines = 0, eventType = void 0, searchIndex = lfIndex + 1, lfIndex = chunk.indexOf(`
1110
+ `, searchIndex);
1111
+ continue;
1112
+ }
1113
+ const firstCharCode = chunk.charCodeAt(searchIndex);
1114
+ if (isDataPrefix(chunk, searchIndex, firstCharCode)) {
1115
+ const valueStart = chunk.charCodeAt(searchIndex + 5) === SPACE ? searchIndex + 6 : searchIndex + 5, value = chunk.slice(valueStart, lfIndex);
1116
+ if (dataLines === 0 && chunk.charCodeAt(lfIndex + 1) === LF) {
1117
+ onEvent({ id, event: eventType, data: value }), id = void 0, data = "", eventType = void 0, searchIndex = lfIndex + 2, lfIndex = chunk.indexOf(`
1118
+ `, searchIndex);
1119
+ continue;
1120
+ }
1121
+ data = dataLines === 0 ? value : `${data}
1122
+ ${value}`, dataLines++;
1123
+ } else isEventPrefix(chunk, searchIndex, firstCharCode) ? eventType = chunk.slice(
1124
+ chunk.charCodeAt(searchIndex + 6) === SPACE ? searchIndex + 7 : searchIndex + 6,
1125
+ lfIndex
1126
+ ) || void 0 : parseLine(chunk, searchIndex, lfIndex);
1127
+ searchIndex = lfIndex + 1, lfIndex = chunk.indexOf(`
1128
+ `, searchIndex);
1129
+ }
1130
+ return chunk.slice(searchIndex);
1131
+ }
1132
+ for (; searchIndex < chunk.length; ) {
1133
+ const crIndex = chunk.indexOf("\r", searchIndex), lfIndex = chunk.indexOf(`
1134
+ `, searchIndex);
1135
+ let lineEnd = -1;
1136
+ if (crIndex !== -1 && lfIndex !== -1 ? lineEnd = crIndex < lfIndex ? crIndex : lfIndex : crIndex !== -1 ? crIndex === chunk.length - 1 ? lineEnd = -1 : lineEnd = crIndex : lfIndex !== -1 && (lineEnd = lfIndex), lineEnd === -1)
1137
+ break;
1138
+ parseLine(chunk, searchIndex, lineEnd), searchIndex = lineEnd + 1, chunk.charCodeAt(searchIndex - 1) === CR && chunk.charCodeAt(searchIndex) === LF && searchIndex++;
1139
+ }
1140
+ return chunk.slice(searchIndex);
1141
+ }
1142
+ function parseLine(chunk, start, end) {
1143
+ if (start === end) {
1144
+ dispatchEvent();
1145
+ return;
1146
+ }
1147
+ const firstCharCode = chunk.charCodeAt(start);
1148
+ if (isDataPrefix(chunk, start, firstCharCode)) {
1149
+ const valueStart = chunk.charCodeAt(start + 5) === SPACE ? start + 6 : start + 5, value2 = chunk.slice(valueStart, end);
1150
+ data = dataLines === 0 ? value2 : `${data}
1151
+ ${value2}`, dataLines++;
1152
+ return;
1153
+ }
1154
+ if (isEventPrefix(chunk, start, firstCharCode)) {
1155
+ eventType = chunk.slice(chunk.charCodeAt(start + 6) === SPACE ? start + 7 : start + 6, end) || void 0;
1156
+ return;
1157
+ }
1158
+ if (firstCharCode === 105 && chunk.charCodeAt(start + 1) === 100 && chunk.charCodeAt(start + 2) === 58) {
1159
+ const value2 = chunk.slice(chunk.charCodeAt(start + 3) === SPACE ? start + 4 : start + 3, end);
1160
+ value2.includes("\0") || (id = value2);
1161
+ return;
1162
+ }
1163
+ if (firstCharCode === 58) {
1164
+ if (onComment) {
1165
+ const line2 = chunk.slice(start, end);
1166
+ onComment(line2.slice(chunk.charCodeAt(start + 1) === SPACE ? 2 : 1));
1167
+ }
1168
+ return;
1169
+ }
1170
+ const line = chunk.slice(start, end), fieldSeparatorIndex = line.indexOf(":");
1171
+ if (fieldSeparatorIndex === -1) {
1172
+ processField(line, "", line);
1173
+ return;
1174
+ }
1175
+ const field = line.slice(0, fieldSeparatorIndex), offset = line.charCodeAt(fieldSeparatorIndex + 1) === SPACE ? 2 : 1, value = line.slice(fieldSeparatorIndex + offset);
1176
+ processField(field, value, line);
1177
+ }
1178
+ function processField(field, value, line) {
1179
+ switch (field) {
1180
+ case "event":
1181
+ eventType = value || void 0;
1182
+ break;
1183
+ case "data":
1184
+ data = dataLines === 0 ? value : `${data}
1185
+ ${value}`, dataLines++;
1186
+ break;
1187
+ case "id":
1188
+ value.includes("\0") || (id = value);
1189
+ break;
1190
+ case "retry":
1191
+ /^\d+$/.test(value) ? onRetry(parseInt(value, 10)) : onError(
1192
+ new ParseError(`Invalid \`retry\` value: "${value}"`, {
1193
+ type: "invalid-retry",
1194
+ value,
1195
+ line
1196
+ })
1197
+ );
1198
+ break;
1199
+ default:
1200
+ onError(
1201
+ new ParseError(
1202
+ `Unknown field "${field.length > 20 ? `${field.slice(0, 20)}\u2026` : field}"`,
1203
+ { type: "unknown-field", field, value, line }
1204
+ )
1205
+ );
1206
+ break;
1207
+ }
1208
+ }
1209
+ function dispatchEvent() {
1210
+ dataLines > 0 && onEvent({
1211
+ id,
1212
+ event: eventType,
1213
+ data
1214
+ }), id = void 0, data = "", dataLines = 0, eventType = void 0;
1215
+ }
1216
+ function reset(options = {}) {
1217
+ if (options.consume && pendingFragments.length > 0) {
1218
+ const incompleteLine = pendingFragments.join("");
1219
+ parseLine(incompleteLine, 0, incompleteLine.length);
1220
+ }
1221
+ isFirstChunk = true, id = void 0, data = "", dataLines = 0, eventType = void 0, pendingFragments.length = 0, pendingFragmentsLength = 0, terminated = false;
1222
+ }
1223
+ return { feed, reset };
1224
+ }
1225
+ function isDataPrefix(chunk, i, firstCharCode) {
1226
+ return firstCharCode === 100 && chunk.charCodeAt(i + 1) === 97 && chunk.charCodeAt(i + 2) === 116 && chunk.charCodeAt(i + 3) === 97 && chunk.charCodeAt(i + 4) === 58;
1227
+ }
1228
+ function isEventPrefix(chunk, i, firstCharCode) {
1229
+ return firstCharCode === 101 && chunk.charCodeAt(i + 1) === 118 && chunk.charCodeAt(i + 2) === 101 && chunk.charCodeAt(i + 3) === 110 && chunk.charCodeAt(i + 4) === 116 && chunk.charCodeAt(i + 5) === 58;
1230
+ }
1231
+
1232
+ // ../http-client/src/speech-stream.ts
1233
+ var MISMATCH = "Speech stream response did not match the SDK contract";
1234
+ var MAX_WIRE_BYTES = 24 * 1024 * 1024;
1235
+ var MAX_EVENT_BYTES = 256 * 1024;
1236
+ var MAX_ERROR_BYTES = 64 * 1024;
1237
+ var FEED_BYTES = 4096;
1238
+ function speechStreamIterator(open, timeoutMs, callerSignal) {
1239
+ const controller = new AbortController();
1240
+ async function* iterate() {
1241
+ const timeout = AbortSignal.timeout(timeoutMs);
1242
+ const signal = AbortSignal.any([controller.signal, timeout, ...callerSignal ? [callerSignal] : []]);
1243
+ try {
1244
+ signal.throwIfAborted();
1245
+ const response = await open(signal);
1246
+ if (response.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase() !== "text/event-stream") {
1247
+ await response.body?.cancel().catch(() => {
1248
+ });
1249
+ throw new RealtimeAvatarError(MISMATCH);
1250
+ }
1251
+ yield* parseEvents(response, signal);
1252
+ } finally {
1253
+ controller.abort();
1254
+ }
1255
+ }
1256
+ const iterator = iterate();
1257
+ return {
1258
+ next: (value) => iterator.next(value),
1259
+ return: (value) => {
1260
+ controller.abort();
1261
+ return iterator.return(value);
1262
+ },
1263
+ throw: (error) => {
1264
+ controller.abort();
1265
+ return iterator.throw(error);
1266
+ },
1267
+ [Symbol.asyncIterator]() {
1268
+ return this;
1269
+ }
1270
+ };
1271
+ }
1272
+ async function* bodyChunks(response, signal, limit) {
1273
+ if (!response.body) throw new RealtimeAvatarError(MISMATCH);
1274
+ const reader = response.body.getReader();
1275
+ const cancel = () => {
1276
+ void reader.cancel().catch(() => {
1277
+ });
1278
+ };
1279
+ signal.addEventListener("abort", cancel, { once: true });
1280
+ let size = 0;
1281
+ try {
1282
+ signal.throwIfAborted();
1283
+ for (; ; ) {
1284
+ const { value, done } = await reader.read();
1285
+ signal.throwIfAborted();
1286
+ if (done) return;
1287
+ size += value.byteLength;
1288
+ if (size > limit) throw new RealtimeAvatarError(MISMATCH);
1289
+ yield value;
1290
+ }
1291
+ } catch (error) {
1292
+ signal.throwIfAborted();
1293
+ if (error instanceof RealtimeAvatarError) throw error;
1294
+ throw new RealtimeAvatarError(MISMATCH);
1295
+ } finally {
1296
+ signal.removeEventListener("abort", cancel);
1297
+ await reader.cancel().catch(() => {
1298
+ });
1299
+ reader.releaseLock();
1300
+ }
1301
+ }
1302
+ async function boundedSpeechErrorResponse(response, signal) {
1303
+ if (!response.body) return response;
1304
+ const chunks = [];
1305
+ for await (const chunk of bodyChunks(response, signal, MAX_ERROR_BYTES)) chunks.push(new Uint8Array(chunk));
1306
+ return new Response(new Blob(chunks), { status: response.status, headers: response.headers });
1307
+ }
1308
+ async function* parseEvents(response, signal) {
1309
+ let requestId;
1310
+ let sequence = 0;
1311
+ let samples = 0;
1312
+ let terminal = false;
1313
+ const queue = [];
1314
+ const decoder = new TextDecoder("utf-8", { fatal: true });
1315
+ const encoder = new TextEncoder();
1316
+ let endsWithCR = false;
1317
+ const parser = createParser({
1318
+ maxBufferSize: MAX_EVENT_BYTES,
1319
+ onError() {
1320
+ throw new RealtimeAvatarError(MISMATCH);
1321
+ },
1322
+ onEvent(message) {
1323
+ if (terminal || encoder.encode(message.data).byteLength > MAX_EVENT_BYTES) throw new RealtimeAvatarError(MISMATCH);
1324
+ const raw = JSON.parse(message.data);
1325
+ const event = speechStreamEventSchema.parse(raw);
1326
+ if (message.event !== void 0 && message.event !== event.type) throw new RealtimeAvatarError(MISMATCH);
1327
+ if (requestId === void 0) {
1328
+ if (event.type !== "started") throw new RealtimeAvatarError(MISMATCH);
1329
+ requestId = event.requestId;
1330
+ } else {
1331
+ if (event.type === "started" || event.requestId !== requestId) throw new RealtimeAvatarError(MISMATCH);
1332
+ }
1333
+ if (event.type === "audio") {
1334
+ const bytes = atob(event.audioBase64).length;
1335
+ if (event.sequence !== sequence || event.sampleOffset !== samples || bytes === 0 || bytes % 2 !== 0 || bytes > SPEECH_STREAM_CONTRACT.maxAudioEventBytes) throw new RealtimeAvatarError(MISMATCH);
1336
+ samples += bytes / 2;
1337
+ sequence++;
1338
+ if (samples > SPEECH_STREAM_CONTRACT.maxSamples) throw new RealtimeAvatarError(MISMATCH);
1339
+ } else if (event.type === "completed") {
1340
+ if (samples <= 0 || event.totalSamples !== samples) throw new RealtimeAvatarError(MISMATCH);
1341
+ terminal = true;
1342
+ } else if (event.type === "failed") {
1343
+ terminal = true;
1344
+ }
1345
+ queue.push(event);
1346
+ }
1347
+ });
1348
+ try {
1349
+ for await (const bytes of bodyChunks(response, signal, MAX_WIRE_BYTES)) {
1350
+ for (let offset = 0; offset < bytes.byteLength; offset += FEED_BYTES) {
1351
+ signal.throwIfAborted();
1352
+ const text = decoder.decode(bytes.subarray(offset, offset + FEED_BYTES), { stream: true });
1353
+ if (text.length) endsWithCR = text.endsWith("\r");
1354
+ parser.feed(text);
1355
+ while (queue.length) {
1356
+ signal.throwIfAborted();
1357
+ const event = queue.shift();
1358
+ if (event) yield event;
1359
+ }
1360
+ }
1361
+ }
1362
+ const remainder = decoder.decode();
1363
+ if (remainder.length) endsWithCR = remainder.endsWith("\r");
1364
+ parser.feed(remainder);
1365
+ if (endsWithCR) parser.feed("\n");
1366
+ while (queue.length) {
1367
+ const event = queue.shift();
1368
+ if (event) yield event;
1369
+ }
1370
+ if (!terminal) throw new RealtimeAvatarError(MISMATCH);
1371
+ parser.feed("\n\n");
1372
+ parser.reset();
1373
+ } catch {
1374
+ signal.throwIfAborted();
1375
+ throw new RealtimeAvatarError(MISMATCH);
1376
+ }
1377
+ }
1378
+ var schema010 = z.url().regex(new RegExp("^https:\\/\\/")).max(500);
1379
+ var schema120 = z.string().min(16).max(200);
1380
+ var schema216 = z.string().min(1).max(200);
1381
+ var schema311 = z.string().min(2).max(35);
1382
+ var schema411 = z.literal([8e3, 16e3, 22050, 24e3, 44100, 48e3]);
1383
+ var schema58 = z.int().min(1e3).max(15e3);
1384
+ var schema66 = z.strictObject({
1385
+ "url": schema010,
1386
+ "secret": schema120,
1387
+ "voice_id": schema216.optional(),
1388
+ "language": schema311.optional(),
1389
+ "sample_rate": schema411.optional(),
1390
+ "timeout_ms": schema58.optional()
1391
+ });
1392
+ var schema76 = z.literal("voice.synthesize");
1393
+ var schema86 = z.literal(1);
1394
+ var schema96 = z.string().min(1).max(200);
1395
+ var schema106 = z.string().min(1).max(200);
1396
+ var schema1111 = z.object({
1397
+ "generation_id": schema96,
1398
+ "utterance_id": schema106
948
1399
  });
949
1400
  var schema125 = z.string().min(1).max(200);
950
- var schema135 = z.string();
951
- var schema145 = z.string().min(1).max(5e3);
952
- var schema155 = z.string();
953
- var schema164 = z.null();
954
- var schema174 = z.union([schema155, schema164]);
955
- var schema184 = z.string();
956
- var schema194 = z.union([schema184, schema164]);
957
- var schema203 = z.literal("pcm_s16le");
958
- var schema215 = z.literal([8e3, 16e3, 22050, 24e3, 44100, 48e3]);
959
- var schema223 = z.object({
960
- "encoding": schema203,
961
- "sample_rate": schema215,
962
- "channels": schema85
963
- });
964
- var schema233 = z.string().min(1).max(64);
965
- var schema243 = z.string().max(200);
966
- var schema253 = z.record(schema233, schema243).refine((value) => Object.keys(value).length <= 16, { message: "Too many keys: at most 16" });
967
- var schema263 = z.object({
968
- "type": schema75,
969
- "version": schema85,
970
- "performance": schema1110.optional(),
1401
+ var schema136 = z.string();
1402
+ var schema146 = z.string().min(1).max(5e3);
1403
+ var schema156 = z.string();
1404
+ var schema165 = z.null();
1405
+ var schema175 = z.union([schema156, schema165]);
1406
+ var schema185 = z.string();
1407
+ var schema195 = z.union([schema185, schema165]);
1408
+ var schema204 = z.literal("pcm_s16le");
1409
+ var schema217 = z.literal([8e3, 16e3, 22050, 24e3, 44100, 48e3]);
1410
+ var schema224 = z.object({
1411
+ "encoding": schema204,
1412
+ "sample_rate": schema217,
1413
+ "channels": schema86
1414
+ });
1415
+ var schema234 = z.string().min(1).max(64);
1416
+ var schema244 = z.string().max(200);
1417
+ var schema254 = z.record(schema234, schema244).refine((value) => Object.keys(value).length <= 16, { message: "Too many keys: at most 16" });
1418
+ var schema264 = z.object({
1419
+ "type": schema76,
1420
+ "version": schema86,
1421
+ "performance": schema1111.optional(),
971
1422
  "request_id": schema125,
972
- "session_id": schema135,
973
- "text": schema145,
974
- "voice_id": schema174,
975
- "language": schema194,
976
- "output": schema223,
977
- "client_metadata": schema253
978
- });
979
- var voiceWebhookWireSchema = schema65;
1423
+ "session_id": schema136,
1424
+ "text": schema146,
1425
+ "voice_id": schema175,
1426
+ "language": schema195,
1427
+ "output": schema224,
1428
+ "client_metadata": schema254
1429
+ });
1430
+ var voiceWebhookWireSchema = schema66;
980
1431
  var voiceWebhookOptionsSchema = z.strictObject({
981
1432
  url: voiceWebhookWireSchema.shape.url,
982
1433
  secret: voiceWebhookWireSchema.shape.secret,
@@ -996,40 +1447,40 @@ function voiceWebhookToWire(input) {
996
1447
  ...options.timeoutMs !== void 0 ? { timeout_ms: options.timeoutMs } : {}
997
1448
  };
998
1449
  }
999
- var voiceWebhookRequestSchema = schema263;
1000
- var schema010 = z.url().regex(new RegExp("^\\s*[Hh][Tt][Tt][Pp][Ss]:\\/\\/")).max(500);
1001
- var schema120 = z.string().min(16).max(4096);
1002
- var schema216 = z.boolean();
1003
- var schema39 = z.literal("external");
1004
- var schema49 = z.strictObject({
1005
- "renderer": schema39
1006
- });
1007
- var schema58 = z.literal("v1");
1008
- var schema66 = z.literal("correlated_pcm_v1");
1009
- var schema76 = z.literal("speech_segments_v1");
1010
- var schema86 = z.literal("v1");
1011
- var schema96 = z.literal(true);
1012
- var schema106 = z.object({
1013
- "performance": schema86,
1014
- "fail_closed": schema96
1015
- });
1016
- var schema1111 = z.literal("correlated_pcm_v1");
1450
+ var voiceWebhookRequestSchema = schema264;
1451
+ var schema011 = z.url().regex(new RegExp("^\\s*[Hh][Tt][Tt][Pp][Ss]:\\/\\/")).max(500);
1452
+ var schema121 = z.string().min(16).max(4096);
1453
+ var schema218 = z.boolean();
1454
+ var schema312 = z.literal("external");
1455
+ var schema412 = z.strictObject({
1456
+ "renderer": schema312
1457
+ });
1458
+ var schema59 = z.literal("v1");
1459
+ var schema67 = z.literal("correlated_pcm_v1");
1460
+ var schema77 = z.literal("speech_segments_v1");
1461
+ var schema87 = z.literal("v1");
1462
+ var schema97 = z.literal(true);
1463
+ var schema107 = z.object({
1464
+ "performance": schema87,
1465
+ "fail_closed": schema97
1466
+ });
1467
+ var schema1112 = z.literal("correlated_pcm_v1");
1017
1468
  var schema126 = z.object({
1018
- "performance": schema86,
1019
- "fail_closed": schema96,
1020
- "audio_output": schema1111
1021
- });
1022
- var schema136 = z.strictObject({
1023
- "base_url": schema010,
1024
- "token": schema120,
1025
- "fail_closed": schema216.optional(),
1026
- "visible_character": schema49.optional(),
1027
- "performance": schema58.optional(),
1028
- "audio_output": schema66.optional(),
1029
- "text_output": schema76.optional()
1469
+ "performance": schema87,
1470
+ "fail_closed": schema97,
1471
+ "audio_output": schema1112
1472
+ });
1473
+ var schema137 = z.strictObject({
1474
+ "base_url": schema011,
1475
+ "token": schema121,
1476
+ "fail_closed": schema218.optional(),
1477
+ "visible_character": schema412.optional(),
1478
+ "performance": schema59.optional(),
1479
+ "audio_output": schema67.optional(),
1480
+ "text_output": schema77.optional()
1030
1481
  }).superRefine((value, ctx) => {
1031
1482
  if (value["audio_output"] !== void 0) {
1032
- const result = schema106.safeParse(value);
1483
+ const result = schema107.safeParse(value);
1033
1484
  if (!result.success) for (const issue of result.error.issues) ctx.addIssue({ code: "custom", message: issue.message, path: issue.path });
1034
1485
  }
1035
1486
  }).superRefine((value, ctx) => {
@@ -1038,7 +1489,7 @@ var schema136 = z.strictObject({
1038
1489
  if (!result.success) for (const issue of result.error.issues) ctx.addIssue({ code: "custom", message: issue.message, path: issue.path });
1039
1490
  }
1040
1491
  });
1041
- var externalLlmWireSchema = schema136;
1492
+ var externalLlmWireSchema = schema137;
1042
1493
  var externalLlmOptionsSchema = z.strictObject({
1043
1494
  baseUrl: externalLlmWireSchema.shape.base_url,
1044
1495
  token: externalLlmWireSchema.shape.token,
@@ -1060,95 +1511,95 @@ function externalLlmToWire(input) {
1060
1511
  ...options.textOutput !== void 0 ? { text_output: options.textOutput } : {}
1061
1512
  });
1062
1513
  }
1063
- var schema011 = z.string().min(8).max(80);
1064
- var schema121 = z.enum(["eou", "llm", "tts", "decision", "hold", "e2e"]);
1065
- var schema217 = z.literal("interrupt_stop");
1066
- var schema310 = z.union([schema121, schema217]);
1067
- var schema410 = z.int().max(9007199254740991).gt(0);
1068
- var schema59 = z.number().min(0);
1069
- var schema67 = z.strictObject({
1070
- "count": schema410,
1071
- "max": schema59,
1072
- "p50": schema59,
1073
- "p90": schema59
1074
- });
1075
- var schema77 = z.partialRecord(schema310, schema67);
1076
- var schema87 = z.literal("available");
1077
- var schema97 = z.literal("dialogue");
1078
- var schema107 = z.string().regex(new RegExp("^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d))|(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?)$"));
1079
- var schema1112 = z.null();
1080
- var schema127 = z.union([schema107, schema1112]);
1081
- var schema137 = z.int().min(0).max(9007199254740991);
1082
- var schema146 = z.strictObject({
1083
- "first_at": schema127,
1084
- "last_at": schema127,
1085
- "lines": schema137
1086
- });
1087
- var schema156 = z.strictObject({
1088
- "latency_ms": schema77,
1089
- "status": schema87,
1090
- "sourceRole": schema97,
1091
- "coverage": schema146
1092
- });
1093
- var schema165 = z.literal("unavailable");
1094
- var schema175 = z.enum(["not_closed", "unconfigured", "missing", "invalid", "oversized", "unscorable", "no_measured_latency", "timeout", "aborted", "storage_unavailable"]);
1095
- var schema185 = z.strictObject({
1096
- "status": schema165,
1097
- "reason": schema175
1098
- });
1099
- var schema195 = z.union([schema156, schema185]);
1100
- var schema204 = z.string().min(1).max(200);
1101
- var schema218 = z.union([schema204, schema1112]);
1102
- var schema224 = z.string().regex(new RegExp("^[0-9a-f]{40}$"));
1103
- var schema234 = z.union([schema224, schema1112]);
1104
- var schema244 = z.literal("cloudflare-worker-version");
1105
- var schema254 = z.literal("authenticated-worker-heartbeat");
1106
- var schema264 = z.union([schema254, schema1112]);
1107
- var schema273 = z.string().min(1).max(160);
1108
- var schema282 = z.union([schema273, schema1112]);
1109
- var schema292 = z.union([schema137, schema1112]);
1110
- var schema30 = z.iso.datetime({ offset: true }).regex(new RegExp("^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$"));
1111
- var schema31 = z.union([schema30, schema1112]);
1112
- var schema322 = z.strictObject({
1113
- "deploymentSource": schema244,
1114
- "workerSource": schema264,
1115
- "workerId": schema282,
1116
- "podStartedAtMs": schema292,
1117
- "workerObservedAt": schema31
1118
- });
1119
- var schema332 = z.strictObject({
1120
- "deploymentId": schema218,
1121
- "workerRevision": schema234,
1122
- "provenance": schema322
1123
- });
1124
- var schema342 = z.string();
1125
- var schema352 = z.union([schema342, schema1112]);
1126
- var schema362 = z.enum(["reserved", "started", "released", "failed"]);
1127
- var schema372 = z.union([schema59, schema1112]);
1514
+ var schema012 = z.string().min(8).max(80);
1515
+ var schema127 = z.enum(["eou", "llm", "tts", "decision", "hold", "e2e"]);
1516
+ var schema219 = z.literal("interrupt_stop");
1517
+ var schema313 = z.union([schema127, schema219]);
1518
+ var schema413 = z.int().max(9007199254740991).gt(0);
1519
+ var schema510 = z.number().min(0);
1520
+ var schema68 = z.strictObject({
1521
+ "count": schema413,
1522
+ "max": schema510,
1523
+ "p50": schema510,
1524
+ "p90": schema510
1525
+ });
1526
+ var schema78 = z.partialRecord(schema313, schema68);
1527
+ var schema88 = z.literal("available");
1528
+ var schema98 = z.literal("dialogue");
1529
+ var schema108 = z.string().regex(new RegExp("^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d))|(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?)$"));
1530
+ var schema1113 = z.null();
1531
+ var schema128 = z.union([schema108, schema1113]);
1532
+ var schema138 = z.int().min(0).max(9007199254740991);
1533
+ var schema147 = z.strictObject({
1534
+ "first_at": schema128,
1535
+ "last_at": schema128,
1536
+ "lines": schema138
1537
+ });
1538
+ var schema157 = z.strictObject({
1539
+ "latency_ms": schema78,
1540
+ "status": schema88,
1541
+ "sourceRole": schema98,
1542
+ "coverage": schema147
1543
+ });
1544
+ var schema166 = z.literal("unavailable");
1545
+ var schema176 = z.enum(["not_closed", "unconfigured", "missing", "invalid", "oversized", "unscorable", "no_measured_latency", "timeout", "aborted", "storage_unavailable"]);
1546
+ var schema186 = z.strictObject({
1547
+ "status": schema166,
1548
+ "reason": schema176
1549
+ });
1550
+ var schema196 = z.union([schema157, schema186]);
1551
+ var schema205 = z.string().min(1).max(200);
1552
+ var schema2110 = z.union([schema205, schema1113]);
1553
+ var schema225 = z.string().regex(new RegExp("^[0-9a-f]{40}$"));
1554
+ var schema235 = z.union([schema225, schema1113]);
1555
+ var schema245 = z.literal("cloudflare-worker-version");
1556
+ var schema255 = z.literal("authenticated-worker-heartbeat");
1557
+ var schema265 = z.union([schema255, schema1113]);
1558
+ var schema274 = z.string().min(1).max(160);
1559
+ var schema283 = z.union([schema274, schema1113]);
1560
+ var schema293 = z.union([schema138, schema1113]);
1561
+ var schema302 = z.iso.datetime({ offset: true }).regex(new RegExp("^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$"));
1562
+ var schema314 = z.union([schema302, schema1113]);
1563
+ var schema323 = z.strictObject({
1564
+ "deploymentSource": schema245,
1565
+ "workerSource": schema265,
1566
+ "workerId": schema283,
1567
+ "podStartedAtMs": schema293,
1568
+ "workerObservedAt": schema314
1569
+ });
1570
+ var schema333 = z.strictObject({
1571
+ "deploymentId": schema2110,
1572
+ "workerRevision": schema235,
1573
+ "provenance": schema323
1574
+ });
1575
+ var schema343 = z.string();
1576
+ var schema353 = z.union([schema343, schema1113]);
1577
+ var schema363 = z.enum(["reserved", "started", "released", "failed"]);
1578
+ var schema373 = z.union([schema510, schema1113]);
1128
1579
  var schema382 = z.custom((value) => typeof value === "object" && value !== null && !Array.isArray(value));
1129
1580
  var schema392 = z.strictObject({
1130
- "sessionId": schema011,
1131
- "speechDiagnostics": schema195.optional(),
1132
- "releaseIdentity": schema332.optional(),
1133
- "avatarId": schema352,
1134
- "avatarName": schema352,
1135
- "status": schema362,
1136
- "startedAt": schema352,
1137
- "endedAt": schema352,
1138
- "activeSeconds": schema372,
1139
- "billedCreditMicros": schema292,
1581
+ "sessionId": schema012,
1582
+ "speechDiagnostics": schema196.optional(),
1583
+ "releaseIdentity": schema333.optional(),
1584
+ "avatarId": schema353,
1585
+ "avatarName": schema353,
1586
+ "status": schema363,
1587
+ "startedAt": schema353,
1588
+ "endedAt": schema353,
1589
+ "activeSeconds": schema373,
1590
+ "billedCreditMicros": schema293,
1140
1591
  "metadata": schema382,
1141
- "createdAt": schema342
1592
+ "createdAt": schema343
1142
1593
  });
1143
- var schema40 = z.array(schema392);
1144
- var schema41 = z.iso.datetime({ offset: true }).regex(new RegExp("^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$"));
1145
- var schema422 = z.strictObject({
1146
- "data": schema40,
1147
- "nextCursor": schema352,
1148
- "from": schema41,
1149
- "to": schema41
1594
+ var schema402 = z.array(schema392);
1595
+ var schema414 = z.iso.datetime({ offset: true }).regex(new RegExp("^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$"));
1596
+ var schema423 = z.strictObject({
1597
+ "data": schema402,
1598
+ "nextCursor": schema353,
1599
+ "from": schema414,
1600
+ "to": schema414
1150
1601
  });
1151
- var listUsageSessionsResponseSchema = schema422;
1602
+ var listUsageSessionsResponseSchema = schema423;
1152
1603
  function toSessionsPage(page) {
1153
1604
  const { data, ...pagination } = page;
1154
1605
  return { ...pagination, sessions: data };
@@ -1157,7 +1608,9 @@ function toSessionsPage(page) {
1157
1608
  // ../http-client/src/client.ts
1158
1609
  var DEFAULT_BASE_URL = "https://realtimeavatar.ai/api/v1";
1159
1610
  var RENDER_MISMATCH = "Render response did not match the SDK contract";
1160
- var SDK_VERSION = "0.35.0";
1611
+ var SPEECH_MISMATCH = "Speech response did not match the SDK contract";
1612
+ var MAX_SPEECH_RESPONSE_BYTES = 24 * 1024 * 1024;
1613
+ var SDK_VERSION = "0.37.0";
1161
1614
  var RealtimeAvatar = class {
1162
1615
  #apiKey;
1163
1616
  #baseUrl;
@@ -1719,6 +2172,65 @@ var RealtimeAvatar = class {
1719
2172
  async creditBalance() {
1720
2173
  return await this.#json(await this.#request("GET", "/credits/balance"));
1721
2174
  }
2175
+ /** Completed speech audio, without a call or LiveKit. Never automatically retried. */
2176
+ async createSpeech(voiceId, input, options = {}) {
2177
+ const id = speechVoiceIdSchema.parse(voiceId);
2178
+ const json = createSpeechRequestSchema.parse(input);
2179
+ const timeout = AbortSignal.timeout(Math.max(0, Math.min(this.#timeoutMs, this.#totalTimeoutMs ?? Infinity)));
2180
+ const signal = options.signal ? AbortSignal.any([options.signal, timeout]) : timeout;
2181
+ const response = await this.#request("POST", `/voices/${encodeURIComponent(id)}/speech`, {
2182
+ json,
2183
+ signal,
2184
+ maxRetries: 0
2185
+ });
2186
+ if (!response.ok) {
2187
+ try {
2188
+ await this.#json(response);
2189
+ } finally {
2190
+ signal.throwIfAborted();
2191
+ }
2192
+ throw new RealtimeAvatarError(SPEECH_MISMATCH);
2193
+ }
2194
+ let metadata;
2195
+ try {
2196
+ const contentType = speechContentTypeSchema.parse(response.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase());
2197
+ const expected = { wav: "audio/wav", mp3: "audio/mpeg" };
2198
+ if (contentType !== expected[json.format]) throw new RealtimeAvatarError(SPEECH_MISMATCH);
2199
+ const requestId = response.headers.get("x-request-id");
2200
+ if (requestId !== null && !isRequestId(requestId)) throw new RealtimeAvatarError(SPEECH_MISMATCH);
2201
+ metadata = { contentType, ...readSpeechHeaders(response.headers), requestId };
2202
+ const length = response.headers.get("content-length");
2203
+ if (length !== null && (!/^[0-9]+$/.test(length) || Number(length) > MAX_SPEECH_RESPONSE_BYTES)) {
2204
+ throw new RealtimeAvatarError(SPEECH_MISMATCH);
2205
+ }
2206
+ } catch {
2207
+ await response.body?.cancel().catch(() => {
2208
+ });
2209
+ throw new RealtimeAvatarError(SPEECH_MISMATCH);
2210
+ }
2211
+ const bytes = await readSpeechBytes(response, signal, metadata.contentType);
2212
+ return { bytes, ...metadata };
2213
+ }
2214
+ /**
2215
+ * Incremental mono PCM and absolute alignment, without a call or LiveKit. The first next()
2216
+ * starts the paid request; break/return or signal abort cancels it. Never retried. A failed
2217
+ * terminal is yielded, not thrown; malformed/truncated transport throws RealtimeAvatarError.
2218
+ */
2219
+ createSpeechStream(voiceId, input, options = {}) {
2220
+ return speechStreamIterator(async (signal) => {
2221
+ const id = speechVoiceIdSchema.parse(voiceId);
2222
+ const json = createSpeechStreamRequestSchema.parse(input);
2223
+ const response = await this.#request("POST", `/voices/${encodeURIComponent(id)}/speech/stream`, {
2224
+ json,
2225
+ signal,
2226
+ maxRetries: 0
2227
+ });
2228
+ if (!response.ok) {
2229
+ await this.#json(await boundedSpeechErrorResponse(response, signal));
2230
+ }
2231
+ return response;
2232
+ }, Math.max(0, Math.min(this.#timeoutMs, this.#totalTimeoutMs ?? Infinity)), options.signal);
2233
+ }
1722
2234
  // ── internals ────────────────────────────────────────────────────────────
1723
2235
  async #request(method, path, init = {}) {
1724
2236
  const headers = {
@@ -1734,25 +2246,29 @@ var RealtimeAvatar = class {
1734
2246
  body = JSON.stringify(init.json);
1735
2247
  }
1736
2248
  if (MUTATING.has(method)) headers["idempotency-key"] = newIdempotencyKey();
2249
+ const maxRetries = init.maxRetries ?? this.#maxRetries;
1737
2250
  const deadline = this.#totalTimeoutMs === void 0 ? Infinity : Date.now() + this.#totalTimeoutMs;
1738
2251
  let lastError;
1739
2252
  for (let attempt = 0; ; attempt++) {
1740
2253
  const startedAt = Date.now();
1741
2254
  try {
1742
- const signal = AbortSignal.timeout(Math.max(0, Math.min(this.#timeoutMs, deadline - startedAt)));
2255
+ const timeout = AbortSignal.timeout(Math.max(0, Math.min(this.#timeoutMs, deadline - startedAt)));
2256
+ const signal = init.signal ? AbortSignal.any([init.signal, timeout]) : timeout;
2257
+ signal.throwIfAborted();
1743
2258
  const response = await this.#fetch(`${this.#baseUrl}${path}`, { method, headers, body, signal });
1744
- if (attempt >= this.#maxRetries || !RETRYABLE_STATUS.has(response.status)) return response;
2259
+ if (attempt >= maxRetries || !RETRYABLE_STATUS.has(response.status)) return response;
1745
2260
  const wait = backoffMs(attempt, response.headers.get("retry-after"));
1746
2261
  if (!retryFits(startedAt, wait, deadline)) return response;
1747
2262
  await response.body?.cancel().catch(() => {
1748
2263
  });
1749
2264
  await sleep(wait);
1750
2265
  } catch (cause) {
2266
+ init.signal?.throwIfAborted();
1751
2267
  lastError = cause;
1752
2268
  const wait = backoffMs(attempt, null);
1753
- if (attempt >= this.#maxRetries || !isTransient(cause) || isStream(body) || !retryFits(startedAt, wait, deadline)) {
2269
+ if (attempt >= maxRetries || !isTransient(cause) || isStream(body) || !retryFits(startedAt, wait, deadline)) {
1754
2270
  throw new RealtimeAvatarError(
1755
- `${method} ${path} failed after ${attempt + 1} attempt(s): ${cause.message}`,
2271
+ `${method} ${path} failed after ${attempt + 1} attempt(s): ${cause instanceof Error ? cause.message : String(cause)}`,
1756
2272
  { cause: lastError }
1757
2273
  );
1758
2274
  }
@@ -1788,6 +2304,47 @@ var RealtimeAvatar = class {
1788
2304
  return parsed.data;
1789
2305
  }
1790
2306
  };
2307
+ async function readSpeechBytes(response, signal, contentType) {
2308
+ if (!response.body) throw new RealtimeAvatarError(SPEECH_MISMATCH);
2309
+ const reader = response.body.getReader();
2310
+ const cancel = () => {
2311
+ void reader.cancel().catch(() => {
2312
+ });
2313
+ };
2314
+ signal.addEventListener("abort", cancel, { once: true });
2315
+ const chunks = [];
2316
+ let size = 0;
2317
+ try {
2318
+ signal.throwIfAborted();
2319
+ for (; ; ) {
2320
+ const { done, value } = await reader.read();
2321
+ signal.throwIfAborted();
2322
+ if (done) break;
2323
+ size += value.byteLength;
2324
+ if (size > MAX_SPEECH_RESPONSE_BYTES) throw new RealtimeAvatarError(SPEECH_MISMATCH);
2325
+ chunks.push(value);
2326
+ }
2327
+ if (size === 0) throw new RealtimeAvatarError(SPEECH_MISMATCH);
2328
+ const bytes = new Uint8Array(size);
2329
+ let offset = 0;
2330
+ for (const chunk of chunks) {
2331
+ bytes.set(chunk, offset);
2332
+ offset += chunk.byteLength;
2333
+ }
2334
+ const matches = (offset2, text) => [...text].every((character, index) => bytes[offset2 + index] === character.charCodeAt(0));
2335
+ const valid = contentType === "audio/wav" ? size >= 44 && matches(0, "RIFF") && matches(8, "WAVE") : size >= 10 && matches(0, "ID3") || size >= 4 && bytes[0] === 255 && (bytes[1] & 224) === 224;
2336
+ if (!valid) throw new RealtimeAvatarError(SPEECH_MISMATCH);
2337
+ return bytes;
2338
+ } catch (error) {
2339
+ await reader.cancel().catch(() => {
2340
+ });
2341
+ signal.throwIfAborted();
2342
+ throw error;
2343
+ } finally {
2344
+ signal.removeEventListener("abort", cancel);
2345
+ reader.releaseLock();
2346
+ }
2347
+ }
1791
2348
  function isRecord(value) {
1792
2349
  return typeof value === "object" && value !== null && !Array.isArray(value);
1793
2350
  }
@@ -1927,4 +2484,4 @@ var proxyEndRequestSchema = z.object({
1927
2484
  message: "session_id or queue_ticket_id is required"
1928
2485
  });
1929
2486
 
1930
- export { DEFAULT_FISH_TTS_MODEL, FISH_DELIVERY_MODELS, ROUTE_TIMEOUT_MS, RealtimeAvatar, RealtimeAvatarError, RealtimeAvatarHttpError, RealtimeAvatarWebhookError, capacityBusyResponseSchema, clipLibraryDeclarationSchema, externalSpeechSegmentSchema, externalTurnContextSchema, externalUtteranceSchema, fishTtsModelSchema, isQueued, listRecordingsResponseSchema, listRendersResponseSchema, liveKitSessionGrantSchema, proxyConnectRequestSchema, proxyEndRequestSchema, recordingAccessResponseSchema, recordingArtifactSchema, recordingModeSchema, renderAccessResponseSchema, renderSchema, verifyTranscript, verifyVoiceWebhook };
2487
+ export { DEFAULT_FISH_TTS_MODEL, FISH_DELIVERY_MODELS, ROUTE_TIMEOUT_MS, RealtimeAvatar, RealtimeAvatarError, RealtimeAvatarHttpError, RealtimeAvatarWebhookError, capacityBusyResponseSchema, clipLibraryDeclarationSchema, createSpeechRequestSchema, createSpeechStreamRequestSchema, externalSpeechSegmentSchema, externalTurnContextSchema, externalUtteranceSchema, fishTtsModelSchema, isQueued, listRecordingsResponseSchema, listRendersResponseSchema, liveKitSessionGrantSchema, proxyConnectRequestSchema, proxyEndRequestSchema, recordingAccessResponseSchema, recordingArtifactSchema, recordingModeSchema, renderAccessResponseSchema, renderSchema, speechAlignedTextSchema, speechStreamEventSchema, verifyTranscript, verifyVoiceWebhook };