@convai/web-sdk 2.0.2 → 2.1.0-beta.1
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.
- package/README.md +37 -0
- package/dist/core/ConvaiClient.d.ts +98 -2
- package/dist/core/ConvaiClient.js +305 -25
- package/dist/core/DataAudioPlayer.d.ts +131 -0
- package/dist/core/DataAudioPlayer.js +397 -0
- package/dist/core/MessageHandler.d.ts +13 -0
- package/dist/core/MessageHandler.js +57 -0
- package/dist/core/SSESession.d.ts +2 -0
- package/dist/core/SSESession.js +8 -0
- package/dist/core/endUserToken.d.ts +7 -0
- package/dist/core/endUserToken.js +11 -0
- package/dist/core/index.d.ts +4 -0
- package/dist/core/index.js +2 -0
- package/dist/core/streamController.d.ts +72 -0
- package/dist/core/streamController.js +110 -0
- package/dist/core/types.d.ts +151 -1
- package/dist/react/hooks/useConvaiClient.js +1 -0
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/package.json +1 -1
|
@@ -6,6 +6,7 @@ import { secureWebSocketUrl } from "./websocketUrl.js";
|
|
|
6
6
|
import { VideoManager } from "./VideoManager.js";
|
|
7
7
|
import { ScreenShareManager } from "./ScreenShareManager.js";
|
|
8
8
|
import { MessageHandler } from "./MessageHandler.js";
|
|
9
|
+
import { DataAudioPlayer } from "./DataAudioPlayer.js";
|
|
9
10
|
import { CharacterRoster } from "./CharacterRoster.js";
|
|
10
11
|
import { buildJoinRequestBody, buildRosterConnectFields, isRosterConfig, validateJoinOptions, validateProtocolTopology, validateRosterConfig, } from "./rosterRequest.js";
|
|
11
12
|
import { ConvaiRoomError, roomErrorFromResponse } from "./ConvaiRoomError.js";
|
|
@@ -16,6 +17,7 @@ import { CharacterVersionManager } from "./CharacterVersionManager.js";
|
|
|
16
17
|
import { resolveCharacterReference, } from "./characterReference.js";
|
|
17
18
|
import { ConnectionStateHandler } from "./ConnectionStateHandler.js";
|
|
18
19
|
import { buildActionConnectConfig, buildBlendshapeConnectConfig, buildEmotionConnectConfig, serializeProtocolCapabilities, validateActionProtocolSelection, validateModelOutputVersionSelection, } from "./connectRequest.js";
|
|
20
|
+
import { resolveEndUserToken } from "./endUserToken.js";
|
|
19
21
|
import { shouldPreemptForContextUpdateResponse, shouldPreemptForExplicitRespondMode, } from "./contextUpdateRequest.js";
|
|
20
22
|
import { resolveVisionInputConfig, serializeVisionInputConfig, } from "./visionRequest.js";
|
|
21
23
|
import { SSESession } from "./SSESession.js";
|
|
@@ -68,6 +70,29 @@ class NoReconnectPolicy extends DefaultReconnectPolicy {
|
|
|
68
70
|
return null; // Always return null to prevent any reconnection attempts
|
|
69
71
|
}
|
|
70
72
|
}
|
|
73
|
+
/**
|
|
74
|
+
* RTVI frames only a running bot pipeline sends. A backend that never sends
|
|
75
|
+
* bot-ready still sends these once it is up.
|
|
76
|
+
*/
|
|
77
|
+
const BOT_PIPELINE_FRAME_TYPES = new Set([
|
|
78
|
+
"user-started-speaking",
|
|
79
|
+
"user-stopped-speaking",
|
|
80
|
+
"user-transcription",
|
|
81
|
+
"bot-llm-started",
|
|
82
|
+
"bot-llm-text",
|
|
83
|
+
"bot-llm-stopped",
|
|
84
|
+
"bot-output",
|
|
85
|
+
"bot-tts-started",
|
|
86
|
+
"bot-tts-text",
|
|
87
|
+
"bot-tts-stopped",
|
|
88
|
+
"bot-started-speaking",
|
|
89
|
+
"bot-stopped-speaking",
|
|
90
|
+
"bot-turn-completed",
|
|
91
|
+
]);
|
|
92
|
+
function isBotPipelineFrame(message) {
|
|
93
|
+
const type = message?.type;
|
|
94
|
+
return typeof type === "string" && BOT_PIPELINE_FRAME_TYPES.has(type);
|
|
95
|
+
}
|
|
71
96
|
/**
|
|
72
97
|
* Main Convai client class for managing AI voice assistant connections
|
|
73
98
|
* Provides complete interface for connecting to Convai's voice assistants,
|
|
@@ -155,6 +180,9 @@ export class ConvaiClient extends EventEmitter {
|
|
|
155
180
|
* room, or a track republished by a reconnect.
|
|
156
181
|
*/
|
|
157
182
|
this._characterMuted = false;
|
|
183
|
+
/** Plays the voice when it arrives over the data channel (audioRouting: 'data_only'). */
|
|
184
|
+
this._dataAudio = null;
|
|
185
|
+
this._audioRouting = "webrtc";
|
|
158
186
|
/**
|
|
159
187
|
* Per-membership overrides of `_characterMuted`. A session-wide call clears
|
|
160
188
|
* this, so "mute everything" never leaves a member behind as an exception.
|
|
@@ -192,6 +220,26 @@ export class ConvaiClient extends EventEmitter {
|
|
|
192
220
|
this._clientReadyRetryTimer = null;
|
|
193
221
|
this._clientReadyTimeoutTimer = null;
|
|
194
222
|
this._clientReadyMsgId = null;
|
|
223
|
+
/**
|
|
224
|
+
* Single-character rooms and WebSocket: whether this room's bot can receive
|
|
225
|
+
* a toggle yet. LiveKit drops data published before the bot participant
|
|
226
|
+
* joins, so until the room shows a running bot (bot-ready, or bot pipeline
|
|
227
|
+
* output from a backend that sends no bot-ready) toggles wait in
|
|
228
|
+
* `_pendingUntilBotReady`, latest value per message type. Roster rooms
|
|
229
|
+
* derive this from the routed member instead (`_canDeliverToggles`). All
|
|
230
|
+
* of it resets when a connection attempt starts, on disconnect() and when
|
|
231
|
+
* the room disconnects, so a held value never reaches another room.
|
|
232
|
+
*/
|
|
233
|
+
this._toggleGate = "hold";
|
|
234
|
+
this._pendingUntilBotReady = new Map();
|
|
235
|
+
/**
|
|
236
|
+
* Roster members seen running in this connection attempt's room: their own
|
|
237
|
+
* identified bot-ready, or bot pipeline output from them on a backend that
|
|
238
|
+
* sends no bot-ready. Cleared with the gate (attempt start, disconnect(),
|
|
239
|
+
* room disconnect), so readiness from an earlier room never counts; the
|
|
240
|
+
* roster's own `isReady` can outlive an unexpected disconnect.
|
|
241
|
+
*/
|
|
242
|
+
this._membersSeenRunning = new Set();
|
|
195
243
|
this._pendingActionResultAcks = new Map();
|
|
196
244
|
// Conversation session tracking
|
|
197
245
|
this._conversationSessionId = 0;
|
|
@@ -439,6 +487,8 @@ export class ConvaiClient extends EventEmitter {
|
|
|
439
487
|
// Pipecat's WebSocket transport plays the character's audio itself and
|
|
440
488
|
// exposes no track, so the session silences its own player instead.
|
|
441
489
|
this._wsSession?.setBotAudioMuted?.(this._characterMuted);
|
|
490
|
+
// Data-channel audio: the SDK's player is the character's voice; mute it there.
|
|
491
|
+
this._dataAudio?.setMuted(this._characterMuted);
|
|
442
492
|
if (this._room.state !== ConnectionState.Connected)
|
|
443
493
|
return;
|
|
444
494
|
this._room.remoteParticipants.forEach((participant) => {
|
|
@@ -455,11 +505,16 @@ export class ConvaiClient extends EventEmitter {
|
|
|
455
505
|
return;
|
|
456
506
|
membershipId = candidate;
|
|
457
507
|
}
|
|
458
|
-
|
|
508
|
+
// Data-channel audio: the voice is played from the data channel, so the
|
|
509
|
+
// WebRTC track stays silent and the server is asked to stop forwarding it.
|
|
510
|
+
const dataOnly = this._audioRouting === "data_only";
|
|
511
|
+
const muted = dataOnly || this.isCharacterMuted(membershipId);
|
|
459
512
|
participant.audioTrackPublications.forEach((publication) => {
|
|
460
513
|
const track = publication.track?.mediaStreamTrack;
|
|
461
514
|
if (track)
|
|
462
515
|
track.enabled = !muted;
|
|
516
|
+
if (dataOnly)
|
|
517
|
+
publication.setEnabled?.(false);
|
|
463
518
|
});
|
|
464
519
|
});
|
|
465
520
|
}
|
|
@@ -469,6 +524,41 @@ export class ConvaiClient extends EventEmitter {
|
|
|
469
524
|
get screenShareControls() {
|
|
470
525
|
return this._screenShareManager;
|
|
471
526
|
}
|
|
527
|
+
get dataAudio() {
|
|
528
|
+
return this._dataAudio;
|
|
529
|
+
}
|
|
530
|
+
/**
|
|
531
|
+
* Data-channel audio (audioRouting: 'data_only'): make the player and hand it
|
|
532
|
+
* the say over "speaking". Idempotent; on the WebRTC path speaking goes back
|
|
533
|
+
* to the server's flags.
|
|
534
|
+
*/
|
|
535
|
+
_configureAudioRouting(config) {
|
|
536
|
+
const dataOnly = config.audioRouting === "data_only";
|
|
537
|
+
this._audioRouting = dataOnly ? "data_only" : "webrtc";
|
|
538
|
+
this._messageHandler.setSpeakingFromPlayback(dataOnly);
|
|
539
|
+
if (!dataOnly || this._dataAudio)
|
|
540
|
+
return;
|
|
541
|
+
const minBuffer = config.dataAudioBufferSeconds;
|
|
542
|
+
const player = new DataAudioPlayer(minBuffer && minBuffer > 0 ? { controller: { minBuffer } } : {});
|
|
543
|
+
this._dataAudio = player;
|
|
544
|
+
player.setMuted(this._characterMuted);
|
|
545
|
+
player.on("replyStarted", () => this._messageHandler.playbackStarted());
|
|
546
|
+
player.on("replyEnded", () => this._messageHandler.playbackEnded());
|
|
547
|
+
this._messageHandler.on("playbackInterrupted", () => player.clear());
|
|
548
|
+
// The server's own flag says when it has finished SENDING the reply; the player uses it
|
|
549
|
+
// to tell a pause in delivery from the reply's end.
|
|
550
|
+
this._messageHandler.on("serverSpeakingChange", (speaking) => player.setServerSpeaking(speaking));
|
|
551
|
+
this._messageHandler.on("blendshapeStatsReceived", (data) => {
|
|
552
|
+
const ms = data?.stats?.total_audio_duration_ms;
|
|
553
|
+
if (typeof ms === "number")
|
|
554
|
+
player.setTurnTotal(ms / 1000);
|
|
555
|
+
});
|
|
556
|
+
this._messageHandler.on("blendshapes", (data) => {
|
|
557
|
+
const n = data?.blendshapes?.length ?? 0;
|
|
558
|
+
if (n)
|
|
559
|
+
player.addFrames(n / (this.blendshapeQueue.getPlaybackFps() || 60));
|
|
560
|
+
});
|
|
561
|
+
}
|
|
472
562
|
get blendshapeQueue() {
|
|
473
563
|
return this._messageHandler.getBlendshapeQueue();
|
|
474
564
|
}
|
|
@@ -524,6 +614,7 @@ export class ConvaiClient extends EventEmitter {
|
|
|
524
614
|
});
|
|
525
615
|
});
|
|
526
616
|
this._room.on(RoomEvent.Disconnected, (reason) => {
|
|
617
|
+
this._resetToggleGate();
|
|
527
618
|
this._connectionStateHandler.handleDisconnected(reason);
|
|
528
619
|
});
|
|
529
620
|
this._room.on(RoomEvent.ConnectionStateChanged, this._connectionStateHandler.handleConnectionStateChanged.bind(this._connectionStateHandler));
|
|
@@ -541,6 +632,17 @@ export class ConvaiClient extends EventEmitter {
|
|
|
541
632
|
if (membershipId)
|
|
542
633
|
this.emit("characterReady", this._roster.find(membershipId));
|
|
543
634
|
}
|
|
635
|
+
if (!this._roster.isMultiCharacter) {
|
|
636
|
+
this._openToggleGate();
|
|
637
|
+
}
|
|
638
|
+
else {
|
|
639
|
+
// Only a member's own identified bot-ready makes it ready for toggles;
|
|
640
|
+
// one that names no member is not credited.
|
|
641
|
+
const membershipId = about?.membership_id;
|
|
642
|
+
if (typeof membershipId === "string")
|
|
643
|
+
this._membersSeenRunning.add(membershipId);
|
|
644
|
+
this._flushHeldToggles();
|
|
645
|
+
}
|
|
544
646
|
// Server may send multiple bot-ready frames (one per client-ready
|
|
545
647
|
// we retried). Only surface the first to consumers per connect.
|
|
546
648
|
if (this._isBotReady) {
|
|
@@ -567,6 +669,11 @@ export class ConvaiClient extends EventEmitter {
|
|
|
567
669
|
this._messageHandler.on("userTranscriptionChange", (transcription) => {
|
|
568
670
|
this.emit("userTranscriptionChange", transcription);
|
|
569
671
|
});
|
|
672
|
+
// Data-channel audio: the server's own speaking flags, for display or logging;
|
|
673
|
+
// speakingChange follows the player instead (audioRouting: 'data_only').
|
|
674
|
+
this._messageHandler.on("serverSpeakingChange", (isSpeaking) => {
|
|
675
|
+
this.emit("serverSpeakingChange", isSpeaking);
|
|
676
|
+
});
|
|
570
677
|
this._messageHandler.on("speakingChange", (isSpeaking) => {
|
|
571
678
|
this.updateState({ isSpeaking });
|
|
572
679
|
this.emit("speakingChange", isSpeaking);
|
|
@@ -660,6 +767,11 @@ export class ConvaiClient extends EventEmitter {
|
|
|
660
767
|
this.emit("llmNoResponse");
|
|
661
768
|
});
|
|
662
769
|
this._messageHandler.on("rawMessage", (event) => {
|
|
770
|
+
// A backend that never sends bot-ready still sends these once its
|
|
771
|
+
// pipeline runs; they are the only sign its bot can receive a toggle.
|
|
772
|
+
if (event.transport === "livekit" && isBotPipelineFrame(event.message)) {
|
|
773
|
+
this._onBotPipelineFrame(event.participant);
|
|
774
|
+
}
|
|
663
775
|
this.emit("rawMessage", event);
|
|
664
776
|
});
|
|
665
777
|
this._messageHandler.on("botTurnCompleted", (data, request) => {
|
|
@@ -681,6 +793,7 @@ export class ConvaiClient extends EventEmitter {
|
|
|
681
793
|
this.emit("botTtsStopped");
|
|
682
794
|
});
|
|
683
795
|
this._messageHandler.on("audioData", (data, request) => {
|
|
796
|
+
this._dataAudio?.pushChunk(data);
|
|
684
797
|
this.emit("audioData", data, request);
|
|
685
798
|
});
|
|
686
799
|
// Forward server-side muting events
|
|
@@ -698,10 +811,13 @@ export class ConvaiClient extends EventEmitter {
|
|
|
698
811
|
});
|
|
699
812
|
this._messageHandler.on("characterStatus", (status) => {
|
|
700
813
|
if (this._roster.applyCharacterStatus(status)) {
|
|
814
|
+
if (status.status === "failed")
|
|
815
|
+
this._membersSeenRunning.delete(status.membershipId);
|
|
701
816
|
this.updateState({
|
|
702
817
|
characters: this._roster.characters,
|
|
703
818
|
activeMembershipId: this._roster.activeMembershipId,
|
|
704
819
|
});
|
|
820
|
+
this._flushHeldToggles();
|
|
705
821
|
}
|
|
706
822
|
this.emit("characterStatus", status);
|
|
707
823
|
});
|
|
@@ -797,7 +913,16 @@ export class ConvaiClient extends EventEmitter {
|
|
|
797
913
|
else if (this._room?.localParticipant &&
|
|
798
914
|
this._room.state !== "disconnected") {
|
|
799
915
|
const encodedData = new TextEncoder().encode(JSON.stringify(message));
|
|
800
|
-
|
|
916
|
+
// publishData rejects when the room is torn down mid-send (for example
|
|
917
|
+
// UnexpectedConnectionState). Nothing awaits it, so catch it here
|
|
918
|
+
// rather than leave an unhandled rejection.
|
|
919
|
+
const warn = (error) => console.warn(`[ConvaiClient] "${type}" was not sent: ${error instanceof Error ? error.message : String(error)}`);
|
|
920
|
+
try {
|
|
921
|
+
Promise.resolve(this._room.localParticipant.publishData(encodedData, { reliable: true })).catch(warn);
|
|
922
|
+
}
|
|
923
|
+
catch (error) {
|
|
924
|
+
warn(error);
|
|
925
|
+
}
|
|
801
926
|
}
|
|
802
927
|
}
|
|
803
928
|
/**
|
|
@@ -850,12 +975,17 @@ export class ConvaiClient extends EventEmitter {
|
|
|
850
975
|
// Store config for reconnection
|
|
851
976
|
this._storedConfig = { ...finalConfig };
|
|
852
977
|
this._isPublishedChatSession = false;
|
|
978
|
+
this._configureAudioRouting(finalConfig);
|
|
853
979
|
// Use characterSessionId from config when reconnecting (so we resume the same session)
|
|
854
980
|
if (finalConfig.characterSessionId &&
|
|
855
981
|
finalConfig.characterSessionId !== "-1") {
|
|
856
982
|
this._characterSessionId = finalConfig.characterSessionId;
|
|
857
983
|
}
|
|
858
984
|
const configWithDefaults = this.applyConfigDefaults(finalConfig);
|
|
985
|
+
const transportType = configWithDefaults.transport ??
|
|
986
|
+
(configWithDefaults.interactionApiUrl ? "sse" : "livekit");
|
|
987
|
+
// Before the first stateChange: a listener may toggle synchronously.
|
|
988
|
+
this._beginAttempt(transportType);
|
|
859
989
|
// A fresh connect starts on the v1 model-output contract; the /connect
|
|
860
990
|
// response upgrades it once the server confirms the negotiated version.
|
|
861
991
|
this._messageHandler.setModelOutputVersion(1);
|
|
@@ -871,15 +1001,12 @@ export class ConvaiClient extends EventEmitter {
|
|
|
871
1001
|
// Determine connection type based on enableVideo
|
|
872
1002
|
const connType = configWithDefaults.enableVideo ? "video" : "audio";
|
|
873
1003
|
this._connectionType = connType;
|
|
874
|
-
const transportType = configWithDefaults.transport ??
|
|
875
|
-
(configWithDefaults.interactionApiUrl ? "sse" : "livekit");
|
|
876
1004
|
if (transportType === "sse" && !configWithDefaults.interactionApiUrl) {
|
|
877
1005
|
throw new Error("interactionApiUrl is required when using the SSE transport");
|
|
878
1006
|
}
|
|
879
1007
|
if (transportType === "sse" && configWithDefaults.enableVideo) {
|
|
880
1008
|
throw new Error("The SSE transport supports text interactions only");
|
|
881
1009
|
}
|
|
882
|
-
this._activeTransport = transportType;
|
|
883
1010
|
const effectiveVisionInputConfig = resolveVisionInputConfig(configWithDefaults);
|
|
884
1011
|
// An explicit stateOfMind in the config wins; otherwise carry whatever
|
|
885
1012
|
// updateEmotion() last set, including before the first connect.
|
|
@@ -913,6 +1040,9 @@ export class ConvaiClient extends EventEmitter {
|
|
|
913
1040
|
},
|
|
914
1041
|
endUserId: configWithDefaults.endUserId,
|
|
915
1042
|
endUserMetadata: configWithDefaults.endUserMetadata,
|
|
1043
|
+
...(configWithDefaults.endUserToken !== undefined && {
|
|
1044
|
+
getEndUserToken: () => resolveEndUserToken(configWithDefaults.endUserToken),
|
|
1045
|
+
}),
|
|
916
1046
|
enableEmotion: configWithDefaults.enableEmotion,
|
|
917
1047
|
emotionConfig: configWithDefaults.emotionConfig,
|
|
918
1048
|
actionConfig: configWithDefaults.actionConfig,
|
|
@@ -924,7 +1054,7 @@ export class ConvaiClient extends EventEmitter {
|
|
|
924
1054
|
respondModes: configWithDefaults.respondModes,
|
|
925
1055
|
useResponseLifecycleContract: configWithDefaults.useResponseLifecycleContract,
|
|
926
1056
|
invocationMetadata: configWithDefaults.invocationMetadata,
|
|
927
|
-
ttsEnabled: configWithDefaults
|
|
1057
|
+
ttsEnabled: this._latestTtsEnabled(configWithDefaults),
|
|
928
1058
|
debug: configWithDefaults.debug,
|
|
929
1059
|
onRawMessage: (event) => this.emit("rawMessage", event),
|
|
930
1060
|
onMessage: (payload, request) => this._messageHandler.handleDataReceivedPublic(payload, "sse", request),
|
|
@@ -950,6 +1080,11 @@ export class ConvaiClient extends EventEmitter {
|
|
|
950
1080
|
const characterSessionIdToSend = configWithDefaults.characterSessionId ?? this._characterSessionId;
|
|
951
1081
|
const isRoster = isRosterConfig(configWithDefaults);
|
|
952
1082
|
const serializedCapabilities = serializeProtocolCapabilities(configWithDefaults.capabilities);
|
|
1083
|
+
// The end user's own credential: one person, one character. A roster
|
|
1084
|
+
// room is shared, so the token is never read or sent there.
|
|
1085
|
+
const endUserToken = !isRoster && configWithDefaults.endUserToken !== undefined
|
|
1086
|
+
? await resolveEndUserToken(configWithDefaults.endUserToken)
|
|
1087
|
+
: undefined;
|
|
953
1088
|
const requestBody = {
|
|
954
1089
|
...(isRoster
|
|
955
1090
|
? buildRosterConnectFields(configWithDefaults)
|
|
@@ -961,6 +1096,7 @@ export class ConvaiClient extends EventEmitter {
|
|
|
961
1096
|
...(configWithDefaults.endUserMetadata != null && {
|
|
962
1097
|
end_user_metadata: configWithDefaults.endUserMetadata,
|
|
963
1098
|
}),
|
|
1099
|
+
...(endUserToken && { end_user_token: endUserToken }),
|
|
964
1100
|
transport: transportType,
|
|
965
1101
|
...(serializedCapabilities && {
|
|
966
1102
|
capabilities: serializedCapabilities,
|
|
@@ -970,9 +1106,11 @@ export class ConvaiClient extends EventEmitter {
|
|
|
970
1106
|
...(buildEmotionConnectConfig(configWithDefaults) && {
|
|
971
1107
|
emotion_config: buildEmotionConnectConfig(configWithDefaults),
|
|
972
1108
|
}),
|
|
973
|
-
default_tts_enabled: configWithDefaults
|
|
974
|
-
|
|
975
|
-
|
|
1109
|
+
default_tts_enabled: this._latestTtsEnabled(configWithDefaults) ?? true,
|
|
1110
|
+
// Data-channel audio: the voice comes as PCM chunks next to the lipsync, played by the SDK.
|
|
1111
|
+
...(configWithDefaults.audioRouting === "data_only" && {
|
|
1112
|
+
audio_config: { output: { audio_routing: "data_only" } },
|
|
1113
|
+
}),
|
|
976
1114
|
default_stt_enabled: true,
|
|
977
1115
|
...(effectiveVisionInputConfig && {
|
|
978
1116
|
vision_input_config: serializeVisionInputConfig(effectiveVisionInputConfig),
|
|
@@ -1027,6 +1165,8 @@ export class ConvaiClient extends EventEmitter {
|
|
|
1027
1165
|
}),
|
|
1028
1166
|
},
|
|
1029
1167
|
};
|
|
1168
|
+
// The boot carries the latest toggleTts value; a held one is redundant.
|
|
1169
|
+
this._pendingUntilBotReady.delete("tts-toggle");
|
|
1030
1170
|
const connectHeaders = {
|
|
1031
1171
|
"Content-Type": "application/json",
|
|
1032
1172
|
};
|
|
@@ -1141,6 +1281,9 @@ export class ConvaiClient extends EventEmitter {
|
|
|
1141
1281
|
const configWithDefaults = this.applyConfigDefaults(finalConfig, {
|
|
1142
1282
|
requireCredential: false,
|
|
1143
1283
|
});
|
|
1284
|
+
// Before the first stateChange, as in connect(). The caller built the
|
|
1285
|
+
// boot request, so a toggle from here on is held for this room.
|
|
1286
|
+
this._beginAttempt(configWithDefaults.transport ?? "livekit");
|
|
1144
1287
|
// Symmetric with connect(): the catch below emits isConnecting: false, so
|
|
1145
1288
|
// without this a UI bound to stateChange never sees a connecting state on
|
|
1146
1289
|
// the proxy path -- and on failure receives a transition out of a state it
|
|
@@ -1223,6 +1366,8 @@ export class ConvaiClient extends EventEmitter {
|
|
|
1223
1366
|
characters: this._roster.characters,
|
|
1224
1367
|
activeMembershipId: this._roster.activeMembershipId,
|
|
1225
1368
|
});
|
|
1369
|
+
// The route may now point at a member that is already ready.
|
|
1370
|
+
this._flushHeldToggles();
|
|
1226
1371
|
}
|
|
1227
1372
|
/** Publish a roster command and settle when its ack arrives. */
|
|
1228
1373
|
_sendRosterCommand(type, build) {
|
|
@@ -1375,6 +1520,9 @@ export class ConvaiClient extends EventEmitter {
|
|
|
1375
1520
|
}
|
|
1376
1521
|
this._logRtviMessages = stored.logRtviMessages !== false;
|
|
1377
1522
|
this._messageHandler.setRtviMessageLogging(this._logRtviMessages);
|
|
1523
|
+
// A join is always LiveKit (see buildJoinRequestBody). Its request has
|
|
1524
|
+
// no TTS field, so a toggle from here on is held for this room.
|
|
1525
|
+
this._beginAttempt("livekit");
|
|
1378
1526
|
this.updateState({ isConnecting: true });
|
|
1379
1527
|
try {
|
|
1380
1528
|
const connectionData = await this._withProvisioningRetry(stored, async () => {
|
|
@@ -1406,7 +1554,9 @@ export class ConvaiClient extends EventEmitter {
|
|
|
1406
1554
|
const rosterCharacters = connectionData.characters;
|
|
1407
1555
|
const initialCharacterId = rosterCharacters?.[0]?.character_id;
|
|
1408
1556
|
const joinConfig = {
|
|
1409
|
-
|
|
1557
|
+
// Read again: a runtime update (toggleTts and others) during the
|
|
1558
|
+
// fetch must not be overwritten by the snapshot taken before it.
|
|
1559
|
+
...(this._storedConfig ?? stored),
|
|
1410
1560
|
characters: undefined,
|
|
1411
1561
|
characterId: initialCharacterId ?? stored.characterId,
|
|
1412
1562
|
endUserId: options.endUserId,
|
|
@@ -1654,6 +1804,8 @@ export class ConvaiClient extends EventEmitter {
|
|
|
1654
1804
|
});
|
|
1655
1805
|
});
|
|
1656
1806
|
});
|
|
1807
|
+
// The session reaches the bot from here: send what this attempt held.
|
|
1808
|
+
this._openToggleGate();
|
|
1657
1809
|
// For WebSocket, mic is already streaming after connect.
|
|
1658
1810
|
// Only mute if the caller explicitly sets startWithAudioOn: false.
|
|
1659
1811
|
// Defaulting to on matches the sandbox behavior and ensures the bot
|
|
@@ -1776,6 +1928,7 @@ export class ConvaiClient extends EventEmitter {
|
|
|
1776
1928
|
}
|
|
1777
1929
|
this._storedConfig = null;
|
|
1778
1930
|
this._isPublishedChatSession = true;
|
|
1931
|
+
this._beginAttempt("livekit");
|
|
1779
1932
|
this._requestTraceId = null;
|
|
1780
1933
|
this._apiKey = null;
|
|
1781
1934
|
this._authToken = null;
|
|
@@ -1786,7 +1939,6 @@ export class ConvaiClient extends EventEmitter {
|
|
|
1786
1939
|
this._requestTraceId = null;
|
|
1787
1940
|
this._memoryManager = null;
|
|
1788
1941
|
this._connectionType = "text";
|
|
1789
|
-
this._activeTransport = "livekit";
|
|
1790
1942
|
// Published chat does not negotiate protocol capabilities. A client may
|
|
1791
1943
|
// have previously connected to a v2 character, so restore the default v1
|
|
1792
1944
|
// handling before accepting this text-only session's legacy envelopes.
|
|
@@ -1956,7 +2108,8 @@ export class ConvaiClient extends EventEmitter {
|
|
|
1956
2108
|
},
|
|
1957
2109
|
};
|
|
1958
2110
|
const encoded = new TextEncoder().encode(JSON.stringify(msg));
|
|
1959
|
-
|
|
2111
|
+
// Asynchronous failures too; the next retry tries again.
|
|
2112
|
+
Promise.resolve(this._room.localParticipant.publishData(encoded, { reliable: true })).catch(() => undefined);
|
|
1960
2113
|
}
|
|
1961
2114
|
catch {
|
|
1962
2115
|
// swallow; next retry will try again
|
|
@@ -1972,6 +2125,107 @@ export class ConvaiClient extends EventEmitter {
|
|
|
1972
2125
|
this.emit("error", err);
|
|
1973
2126
|
}, ConvaiClient.CLIENT_READY_TIMEOUT_MS);
|
|
1974
2127
|
}
|
|
2128
|
+
/**
|
|
2129
|
+
* Send a toggle on the active transport. On LiveKit it waits, latest value
|
|
2130
|
+
* only, until this room's bot can receive it (see `_toggleGate`); the bot
|
|
2131
|
+
* joins after the client and LiveKit drops data published before that.
|
|
2132
|
+
*/
|
|
2133
|
+
_sendToggle(type, data) {
|
|
2134
|
+
const hold = this._activeTransport === "livekit"
|
|
2135
|
+
? // Also while the room is not connected (an attempt in flight).
|
|
2136
|
+
!this._canDeliverToggles() || !this.isTransportReady()
|
|
2137
|
+
: // WebSocket: held during the attempt, sent once its session connects.
|
|
2138
|
+
this._activeTransport === "websocket" && !this.isTransportReady();
|
|
2139
|
+
if (hold) {
|
|
2140
|
+
this._pendingUntilBotReady.set(type, data); // last call wins
|
|
2141
|
+
return;
|
|
2142
|
+
}
|
|
2143
|
+
if (!this.isTransportReady())
|
|
2144
|
+
return;
|
|
2145
|
+
// This value supersedes a held one of the same type.
|
|
2146
|
+
this._pendingUntilBotReady.delete(type);
|
|
2147
|
+
this._flushHeldToggles();
|
|
2148
|
+
this.publishMessage(type, data);
|
|
2149
|
+
}
|
|
2150
|
+
/**
|
|
2151
|
+
* Whether a toggle published now reaches a bot that consumes it. Roster
|
|
2152
|
+
* rooms: the routed member must be running in this attempt's room (its
|
|
2153
|
+
* bot-ready, or pipeline output from it), re-evaluated on every route or
|
|
2154
|
+
* status change, so a member that fails or a route to one that is not ready
|
|
2155
|
+
* holds toggles again. Elsewhere: this room's gate.
|
|
2156
|
+
*/
|
|
2157
|
+
_canDeliverToggles() {
|
|
2158
|
+
const recipient = this._toggleRecipient();
|
|
2159
|
+
if (recipient === undefined)
|
|
2160
|
+
return this._toggleGate === "open";
|
|
2161
|
+
return recipient !== null && this._membersSeenRunning.has(recipient.membershipId);
|
|
2162
|
+
}
|
|
2163
|
+
/** Send the held toggles, once, if they can be delivered now. */
|
|
2164
|
+
_flushHeldToggles() {
|
|
2165
|
+
if (this._pendingUntilBotReady.size === 0 || !this._canDeliverToggles())
|
|
2166
|
+
return;
|
|
2167
|
+
const pending = [...this._pendingUntilBotReady];
|
|
2168
|
+
this._pendingUntilBotReady.clear();
|
|
2169
|
+
for (const [type, data] of pending)
|
|
2170
|
+
this.publishMessage(type, data);
|
|
2171
|
+
}
|
|
2172
|
+
/** Single-character room or WebSocket: the bot can receive toggles now. */
|
|
2173
|
+
_openToggleGate() {
|
|
2174
|
+
this._toggleGate = "open";
|
|
2175
|
+
this._flushHeldToggles();
|
|
2176
|
+
}
|
|
2177
|
+
/** Bot pipeline output: the sender is running (backends without bot-ready). */
|
|
2178
|
+
_onBotPipelineFrame(participant) {
|
|
2179
|
+
if (!this._roster.isMultiCharacter) {
|
|
2180
|
+
this._openToggleGate();
|
|
2181
|
+
return;
|
|
2182
|
+
}
|
|
2183
|
+
const identity = participant?.identity;
|
|
2184
|
+
const sender = this._roster.characters.find((c) => c.participantIdentity === identity);
|
|
2185
|
+
if (!sender)
|
|
2186
|
+
return;
|
|
2187
|
+
this._membersSeenRunning.add(sender.membershipId);
|
|
2188
|
+
this._flushHeldToggles();
|
|
2189
|
+
}
|
|
2190
|
+
/**
|
|
2191
|
+
* The member that consumes toggles. In a multi-character room
|
|
2192
|
+
* core-service delivers tts-toggle and stt-toggle only to the routed
|
|
2193
|
+
* (active) member and the others drop them, so another member's readiness
|
|
2194
|
+
* must not open the gate. `undefined`: not a roster room, any bot counts.
|
|
2195
|
+
* `null`: a roster room with no target (an acknowledged
|
|
2196
|
+
* setInteractionTarget(null)), where no member consumes them.
|
|
2197
|
+
*/
|
|
2198
|
+
_toggleRecipient() {
|
|
2199
|
+
if (!this._roster.isMultiCharacter)
|
|
2200
|
+
return undefined;
|
|
2201
|
+
const active = this._roster.activeMembershipId;
|
|
2202
|
+
return active ? (this._roster.find(active) ?? null) : null;
|
|
2203
|
+
}
|
|
2204
|
+
_resetToggleGate() {
|
|
2205
|
+
this._toggleGate = "hold";
|
|
2206
|
+
this._pendingUntilBotReady.clear();
|
|
2207
|
+
this._membersSeenRunning.clear();
|
|
2208
|
+
}
|
|
2209
|
+
/**
|
|
2210
|
+
* Start a connection attempt: drop anything held for an earlier room and
|
|
2211
|
+
* name the transport this attempt uses. Every entry point calls it after
|
|
2212
|
+
* its synchronous validation and before its first stateChange or await, so
|
|
2213
|
+
* a toggle made at any point of the attempt is held for this attempt's room
|
|
2214
|
+
* (or, on SSE, applied to the session it creates).
|
|
2215
|
+
*/
|
|
2216
|
+
_beginAttempt(transport) {
|
|
2217
|
+
this._resetToggleGate();
|
|
2218
|
+
this._activeTransport = transport;
|
|
2219
|
+
}
|
|
2220
|
+
/**
|
|
2221
|
+
* ttsEnabled for a boot built now: toggleTts() may have run since the
|
|
2222
|
+
* attempt captured its config (a stateChange listener, for example).
|
|
2223
|
+
*/
|
|
2224
|
+
_latestTtsEnabled(configWithDefaults) {
|
|
2225
|
+
return this._storedConfig
|
|
2226
|
+
? this._storedConfig.ttsEnabled
|
|
2227
|
+
: configWithDefaults.ttsEnabled;
|
|
2228
|
+
}
|
|
1975
2229
|
_stopClientReadyHandshake() {
|
|
1976
2230
|
if (this._clientReadyRetryTimer) {
|
|
1977
2231
|
clearTimeout(this._clientReadyRetryTimer);
|
|
@@ -1987,6 +2241,7 @@ export class ConvaiClient extends EventEmitter {
|
|
|
1987
2241
|
*/
|
|
1988
2242
|
async disconnect() {
|
|
1989
2243
|
this._stopClientReadyHandshake();
|
|
2244
|
+
this._resetToggleGate();
|
|
1990
2245
|
// Unconditional: the branches below each depend on a transport being
|
|
1991
2246
|
// matched, and none of them runs when there is nothing to tear down. A
|
|
1992
2247
|
// command in flight must still be settled either way.
|
|
@@ -2037,6 +2292,7 @@ export class ConvaiClient extends EventEmitter {
|
|
|
2037
2292
|
* Clear all manager states
|
|
2038
2293
|
*/
|
|
2039
2294
|
clearAllManagers() {
|
|
2295
|
+
this._dataAudio?.clear();
|
|
2040
2296
|
this._connectionType = null;
|
|
2041
2297
|
this._activeTransport = null;
|
|
2042
2298
|
this._wsSession = null;
|
|
@@ -2434,12 +2690,15 @@ export class ConvaiClient extends EventEmitter {
|
|
|
2434
2690
|
* Update dynamic information about the current context
|
|
2435
2691
|
*/
|
|
2436
2692
|
updateDynamicInfo(dynamicInfo) {
|
|
2437
|
-
if (!
|
|
2693
|
+
if (!dynamicInfo?.trim())
|
|
2438
2694
|
return;
|
|
2439
2695
|
const nextDynamicInfo = dynamicInfo.trim();
|
|
2696
|
+
// Kept while disconnected too: reconnect() replays _storedConfig.
|
|
2440
2697
|
if (this._storedConfig) {
|
|
2441
2698
|
this._storedConfig = { ...this._storedConfig, dynamicInfo: nextDynamicInfo };
|
|
2442
2699
|
}
|
|
2700
|
+
if (!this.isTransportReady())
|
|
2701
|
+
return;
|
|
2443
2702
|
if (this._activeTransport === "sse" && this._sseSession) {
|
|
2444
2703
|
this._sseSession.updateDynamicInfo(nextDynamicInfo);
|
|
2445
2704
|
return;
|
|
@@ -2547,9 +2806,10 @@ export class ConvaiClient extends EventEmitter {
|
|
|
2547
2806
|
return updateId;
|
|
2548
2807
|
}
|
|
2549
2808
|
respondModeUpdate(options) {
|
|
2809
|
+
// Kept while disconnected too: reconnect() replays _storedConfig.
|
|
2810
|
+
this.rememberRespondMode(options.modality, options.mode);
|
|
2550
2811
|
if (!this.isTransportReady())
|
|
2551
2812
|
return null;
|
|
2552
|
-
this.rememberRespondMode(options.modality, options.mode);
|
|
2553
2813
|
const updateId = options.updateId ?? this.createUpdateId("respond-mode");
|
|
2554
2814
|
this.publishMessage("respond-mode-update", {
|
|
2555
2815
|
update_id: updateId,
|
|
@@ -2658,28 +2918,48 @@ export class ConvaiClient extends EventEmitter {
|
|
|
2658
2918
|
});
|
|
2659
2919
|
}
|
|
2660
2920
|
/**
|
|
2661
|
-
* Toggle text-to-speech on or off
|
|
2921
|
+
* Toggle text-to-speech on or off.
|
|
2922
|
+
*
|
|
2923
|
+
* The value is recorded in every connection state, and `reconnect()` and
|
|
2924
|
+
* `connect()` without a config start the next session with it.
|
|
2925
|
+
* `connect(config)` replaces the stored config, so pass `ttsEnabled` there.
|
|
2926
|
+
*
|
|
2927
|
+
* On LiveKit it is sent once this room's character can receive it: at
|
|
2928
|
+
* `botReady`, or at the character's first speech or transcription event on
|
|
2929
|
+
* a backend that sends no `botReady`. Until then only the latest value is
|
|
2930
|
+
* held; a disconnect drops it, and the next session starts from the
|
|
2931
|
+
* recorded value instead. In a multi-character room it goes to the routed
|
|
2932
|
+
* character: held while it is not ready (including after it fails or a
|
|
2933
|
+
* route moves to one that is not ready yet) and while no character is
|
|
2934
|
+
* routed (`setInteractionTarget(null)`); switching between ready routed
|
|
2935
|
+
* characters re-sends nothing. A failed LiveKit publish is logged,
|
|
2936
|
+
* not thrown or left as an unhandled rejection. SSE applies it to
|
|
2937
|
+
* subsequent requests; WebSocket holds it during a connection attempt and
|
|
2938
|
+
* sends it once the session connects.
|
|
2662
2939
|
*/
|
|
2663
2940
|
toggleTts(enabled) {
|
|
2664
|
-
|
|
2665
|
-
|
|
2666
|
-
// Every transport, not only SSE: reconnect() replays _storedConfig.
|
|
2941
|
+
// Recorded in every connection state, before anything else:
|
|
2942
|
+
// reconnect() and connect() without a config boot from _storedConfig.
|
|
2667
2943
|
if (this._storedConfig) {
|
|
2668
2944
|
this._storedConfig = { ...this._storedConfig, ttsEnabled: enabled };
|
|
2669
2945
|
}
|
|
2670
|
-
if (this._activeTransport === "sse"
|
|
2671
|
-
this.
|
|
2946
|
+
if (this._activeTransport === "sse") {
|
|
2947
|
+
if (this.isTransportReady())
|
|
2948
|
+
this._sseSession?.setTtsEnabled(enabled);
|
|
2672
2949
|
return;
|
|
2673
2950
|
}
|
|
2674
|
-
this.
|
|
2951
|
+
this._sendToggle("tts-toggle", { enabled });
|
|
2675
2952
|
}
|
|
2676
2953
|
/**
|
|
2677
|
-
* Toggle speech-to-text on or off
|
|
2954
|
+
* Toggle speech-to-text on or off.
|
|
2955
|
+
*
|
|
2956
|
+
* On LiveKit and WebSocket it is held and sent like `toggleTts()`, latest
|
|
2957
|
+
* value only. Unlike `toggleTts()` it is not recorded for the next session:
|
|
2958
|
+
* every session starts with speech-to-text on. SSE sends it while
|
|
2959
|
+
* connected.
|
|
2678
2960
|
*/
|
|
2679
2961
|
toggleStt(enabled) {
|
|
2680
|
-
|
|
2681
|
-
return;
|
|
2682
|
-
this.publishMessage("stt-toggle", { muted: !enabled });
|
|
2962
|
+
this._sendToggle("stt-toggle", { muted: !enabled });
|
|
2683
2963
|
}
|
|
2684
2964
|
/**
|
|
2685
2965
|
* Reset the server-side idle timer.
|