@convai/web-sdk 2.0.2-beta.0 → 2.1.0-beta.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.
@@ -127,6 +127,26 @@ export declare class ConvaiClient extends EventEmitter implements IConvaiClient
127
127
  private _clientReadyRetryTimer;
128
128
  private _clientReadyTimeoutTimer;
129
129
  private _clientReadyMsgId;
130
+ /**
131
+ * Single-character rooms and WebSocket: whether this room's bot can receive
132
+ * a toggle yet. LiveKit drops data published before the bot participant
133
+ * joins, so until the room shows a running bot (bot-ready, or bot pipeline
134
+ * output from a backend that sends no bot-ready) toggles wait in
135
+ * `_pendingUntilBotReady`, latest value per message type. Roster rooms
136
+ * derive this from the routed member instead (`_canDeliverToggles`). All
137
+ * of it resets when a connection attempt starts, on disconnect() and when
138
+ * the room disconnects, so a held value never reaches another room.
139
+ */
140
+ private _toggleGate;
141
+ private _pendingUntilBotReady;
142
+ /**
143
+ * Roster members seen running in this connection attempt's room: their own
144
+ * identified bot-ready, or bot pipeline output from them on a backend that
145
+ * sends no bot-ready. Cleared with the gate (attempt start, disconnect(),
146
+ * room disconnect), so readiness from an earlier room never counts; the
147
+ * roster's own `isReady` can outlive an unexpected disconnect.
148
+ */
149
+ private _membersSeenRunning;
130
150
  private _pendingActionResultAcks;
131
151
  private static readonly CLIENT_READY_RETRY_MS;
132
152
  private static readonly CLIENT_READY_TIMEOUT_MS;
@@ -385,6 +405,49 @@ export declare class ConvaiClient extends EventEmitter implements IConvaiClient
385
405
  * bot publishes bot-ready before the client data-channel is subscribed.
386
406
  */
387
407
  private _startClientReadyHandshake;
408
+ /**
409
+ * Send a toggle on the active transport. On LiveKit it waits, latest value
410
+ * only, until this room's bot can receive it (see `_toggleGate`); the bot
411
+ * joins after the client and LiveKit drops data published before that.
412
+ */
413
+ private _sendToggle;
414
+ /**
415
+ * Whether a toggle published now reaches a bot that consumes it. Roster
416
+ * rooms: the routed member must be running in this attempt's room (its
417
+ * bot-ready, or pipeline output from it), re-evaluated on every route or
418
+ * status change, so a member that fails or a route to one that is not ready
419
+ * holds toggles again. Elsewhere: this room's gate.
420
+ */
421
+ private _canDeliverToggles;
422
+ /** Send the held toggles, once, if they can be delivered now. */
423
+ private _flushHeldToggles;
424
+ /** Single-character room or WebSocket: the bot can receive toggles now. */
425
+ private _openToggleGate;
426
+ /** Bot pipeline output: the sender is running (backends without bot-ready). */
427
+ private _onBotPipelineFrame;
428
+ /**
429
+ * The member that consumes toggles. In a multi-character room
430
+ * core-service delivers tts-toggle and stt-toggle only to the routed
431
+ * (active) member and the others drop them, so another member's readiness
432
+ * must not open the gate. `undefined`: not a roster room, any bot counts.
433
+ * `null`: a roster room with no target (an acknowledged
434
+ * setInteractionTarget(null)), where no member consumes them.
435
+ */
436
+ private _toggleRecipient;
437
+ private _resetToggleGate;
438
+ /**
439
+ * Start a connection attempt: drop anything held for an earlier room and
440
+ * name the transport this attempt uses. Every entry point calls it after
441
+ * its synchronous validation and before its first stateChange or await, so
442
+ * a toggle made at any point of the attempt is held for this attempt's room
443
+ * (or, on SSE, applied to the session it creates).
444
+ */
445
+ private _beginAttempt;
446
+ /**
447
+ * ttsEnabled for a boot built now: toggleTts() may have run since the
448
+ * attempt captured its config (a stateChange listener, for example).
449
+ */
450
+ private _latestTtsEnabled;
388
451
  private _stopClientReadyHandshake;
389
452
  /**
390
453
  * Disconnect from the current character session
@@ -504,11 +567,33 @@ export declare class ConvaiClient extends EventEmitter implements IConvaiClient
504
567
  */
505
568
  uploadFile(file: File, options?: UploadFileOptions): Promise<void>;
506
569
  /**
507
- * Toggle text-to-speech on or off
570
+ * Toggle text-to-speech on or off.
571
+ *
572
+ * The value is recorded in every connection state, and `reconnect()` and
573
+ * `connect()` without a config start the next session with it.
574
+ * `connect(config)` replaces the stored config, so pass `ttsEnabled` there.
575
+ *
576
+ * On LiveKit it is sent once this room's character can receive it: at
577
+ * `botReady`, or at the character's first speech or transcription event on
578
+ * a backend that sends no `botReady`. Until then only the latest value is
579
+ * held; a disconnect drops it, and the next session starts from the
580
+ * recorded value instead. In a multi-character room it goes to the routed
581
+ * character: held while it is not ready (including after it fails or a
582
+ * route moves to one that is not ready yet) and while no character is
583
+ * routed (`setInteractionTarget(null)`); switching between ready routed
584
+ * characters re-sends nothing. A failed LiveKit publish is logged,
585
+ * not thrown or left as an unhandled rejection. SSE applies it to
586
+ * subsequent requests; WebSocket holds it during a connection attempt and
587
+ * sends it once the session connects.
508
588
  */
509
589
  toggleTts(enabled: boolean): void;
510
590
  /**
511
- * Toggle speech-to-text on or off
591
+ * Toggle speech-to-text on or off.
592
+ *
593
+ * On LiveKit and WebSocket it is held and sent like `toggleTts()`, latest
594
+ * value only. Unlike `toggleTts()` it is not recorded for the next session:
595
+ * every session starts with speech-to-text on. SSE sends it while
596
+ * connected.
512
597
  */
513
598
  toggleStt(enabled: boolean): void;
514
599
  /**
@@ -16,6 +16,7 @@ import { CharacterVersionManager } from "./CharacterVersionManager.js";
16
16
  import { resolveCharacterReference, } from "./characterReference.js";
17
17
  import { ConnectionStateHandler } from "./ConnectionStateHandler.js";
18
18
  import { buildActionConnectConfig, buildBlendshapeConnectConfig, buildEmotionConnectConfig, serializeProtocolCapabilities, validateActionProtocolSelection, validateModelOutputVersionSelection, } from "./connectRequest.js";
19
+ import { resolveEndUserToken } from "./endUserToken.js";
19
20
  import { shouldPreemptForContextUpdateResponse, shouldPreemptForExplicitRespondMode, } from "./contextUpdateRequest.js";
20
21
  import { resolveVisionInputConfig, serializeVisionInputConfig, } from "./visionRequest.js";
21
22
  import { SSESession } from "./SSESession.js";
@@ -68,6 +69,29 @@ class NoReconnectPolicy extends DefaultReconnectPolicy {
68
69
  return null; // Always return null to prevent any reconnection attempts
69
70
  }
70
71
  }
72
+ /**
73
+ * RTVI frames only a running bot pipeline sends. A backend that never sends
74
+ * bot-ready still sends these once it is up.
75
+ */
76
+ const BOT_PIPELINE_FRAME_TYPES = new Set([
77
+ "user-started-speaking",
78
+ "user-stopped-speaking",
79
+ "user-transcription",
80
+ "bot-llm-started",
81
+ "bot-llm-text",
82
+ "bot-llm-stopped",
83
+ "bot-output",
84
+ "bot-tts-started",
85
+ "bot-tts-text",
86
+ "bot-tts-stopped",
87
+ "bot-started-speaking",
88
+ "bot-stopped-speaking",
89
+ "bot-turn-completed",
90
+ ]);
91
+ function isBotPipelineFrame(message) {
92
+ const type = message?.type;
93
+ return typeof type === "string" && BOT_PIPELINE_FRAME_TYPES.has(type);
94
+ }
71
95
  /**
72
96
  * Main Convai client class for managing AI voice assistant connections
73
97
  * Provides complete interface for connecting to Convai's voice assistants,
@@ -192,6 +216,26 @@ export class ConvaiClient extends EventEmitter {
192
216
  this._clientReadyRetryTimer = null;
193
217
  this._clientReadyTimeoutTimer = null;
194
218
  this._clientReadyMsgId = null;
219
+ /**
220
+ * Single-character rooms and WebSocket: whether this room's bot can receive
221
+ * a toggle yet. LiveKit drops data published before the bot participant
222
+ * joins, so until the room shows a running bot (bot-ready, or bot pipeline
223
+ * output from a backend that sends no bot-ready) toggles wait in
224
+ * `_pendingUntilBotReady`, latest value per message type. Roster rooms
225
+ * derive this from the routed member instead (`_canDeliverToggles`). All
226
+ * of it resets when a connection attempt starts, on disconnect() and when
227
+ * the room disconnects, so a held value never reaches another room.
228
+ */
229
+ this._toggleGate = "hold";
230
+ this._pendingUntilBotReady = new Map();
231
+ /**
232
+ * Roster members seen running in this connection attempt's room: their own
233
+ * identified bot-ready, or bot pipeline output from them on a backend that
234
+ * sends no bot-ready. Cleared with the gate (attempt start, disconnect(),
235
+ * room disconnect), so readiness from an earlier room never counts; the
236
+ * roster's own `isReady` can outlive an unexpected disconnect.
237
+ */
238
+ this._membersSeenRunning = new Set();
195
239
  this._pendingActionResultAcks = new Map();
196
240
  // Conversation session tracking
197
241
  this._conversationSessionId = 0;
@@ -524,6 +568,7 @@ export class ConvaiClient extends EventEmitter {
524
568
  });
525
569
  });
526
570
  this._room.on(RoomEvent.Disconnected, (reason) => {
571
+ this._resetToggleGate();
527
572
  this._connectionStateHandler.handleDisconnected(reason);
528
573
  });
529
574
  this._room.on(RoomEvent.ConnectionStateChanged, this._connectionStateHandler.handleConnectionStateChanged.bind(this._connectionStateHandler));
@@ -541,6 +586,17 @@ export class ConvaiClient extends EventEmitter {
541
586
  if (membershipId)
542
587
  this.emit("characterReady", this._roster.find(membershipId));
543
588
  }
589
+ if (!this._roster.isMultiCharacter) {
590
+ this._openToggleGate();
591
+ }
592
+ else {
593
+ // Only a member's own identified bot-ready makes it ready for toggles;
594
+ // one that names no member is not credited.
595
+ const membershipId = about?.membership_id;
596
+ if (typeof membershipId === "string")
597
+ this._membersSeenRunning.add(membershipId);
598
+ this._flushHeldToggles();
599
+ }
544
600
  // Server may send multiple bot-ready frames (one per client-ready
545
601
  // we retried). Only surface the first to consumers per connect.
546
602
  if (this._isBotReady) {
@@ -660,6 +716,11 @@ export class ConvaiClient extends EventEmitter {
660
716
  this.emit("llmNoResponse");
661
717
  });
662
718
  this._messageHandler.on("rawMessage", (event) => {
719
+ // A backend that never sends bot-ready still sends these once its
720
+ // pipeline runs; they are the only sign its bot can receive a toggle.
721
+ if (event.transport === "livekit" && isBotPipelineFrame(event.message)) {
722
+ this._onBotPipelineFrame(event.participant);
723
+ }
663
724
  this.emit("rawMessage", event);
664
725
  });
665
726
  this._messageHandler.on("botTurnCompleted", (data, request) => {
@@ -698,10 +759,13 @@ export class ConvaiClient extends EventEmitter {
698
759
  });
699
760
  this._messageHandler.on("characterStatus", (status) => {
700
761
  if (this._roster.applyCharacterStatus(status)) {
762
+ if (status.status === "failed")
763
+ this._membersSeenRunning.delete(status.membershipId);
701
764
  this.updateState({
702
765
  characters: this._roster.characters,
703
766
  activeMembershipId: this._roster.activeMembershipId,
704
767
  });
768
+ this._flushHeldToggles();
705
769
  }
706
770
  this.emit("characterStatus", status);
707
771
  });
@@ -797,7 +861,16 @@ export class ConvaiClient extends EventEmitter {
797
861
  else if (this._room?.localParticipant &&
798
862
  this._room.state !== "disconnected") {
799
863
  const encodedData = new TextEncoder().encode(JSON.stringify(message));
800
- this._room.localParticipant.publishData(encodedData, { reliable: true });
864
+ // publishData rejects when the room is torn down mid-send (for example
865
+ // UnexpectedConnectionState). Nothing awaits it, so catch it here
866
+ // rather than leave an unhandled rejection.
867
+ const warn = (error) => console.warn(`[ConvaiClient] "${type}" was not sent: ${error instanceof Error ? error.message : String(error)}`);
868
+ try {
869
+ Promise.resolve(this._room.localParticipant.publishData(encodedData, { reliable: true })).catch(warn);
870
+ }
871
+ catch (error) {
872
+ warn(error);
873
+ }
801
874
  }
802
875
  }
803
876
  /**
@@ -856,6 +929,10 @@ export class ConvaiClient extends EventEmitter {
856
929
  this._characterSessionId = finalConfig.characterSessionId;
857
930
  }
858
931
  const configWithDefaults = this.applyConfigDefaults(finalConfig);
932
+ const transportType = configWithDefaults.transport ??
933
+ (configWithDefaults.interactionApiUrl ? "sse" : "livekit");
934
+ // Before the first stateChange: a listener may toggle synchronously.
935
+ this._beginAttempt(transportType);
859
936
  // A fresh connect starts on the v1 model-output contract; the /connect
860
937
  // response upgrades it once the server confirms the negotiated version.
861
938
  this._messageHandler.setModelOutputVersion(1);
@@ -871,15 +948,12 @@ export class ConvaiClient extends EventEmitter {
871
948
  // Determine connection type based on enableVideo
872
949
  const connType = configWithDefaults.enableVideo ? "video" : "audio";
873
950
  this._connectionType = connType;
874
- const transportType = configWithDefaults.transport ??
875
- (configWithDefaults.interactionApiUrl ? "sse" : "livekit");
876
951
  if (transportType === "sse" && !configWithDefaults.interactionApiUrl) {
877
952
  throw new Error("interactionApiUrl is required when using the SSE transport");
878
953
  }
879
954
  if (transportType === "sse" && configWithDefaults.enableVideo) {
880
955
  throw new Error("The SSE transport supports text interactions only");
881
956
  }
882
- this._activeTransport = transportType;
883
957
  const effectiveVisionInputConfig = resolveVisionInputConfig(configWithDefaults);
884
958
  // An explicit stateOfMind in the config wins; otherwise carry whatever
885
959
  // updateEmotion() last set, including before the first connect.
@@ -913,6 +987,9 @@ export class ConvaiClient extends EventEmitter {
913
987
  },
914
988
  endUserId: configWithDefaults.endUserId,
915
989
  endUserMetadata: configWithDefaults.endUserMetadata,
990
+ ...(configWithDefaults.endUserToken !== undefined && {
991
+ getEndUserToken: () => resolveEndUserToken(configWithDefaults.endUserToken),
992
+ }),
916
993
  enableEmotion: configWithDefaults.enableEmotion,
917
994
  emotionConfig: configWithDefaults.emotionConfig,
918
995
  actionConfig: configWithDefaults.actionConfig,
@@ -924,7 +1001,7 @@ export class ConvaiClient extends EventEmitter {
924
1001
  respondModes: configWithDefaults.respondModes,
925
1002
  useResponseLifecycleContract: configWithDefaults.useResponseLifecycleContract,
926
1003
  invocationMetadata: configWithDefaults.invocationMetadata,
927
- ttsEnabled: configWithDefaults.ttsEnabled,
1004
+ ttsEnabled: this._latestTtsEnabled(configWithDefaults),
928
1005
  debug: configWithDefaults.debug,
929
1006
  onRawMessage: (event) => this.emit("rawMessage", event),
930
1007
  onMessage: (payload, request) => this._messageHandler.handleDataReceivedPublic(payload, "sse", request),
@@ -950,6 +1027,11 @@ export class ConvaiClient extends EventEmitter {
950
1027
  const characterSessionIdToSend = configWithDefaults.characterSessionId ?? this._characterSessionId;
951
1028
  const isRoster = isRosterConfig(configWithDefaults);
952
1029
  const serializedCapabilities = serializeProtocolCapabilities(configWithDefaults.capabilities);
1030
+ // The end user's own credential: one person, one character. A roster
1031
+ // room is shared, so the token is never read or sent there.
1032
+ const endUserToken = !isRoster && configWithDefaults.endUserToken !== undefined
1033
+ ? await resolveEndUserToken(configWithDefaults.endUserToken)
1034
+ : undefined;
953
1035
  const requestBody = {
954
1036
  ...(isRoster
955
1037
  ? buildRosterConnectFields(configWithDefaults)
@@ -961,6 +1043,7 @@ export class ConvaiClient extends EventEmitter {
961
1043
  ...(configWithDefaults.endUserMetadata != null && {
962
1044
  end_user_metadata: configWithDefaults.endUserMetadata,
963
1045
  }),
1046
+ ...(endUserToken && { end_user_token: endUserToken }),
964
1047
  transport: transportType,
965
1048
  ...(serializedCapabilities && {
966
1049
  capabilities: serializedCapabilities,
@@ -970,9 +1053,7 @@ export class ConvaiClient extends EventEmitter {
970
1053
  ...(buildEmotionConnectConfig(configWithDefaults) && {
971
1054
  emotion_config: buildEmotionConnectConfig(configWithDefaults),
972
1055
  }),
973
- default_tts_enabled: configWithDefaults.ttsEnabled !== undefined
974
- ? configWithDefaults.ttsEnabled
975
- : true,
1056
+ default_tts_enabled: this._latestTtsEnabled(configWithDefaults) ?? true,
976
1057
  default_stt_enabled: true,
977
1058
  ...(effectiveVisionInputConfig && {
978
1059
  vision_input_config: serializeVisionInputConfig(effectiveVisionInputConfig),
@@ -1027,6 +1108,8 @@ export class ConvaiClient extends EventEmitter {
1027
1108
  }),
1028
1109
  },
1029
1110
  };
1111
+ // The boot carries the latest toggleTts value; a held one is redundant.
1112
+ this._pendingUntilBotReady.delete("tts-toggle");
1030
1113
  const connectHeaders = {
1031
1114
  "Content-Type": "application/json",
1032
1115
  };
@@ -1141,6 +1224,9 @@ export class ConvaiClient extends EventEmitter {
1141
1224
  const configWithDefaults = this.applyConfigDefaults(finalConfig, {
1142
1225
  requireCredential: false,
1143
1226
  });
1227
+ // Before the first stateChange, as in connect(). The caller built the
1228
+ // boot request, so a toggle from here on is held for this room.
1229
+ this._beginAttempt(configWithDefaults.transport ?? "livekit");
1144
1230
  // Symmetric with connect(): the catch below emits isConnecting: false, so
1145
1231
  // without this a UI bound to stateChange never sees a connecting state on
1146
1232
  // the proxy path -- and on failure receives a transition out of a state it
@@ -1223,6 +1309,8 @@ export class ConvaiClient extends EventEmitter {
1223
1309
  characters: this._roster.characters,
1224
1310
  activeMembershipId: this._roster.activeMembershipId,
1225
1311
  });
1312
+ // The route may now point at a member that is already ready.
1313
+ this._flushHeldToggles();
1226
1314
  }
1227
1315
  /** Publish a roster command and settle when its ack arrives. */
1228
1316
  _sendRosterCommand(type, build) {
@@ -1375,6 +1463,9 @@ export class ConvaiClient extends EventEmitter {
1375
1463
  }
1376
1464
  this._logRtviMessages = stored.logRtviMessages !== false;
1377
1465
  this._messageHandler.setRtviMessageLogging(this._logRtviMessages);
1466
+ // A join is always LiveKit (see buildJoinRequestBody). Its request has
1467
+ // no TTS field, so a toggle from here on is held for this room.
1468
+ this._beginAttempt("livekit");
1378
1469
  this.updateState({ isConnecting: true });
1379
1470
  try {
1380
1471
  const connectionData = await this._withProvisioningRetry(stored, async () => {
@@ -1406,7 +1497,9 @@ export class ConvaiClient extends EventEmitter {
1406
1497
  const rosterCharacters = connectionData.characters;
1407
1498
  const initialCharacterId = rosterCharacters?.[0]?.character_id;
1408
1499
  const joinConfig = {
1409
- ...stored,
1500
+ // Read again: a runtime update (toggleTts and others) during the
1501
+ // fetch must not be overwritten by the snapshot taken before it.
1502
+ ...(this._storedConfig ?? stored),
1410
1503
  characters: undefined,
1411
1504
  characterId: initialCharacterId ?? stored.characterId,
1412
1505
  endUserId: options.endUserId,
@@ -1654,6 +1747,8 @@ export class ConvaiClient extends EventEmitter {
1654
1747
  });
1655
1748
  });
1656
1749
  });
1750
+ // The session reaches the bot from here: send what this attempt held.
1751
+ this._openToggleGate();
1657
1752
  // For WebSocket, mic is already streaming after connect.
1658
1753
  // Only mute if the caller explicitly sets startWithAudioOn: false.
1659
1754
  // Defaulting to on matches the sandbox behavior and ensures the bot
@@ -1776,6 +1871,7 @@ export class ConvaiClient extends EventEmitter {
1776
1871
  }
1777
1872
  this._storedConfig = null;
1778
1873
  this._isPublishedChatSession = true;
1874
+ this._beginAttempt("livekit");
1779
1875
  this._requestTraceId = null;
1780
1876
  this._apiKey = null;
1781
1877
  this._authToken = null;
@@ -1786,7 +1882,6 @@ export class ConvaiClient extends EventEmitter {
1786
1882
  this._requestTraceId = null;
1787
1883
  this._memoryManager = null;
1788
1884
  this._connectionType = "text";
1789
- this._activeTransport = "livekit";
1790
1885
  // Published chat does not negotiate protocol capabilities. A client may
1791
1886
  // have previously connected to a v2 character, so restore the default v1
1792
1887
  // handling before accepting this text-only session's legacy envelopes.
@@ -1956,7 +2051,8 @@ export class ConvaiClient extends EventEmitter {
1956
2051
  },
1957
2052
  };
1958
2053
  const encoded = new TextEncoder().encode(JSON.stringify(msg));
1959
- this._room.localParticipant.publishData(encoded, { reliable: true });
2054
+ // Asynchronous failures too; the next retry tries again.
2055
+ Promise.resolve(this._room.localParticipant.publishData(encoded, { reliable: true })).catch(() => undefined);
1960
2056
  }
1961
2057
  catch {
1962
2058
  // swallow; next retry will try again
@@ -1972,6 +2068,107 @@ export class ConvaiClient extends EventEmitter {
1972
2068
  this.emit("error", err);
1973
2069
  }, ConvaiClient.CLIENT_READY_TIMEOUT_MS);
1974
2070
  }
2071
+ /**
2072
+ * Send a toggle on the active transport. On LiveKit it waits, latest value
2073
+ * only, until this room's bot can receive it (see `_toggleGate`); the bot
2074
+ * joins after the client and LiveKit drops data published before that.
2075
+ */
2076
+ _sendToggle(type, data) {
2077
+ const hold = this._activeTransport === "livekit"
2078
+ ? // Also while the room is not connected (an attempt in flight).
2079
+ !this._canDeliverToggles() || !this.isTransportReady()
2080
+ : // WebSocket: held during the attempt, sent once its session connects.
2081
+ this._activeTransport === "websocket" && !this.isTransportReady();
2082
+ if (hold) {
2083
+ this._pendingUntilBotReady.set(type, data); // last call wins
2084
+ return;
2085
+ }
2086
+ if (!this.isTransportReady())
2087
+ return;
2088
+ // This value supersedes a held one of the same type.
2089
+ this._pendingUntilBotReady.delete(type);
2090
+ this._flushHeldToggles();
2091
+ this.publishMessage(type, data);
2092
+ }
2093
+ /**
2094
+ * Whether a toggle published now reaches a bot that consumes it. Roster
2095
+ * rooms: the routed member must be running in this attempt's room (its
2096
+ * bot-ready, or pipeline output from it), re-evaluated on every route or
2097
+ * status change, so a member that fails or a route to one that is not ready
2098
+ * holds toggles again. Elsewhere: this room's gate.
2099
+ */
2100
+ _canDeliverToggles() {
2101
+ const recipient = this._toggleRecipient();
2102
+ if (recipient === undefined)
2103
+ return this._toggleGate === "open";
2104
+ return recipient !== null && this._membersSeenRunning.has(recipient.membershipId);
2105
+ }
2106
+ /** Send the held toggles, once, if they can be delivered now. */
2107
+ _flushHeldToggles() {
2108
+ if (this._pendingUntilBotReady.size === 0 || !this._canDeliverToggles())
2109
+ return;
2110
+ const pending = [...this._pendingUntilBotReady];
2111
+ this._pendingUntilBotReady.clear();
2112
+ for (const [type, data] of pending)
2113
+ this.publishMessage(type, data);
2114
+ }
2115
+ /** Single-character room or WebSocket: the bot can receive toggles now. */
2116
+ _openToggleGate() {
2117
+ this._toggleGate = "open";
2118
+ this._flushHeldToggles();
2119
+ }
2120
+ /** Bot pipeline output: the sender is running (backends without bot-ready). */
2121
+ _onBotPipelineFrame(participant) {
2122
+ if (!this._roster.isMultiCharacter) {
2123
+ this._openToggleGate();
2124
+ return;
2125
+ }
2126
+ const identity = participant?.identity;
2127
+ const sender = this._roster.characters.find((c) => c.participantIdentity === identity);
2128
+ if (!sender)
2129
+ return;
2130
+ this._membersSeenRunning.add(sender.membershipId);
2131
+ this._flushHeldToggles();
2132
+ }
2133
+ /**
2134
+ * The member that consumes toggles. In a multi-character room
2135
+ * core-service delivers tts-toggle and stt-toggle only to the routed
2136
+ * (active) member and the others drop them, so another member's readiness
2137
+ * must not open the gate. `undefined`: not a roster room, any bot counts.
2138
+ * `null`: a roster room with no target (an acknowledged
2139
+ * setInteractionTarget(null)), where no member consumes them.
2140
+ */
2141
+ _toggleRecipient() {
2142
+ if (!this._roster.isMultiCharacter)
2143
+ return undefined;
2144
+ const active = this._roster.activeMembershipId;
2145
+ return active ? (this._roster.find(active) ?? null) : null;
2146
+ }
2147
+ _resetToggleGate() {
2148
+ this._toggleGate = "hold";
2149
+ this._pendingUntilBotReady.clear();
2150
+ this._membersSeenRunning.clear();
2151
+ }
2152
+ /**
2153
+ * Start a connection attempt: drop anything held for an earlier room and
2154
+ * name the transport this attempt uses. Every entry point calls it after
2155
+ * its synchronous validation and before its first stateChange or await, so
2156
+ * a toggle made at any point of the attempt is held for this attempt's room
2157
+ * (or, on SSE, applied to the session it creates).
2158
+ */
2159
+ _beginAttempt(transport) {
2160
+ this._resetToggleGate();
2161
+ this._activeTransport = transport;
2162
+ }
2163
+ /**
2164
+ * ttsEnabled for a boot built now: toggleTts() may have run since the
2165
+ * attempt captured its config (a stateChange listener, for example).
2166
+ */
2167
+ _latestTtsEnabled(configWithDefaults) {
2168
+ return this._storedConfig
2169
+ ? this._storedConfig.ttsEnabled
2170
+ : configWithDefaults.ttsEnabled;
2171
+ }
1975
2172
  _stopClientReadyHandshake() {
1976
2173
  if (this._clientReadyRetryTimer) {
1977
2174
  clearTimeout(this._clientReadyRetryTimer);
@@ -1987,6 +2184,7 @@ export class ConvaiClient extends EventEmitter {
1987
2184
  */
1988
2185
  async disconnect() {
1989
2186
  this._stopClientReadyHandshake();
2187
+ this._resetToggleGate();
1990
2188
  // Unconditional: the branches below each depend on a transport being
1991
2189
  // matched, and none of them runs when there is nothing to tear down. A
1992
2190
  // command in flight must still be settled either way.
@@ -2434,12 +2632,15 @@ export class ConvaiClient extends EventEmitter {
2434
2632
  * Update dynamic information about the current context
2435
2633
  */
2436
2634
  updateDynamicInfo(dynamicInfo) {
2437
- if (!this.isTransportReady() || !dynamicInfo?.trim())
2635
+ if (!dynamicInfo?.trim())
2438
2636
  return;
2439
2637
  const nextDynamicInfo = dynamicInfo.trim();
2638
+ // Kept while disconnected too: reconnect() replays _storedConfig.
2440
2639
  if (this._storedConfig) {
2441
2640
  this._storedConfig = { ...this._storedConfig, dynamicInfo: nextDynamicInfo };
2442
2641
  }
2642
+ if (!this.isTransportReady())
2643
+ return;
2443
2644
  if (this._activeTransport === "sse" && this._sseSession) {
2444
2645
  this._sseSession.updateDynamicInfo(nextDynamicInfo);
2445
2646
  return;
@@ -2547,9 +2748,10 @@ export class ConvaiClient extends EventEmitter {
2547
2748
  return updateId;
2548
2749
  }
2549
2750
  respondModeUpdate(options) {
2751
+ // Kept while disconnected too: reconnect() replays _storedConfig.
2752
+ this.rememberRespondMode(options.modality, options.mode);
2550
2753
  if (!this.isTransportReady())
2551
2754
  return null;
2552
- this.rememberRespondMode(options.modality, options.mode);
2553
2755
  const updateId = options.updateId ?? this.createUpdateId("respond-mode");
2554
2756
  this.publishMessage("respond-mode-update", {
2555
2757
  update_id: updateId,
@@ -2658,28 +2860,48 @@ export class ConvaiClient extends EventEmitter {
2658
2860
  });
2659
2861
  }
2660
2862
  /**
2661
- * Toggle text-to-speech on or off
2863
+ * Toggle text-to-speech on or off.
2864
+ *
2865
+ * The value is recorded in every connection state, and `reconnect()` and
2866
+ * `connect()` without a config start the next session with it.
2867
+ * `connect(config)` replaces the stored config, so pass `ttsEnabled` there.
2868
+ *
2869
+ * On LiveKit it is sent once this room's character can receive it: at
2870
+ * `botReady`, or at the character's first speech or transcription event on
2871
+ * a backend that sends no `botReady`. Until then only the latest value is
2872
+ * held; a disconnect drops it, and the next session starts from the
2873
+ * recorded value instead. In a multi-character room it goes to the routed
2874
+ * character: held while it is not ready (including after it fails or a
2875
+ * route moves to one that is not ready yet) and while no character is
2876
+ * routed (`setInteractionTarget(null)`); switching between ready routed
2877
+ * characters re-sends nothing. A failed LiveKit publish is logged,
2878
+ * not thrown or left as an unhandled rejection. SSE applies it to
2879
+ * subsequent requests; WebSocket holds it during a connection attempt and
2880
+ * sends it once the session connects.
2662
2881
  */
2663
2882
  toggleTts(enabled) {
2664
- if (!this.isTransportReady())
2665
- return;
2666
- // Every transport, not only SSE: reconnect() replays _storedConfig.
2883
+ // Recorded in every connection state, before anything else:
2884
+ // reconnect() and connect() without a config boot from _storedConfig.
2667
2885
  if (this._storedConfig) {
2668
2886
  this._storedConfig = { ...this._storedConfig, ttsEnabled: enabled };
2669
2887
  }
2670
- if (this._activeTransport === "sse" && this._sseSession) {
2671
- this._sseSession.setTtsEnabled(enabled);
2888
+ if (this._activeTransport === "sse") {
2889
+ if (this.isTransportReady())
2890
+ this._sseSession?.setTtsEnabled(enabled);
2672
2891
  return;
2673
2892
  }
2674
- this.publishMessage("tts-toggle", { enabled });
2893
+ this._sendToggle("tts-toggle", { enabled });
2675
2894
  }
2676
2895
  /**
2677
- * Toggle speech-to-text on or off
2896
+ * Toggle speech-to-text on or off.
2897
+ *
2898
+ * On LiveKit and WebSocket it is held and sent like `toggleTts()`, latest
2899
+ * value only. Unlike `toggleTts()` it is not recorded for the next session:
2900
+ * every session starts with speech-to-text on. SSE sends it while
2901
+ * connected.
2678
2902
  */
2679
2903
  toggleStt(enabled) {
2680
- if (!this.isTransportReady())
2681
- return;
2682
- this.publishMessage("stt-toggle", { muted: !enabled });
2904
+ this._sendToggle("stt-toggle", { muted: !enabled });
2683
2905
  }
2684
2906
  /**
2685
2907
  * Reset the server-side idle timer.
@@ -15,6 +15,8 @@ export interface SSESessionOptions {
15
15
  onCharacterSessionId: (characterSessionId: string) => void;
16
16
  endUserId?: string;
17
17
  endUserMetadata?: Record<string, unknown>;
18
+ /** Read before every request, so each message carries a current token. */
19
+ getEndUserToken?: () => Promise<string | undefined>;
18
20
  takeStateOfMind: () => string | null;
19
21
  enableEmotion?: ConvaiConfig["enableEmotion"];
20
22
  emotionConfig?: ConvaiConfig["emotionConfig"];
@@ -118,6 +118,13 @@ export class SSESession {
118
118
  credentialHeaders = { "API-AUTH-TOKEN": issued.authToken };
119
119
  connectAttemptId = createWorkspaceConnectAttemptId();
120
120
  }
121
+ let endUserToken;
122
+ if (this.options.getEndUserToken) {
123
+ const getEndUserToken = this.options.getEndUserToken;
124
+ endUserToken = await abortableOperation(() => getEndUserToken(), controller.signal);
125
+ if (controller.signal.aborted || !this.connected)
126
+ return;
127
+ }
121
128
  const characterSessionId = this.options.getCharacterSessionId();
122
129
  const response = await abortableOperation(() => fetch(this.options.interactionApiUrl, {
123
130
  method: "POST",
@@ -140,6 +147,7 @@ export class SSESession {
140
147
  ...(this.options.endUserMetadata
141
148
  ? { end_user_metadata: this.options.endUserMetadata }
142
149
  : {}),
150
+ ...(endUserToken ? { end_user_token: endUserToken } : {}),
143
151
  ...(buildEmotionConnectConfig(this.options) && {
144
152
  emotion_config: buildEmotionConnectConfig(this.options),
145
153
  }),
@@ -0,0 +1,7 @@
1
+ import type { EndUserTokenSource } from "./types.js";
2
+ /**
3
+ * Read the end user's token from its source. A function source is called
4
+ * every time, so the caller always gets what the page considers current.
5
+ * Anything that is not a non-empty string means "no token".
6
+ */
7
+ export declare function resolveEndUserToken(source: EndUserTokenSource | null | undefined): Promise<string | undefined>;
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Read the end user's token from its source. A function source is called
3
+ * every time, so the caller always gets what the page considers current.
4
+ * Anything that is not a non-empty string means "no token".
5
+ */
6
+ export async function resolveEndUserToken(source) {
7
+ if (source === undefined || source === null)
8
+ return undefined;
9
+ const value = typeof source === "function" ? await source() : source;
10
+ return typeof value === "string" && value !== "" ? value : undefined;
11
+ }
@@ -530,6 +530,11 @@ export interface AudioSettings {
530
530
  /** Number of audio channels, 1 for mono, 2 for stereo (default: 1) */
531
531
  channelCount?: number;
532
532
  }
533
+ /**
534
+ * The signed-in end user's bearer token, or a function that returns a current
535
+ * one. See {@link ConvaiConfig.endUserToken}.
536
+ */
537
+ export type EndUserTokenSource = string | (() => string | null | undefined | Promise<string | null | undefined>);
533
538
  /**
534
539
  * Configuration object for connecting to a Convai character.
535
540
  *
@@ -695,6 +700,39 @@ export interface ConvaiConfig {
695
700
  endUserId?: string;
696
701
  /** Optional metadata object for the end user (sent as end_user_metadata to the API) */
697
702
  endUserMetadata?: Record<string, unknown>;
703
+ /**
704
+ * Bearer token that belongs to the signed-in end user (optional), for example
705
+ * the JWT your site already holds for that person. Sent as `end_user_token`.
706
+ *
707
+ * For MCP servers the Convai deployment has opted in, the character's tools
708
+ * call the server with this token instead of the server's stored credential,
709
+ * so the server applies that person's access. Deployments that have not
710
+ * opted in ignore it.
711
+ *
712
+ * Pass a string, or a function that returns a current token. Prefer the
713
+ * function when the token expires: the SDK calls it each time it needs the
714
+ * token, so the page never hands over a stale one.
715
+ *
716
+ * ```ts
717
+ * endUserToken: () => auth.getAccessToken({ audience: 'enterprise-search' })
718
+ * ```
719
+ *
720
+ * - Your page obtains the token; the SDK only forwards it.
721
+ * - `livekit` transport: sent once on `/connect` and used for that session.
722
+ * Once the token expires the MCP server rejects those tool calls for the
723
+ * rest of the session. `reconnect()` sends a current token, except when
724
+ * the reconnect reattaches to the session that is still running (sessions
725
+ * with client tools), which keeps the token it started with.
726
+ * - `sse` transport: sent with every message, so a function source keeps a
727
+ * long conversation on a current token.
728
+ * - `websocket` transport: not supported yet. The session does not use the
729
+ * token and keeps the server's stored credential.
730
+ * - Not sent for roster rooms.
731
+ * - Never written to client state, events or storage.
732
+ * - If the function throws, the connect (or that SSE message) fails with its
733
+ * error. Return `undefined` to continue without a token.
734
+ */
735
+ endUserToken?: EndUserTokenSource;
698
736
  /** Custom Convai API URL (optional, defaults to production endpoint) */
699
737
  url?: string;
700
738
  /** Transport layer to use. Default: "livekit". */
@@ -2282,6 +2320,7 @@ export interface IConvaiClient {
2282
2320
  * Update dynamic information about the current context.
2283
2321
  * This helps the character understand the current situation.
2284
2322
  * Pass any key-value pairs you want, but "text" field is required.
2323
+ * Recorded for `reconnect()` even when not connected.
2285
2324
  */
2286
2325
  updateDynamicInfo: (dynamicInfo: DynamicInfo) => void;
2287
2326
  /**
@@ -2315,7 +2354,13 @@ export interface IConvaiClient {
2315
2354
  visionStatus: (options?: VisionStatusOptions) => string | null;
2316
2355
  /** Attach buffered frames and optionally trigger a response. */
2317
2356
  visionTrigger: (options?: VisionTriggerOptions) => string | null;
2318
- /** Update a session respond-mode default. */
2357
+ /**
2358
+ * Update a session respond-mode default. Returns the update id, or `null`
2359
+ * when not connected. A mode the connect request accepts is recorded for
2360
+ * `reconnect()` either way; `"auto"` and `"silent"` for `text` and `audio`
2361
+ * are runtime-only (the connect request rejects lowering user input below
2362
+ * `"must_respond"`), so they are not replayed.
2363
+ */
2319
2364
  respondModeUpdate: (options: RespondModeUpdateOptions) => string | null;
2320
2365
  /**
2321
2366
  * Set or clear the character's temporary state of mind without triggering a response.
@@ -2337,12 +2382,33 @@ export interface IConvaiClient {
2337
2382
  /**
2338
2383
  * Toggle text-to-speech on or off.
2339
2384
  * SSE applies the setting to subsequent interaction requests.
2385
+ *
2386
+ * The value is recorded in every connection state (disconnected,
2387
+ * connecting, connected), and `reconnect()` and `connect()` without a
2388
+ * config start the next session with it. `connect(config)` replaces the
2389
+ * stored config, so its `ttsEnabled` wins. A client constructed without a
2390
+ * config has nothing to record into until it connects.
2391
+ *
2392
+ * On LiveKit it is sent once this room's character can receive it: at
2393
+ * `botReady`, or at the character's first speech or transcription event on
2394
+ * a backend that sends no `botReady`. Until then only the latest value is
2395
+ * held, and a disconnect drops it. In a multi-character room it goes to
2396
+ * the routed character: held while it is not ready (including after it
2397
+ * fails or a route moves to one that is not ready yet) and while no
2398
+ * character is routed (`setInteractionTarget(null)`); switching between
2399
+ * ready routed characters re-sends nothing. On WebSocket it is
2400
+ * held during a connection attempt and sent once the session connects.
2401
+ * Neither a missing transport nor a failed LiveKit publish throws.
2340
2402
  */
2341
2403
  toggleTts: (enabled: boolean) => void;
2342
2404
  /**
2343
2405
  * Toggle speech-to-text on or off.
2344
2406
  * When enabled, user speech is transcribed to text (e.g. for dictation).
2345
2407
  * When disabled, STT is off.
2408
+ *
2409
+ * On LiveKit and WebSocket it is held and sent like `toggleTts()`, latest
2410
+ * value only. It is not recorded for the next session: every session
2411
+ * starts with speech-to-text on.
2346
2412
  */
2347
2413
  toggleStt: (enabled: boolean) => void;
2348
2414
  /**
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const SDK_VERSION = "2.0.2-beta.0";
1
+ export declare const SDK_VERSION = "2.1.0-beta.0";
package/dist/version.js CHANGED
@@ -1,3 +1,3 @@
1
1
  // GENERATED by scripts/sync-version.mjs — do not edit by hand.
2
2
  // Regenerated from package.json on every build.
3
- export const SDK_VERSION = "2.0.2-beta.0";
3
+ export const SDK_VERSION = "2.1.0-beta.0";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@convai/web-sdk",
3
- "version": "2.0.2-beta.0",
3
+ "version": "2.1.0-beta.0",
4
4
  "description": "Build web apps with lifelike AI characters. The Convai Web SDK gives you real-time voice, lipsync, emotions, and dynamic context — with first-class support for React and vanilla TypeScript.",
5
5
  "private": false,
6
6
  "type": "module",