@convai/web-sdk 1.8.0 → 1.9.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.
- package/README.md +213 -45
- package/dist/core/CharacterRoster.d.ts +84 -0
- package/dist/core/CharacterRoster.d.ts.map +1 -0
- package/dist/core/CharacterRoster.js +348 -0
- package/dist/core/CharacterRoster.js.map +1 -0
- package/dist/core/CharacterVersionManager.d.ts +100 -0
- package/dist/core/CharacterVersionManager.d.ts.map +1 -0
- package/dist/core/CharacterVersionManager.js +227 -0
- package/dist/core/CharacterVersionManager.js.map +1 -0
- package/dist/core/ConvaiClient.d.ts +190 -1
- package/dist/core/ConvaiClient.d.ts.map +1 -1
- package/dist/core/ConvaiClient.js +1328 -289
- package/dist/core/ConvaiClient.js.map +1 -1
- package/dist/core/ConvaiRoomError.d.ts +48 -0
- package/dist/core/ConvaiRoomError.d.ts.map +1 -0
- package/dist/core/ConvaiRoomError.js +111 -0
- package/dist/core/ConvaiRoomError.js.map +1 -0
- package/dist/core/MessageHandler.d.ts +26 -2
- package/dist/core/MessageHandler.d.ts.map +1 -1
- package/dist/core/MessageHandler.js +397 -32
- package/dist/core/MessageHandler.js.map +1 -1
- package/dist/core/SSESession.d.ts +74 -0
- package/dist/core/SSESession.d.ts.map +1 -0
- package/dist/core/SSESession.js +499 -0
- package/dist/core/SSESession.js.map +1 -0
- package/dist/core/characterReference.d.ts +40 -0
- package/dist/core/characterReference.d.ts.map +1 -0
- package/dist/core/characterReference.js +72 -0
- package/dist/core/characterReference.js.map +1 -0
- package/dist/core/connectRequest.d.ts +17 -4
- package/dist/core/connectRequest.d.ts.map +1 -1
- package/dist/core/connectRequest.js +28 -17
- package/dist/core/connectRequest.js.map +1 -1
- package/dist/core/index.d.ts +8 -1
- package/dist/core/index.d.ts.map +1 -1
- package/dist/core/index.js +13 -1
- package/dist/core/index.js.map +1 -1
- package/dist/core/logicalTurn.d.ts +4 -6
- package/dist/core/logicalTurn.d.ts.map +1 -1
- package/dist/core/logicalTurn.js +29 -4
- package/dist/core/logicalTurn.js.map +1 -1
- package/dist/core/modelOutput.d.ts.map +1 -1
- package/dist/core/modelOutput.js +2 -2
- package/dist/core/modelOutput.js.map +1 -1
- package/dist/core/rosterRequest.d.ts +57 -0
- package/dist/core/rosterRequest.d.ts.map +1 -0
- package/dist/core/rosterRequest.js +210 -0
- package/dist/core/rosterRequest.js.map +1 -0
- package/dist/core/types.d.ts +869 -22
- package/dist/core/types.d.ts.map +1 -1
- package/dist/core/types.js.map +1 -1
- package/dist/embed/ConvaiChatElement.d.ts +77 -1
- package/dist/embed/ConvaiChatElement.d.ts.map +1 -1
- package/dist/embed/ConvaiChatElement.js +433 -54
- package/dist/embed/ConvaiChatElement.js.map +1 -1
- package/dist/embed/chat-embed-v1.js +136 -35
- package/dist/embed/chat-embed-v1.js.map +4 -4
- package/dist/react/components/ConvaiWidget.d.ts.map +1 -1
- package/dist/react/components/ConvaiWidget.js +6 -1
- package/dist/react/components/ConvaiWidget.js.map +1 -1
- package/dist/react/components/rtc-widget/components/AudioVisualizer.d.ts.map +1 -1
- package/dist/react/components/rtc-widget/components/AudioVisualizer.js +28 -1
- package/dist/react/components/rtc-widget/components/AudioVisualizer.js.map +1 -1
- package/dist/react/components/rtc-widget/components/MarkdownRenderer.d.ts +7 -0
- package/dist/react/components/rtc-widget/components/MarkdownRenderer.d.ts.map +1 -1
- package/dist/react/components/rtc-widget/components/MarkdownRenderer.js +135 -46
- package/dist/react/components/rtc-widget/components/MarkdownRenderer.js.map +1 -1
- package/dist/react/components/rtc-widget/components/UserMessage.js +1 -1
- package/dist/react/components/rtc-widget/components/UserMessage.js.map +1 -1
- package/dist/react/components/rtc-widget/components/conviComponents/VoiceModeOverlay.d.ts.map +1 -1
- package/dist/react/components/rtc-widget/components/conviComponents/VoiceModeOverlay.js +93 -49
- package/dist/react/components/rtc-widget/components/conviComponents/VoiceModeOverlay.js.map +1 -1
- package/dist/react/hooks/useConvaiClient.d.ts.map +1 -1
- package/dist/react/hooks/useConvaiClient.js +17 -2
- package/dist/react/hooks/useConvaiClient.js.map +1 -1
- package/dist/react/index.d.ts +4 -1
- package/dist/react/index.d.ts.map +1 -1
- package/dist/react/index.js +8 -1
- package/dist/react/index.js.map +1 -1
- package/dist/utils/inlineMarkdown.d.ts +60 -0
- package/dist/utils/inlineMarkdown.d.ts.map +1 -0
- package/dist/utils/inlineMarkdown.js +183 -0
- package/dist/utils/inlineMarkdown.js.map +1 -0
- package/dist/vanilla/AudioRenderer.d.ts +3 -1
- package/dist/vanilla/AudioRenderer.d.ts.map +1 -1
- package/dist/vanilla/AudioRenderer.js +8 -2
- package/dist/vanilla/AudioRenderer.js.map +1 -1
- package/dist/vanilla/ConvaiWidget.d.ts.map +1 -1
- package/dist/vanilla/ConvaiWidget.js +1122 -302
- package/dist/vanilla/ConvaiWidget.js.map +1 -1
- package/dist/vanilla/WidgetEventSubscriptions.d.ts +1 -1
- package/dist/vanilla/WidgetEventSubscriptions.d.ts.map +1 -1
- package/dist/vanilla/WidgetEventSubscriptions.js +5 -0
- package/dist/vanilla/WidgetEventSubscriptions.js.map +1 -1
- package/dist/vanilla/icons.d.ts.map +1 -1
- package/dist/vanilla/icons.js +62 -15
- package/dist/vanilla/icons.js.map +1 -1
- package/dist/vanilla/index.d.ts +6 -2
- package/dist/vanilla/index.d.ts.map +1 -1
- package/dist/vanilla/index.js +5 -1
- package/dist/vanilla/index.js.map +1 -1
- package/dist/vanilla/styles.d.ts +18 -1
- package/dist/vanilla/styles.d.ts.map +1 -1
- package/dist/vanilla/styles.js +141 -29
- package/dist/vanilla/styles.js.map +1 -1
- package/dist/vanilla/types.d.ts +74 -0
- package/dist/vanilla/types.d.ts.map +1 -1
- package/dist/vanilla/types.js.map +1 -1
- package/dist/version.d.ts +1 -1
- package/dist/version.d.ts.map +1 -1
- package/dist/version.js +1 -1
- package/dist/version.js.map +1 -1
- package/package.json +45 -18
|
@@ -5,13 +5,19 @@ import { AudioManager } from "./AudioManager.js";
|
|
|
5
5
|
import { VideoManager } from "./VideoManager.js";
|
|
6
6
|
import { ScreenShareManager } from "./ScreenShareManager.js";
|
|
7
7
|
import { MessageHandler } from "./MessageHandler.js";
|
|
8
|
+
import { CharacterRoster } from "./CharacterRoster.js";
|
|
9
|
+
import { buildJoinRequestBody, buildRosterConnectFields, isRosterConfig, validateJoinOptions, validateProtocolTopology, validateRosterConfig, } from "./rosterRequest.js";
|
|
10
|
+
import { ConvaiRoomError, roomErrorFromResponse } from "./ConvaiRoomError.js";
|
|
8
11
|
import { SDK_VERSION } from "../version.js";
|
|
9
12
|
import { EventEmitter } from "./EventEmitter.js";
|
|
10
13
|
import { MemoryManager } from "./MemoryManager.js";
|
|
14
|
+
import { CharacterVersionManager } from "./CharacterVersionManager.js";
|
|
15
|
+
import { resolveCharacterReference, } from "./characterReference.js";
|
|
11
16
|
import { ConnectionStateHandler } from "./ConnectionStateHandler.js";
|
|
12
|
-
import { buildBlendshapeConnectConfig,
|
|
17
|
+
import { buildActionConnectConfig, buildBlendshapeConnectConfig, buildEmotionConnectConfig, serializeProtocolCapabilities, validateActionProtocolSelection, validateModelOutputVersionSelection, } from "./connectRequest.js";
|
|
13
18
|
import { shouldPreemptForContextUpdateResponse, shouldPreemptForExplicitRespondMode, } from "./contextUpdateRequest.js";
|
|
14
19
|
import { resolveVisionInputConfig, serializeVisionInputConfig, } from "./visionRequest.js";
|
|
20
|
+
import { SSESession } from "./SSESession.js";
|
|
15
21
|
import { isJsonValue } from "./modelOutput.js";
|
|
16
22
|
import { isValidLogicalTurnId } from "./logicalTurn.js";
|
|
17
23
|
// Module-level registry — populated by importing @convai/web-sdk/vanilla/websocket
|
|
@@ -22,6 +28,33 @@ function normalizeStateOfMind(value) {
|
|
|
22
28
|
const normalized = value.trim().toLowerCase();
|
|
23
29
|
return normalized === "neutral" || normalized === "" ? null : normalized;
|
|
24
30
|
}
|
|
31
|
+
/**
|
|
32
|
+
* Rejection from {@link ConvaiClient.sendActionResultAndWait} after local
|
|
33
|
+
* validation succeeds. Inspect `reason` rather than parsing the message.
|
|
34
|
+
*/
|
|
35
|
+
export class ActionResultAckError extends Error {
|
|
36
|
+
constructor(message, options) {
|
|
37
|
+
super(message);
|
|
38
|
+
this.name =
|
|
39
|
+
options.reason === "aborted"
|
|
40
|
+
? "AbortError"
|
|
41
|
+
: options.reason === "timeout"
|
|
42
|
+
? "TimeoutError"
|
|
43
|
+
: "ActionResultAckError";
|
|
44
|
+
this.reason = options.reason;
|
|
45
|
+
this.toolCallId = options.toolCallId;
|
|
46
|
+
this.errorCode = options.errorCode;
|
|
47
|
+
this.response = options.response;
|
|
48
|
+
this.cause = options.cause;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Marks a publication exchange failure that is safe to retry with the same
|
|
53
|
+
* logical connect attempt. The launch grant itself is single-use, so callers
|
|
54
|
+
* must never mint or submit a second grant for this recovery path.
|
|
55
|
+
*/
|
|
56
|
+
class RetryablePublishedChatExchangeError extends Error {
|
|
57
|
+
}
|
|
25
58
|
/**
|
|
26
59
|
* Custom reconnect policy that disables automatic reconnection
|
|
27
60
|
*/
|
|
@@ -81,7 +114,16 @@ export class ConvaiClient extends EventEmitter {
|
|
|
81
114
|
this._apiKey = null;
|
|
82
115
|
this._authToken = null;
|
|
83
116
|
this._characterId = null;
|
|
117
|
+
this._characterVersion = null;
|
|
118
|
+
this._characterReference = null;
|
|
119
|
+
this._characterVersionManager = null;
|
|
120
|
+
this._characterVersionManagerKey = null;
|
|
84
121
|
this._characterSessionId = "-1";
|
|
122
|
+
/** Roster state for multi-character rooms. Empty for single-character sessions. */
|
|
123
|
+
this._roster = new CharacterRoster();
|
|
124
|
+
/** Roster commands awaiting their ack, keyed by command id. */
|
|
125
|
+
this._pendingRosterCommands = new Map();
|
|
126
|
+
this._rosterCommandSeq = 0;
|
|
85
127
|
this._requestTraceId = null;
|
|
86
128
|
this._isBotReady = false;
|
|
87
129
|
this._participantSid = "";
|
|
@@ -95,6 +137,7 @@ export class ConvaiClient extends EventEmitter {
|
|
|
95
137
|
this._endUserMetadata = null;
|
|
96
138
|
this._wsSession = null;
|
|
97
139
|
this._activeTransport = null;
|
|
140
|
+
this._sseSession = null;
|
|
98
141
|
this._logRtviMessages = true;
|
|
99
142
|
this._isDisconnecting = false;
|
|
100
143
|
this._isPublishedChatSession = false;
|
|
@@ -102,6 +145,7 @@ export class ConvaiClient extends EventEmitter {
|
|
|
102
145
|
this._clientReadyRetryTimer = null;
|
|
103
146
|
this._clientReadyTimeoutTimer = null;
|
|
104
147
|
this._clientReadyMsgId = null;
|
|
148
|
+
this._pendingActionResultAcks = new Map();
|
|
105
149
|
// Conversation session tracking
|
|
106
150
|
this._conversationSessionId = 0;
|
|
107
151
|
this._conversationStartTime = 0;
|
|
@@ -111,6 +155,23 @@ export class ConvaiClient extends EventEmitter {
|
|
|
111
155
|
if (config) {
|
|
112
156
|
this._storedConfig = config;
|
|
113
157
|
this._logRtviMessages = config.logRtviMessages !== false;
|
|
158
|
+
// Derive the version readouts from the config eagerly, as
|
|
159
|
+
// characterVersions already is, so a React consumer destructuring
|
|
160
|
+
// characterReference off the hook sees the selector on first render
|
|
161
|
+
// rather than null until connect(). A malformed selector is left for
|
|
162
|
+
// connect() to reject -- the constructor has never thrown on config and
|
|
163
|
+
// starting to would be a behaviour change.
|
|
164
|
+
if (config.characterId && !isRosterConfig(config)) {
|
|
165
|
+
try {
|
|
166
|
+
const ref = resolveCharacterReference(config.characterId, config.characterVersion);
|
|
167
|
+
this._characterId = ref.characterId;
|
|
168
|
+
this._characterVersion = ref.version;
|
|
169
|
+
this._characterReference = ref.reference;
|
|
170
|
+
}
|
|
171
|
+
catch {
|
|
172
|
+
/* reported by connect() */
|
|
173
|
+
}
|
|
174
|
+
}
|
|
114
175
|
}
|
|
115
176
|
// Initialize room with no reconnect policy
|
|
116
177
|
this._room = new Room({
|
|
@@ -128,6 +189,8 @@ export class ConvaiClient extends EventEmitter {
|
|
|
128
189
|
endUserId: null,
|
|
129
190
|
endUserMetadata: null,
|
|
130
191
|
metrics: [],
|
|
192
|
+
characters: [],
|
|
193
|
+
activeMembershipId: null,
|
|
131
194
|
disconnectReason: null,
|
|
132
195
|
};
|
|
133
196
|
// Default audio settings for optimal interruption handling
|
|
@@ -173,6 +236,42 @@ export class ConvaiClient extends EventEmitter {
|
|
|
173
236
|
get characterId() {
|
|
174
237
|
return this._characterId;
|
|
175
238
|
}
|
|
239
|
+
get characterVersion() {
|
|
240
|
+
return this._characterVersion;
|
|
241
|
+
}
|
|
242
|
+
get characterReference() {
|
|
243
|
+
return this._characterReference;
|
|
244
|
+
}
|
|
245
|
+
/**
|
|
246
|
+
* Character version manager for the configured character. Built from the
|
|
247
|
+
* live connection when there is one, otherwise from the stored config, so
|
|
248
|
+
* versions can be listed and released before connecting. Null without an
|
|
249
|
+
* API key (the Character REST platform does not accept realtime auth tokens).
|
|
250
|
+
*/
|
|
251
|
+
get characterVersions() {
|
|
252
|
+
const apiKey = this._apiKey ?? this._storedConfig?.apiKey ?? null;
|
|
253
|
+
const rawCharacterId = this._characterId ?? this._storedConfig?.characterId ?? null;
|
|
254
|
+
if (!apiKey || !rawCharacterId)
|
|
255
|
+
return null;
|
|
256
|
+
let characterId = rawCharacterId;
|
|
257
|
+
try {
|
|
258
|
+
characterId = resolveCharacterReference(rawCharacterId).characterId;
|
|
259
|
+
}
|
|
260
|
+
catch {
|
|
261
|
+
// A malformed id is reported by connect(); use it verbatim here.
|
|
262
|
+
}
|
|
263
|
+
const baseUrl = this._storedConfig?.characterApiUrl ?? undefined;
|
|
264
|
+
const key = `${apiKey}\u0000${characterId}\u0000${baseUrl ?? ""}`;
|
|
265
|
+
if (this._characterVersionManagerKey !== key) {
|
|
266
|
+
this._characterVersionManager = new CharacterVersionManager({
|
|
267
|
+
apiKey,
|
|
268
|
+
characterId,
|
|
269
|
+
baseUrl,
|
|
270
|
+
});
|
|
271
|
+
this._characterVersionManagerKey = key;
|
|
272
|
+
}
|
|
273
|
+
return this._characterVersionManager;
|
|
274
|
+
}
|
|
176
275
|
get room() {
|
|
177
276
|
return this._room;
|
|
178
277
|
}
|
|
@@ -185,6 +284,45 @@ export class ConvaiClient extends EventEmitter {
|
|
|
185
284
|
get characterSessionId() {
|
|
186
285
|
return this._characterSessionId;
|
|
187
286
|
}
|
|
287
|
+
on(event, callback) {
|
|
288
|
+
return super.on(event, callback);
|
|
289
|
+
}
|
|
290
|
+
/**
|
|
291
|
+
* Server-owned snapshot of a multi-character room, or null for a
|
|
292
|
+
* single-character session. Carries the room id, epochs and roster.
|
|
293
|
+
*/
|
|
294
|
+
get roomSession() {
|
|
295
|
+
return this._roster.roomSession;
|
|
296
|
+
}
|
|
297
|
+
/**
|
|
298
|
+
* Character instances in a multi-character room, in roster order. Empty for a
|
|
299
|
+
* single-character session, so `length` distinguishes the two.
|
|
300
|
+
*/
|
|
301
|
+
get characters() {
|
|
302
|
+
return this._roster.characters;
|
|
303
|
+
}
|
|
304
|
+
/** Membership currently receiving user turns, or null. */
|
|
305
|
+
get activeMembershipId() {
|
|
306
|
+
return this._roster.activeMembershipId;
|
|
307
|
+
}
|
|
308
|
+
/**
|
|
309
|
+
* Start or stop the server streaming per-turn usage/cost breakdowns as
|
|
310
|
+
* `usageUpdate` events. Informational only; server-side usage tracking and
|
|
311
|
+
* billing are unaffected either way.
|
|
312
|
+
*/
|
|
313
|
+
toggleUsageUpdates(enabled) {
|
|
314
|
+
if (!this.isTransportReady())
|
|
315
|
+
return;
|
|
316
|
+
this.publishMessage("usage-toggle", { enabled });
|
|
317
|
+
}
|
|
318
|
+
/** Insert a transcript line locally. Nothing is sent; nothing is billed. */
|
|
319
|
+
appendMessage(message) {
|
|
320
|
+
if (!message?.content?.trim()) {
|
|
321
|
+
throw new Error("appendMessage requires non-empty content");
|
|
322
|
+
}
|
|
323
|
+
return this._messageHandler.appendLocalMessage(message);
|
|
324
|
+
}
|
|
325
|
+
/** Trace id of the /connect that produced this session; quote it to backend support. */
|
|
188
326
|
get requestTraceId() {
|
|
189
327
|
return this._requestTraceId;
|
|
190
328
|
}
|
|
@@ -214,12 +352,60 @@ export class ConvaiClient extends EventEmitter {
|
|
|
214
352
|
*/
|
|
215
353
|
setupEventListeners() {
|
|
216
354
|
// Room event listeners
|
|
355
|
+
// Per-membership audio binding. In a roster room every character is its
|
|
356
|
+
// own participant with identity `character:{membership_id}`; the guide's
|
|
357
|
+
// rule is to bind a track to the exact member or drop it, never to fall
|
|
358
|
+
// back to the active character. Single-character rooms keep the legacy
|
|
359
|
+
// behaviour: the track is surfaced with no attribution.
|
|
360
|
+
this._room.on(RoomEvent.TrackSubscribed, (track, _publication, participant) => {
|
|
361
|
+
if (track.kind !== "audio")
|
|
362
|
+
return;
|
|
363
|
+
const identity = participant.identity;
|
|
364
|
+
if (!this._roster.isMultiCharacter) {
|
|
365
|
+
this.emit("characterAudioTrack", {
|
|
366
|
+
membershipId: null,
|
|
367
|
+
characterId: this._characterId,
|
|
368
|
+
participantIdentity: identity,
|
|
369
|
+
track: track.mediaStreamTrack,
|
|
370
|
+
});
|
|
371
|
+
return;
|
|
372
|
+
}
|
|
373
|
+
const membershipId = identity.startsWith("character:")
|
|
374
|
+
? identity.slice("character:".length)
|
|
375
|
+
: null;
|
|
376
|
+
const member = membershipId ? this._roster.find(membershipId) : undefined;
|
|
377
|
+
if (!member) {
|
|
378
|
+
// Unattributable in a roster room: quarantine rather than guess.
|
|
379
|
+
if (this._logRtviMessages) {
|
|
380
|
+
console.warn(`[ConvaiClient] dropped audio track from unattributed participant "${identity}"`);
|
|
381
|
+
}
|
|
382
|
+
return;
|
|
383
|
+
}
|
|
384
|
+
this.emit("characterAudioTrack", {
|
|
385
|
+
membershipId: member.membershipId,
|
|
386
|
+
characterId: member.characterId,
|
|
387
|
+
participantIdentity: identity,
|
|
388
|
+
track: track.mediaStreamTrack,
|
|
389
|
+
});
|
|
390
|
+
});
|
|
217
391
|
this._room.on(RoomEvent.Disconnected, (reason) => {
|
|
218
392
|
this._connectionStateHandler.handleDisconnected(reason);
|
|
219
393
|
});
|
|
220
394
|
this._room.on(RoomEvent.ConnectionStateChanged, this._connectionStateHandler.handleConnectionStateChanged.bind(this._connectionStateHandler));
|
|
221
395
|
// Message handler events
|
|
222
|
-
this._messageHandler.on("botReady", () => {
|
|
396
|
+
this._messageHandler.on("botReady", (about) => {
|
|
397
|
+
// Each roster member sends its own bot-ready. Feed the roster before the
|
|
398
|
+
// de-dupe below, which only guards the single consumer-facing event --
|
|
399
|
+
// otherwise every member after the first would be dropped.
|
|
400
|
+
if (this._roster.applyBotReady(about)) {
|
|
401
|
+
this.updateState({
|
|
402
|
+
characters: this._roster.characters,
|
|
403
|
+
activeMembershipId: this._roster.activeMembershipId,
|
|
404
|
+
});
|
|
405
|
+
const membershipId = about?.membership_id;
|
|
406
|
+
if (membershipId)
|
|
407
|
+
this.emit("characterReady", this._roster.find(membershipId));
|
|
408
|
+
}
|
|
223
409
|
// Server may send multiple bot-ready frames (one per client-ready
|
|
224
410
|
// we retried). Only surface the first to consumers per connect.
|
|
225
411
|
if (this._isBotReady) {
|
|
@@ -230,8 +416,17 @@ export class ConvaiClient extends EventEmitter {
|
|
|
230
416
|
this.updateState({ isConnected: true });
|
|
231
417
|
this.emit("botReady");
|
|
232
418
|
});
|
|
233
|
-
this._messageHandler.on("messagesChange", (messages) => {
|
|
234
|
-
|
|
419
|
+
this._messageHandler.on("messagesChange", (messages, updatedMessage, updatedMessages) => {
|
|
420
|
+
// Most updates target the tail. Correlated v2 chunks can update an
|
|
421
|
+
// earlier streaming row. A v2 stop can finalize several rows at once.
|
|
422
|
+
if (updatedMessages?.length) {
|
|
423
|
+
for (const message of updatedMessages) {
|
|
424
|
+
this.emit("message", message);
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
else {
|
|
428
|
+
this.emit("message", updatedMessage ?? messages[messages.length - 1]);
|
|
429
|
+
}
|
|
235
430
|
this.emit("messagesChange", messages);
|
|
236
431
|
});
|
|
237
432
|
this._messageHandler.on("userTranscriptionChange", (transcription) => {
|
|
@@ -313,6 +508,9 @@ export class ConvaiClient extends EventEmitter {
|
|
|
313
508
|
this._messageHandler.on("llmNoResponse", () => {
|
|
314
509
|
this.emit("llmNoResponse");
|
|
315
510
|
});
|
|
511
|
+
this._messageHandler.on("botTurnCompleted", (data) => {
|
|
512
|
+
this.emit("botTurnCompleted", data);
|
|
513
|
+
});
|
|
316
514
|
// Forward bot-output event (aggregated output with spoken status)
|
|
317
515
|
this._messageHandler.on("botOutput", (data) => {
|
|
318
516
|
this.emit("botOutput", data);
|
|
@@ -338,13 +536,29 @@ export class ConvaiClient extends EventEmitter {
|
|
|
338
536
|
this._messageHandler.on("actionResponse", (data) => {
|
|
339
537
|
this.emit("actionResponse", data);
|
|
340
538
|
});
|
|
539
|
+
this._messageHandler.on("usageUpdate", (data) => {
|
|
540
|
+
this.emit("usageUpdate", data);
|
|
541
|
+
});
|
|
542
|
+
this._messageHandler.on("characterStatus", (status) => {
|
|
543
|
+
if (this._roster.applyCharacterStatus(status)) {
|
|
544
|
+
this.updateState({
|
|
545
|
+
characters: this._roster.characters,
|
|
546
|
+
activeMembershipId: this._roster.activeMembershipId,
|
|
547
|
+
});
|
|
548
|
+
}
|
|
549
|
+
this.emit("characterStatus", status);
|
|
550
|
+
});
|
|
341
551
|
this._messageHandler.on("modelOutput", (data) => {
|
|
342
552
|
this.emit("modelOutput", data);
|
|
343
553
|
});
|
|
554
|
+
this._messageHandler.on("botLlmTextRaw", (data) => {
|
|
555
|
+
this.emit("botLlmTextRaw", data);
|
|
556
|
+
});
|
|
344
557
|
this._messageHandler.on("modelOutputProtocolError", (data) => {
|
|
345
558
|
this.emit("modelOutputProtocolError", data);
|
|
346
559
|
});
|
|
347
560
|
this._messageHandler.on("serverResponse", (response) => {
|
|
561
|
+
this._handleRosterServerResponse(response);
|
|
348
562
|
this.emit("serverResponse", response);
|
|
349
563
|
});
|
|
350
564
|
this._messageHandler.on("interactionCreated", (data) => {
|
|
@@ -395,6 +609,10 @@ export class ConvaiClient extends EventEmitter {
|
|
|
395
609
|
*/
|
|
396
610
|
publishMessage(type, data, id) {
|
|
397
611
|
const message = id === undefined ? { type, data } : { type, id, data };
|
|
612
|
+
if (this._activeTransport === "sse" && this._sseSession?.isConnected) {
|
|
613
|
+
this._sseSession.sendMessage(type, data, id);
|
|
614
|
+
return;
|
|
615
|
+
}
|
|
398
616
|
if (this._activeTransport === "websocket" && this._wsSession?.isConnected) {
|
|
399
617
|
this._wsSession.sendMessage(type, data);
|
|
400
618
|
}
|
|
@@ -404,10 +622,37 @@ export class ConvaiClient extends EventEmitter {
|
|
|
404
622
|
this._room.localParticipant.publishData(encodedData, { reliable: true });
|
|
405
623
|
}
|
|
406
624
|
}
|
|
625
|
+
/**
|
|
626
|
+
* Publish exactly one message while retaining the transport's local completion
|
|
627
|
+
* signal. Server acceptance is still proved separately by `serverResponse`.
|
|
628
|
+
*/
|
|
629
|
+
async publishMessageAndWaitForLocalPublication(type, data, id) {
|
|
630
|
+
const message = id === undefined ? { type, data } : { type, id, data };
|
|
631
|
+
if (this._activeTransport === "websocket") {
|
|
632
|
+
if (!this._wsSession?.isConnected) {
|
|
633
|
+
throw new Error("The action-result WebSocket transport is no longer available");
|
|
634
|
+
}
|
|
635
|
+
this._wsSession.sendMessage(type, data);
|
|
636
|
+
return;
|
|
637
|
+
}
|
|
638
|
+
if (this._activeTransport === "livekit" &&
|
|
639
|
+
this._room?.localParticipant &&
|
|
640
|
+
this._room.state !== "disconnected") {
|
|
641
|
+
const encodedData = new TextEncoder().encode(JSON.stringify(message));
|
|
642
|
+
await this._room.localParticipant.publishData(encodedData, {
|
|
643
|
+
reliable: true,
|
|
644
|
+
});
|
|
645
|
+
return;
|
|
646
|
+
}
|
|
647
|
+
throw new Error("The action-result transport is no longer available");
|
|
648
|
+
}
|
|
407
649
|
/**
|
|
408
650
|
* Returns true when a message can be sent on the active transport.
|
|
409
651
|
*/
|
|
410
652
|
isTransportReady() {
|
|
653
|
+
if (this._activeTransport === "sse") {
|
|
654
|
+
return this._sseSession?.isConnected ?? false;
|
|
655
|
+
}
|
|
411
656
|
if (this._activeTransport === "websocket") {
|
|
412
657
|
return this._wsSession?.isConnected ?? false;
|
|
413
658
|
}
|
|
@@ -430,19 +675,10 @@ export class ConvaiClient extends EventEmitter {
|
|
|
430
675
|
finalConfig.characterSessionId !== "-1") {
|
|
431
676
|
this._characterSessionId = finalConfig.characterSessionId;
|
|
432
677
|
}
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
...finalConfig,
|
|
437
|
-
};
|
|
438
|
-
this._logRtviMessages = configWithDefaults.logRtviMessages !== false;
|
|
439
|
-
this._messageHandler.setRtviMessageLogging(this._logRtviMessages);
|
|
678
|
+
const configWithDefaults = this.applyConfigDefaults(finalConfig);
|
|
679
|
+
// A fresh connect starts on the v1 model-output contract; the /connect
|
|
680
|
+
// response upgrades it once the server confirms the negotiated version.
|
|
440
681
|
this._messageHandler.setModelOutputVersion(1);
|
|
441
|
-
const hasApiKey = Boolean(configWithDefaults.apiKey);
|
|
442
|
-
const hasAuthToken = Boolean(configWithDefaults.authToken);
|
|
443
|
-
if ((!hasApiKey && !hasAuthToken) || !configWithDefaults.characterId) {
|
|
444
|
-
throw new Error("Either apiKey or authToken is required, and characterId is required");
|
|
445
|
-
}
|
|
446
682
|
this.updateState({ isConnecting: true });
|
|
447
683
|
this._requestTraceId = null;
|
|
448
684
|
try {
|
|
@@ -450,23 +686,91 @@ export class ConvaiClient extends EventEmitter {
|
|
|
450
686
|
this._apiKey = configWithDefaults.apiKey ?? null;
|
|
451
687
|
this._authToken = configWithDefaults.authToken ?? null;
|
|
452
688
|
this._characterId = configWithDefaults.characterId;
|
|
689
|
+
this._characterVersion = configWithDefaults.characterVersion ?? null;
|
|
690
|
+
this._characterReference = configWithDefaults.characterReference;
|
|
453
691
|
// Determine connection type based on enableVideo
|
|
454
692
|
const connType = configWithDefaults.enableVideo ? "video" : "audio";
|
|
455
693
|
this._connectionType = connType;
|
|
456
|
-
const transportType = configWithDefaults.transport ??
|
|
694
|
+
const transportType = configWithDefaults.transport ??
|
|
695
|
+
(configWithDefaults.interactionApiUrl ? "sse" : "livekit");
|
|
696
|
+
if (transportType === "sse" && !configWithDefaults.interactionApiUrl) {
|
|
697
|
+
throw new Error("interactionApiUrl is required when using the SSE transport");
|
|
698
|
+
}
|
|
699
|
+
if (transportType === "sse" && configWithDefaults.enableVideo) {
|
|
700
|
+
throw new Error("The SSE transport supports text interactions only");
|
|
701
|
+
}
|
|
457
702
|
this._activeTransport = transportType;
|
|
458
703
|
const effectiveVisionInputConfig = resolveVisionInputConfig(configWithDefaults);
|
|
459
|
-
// Prepare request body with required parameters
|
|
460
704
|
// An explicit stateOfMind in the config wins; otherwise carry whatever
|
|
461
705
|
// updateEmotion() last set, including before the first connect.
|
|
462
706
|
const stateOfMind = configWithDefaults.stateOfMind !== undefined
|
|
463
707
|
? normalizeStateOfMind(configWithDefaults.stateOfMind) ?? null
|
|
464
708
|
: this._stateOfMind;
|
|
465
709
|
this._stateOfMind = stateOfMind;
|
|
710
|
+
if (transportType === "sse") {
|
|
711
|
+
this._sseSession = new SSESession({
|
|
712
|
+
interactionApiUrl: configWithDefaults.interactionApiUrl,
|
|
713
|
+
authorization: configWithDefaults.authToken ?? configWithDefaults.apiKey,
|
|
714
|
+
credentialProvider: configWithDefaults.interactionCredentialProvider,
|
|
715
|
+
characterId: configWithDefaults.characterReference,
|
|
716
|
+
getCharacterSessionId: () => this._characterSessionId,
|
|
717
|
+
takeStateOfMind: () => {
|
|
718
|
+
const stateOfMind = this._stateOfMind;
|
|
719
|
+
this._stateOfMind = null;
|
|
720
|
+
if (this._storedConfig?.stateOfMind !== undefined) {
|
|
721
|
+
this._storedConfig = { ...this._storedConfig, stateOfMind: null };
|
|
722
|
+
}
|
|
723
|
+
return stateOfMind;
|
|
724
|
+
},
|
|
725
|
+
onCharacterSessionId: (characterSessionId) => {
|
|
726
|
+
this._characterSessionId = characterSessionId;
|
|
727
|
+
this.emit("characterSessionId", characterSessionId);
|
|
728
|
+
this._storedConfig = {
|
|
729
|
+
...this._storedConfig,
|
|
730
|
+
characterSessionId,
|
|
731
|
+
};
|
|
732
|
+
},
|
|
733
|
+
endUserId: configWithDefaults.endUserId,
|
|
734
|
+
endUserMetadata: configWithDefaults.endUserMetadata,
|
|
735
|
+
enableEmotion: configWithDefaults.enableEmotion,
|
|
736
|
+
emotionConfig: configWithDefaults.emotionConfig,
|
|
737
|
+
actionConfig: configWithDefaults.actionConfig,
|
|
738
|
+
capabilities: configWithDefaults.capabilities,
|
|
739
|
+
dynamicInfo: configWithDefaults.dynamicInfo,
|
|
740
|
+
keepInContext: configWithDefaults.keepInContext,
|
|
741
|
+
narrativeTemplateKeys: configWithDefaults.narrativeTemplateKeys,
|
|
742
|
+
sceneDescription: configWithDefaults.sceneDescription,
|
|
743
|
+
respondModes: configWithDefaults.respondModes,
|
|
744
|
+
useResponseLifecycleContract: configWithDefaults.useResponseLifecycleContract,
|
|
745
|
+
invocationMetadata: configWithDefaults.invocationMetadata,
|
|
746
|
+
debug: configWithDefaults.debug,
|
|
747
|
+
onMessage: (payload) => this._messageHandler.handleDataReceivedPublic(payload, "sse"),
|
|
748
|
+
onError: (error) => this.emit("error", error),
|
|
749
|
+
// EOF/rejection is a local transport boundary, not a synthetic Core
|
|
750
|
+
// completion. Close every row before the next stateless request.
|
|
751
|
+
onResponseFinished: () => this._messageHandler.finalizeInterruptedResponse(true),
|
|
752
|
+
});
|
|
753
|
+
this._sseSession.connect();
|
|
754
|
+
this._connectionType = "audio";
|
|
755
|
+
this._isBotReady = true;
|
|
756
|
+
this.updateState({
|
|
757
|
+
isConnected: true,
|
|
758
|
+
isConnecting: false,
|
|
759
|
+
endUserId: configWithDefaults.endUserId ?? null,
|
|
760
|
+
endUserMetadata: configWithDefaults.endUserMetadata ?? null,
|
|
761
|
+
});
|
|
762
|
+
this.emit("connect");
|
|
763
|
+
this.emit("botReady");
|
|
764
|
+
return;
|
|
765
|
+
}
|
|
766
|
+
// Prepare request body with required parameters
|
|
466
767
|
const characterSessionIdToSend = configWithDefaults.characterSessionId ?? this._characterSessionId;
|
|
768
|
+
const isRoster = isRosterConfig(configWithDefaults);
|
|
467
769
|
const serializedCapabilities = serializeProtocolCapabilities(configWithDefaults.capabilities);
|
|
468
770
|
const requestBody = {
|
|
469
|
-
|
|
771
|
+
...(isRoster
|
|
772
|
+
? buildRosterConnectFields(configWithDefaults)
|
|
773
|
+
: { character_id: configWithDefaults.characterReference }),
|
|
470
774
|
...(stateOfMind ? { state_of_mind: stateOfMind } : {}),
|
|
471
775
|
...(configWithDefaults.endUserId && {
|
|
472
776
|
end_user_id: configWithDefaults.endUserId,
|
|
@@ -480,21 +784,8 @@ export class ConvaiClient extends EventEmitter {
|
|
|
480
784
|
}),
|
|
481
785
|
connection_type: connType,
|
|
482
786
|
...buildBlendshapeConnectConfig(configWithDefaults),
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
emotion_config: (() => {
|
|
486
|
-
const cfg = configWithDefaults.emotionConfig;
|
|
487
|
-
const provider = cfg?.provider ?? "llm";
|
|
488
|
-
if (provider === "nrclex") {
|
|
489
|
-
return {
|
|
490
|
-
provider,
|
|
491
|
-
min_word_threshold: cfg.min_word_threshold ?? 3,
|
|
492
|
-
low_intensity_threshold: cfg.low_intensity_threshold ?? 0.33,
|
|
493
|
-
high_intensity_threshold: cfg.high_intensity_threshold ?? 0.66,
|
|
494
|
-
};
|
|
495
|
-
}
|
|
496
|
-
return { provider };
|
|
497
|
-
})(),
|
|
787
|
+
...(buildEmotionConnectConfig(configWithDefaults) && {
|
|
788
|
+
emotion_config: buildEmotionConnectConfig(configWithDefaults),
|
|
498
789
|
}),
|
|
499
790
|
default_tts_enabled: configWithDefaults.ttsEnabled !== undefined
|
|
500
791
|
? configWithDefaults.ttsEnabled
|
|
@@ -503,25 +794,25 @@ export class ConvaiClient extends EventEmitter {
|
|
|
503
794
|
...(effectiveVisionInputConfig && {
|
|
504
795
|
vision_input_config: serializeVisionInputConfig(effectiveVisionInputConfig),
|
|
505
796
|
}),
|
|
797
|
+
...(configWithDefaults.visionPromptMode !== undefined && {
|
|
798
|
+
vision_prompt_mode: configWithDefaults.visionPromptMode,
|
|
799
|
+
}),
|
|
506
800
|
...(configWithDefaults.respondModes && {
|
|
507
801
|
respond_modes: this.serializeRespondModes(configWithDefaults.respondModes),
|
|
508
802
|
}),
|
|
509
|
-
...(
|
|
803
|
+
...(serializedCapabilities && { capabilities: serializedCapabilities }),
|
|
804
|
+
...(configWithDefaults.sceneDescription && {
|
|
805
|
+
scene_description: configWithDefaults.sceneDescription,
|
|
806
|
+
}),
|
|
807
|
+
// A roster room owns its members' sessions; the singular resume id is
|
|
808
|
+
// a compatibility mirror and must not go back on the wire.
|
|
809
|
+
...(!isRoster &&
|
|
810
|
+
characterSessionIdToSend &&
|
|
510
811
|
characterSessionIdToSend !== "-1" && {
|
|
511
812
|
character_session_id: characterSessionIdToSend,
|
|
512
813
|
}),
|
|
513
|
-
...(configWithDefaults
|
|
514
|
-
action_config:
|
|
515
|
-
actions: configWithDefaults.actionConfig.actions,
|
|
516
|
-
objects: configWithDefaults.actionConfig.objects,
|
|
517
|
-
characters: configWithDefaults.actionConfig.characters,
|
|
518
|
-
...(configWithDefaults.actionConfig.current_attention_object && {
|
|
519
|
-
current_attention_object: configWithDefaults.actionConfig.current_attention_object,
|
|
520
|
-
}),
|
|
521
|
-
...(configWithDefaults.actionConfig.tools && {
|
|
522
|
-
tools: serializeClientTools(configWithDefaults.actionConfig.tools),
|
|
523
|
-
}),
|
|
524
|
-
},
|
|
814
|
+
...(buildActionConnectConfig(configWithDefaults) && {
|
|
815
|
+
action_config: buildActionConnectConfig(configWithDefaults),
|
|
525
816
|
}),
|
|
526
817
|
...(configWithDefaults.dynamicInfo && {
|
|
527
818
|
dynamic_info: {
|
|
@@ -538,6 +829,12 @@ export class ConvaiClient extends EventEmitter {
|
|
|
538
829
|
...(configWithDefaults.debug !== undefined && {
|
|
539
830
|
debug: configWithDefaults.debug,
|
|
540
831
|
}),
|
|
832
|
+
...(configWithDefaults.preserveLinksInOutput !== undefined && {
|
|
833
|
+
preserve_links_in_output: configWithDefaults.preserveLinksInOutput,
|
|
834
|
+
}),
|
|
835
|
+
...(configWithDefaults.useResponseLifecycleContract !== undefined && {
|
|
836
|
+
use_response_lifecycle_contract: configWithDefaults.useResponseLifecycleContract,
|
|
837
|
+
}),
|
|
541
838
|
invocation_metadata: {
|
|
542
839
|
source: configWithDefaults.invocationMetadata?.source ?? "web_sdk",
|
|
543
840
|
client_version: configWithDefaults.invocationMetadata?.clientVersion ??
|
|
@@ -556,217 +853,684 @@ export class ConvaiClient extends EventEmitter {
|
|
|
556
853
|
else if (configWithDefaults.apiKey) {
|
|
557
854
|
connectHeaders["X-API-Key"] = configWithDefaults.apiKey;
|
|
558
855
|
}
|
|
559
|
-
// HTTP POST /connect — same request for both transports
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
const
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
856
|
+
// HTTP POST /connect — same request for both transports. A roster room
|
|
857
|
+
// may still be provisioning from an identical concurrent create, which
|
|
858
|
+
// the runtime answers with a retryable 409; the wrapper replays the
|
|
859
|
+
// identical payload and is a straight pass-through otherwise.
|
|
860
|
+
const connectOnce = async () => {
|
|
861
|
+
const response = await fetch(`${configWithDefaults.url}/connect`, {
|
|
862
|
+
method: "POST",
|
|
863
|
+
headers: connectHeaders,
|
|
864
|
+
body: JSON.stringify(requestBody),
|
|
865
|
+
});
|
|
866
|
+
if (!response.ok) {
|
|
867
|
+
const errorText = await response.text();
|
|
868
|
+
let errorMessage = `HTTP ${response.status}`;
|
|
869
|
+
try {
|
|
870
|
+
const errorData = JSON.parse(errorText);
|
|
871
|
+
const raw = errorData.message ?? errorData.error ?? errorData.detail;
|
|
872
|
+
if (typeof raw === "string") {
|
|
873
|
+
errorMessage = raw;
|
|
874
|
+
}
|
|
875
|
+
else if (Array.isArray(raw)) {
|
|
876
|
+
// FastAPI/Pydantic 422 — detail is an array of validation error objects
|
|
877
|
+
errorMessage = raw
|
|
878
|
+
.map((e) => [e.loc?.join("."), e.msg].filter(Boolean).join(": "))
|
|
879
|
+
.join("; ") || errorMessage;
|
|
880
|
+
}
|
|
881
|
+
else if (raw != null) {
|
|
882
|
+
errorMessage = JSON.stringify(raw);
|
|
883
|
+
}
|
|
884
|
+
else if (errorText) {
|
|
885
|
+
errorMessage = `${errorMessage}: ${errorText}`;
|
|
886
|
+
}
|
|
579
887
|
}
|
|
580
|
-
|
|
581
|
-
|
|
888
|
+
catch {
|
|
889
|
+
if (errorText)
|
|
890
|
+
errorMessage = `${errorMessage}: ${errorText}`;
|
|
582
891
|
}
|
|
583
|
-
|
|
584
|
-
|
|
892
|
+
// A roster room's failures are named and machine-actionable, and the
|
|
893
|
+
// trace id is what backend support correlates on, so they get a typed
|
|
894
|
+
// error. Single-character behaviour is unchanged.
|
|
895
|
+
if (isRoster) {
|
|
896
|
+
let parsed = errorText;
|
|
897
|
+
try {
|
|
898
|
+
parsed = JSON.parse(errorText);
|
|
899
|
+
}
|
|
900
|
+
catch {
|
|
901
|
+
/* keep the raw text as the detail */
|
|
902
|
+
}
|
|
903
|
+
throw roomErrorFromResponse(response.status, parsed);
|
|
585
904
|
}
|
|
905
|
+
throw new Error(errorMessage);
|
|
586
906
|
}
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
907
|
+
return await response.json();
|
|
908
|
+
};
|
|
909
|
+
const connectionData = isRoster
|
|
910
|
+
? await this._withProvisioningRetry(configWithDefaults, connectOnce)
|
|
911
|
+
: await connectOnce();
|
|
912
|
+
return await this.consumeConnectionData(connectionData, configWithDefaults);
|
|
913
|
+
}
|
|
914
|
+
catch (error) {
|
|
915
|
+
await this.cleanupWebSocketSessionAfterConnectFailure();
|
|
916
|
+
this.updateState({
|
|
917
|
+
isConnected: false,
|
|
918
|
+
isConnecting: false,
|
|
919
|
+
});
|
|
920
|
+
this.emit("error", error);
|
|
921
|
+
throw error;
|
|
922
|
+
}
|
|
923
|
+
}
|
|
924
|
+
/**
|
|
925
|
+
* Complete a connection from an already-fetched /connect response body.
|
|
926
|
+
*
|
|
927
|
+
* `connect()` fetches /connect and then calls this internally. Call it
|
|
928
|
+
* directly when the response was obtained elsewhere — a server-side session
|
|
929
|
+
* manager, or the embed's connect-proxy flow, where the API key must never
|
|
930
|
+
* reach the browser.
|
|
931
|
+
*
|
|
932
|
+
* @example
|
|
933
|
+
* // Server (customer's backend): holds the API key, calls Convai's
|
|
934
|
+
* // /connect, and relays the response body verbatim.
|
|
935
|
+
* // Browser: never sees the API key, only the relayed response.
|
|
936
|
+
* const data = await fetch('/api/convai-connect', {
|
|
937
|
+
* method: 'POST',
|
|
938
|
+
* headers: { 'Content-Type': 'application/json' },
|
|
939
|
+
* body: JSON.stringify({ characterId: 'your-character-id' }),
|
|
940
|
+
* }).then(r => r.json())
|
|
941
|
+
* await client.connectWithConnectionData(data)
|
|
942
|
+
*/
|
|
943
|
+
async connectWithConnectionData(data, config) {
|
|
944
|
+
// A client can be reused after a published session. This is a normal
|
|
945
|
+
// credentialed/proxy connection path, so never leave published-only UI
|
|
946
|
+
// semantics (fresh grant requirement, text-only controls) enabled.
|
|
947
|
+
this._isPublishedChatSession = false;
|
|
948
|
+
const finalConfig = config || this._storedConfig;
|
|
949
|
+
if (!finalConfig) {
|
|
950
|
+
throw new Error("No configuration provided. Pass config to connectWithConnectionData() or store it in the client");
|
|
951
|
+
}
|
|
952
|
+
this._storedConfig = { ...finalConfig };
|
|
953
|
+
// Use characterSessionId from config when reconnecting (so we resume the same session)
|
|
954
|
+
if (finalConfig.characterSessionId &&
|
|
955
|
+
finalConfig.characterSessionId !== "-1") {
|
|
956
|
+
this._characterSessionId = finalConfig.characterSessionId;
|
|
957
|
+
}
|
|
958
|
+
const configWithDefaults = this.applyConfigDefaults(finalConfig, {
|
|
959
|
+
requireCredential: false,
|
|
960
|
+
});
|
|
961
|
+
// Symmetric with connect(): the catch below emits isConnecting: false, so
|
|
962
|
+
// without this a UI bound to stateChange never sees a connecting state on
|
|
963
|
+
// the proxy path -- and on failure receives a transition out of a state it
|
|
964
|
+
// was never told about. consumeConnectionData() clears the flag on success.
|
|
965
|
+
this.updateState({ isConnecting: true });
|
|
966
|
+
try {
|
|
967
|
+
return await this.consumeConnectionData(data, configWithDefaults);
|
|
968
|
+
}
|
|
969
|
+
catch (error) {
|
|
970
|
+
await this.cleanupWebSocketSessionAfterConnectFailure();
|
|
971
|
+
this.updateState({
|
|
972
|
+
isConnected: false,
|
|
973
|
+
isConnecting: false,
|
|
974
|
+
});
|
|
975
|
+
this.emit("error", error);
|
|
976
|
+
throw error;
|
|
977
|
+
}
|
|
978
|
+
}
|
|
979
|
+
/** Correlate roster acks back to the promise that issued the command. */
|
|
980
|
+
_handleRosterServerResponse(response) {
|
|
981
|
+
const eventType = response.event_type;
|
|
982
|
+
if (eventType !== "interaction-target" &&
|
|
983
|
+
eventType !== "character-roster-update") {
|
|
984
|
+
return;
|
|
985
|
+
}
|
|
986
|
+
const extras = response.extras ?? null;
|
|
987
|
+
const commandId = extras?.command_id;
|
|
988
|
+
const pending = commandId
|
|
989
|
+
? this._pendingRosterCommands.get(commandId)
|
|
990
|
+
: undefined;
|
|
991
|
+
if (response.status === "error") {
|
|
992
|
+
// Adopt the server's epochs even from a rejection -- a stale-epoch error
|
|
993
|
+
// carries the authoritative value, and that is what makes a retry
|
|
994
|
+
// meaningful.
|
|
995
|
+
this._roster.adoptEpochs(extras);
|
|
996
|
+
this._pushRosterState();
|
|
997
|
+
if (pending && commandId) {
|
|
998
|
+
this._pendingRosterCommands.delete(commandId);
|
|
999
|
+
clearTimeout(pending.timer);
|
|
1000
|
+
pending.reject(Object.assign(new Error(response.message ?? `${eventType} was rejected`), { code: extras?.code ?? null, extras }));
|
|
592
1001
|
}
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
1002
|
+
return;
|
|
1003
|
+
}
|
|
1004
|
+
// Apply the change whether or not this client asked for it: another
|
|
1005
|
+
// participant's switch reaches us through the same event.
|
|
1006
|
+
let change;
|
|
1007
|
+
if (eventType === "interaction-target") {
|
|
1008
|
+
change = this._roster.applyInteractionTarget(extras);
|
|
1009
|
+
this._pushRosterState();
|
|
1010
|
+
this.emit("activeCharacterChange", change);
|
|
1011
|
+
}
|
|
1012
|
+
else {
|
|
1013
|
+
change = this._roster.applyRosterUpdate(extras);
|
|
1014
|
+
this._pushRosterState();
|
|
1015
|
+
this.emit("rosterChange", change);
|
|
1016
|
+
}
|
|
1017
|
+
if (pending && commandId) {
|
|
1018
|
+
this._pendingRosterCommands.delete(commandId);
|
|
1019
|
+
clearTimeout(pending.timer);
|
|
1020
|
+
pending.resolve(change);
|
|
1021
|
+
}
|
|
1022
|
+
}
|
|
1023
|
+
/**
|
|
1024
|
+
* Settle every in-flight roster command.
|
|
1025
|
+
*
|
|
1026
|
+
* Without this a caller who disconnects mid-command keeps a live 10s timer
|
|
1027
|
+
* and gets a rejection long after the session ended -- an unhandled rejection
|
|
1028
|
+
* if they stopped awaiting when they tore the client down. The roster is
|
|
1029
|
+
* reset alongside, so the command could not be applied meaningfully anyway.
|
|
1030
|
+
*/
|
|
1031
|
+
_failPendingRosterCommands(reason) {
|
|
1032
|
+
for (const [, pending] of this._pendingRosterCommands) {
|
|
1033
|
+
clearTimeout(pending.timer);
|
|
1034
|
+
pending.reject(new Error(reason));
|
|
1035
|
+
}
|
|
1036
|
+
this._pendingRosterCommands.clear();
|
|
1037
|
+
}
|
|
1038
|
+
_pushRosterState() {
|
|
1039
|
+
this.updateState({
|
|
1040
|
+
characters: this._roster.characters,
|
|
1041
|
+
activeMembershipId: this._roster.activeMembershipId,
|
|
1042
|
+
});
|
|
1043
|
+
}
|
|
1044
|
+
/** Publish a roster command and settle when its ack arrives. */
|
|
1045
|
+
_sendRosterCommand(type, build) {
|
|
1046
|
+
if (!this._roster.isMultiCharacter) {
|
|
1047
|
+
return Promise.reject(new Error(`Cannot send ${type}: this session was not created with a characters array`));
|
|
1048
|
+
}
|
|
1049
|
+
if (!this.isTransportReady()) {
|
|
1050
|
+
return Promise.reject(new Error(`Cannot send ${type}: not connected`));
|
|
1051
|
+
}
|
|
1052
|
+
const commandId = `${type}-${++this._rosterCommandSeq}-${Date.now()}`;
|
|
1053
|
+
return new Promise((resolve, reject) => {
|
|
1054
|
+
const timer = setTimeout(() => {
|
|
1055
|
+
this._pendingRosterCommands.delete(commandId);
|
|
1056
|
+
reject(new Error(`${type} was not acknowledged within ${ConvaiClient.ROSTER_COMMAND_TIMEOUT_MS}ms. ` +
|
|
1057
|
+
`The outcome is unknown -- acks can be suppressed as duplicates. ` +
|
|
1058
|
+
`Reconcile from the next authoritative room state before sending a conflicting command.`));
|
|
1059
|
+
}, ConvaiClient.ROSTER_COMMAND_TIMEOUT_MS);
|
|
1060
|
+
this._pendingRosterCommands.set(commandId, { resolve, reject, timer });
|
|
1061
|
+
this.publishMessage(type, build(commandId), commandId);
|
|
1062
|
+
});
|
|
1063
|
+
}
|
|
1064
|
+
/**
|
|
1065
|
+
* Route subsequent user turns to a different character instance.
|
|
1066
|
+
*
|
|
1067
|
+
* Pass null to close every gate, so no member consumes the user until a
|
|
1068
|
+
* target is set again.
|
|
1069
|
+
*/
|
|
1070
|
+
async setInteractionTarget(membershipId) {
|
|
1071
|
+
if (!this._roster.isMultiCharacter) {
|
|
1072
|
+
throw new Error("Cannot send interaction-target: this session was not created with a characters array");
|
|
1073
|
+
}
|
|
1074
|
+
if (membershipId !== null) {
|
|
1075
|
+
if (!membershipId) {
|
|
1076
|
+
throw new Error("setInteractionTarget requires a membershipId, or null to close all gates");
|
|
606
1077
|
}
|
|
607
|
-
|
|
608
|
-
|
|
1078
|
+
const instance = this._roster.find(membershipId);
|
|
1079
|
+
if (this._roster.isMultiCharacter && !instance) {
|
|
1080
|
+
throw new Error(`Unknown membershipId "${membershipId}". Address instances by membershipId, not characterId.`);
|
|
609
1081
|
}
|
|
610
|
-
if (
|
|
611
|
-
|
|
1082
|
+
if (instance && !instance.isReady) {
|
|
1083
|
+
throw new Error(`Membership "${membershipId}" has not sent bot-ready yet; the runtime refuses an unready target`);
|
|
612
1084
|
}
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
1085
|
+
}
|
|
1086
|
+
const send = () => this._sendRosterCommand("interaction-target", (commandId) => this._roster.buildInteractionTarget(membershipId, commandId));
|
|
1087
|
+
try {
|
|
1088
|
+
return (await send());
|
|
1089
|
+
}
|
|
1090
|
+
catch (error) {
|
|
1091
|
+
// Another participant switched first. The roster adopted the server's
|
|
1092
|
+
// epoch when the rejection arrived, so exactly one retry is now fenced
|
|
1093
|
+
// correctly; a second would mean we are losing a race we should report.
|
|
1094
|
+
if (error?.code !== "stale_route_epoch")
|
|
1095
|
+
throw error;
|
|
1096
|
+
return (await send());
|
|
1097
|
+
}
|
|
1098
|
+
}
|
|
1099
|
+
/** Add or remove character instances on a live room, without reconnecting. */
|
|
1100
|
+
async updateCharacterRoster(options) {
|
|
1101
|
+
// Report the wrong-session-shape first. Otherwise a single-character
|
|
1102
|
+
// client, whose roster is empty, trips the "cannot be emptied" rule below
|
|
1103
|
+
// and gets an error about a room it never had.
|
|
1104
|
+
if (!this._roster.isMultiCharacter) {
|
|
1105
|
+
throw new Error("Cannot send character-roster-update: this session was not created with a characters array");
|
|
1106
|
+
}
|
|
1107
|
+
const add = options?.add ?? [];
|
|
1108
|
+
const remove = options?.remove ?? [];
|
|
1109
|
+
if (add.length === 0 && remove.length === 0) {
|
|
1110
|
+
throw new Error("updateCharacterRoster requires at least one add or remove");
|
|
1111
|
+
}
|
|
1112
|
+
if (add.some((c) => !c?.characterId?.trim())) {
|
|
1113
|
+
throw new Error("Every entry in add requires a characterId");
|
|
1114
|
+
}
|
|
1115
|
+
if (remove.length && remove.length >= this._roster.characters.length && add.length === 0) {
|
|
1116
|
+
throw new Error("A roster room cannot be emptied; add a replacement or keep one member");
|
|
1117
|
+
}
|
|
1118
|
+
// Removing the active member needs an explicit, ready replacement --
|
|
1119
|
+
// the runtime answers `replacement_target_required` otherwise, and
|
|
1120
|
+
// `replacement_target_unavailable` for one that has not sent bot-ready.
|
|
1121
|
+
const active = this._roster.activeMembershipId;
|
|
1122
|
+
const effective = !options.replacementTarget && active && remove.includes(active)
|
|
1123
|
+
? { ...options, replacementTarget: this._roster.pickReplacement(remove) }
|
|
1124
|
+
: options;
|
|
1125
|
+
return (await this._sendRosterCommand("character-roster-update", (commandId) => this._roster.buildRosterUpdate(effective, commandId)));
|
|
1126
|
+
}
|
|
1127
|
+
/**
|
|
1128
|
+
* Run a room request, retrying only the conflicts that mean "still working".
|
|
1129
|
+
*
|
|
1130
|
+
* The runtime answers a create that collides with an in-flight identical
|
|
1131
|
+
* create with 409 `ROSTER_PROVISIONING_IN_PROGRESS`, and the documented
|
|
1132
|
+
* recovery is to retry the same key with bounded backoff. Left to callers,
|
|
1133
|
+
* every integration reimplements that, usually without a cap. The payload is
|
|
1134
|
+
* replayed verbatim -- changing it would turn the retry into a fingerprint
|
|
1135
|
+
* mismatch.
|
|
1136
|
+
*/
|
|
1137
|
+
async _withProvisioningRetry(config, run) {
|
|
1138
|
+
const setting = config.rosterProvisioningRetry;
|
|
1139
|
+
if (setting === false)
|
|
1140
|
+
return run();
|
|
1141
|
+
const attempts = Math.max(1, setting?.attempts ?? ConvaiClient.ROSTER_RETRY_ATTEMPTS);
|
|
1142
|
+
const initialDelayMs = Math.max(0, setting?.initialDelayMs ?? ConvaiClient.ROSTER_RETRY_INITIAL_MS);
|
|
1143
|
+
let lastError;
|
|
1144
|
+
for (let attempt = 0; attempt < attempts; attempt++) {
|
|
1145
|
+
try {
|
|
1146
|
+
return await run();
|
|
1147
|
+
}
|
|
1148
|
+
catch (error) {
|
|
1149
|
+
lastError = error;
|
|
1150
|
+
const retryable = error instanceof ConvaiRoomError && error.isRetryable;
|
|
1151
|
+
if (!retryable || attempt === attempts - 1)
|
|
1152
|
+
throw error;
|
|
1153
|
+
// Jitter so a lobby of clients waking on the same room does not
|
|
1154
|
+
// retry in lockstep.
|
|
1155
|
+
const base = initialDelayMs * 2 ** attempt;
|
|
1156
|
+
const jittered = base * (0.8 + Math.random() * 0.4);
|
|
1157
|
+
await new Promise((resolve) => setTimeout(resolve, jittered));
|
|
1158
|
+
}
|
|
1159
|
+
}
|
|
1160
|
+
throw lastError;
|
|
1161
|
+
}
|
|
1162
|
+
/**
|
|
1163
|
+
* Join a multi-character room that already exists.
|
|
1164
|
+
*
|
|
1165
|
+
* A join supplies a locator and the joining human, and nothing else: the
|
|
1166
|
+
* roster is server-owned, so resending topology is rejected. It never spawns,
|
|
1167
|
+
* removes or repairs a character -- only room creation does that.
|
|
1168
|
+
*
|
|
1169
|
+
* Capacity counts distinct speakers derived from `endUserId`, and defaults to
|
|
1170
|
+
* one, so raise `maxNumParticipants` at creation before expecting a second
|
|
1171
|
+
* human to get in.
|
|
1172
|
+
*
|
|
1173
|
+
* @example
|
|
1174
|
+
* ```ts
|
|
1175
|
+
* const client = new ConvaiClient({ apiKey: 'YOUR_API_KEY' })
|
|
1176
|
+
* await client.joinRoom({
|
|
1177
|
+
* roomSessionId: 'the-room-session-id',
|
|
1178
|
+
* endUserId: 'player-99',
|
|
1179
|
+
* })
|
|
1180
|
+
* ```
|
|
1181
|
+
*/
|
|
1182
|
+
async joinRoom(options) {
|
|
1183
|
+
validateJoinOptions(options);
|
|
1184
|
+
// joinRoom is a credentialed Workspace connection, not a publication.
|
|
1185
|
+
// Reset this before further validation so a rejected normal attempt also
|
|
1186
|
+
// cannot leave a reused client in published-session mode.
|
|
1187
|
+
this._isPublishedChatSession = false;
|
|
1188
|
+
const stored = this._storedConfig ?? {};
|
|
1189
|
+
const url = stored.url ?? "https://realtime-api.convai.com";
|
|
1190
|
+
if (!stored.apiKey && !stored.authToken) {
|
|
1191
|
+
throw new Error("Either apiKey or authToken is required to join a room");
|
|
1192
|
+
}
|
|
1193
|
+
this._logRtviMessages = stored.logRtviMessages !== false;
|
|
1194
|
+
this._messageHandler.setRtviMessageLogging(this._logRtviMessages);
|
|
1195
|
+
this.updateState({ isConnecting: true });
|
|
1196
|
+
try {
|
|
1197
|
+
const connectionData = await this._withProvisioningRetry(stored, async () => {
|
|
1198
|
+
const response = await fetch(`${url}/connect`, {
|
|
1199
|
+
method: "POST",
|
|
1200
|
+
headers: {
|
|
1201
|
+
"Content-Type": "application/json",
|
|
1202
|
+
...(stored.apiKey
|
|
1203
|
+
? { "X-API-Key": stored.apiKey }
|
|
1204
|
+
: { "API-AUTH-TOKEN": stored.authToken }),
|
|
1205
|
+
},
|
|
1206
|
+
body: JSON.stringify(buildJoinRequestBody(options)),
|
|
646
1207
|
});
|
|
647
|
-
|
|
648
|
-
|
|
1208
|
+
if (!response.ok) {
|
|
1209
|
+
const text = await response.text();
|
|
1210
|
+
let parsed = text;
|
|
1211
|
+
try {
|
|
1212
|
+
parsed = JSON.parse(text);
|
|
1213
|
+
}
|
|
1214
|
+
catch {
|
|
1215
|
+
/* keep the raw text as the detail */
|
|
1216
|
+
}
|
|
1217
|
+
throw roomErrorFromResponse(response.status, parsed);
|
|
1218
|
+
}
|
|
1219
|
+
return (await response.json());
|
|
1220
|
+
});
|
|
1221
|
+
// The join response carries the persisted roster, so the joining client
|
|
1222
|
+
// learns the topology it never sent.
|
|
1223
|
+
const rosterCharacters = connectionData.characters;
|
|
1224
|
+
const initialCharacterId = rosterCharacters?.[0]?.character_id;
|
|
1225
|
+
const joinConfig = {
|
|
1226
|
+
...stored,
|
|
1227
|
+
characters: undefined,
|
|
1228
|
+
characterId: initialCharacterId ?? stored.characterId,
|
|
1229
|
+
endUserId: options.endUserId,
|
|
1230
|
+
...(options.endUserMetadata
|
|
1231
|
+
? { endUserMetadata: options.endUserMetadata }
|
|
1232
|
+
: {}),
|
|
1233
|
+
};
|
|
1234
|
+
this._storedConfig = joinConfig;
|
|
1235
|
+
const configWithDefaults = this.applyConfigDefaults(joinConfig, {
|
|
1236
|
+
requireCredential: false,
|
|
1237
|
+
});
|
|
1238
|
+
return await this.consumeConnectionData(connectionData, configWithDefaults);
|
|
1239
|
+
}
|
|
1240
|
+
catch (error) {
|
|
1241
|
+
await this.cleanupWebSocketSessionAfterConnectFailure();
|
|
1242
|
+
this.updateState({ isConnected: false, isConnecting: false });
|
|
1243
|
+
this.emit("error", error);
|
|
1244
|
+
throw error;
|
|
1245
|
+
}
|
|
1246
|
+
}
|
|
1247
|
+
/**
|
|
1248
|
+
* Add default URL, apply RTVI-logging config, and validate that either an
|
|
1249
|
+
* API key or auth token plus a character ID are present.
|
|
1250
|
+
* Shared by connect() and connectWithConnectionData() so both derive
|
|
1251
|
+
* `configWithDefaults` identically.
|
|
1252
|
+
*
|
|
1253
|
+
* `connect()` performs its own /connect fetch and always needs a credential
|
|
1254
|
+
* to do so, so it uses the default `requireCredential: true`.
|
|
1255
|
+
* `connectWithConnectionData()` consumes a response obtained elsewhere (e.g.
|
|
1256
|
+
* a proxy that holds the credential server-side) and passes
|
|
1257
|
+
* `requireCredential: false` — a character ID is still required either way.
|
|
1258
|
+
*/
|
|
1259
|
+
applyConfigDefaults(finalConfig, opts = {}) {
|
|
1260
|
+
const { requireCredential = true } = opts;
|
|
1261
|
+
// Add default URL if not provided
|
|
1262
|
+
const configWithDefaults = {
|
|
1263
|
+
url: "https://realtime-api.convai.com",
|
|
1264
|
+
...finalConfig,
|
|
1265
|
+
};
|
|
1266
|
+
this._logRtviMessages = configWithDefaults.logRtviMessages !== false;
|
|
1267
|
+
this._messageHandler.setRtviMessageLogging(this._logRtviMessages);
|
|
1268
|
+
const hasApiKey = Boolean(configWithDefaults.apiKey);
|
|
1269
|
+
const hasAuthToken = Boolean(configWithDefaults.authToken);
|
|
1270
|
+
const hasInteractionProvider = Boolean(configWithDefaults.interactionCredentialProvider);
|
|
1271
|
+
const hasEndUserId = configWithDefaults.endUserId !== undefined &&
|
|
1272
|
+
configWithDefaults.endUserId !== null;
|
|
1273
|
+
if (hasInteractionProvider && (hasApiKey || hasAuthToken || hasEndUserId ||
|
|
1274
|
+
configWithDefaults.endUserMetadata !== undefined ||
|
|
1275
|
+
(configWithDefaults.transport ?? (configWithDefaults.interactionApiUrl ? "sse" : "livekit")) !== "sse")) {
|
|
1276
|
+
throw new Error("interactionCredentialProvider requires SSE without static credentials or end-user overrides");
|
|
1277
|
+
}
|
|
1278
|
+
const missingCredential = requireCredential && !hasApiKey && !hasAuthToken && !hasInteractionProvider;
|
|
1279
|
+
// Runs for every topology: the v2 protocol constraints rule out
|
|
1280
|
+
// sharedSessionKey and extra human capacity in single-character rooms too.
|
|
1281
|
+
validateProtocolTopology(configWithDefaults);
|
|
1282
|
+
const roster = isRosterConfig(configWithDefaults);
|
|
1283
|
+
if (missingCredential || (!roster && !configWithDefaults.characterId)) {
|
|
1284
|
+
throw new Error("Either apiKey or authToken is required, and characterId is required");
|
|
1285
|
+
}
|
|
1286
|
+
// A roster names its members individually; every roster rule is checked
|
|
1287
|
+
// before a request is built.
|
|
1288
|
+
if (roster) {
|
|
1289
|
+
validateRosterConfig(configWithDefaults);
|
|
1290
|
+
const initial = configWithDefaults.characters[0].characterId.trim();
|
|
1291
|
+
return {
|
|
1292
|
+
...configWithDefaults,
|
|
1293
|
+
// Singular readouts mirror characters[0], exactly as the wire's own
|
|
1294
|
+
// top-level session_id/character_session_id aliases do.
|
|
1295
|
+
characterId: initial,
|
|
1296
|
+
characterVersion: null,
|
|
1297
|
+
characterReference: initial,
|
|
1298
|
+
};
|
|
1299
|
+
}
|
|
1300
|
+
// Split the character id from its version selector. The bare UUID names
|
|
1301
|
+
// the character everywhere inside the SDK (memory, character info); the
|
|
1302
|
+
// joined reference is what the runtime receives.
|
|
1303
|
+
const reference = resolveCharacterReference(configWithDefaults.characterId, configWithDefaults.characterVersion);
|
|
1304
|
+
return {
|
|
1305
|
+
...configWithDefaults,
|
|
1306
|
+
characterId: reference.characterId,
|
|
1307
|
+
characterVersion: reference.version,
|
|
1308
|
+
characterReference: reference.reference,
|
|
1309
|
+
};
|
|
1310
|
+
}
|
|
1311
|
+
/**
|
|
1312
|
+
* Consume a /connect response and bring up the transport.
|
|
1313
|
+
* `connect()` calls this after its own fetch; external callers use it
|
|
1314
|
+
* when the response came from a proxy.
|
|
1315
|
+
*/
|
|
1316
|
+
async consumeConnectionData(connectionData, configWithDefaults) {
|
|
1317
|
+
// Store connection config (mirrors connect()'s pre-fetch setup so this
|
|
1318
|
+
// method is self-sufficient when called directly, without connect()
|
|
1319
|
+
// having run first).
|
|
1320
|
+
//
|
|
1321
|
+
// Known race, judged acceptable: when called from connect(), that method
|
|
1322
|
+
// sets these same fields once, before the /connect fetch, then awaits
|
|
1323
|
+
// the network round trip. If disconnect() -> clearAllManagers() lands in
|
|
1324
|
+
// that await window, the pre-split code left these fields null (nothing
|
|
1325
|
+
// re-set them post-fetch), whereas re-deriving them here re-arms them
|
|
1326
|
+
// once the response arrives. Checked `_isDisconnecting` as a guard: it
|
|
1327
|
+
// doesn't cover this window — it's flipped back to false (in a
|
|
1328
|
+
// `finally`) before clearAllManagers() runs on the websocket path, and
|
|
1329
|
+
// disconnect()'s LiveKit-room path never sets it at all — so it can't
|
|
1330
|
+
// reliably detect "a disconnect landed mid-connect" here. Even
|
|
1331
|
+
// pre-split, connect() never checked for a concurrent disconnect after
|
|
1332
|
+
// the fetch resolved; it always went on to establish a new room/session
|
|
1333
|
+
// regardless. Re-arming these fields keeps them consistent with the
|
|
1334
|
+
// connection actually being brought up in that case, rather than
|
|
1335
|
+
// silently stale. Building a proper cancellation token for
|
|
1336
|
+
// connect()-vs-disconnect() races is out of scope for this additive
|
|
1337
|
+
// split.
|
|
1338
|
+
this._apiKey = configWithDefaults.apiKey ?? null;
|
|
1339
|
+
this._authToken = configWithDefaults.authToken ?? null;
|
|
1340
|
+
this._characterId = configWithDefaults.characterId;
|
|
1341
|
+
this._characterVersion = configWithDefaults.characterVersion ?? null;
|
|
1342
|
+
this._characterReference = configWithDefaults.characterReference;
|
|
1343
|
+
const connType = configWithDefaults.enableVideo ? "video" : "audio";
|
|
1344
|
+
this._connectionType = connType;
|
|
1345
|
+
const transportType = configWithDefaults.transport ?? "livekit";
|
|
1346
|
+
this._activeTransport = transportType;
|
|
1347
|
+
const effectiveVisionInputConfig = resolveVisionInputConfig(configWithDefaults);
|
|
1348
|
+
// Capture session identifiers from /connect response
|
|
1349
|
+
if (connectionData.character_session_id) {
|
|
1350
|
+
this._characterSessionId = connectionData.character_session_id;
|
|
1351
|
+
// Emitted here rather than in connect(), so the proxy-auth path
|
|
1352
|
+
// (connectWithConnectionData) surfaces the session id too -- both routes
|
|
1353
|
+
// establish it at exactly this point.
|
|
1354
|
+
this.emit("characterSessionId", connectionData.character_session_id);
|
|
1355
|
+
this._storedConfig = {
|
|
1356
|
+
...this._storedConfig,
|
|
1357
|
+
characterSessionId: connectionData.character_session_id,
|
|
1358
|
+
};
|
|
1359
|
+
}
|
|
1360
|
+
// The server answers a capability request with what it actually selected.
|
|
1361
|
+
// A silent downgrade would leave the client parsing v2 frames as v1 (or the
|
|
1362
|
+
// reverse), so each selection is validated and the model-output version the
|
|
1363
|
+
// message handler decodes is set from the server's answer, not the request.
|
|
1364
|
+
const selectedCapabilities = connectionData.capabilities ?? {};
|
|
1365
|
+
const requestedCapabilities = configWithDefaults.capabilities;
|
|
1366
|
+
validateActionProtocolSelection(requestedCapabilities?.actionProtocolVersion, selectedCapabilities.action_protocol_version);
|
|
1367
|
+
this._messageHandler.setModelOutputVersion(validateModelOutputVersionSelection(requestedCapabilities?.modelOutputVersion, selectedCapabilities.model_output_version));
|
|
1368
|
+
this._requestTraceId =
|
|
1369
|
+
connectionData.request_trace_id ?? null;
|
|
1370
|
+
// Seed the roster before the transport comes up, so the first bot-ready and
|
|
1371
|
+
// any early roster change already have instances to match against.
|
|
1372
|
+
if (this._roster.applyConnectResponse(connectionData)) {
|
|
1373
|
+
this.updateState({
|
|
1374
|
+
characters: this._roster.characters,
|
|
1375
|
+
activeMembershipId: this._roster.activeMembershipId,
|
|
1376
|
+
});
|
|
1377
|
+
}
|
|
1378
|
+
if (connectionData.end_user_id) {
|
|
1379
|
+
this._endUserId = connectionData.end_user_id;
|
|
1380
|
+
}
|
|
1381
|
+
if (connectionData.end_user_metadata) {
|
|
1382
|
+
this._endUserMetadata = connectionData.end_user_metadata;
|
|
1383
|
+
}
|
|
1384
|
+
if (transportType === "websocket") {
|
|
1385
|
+
// ── WebSocket (Pipecat) transport path ────────────────────────────
|
|
1386
|
+
// Server returns the WebSocket URL in room_url (same field as LiveKit).
|
|
1387
|
+
const wsUrl = connectionData.room_url;
|
|
1388
|
+
if (!wsUrl) {
|
|
1389
|
+
throw new Error("No WebSocket URL returned from /connect endpoint (expected room_url)");
|
|
1390
|
+
}
|
|
1391
|
+
if (!_wsFactory) {
|
|
1392
|
+
throw new Error("[ConvaiClient] WebSocket transport is not registered. " +
|
|
1393
|
+
"Add `import '@convai/web-sdk/vanilla/websocket'` before calling connect().");
|
|
1394
|
+
}
|
|
1395
|
+
// Always enable mic at construction so WavMediaManager initializes the
|
|
1396
|
+
// audio stream during connect(). If startWithAudioOn is false, we mute
|
|
1397
|
+
// after the connection is established (enableMic(false) works once the
|
|
1398
|
+
// stream exists, but not before it is initialized).
|
|
1399
|
+
this._wsSession = _wsFactory((payload) => this._messageHandler.handleDataReceivedPublic(payload), true);
|
|
1400
|
+
const webSocketVisionEnabled = configWithDefaults.enableVideo === true &&
|
|
1401
|
+
effectiveVisionInputConfig?.enabled !== false;
|
|
1402
|
+
if (webSocketVisionEnabled) {
|
|
1403
|
+
this._videoManager.setWebSocketVisionMessageSender((type, data) => {
|
|
1404
|
+
if (this._activeTransport !== "websocket" ||
|
|
1405
|
+
!this._wsSession?.isConnected) {
|
|
649
1406
|
return;
|
|
650
1407
|
}
|
|
651
|
-
this.
|
|
652
|
-
this.clearAllManagers();
|
|
1408
|
+
this._wsSession.sendMessage(type, data);
|
|
653
1409
|
});
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
1410
|
+
}
|
|
1411
|
+
else {
|
|
1412
|
+
this._videoManager.setWebSocketVisionDisabled();
|
|
1413
|
+
}
|
|
1414
|
+
const wsSession = this._wsSession;
|
|
1415
|
+
wsSession.on("botAudioTrack", (track) => {
|
|
1416
|
+
this.emit("botAudioTrack", track);
|
|
1417
|
+
});
|
|
1418
|
+
wsSession.on("disconnected", () => {
|
|
1419
|
+
if (this._wsSession !== wsSession || this._isDisconnecting) {
|
|
1420
|
+
return;
|
|
1421
|
+
}
|
|
1422
|
+
this._connectionStateHandler.handleDisconnected();
|
|
1423
|
+
this.clearAllManagers();
|
|
1424
|
+
});
|
|
1425
|
+
this._audioManager.setWebSocketSession(this._wsSession);
|
|
1426
|
+
// Wait for WebSocket transport to connect (fires before bot-ready)
|
|
1427
|
+
await new Promise((resolve, reject) => {
|
|
1428
|
+
let settled = false;
|
|
1429
|
+
const cleanupConnectListeners = () => {
|
|
1430
|
+
wsSession.off("connected", onConnected);
|
|
1431
|
+
wsSession.off("error", onError);
|
|
1432
|
+
wsSession.off("disconnected", onDisconnected);
|
|
1433
|
+
};
|
|
1434
|
+
const settle = (callback) => {
|
|
1435
|
+
if (settled) {
|
|
1436
|
+
return;
|
|
1437
|
+
}
|
|
1438
|
+
settled = true;
|
|
1439
|
+
cleanupConnectListeners();
|
|
1440
|
+
callback();
|
|
1441
|
+
};
|
|
1442
|
+
const onConnected = () => {
|
|
1443
|
+
settle(resolve);
|
|
1444
|
+
};
|
|
1445
|
+
const onError = (err) => {
|
|
1446
|
+
settle(() => {
|
|
1447
|
+
reject(err instanceof Error ? err : new Error(String(err)));
|
|
1448
|
+
});
|
|
1449
|
+
};
|
|
1450
|
+
const onDisconnected = () => {
|
|
1451
|
+
settle(() => {
|
|
1452
|
+
reject(new Error("WebSocket disconnected before connect completed"));
|
|
1453
|
+
});
|
|
1454
|
+
};
|
|
1455
|
+
wsSession.on("connected", onConnected);
|
|
1456
|
+
wsSession.on("error", onError);
|
|
1457
|
+
wsSession.on("disconnected", onDisconnected);
|
|
1458
|
+
// connectWithUrl calls initDevices() then connect({ wsUrl }) — matches sandbox flow
|
|
1459
|
+
wsSession.connectWithUrl(wsUrl).catch((err) => {
|
|
1460
|
+
settle(() => {
|
|
1461
|
+
reject(err instanceof Error ? err : new Error(String(err)));
|
|
692
1462
|
});
|
|
693
1463
|
});
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
else {
|
|
703
|
-
this._audioManager.syncWsAudioState(true);
|
|
704
|
-
}
|
|
705
|
-
if (webSocketVisionEnabled &&
|
|
706
|
-
configWithDefaults.enableVideo &&
|
|
707
|
-
configWithDefaults.startWithVideoOn) {
|
|
708
|
-
await this._videoManager.enableVideo();
|
|
709
|
-
}
|
|
1464
|
+
});
|
|
1465
|
+
// For WebSocket, mic is already streaming after connect.
|
|
1466
|
+
// Only mute if the caller explicitly sets startWithAudioOn: false.
|
|
1467
|
+
// Defaulting to on matches the sandbox behavior and ensures the bot
|
|
1468
|
+
// sees audio when it initializes (avoids server "tap mic to talk" prompt).
|
|
1469
|
+
if (configWithDefaults.startWithAudioOn === false) {
|
|
1470
|
+
this._wsSession.enableMic(false);
|
|
1471
|
+
this._audioManager.syncWsAudioState(false);
|
|
710
1472
|
}
|
|
711
1473
|
else {
|
|
712
|
-
this.
|
|
713
|
-
// ── LiveKit transport path (default) ─────────────────────────────
|
|
714
|
-
await this._room.connect(connectionData.room_url, connectionData.token, {
|
|
715
|
-
rtcConfig: {
|
|
716
|
-
iceTransportPolicy: "relay",
|
|
717
|
-
},
|
|
718
|
-
});
|
|
719
|
-
if (configWithDefaults.startWithAudioOn) {
|
|
720
|
-
await this._room.localParticipant.setMicrophoneEnabled(true, {
|
|
721
|
-
echoCancellation: this._audioSettings.echoCancellation,
|
|
722
|
-
noiseSuppression: this._audioSettings.noiseSuppression,
|
|
723
|
-
autoGainControl: this._audioSettings.autoGainControl,
|
|
724
|
-
sampleRate: this._audioSettings.sampleRate,
|
|
725
|
-
channelCount: this._audioSettings.channelCount,
|
|
726
|
-
});
|
|
727
|
-
}
|
|
728
|
-
if (configWithDefaults.enableVideo &&
|
|
729
|
-
configWithDefaults.startWithVideoOn) {
|
|
730
|
-
await this._room.localParticipant.setCameraEnabled(true);
|
|
731
|
-
}
|
|
732
|
-
this._audioManager.syncStateFromRoom({ emit: true });
|
|
733
|
-
this._participantSid = this._room.localParticipant.sid;
|
|
1474
|
+
this._audioManager.syncWsAudioState(true);
|
|
734
1475
|
}
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
1476
|
+
if (webSocketVisionEnabled &&
|
|
1477
|
+
configWithDefaults.enableVideo &&
|
|
1478
|
+
configWithDefaults.startWithVideoOn) {
|
|
1479
|
+
await this._videoManager.enableVideo();
|
|
738
1480
|
}
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
1481
|
+
}
|
|
1482
|
+
else {
|
|
1483
|
+
this._videoManager.setWebSocketVisionMessageSender(null);
|
|
1484
|
+
// ── LiveKit transport path (default) ─────────────────────────────
|
|
1485
|
+
await this._room.connect(connectionData.room_url, connectionData.token, {
|
|
1486
|
+
rtcConfig: {
|
|
1487
|
+
// Defaults to "relay" (TURN-only) for reliable NAT traversal
|
|
1488
|
+
// against Convai's hosted LiveKit. Set iceTransportPolicy: "all"
|
|
1489
|
+
// when pointing at a LiveKit without TURN (e.g. local dev).
|
|
1490
|
+
iceTransportPolicy: configWithDefaults.iceTransportPolicy ?? "relay",
|
|
1491
|
+
},
|
|
744
1492
|
});
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
// Use auth token authentication
|
|
754
|
-
this._memoryManager = new MemoryManager(this._authToken, this._characterId, this._endUserId, undefined, // Use default base URL
|
|
755
|
-
true);
|
|
756
|
-
}
|
|
1493
|
+
if (configWithDefaults.startWithAudioOn) {
|
|
1494
|
+
await this._room.localParticipant.setMicrophoneEnabled(true, {
|
|
1495
|
+
echoCancellation: this._audioSettings.echoCancellation,
|
|
1496
|
+
noiseSuppression: this._audioSettings.noiseSuppression,
|
|
1497
|
+
autoGainControl: this._audioSettings.autoGainControl,
|
|
1498
|
+
sampleRate: this._audioSettings.sampleRate,
|
|
1499
|
+
channelCount: this._audioSettings.channelCount,
|
|
1500
|
+
});
|
|
757
1501
|
}
|
|
758
|
-
|
|
759
|
-
|
|
1502
|
+
if (configWithDefaults.enableVideo &&
|
|
1503
|
+
configWithDefaults.startWithVideoOn) {
|
|
1504
|
+
await this._room.localParticipant.setCameraEnabled(true);
|
|
1505
|
+
}
|
|
1506
|
+
this._audioManager.syncStateFromRoom({ emit: true });
|
|
1507
|
+
this._participantSid = this._room.localParticipant.sid;
|
|
760
1508
|
}
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
this.
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
1509
|
+
// Apply custom mapper to blendshape queue if provided
|
|
1510
|
+
if (configWithDefaults.blendshapeConfig?.customMapper) {
|
|
1511
|
+
this.blendshapeQueue.setMapper(configWithDefaults.blendshapeConfig.customMapper);
|
|
1512
|
+
}
|
|
1513
|
+
this.updateState({
|
|
1514
|
+
isConnected: true,
|
|
1515
|
+
isConnecting: false,
|
|
1516
|
+
endUserId: this._endUserId,
|
|
1517
|
+
endUserMetadata: this._endUserMetadata,
|
|
1518
|
+
});
|
|
1519
|
+
// Initialize memory manager if we have authentication and endUserId
|
|
1520
|
+
if (this._endUserId) {
|
|
1521
|
+
if (this._apiKey) {
|
|
1522
|
+
// Use API key authentication
|
|
1523
|
+
this._memoryManager = new MemoryManager(this._apiKey, this._characterId, this._endUserId, undefined, // Use default base URL
|
|
1524
|
+
false);
|
|
1525
|
+
}
|
|
1526
|
+
else if (this._authToken) {
|
|
1527
|
+
// Use auth token authentication
|
|
1528
|
+
this._memoryManager = new MemoryManager(this._authToken, this._characterId, this._endUserId, undefined, // Use default base URL
|
|
1529
|
+
true);
|
|
1530
|
+
}
|
|
769
1531
|
}
|
|
1532
|
+
this.emit("connect");
|
|
1533
|
+
this._startClientReadyHandshake();
|
|
770
1534
|
}
|
|
771
1535
|
async cleanupWebSocketSessionAfterConnectFailure() {
|
|
772
1536
|
if (this._activeTransport !== "websocket" || !this._wsSession) {
|
|
@@ -827,6 +1591,7 @@ export class ConvaiClient extends EventEmitter {
|
|
|
827
1591
|
this._characterSessionId = "-1";
|
|
828
1592
|
this._endUserId = null;
|
|
829
1593
|
this._endUserMetadata = null;
|
|
1594
|
+
this._requestTraceId = null;
|
|
830
1595
|
this._memoryManager = null;
|
|
831
1596
|
this._connectionType = "text";
|
|
832
1597
|
this._activeTransport = "livekit";
|
|
@@ -851,58 +1616,95 @@ export class ConvaiClient extends EventEmitter {
|
|
|
851
1616
|
}),
|
|
852
1617
|
signal: options.signal,
|
|
853
1618
|
});
|
|
854
|
-
|
|
855
|
-
|
|
1619
|
+
const readConnectionResponse = async (response, retryTransientFailure) => {
|
|
1620
|
+
if (!response.ok) {
|
|
1621
|
+
if (retryTransientFailure && response.status >= 500) {
|
|
1622
|
+
throw new RetryablePublishedChatExchangeError();
|
|
1623
|
+
}
|
|
1624
|
+
const errorText = await response.text();
|
|
1625
|
+
let errorMessage = `HTTP ${response.status}`;
|
|
1626
|
+
try {
|
|
1627
|
+
const errorData = JSON.parse(errorText);
|
|
1628
|
+
this._requestTraceId =
|
|
1629
|
+
errorData.request_trace_id ?? errorData.requestTraceId ?? null;
|
|
1630
|
+
const raw = errorData.message ?? errorData.error ?? errorData.detail;
|
|
1631
|
+
errorMessage =
|
|
1632
|
+
typeof raw === "string"
|
|
1633
|
+
? raw
|
|
1634
|
+
: raw == null
|
|
1635
|
+
? errorMessage
|
|
1636
|
+
: JSON.stringify(raw);
|
|
1637
|
+
}
|
|
1638
|
+
catch {
|
|
1639
|
+
if (errorText)
|
|
1640
|
+
errorMessage = `${errorMessage}: ${errorText}`;
|
|
1641
|
+
}
|
|
1642
|
+
throw new Error(errorMessage);
|
|
1643
|
+
}
|
|
1644
|
+
let connectionData;
|
|
1645
|
+
try {
|
|
1646
|
+
connectionData = await response.json();
|
|
1647
|
+
}
|
|
1648
|
+
catch {
|
|
1649
|
+
if (retryTransientFailure) {
|
|
1650
|
+
throw new RetryablePublishedChatExchangeError();
|
|
1651
|
+
}
|
|
1652
|
+
throw new Error("Published chat returned an invalid connection response");
|
|
1653
|
+
}
|
|
1654
|
+
throwIfAborted();
|
|
1655
|
+
if (typeof connectionData !== "object" ||
|
|
1656
|
+
connectionData === null ||
|
|
1657
|
+
typeof connectionData.room_url !== "string" ||
|
|
1658
|
+
typeof connectionData.token !== "string" ||
|
|
1659
|
+
typeof connectionData.character_session_id !==
|
|
1660
|
+
"string") {
|
|
1661
|
+
if (retryTransientFailure) {
|
|
1662
|
+
throw new RetryablePublishedChatExchangeError();
|
|
1663
|
+
}
|
|
1664
|
+
throw new Error("Published chat returned an invalid connection response");
|
|
1665
|
+
}
|
|
1666
|
+
return connectionData;
|
|
1667
|
+
};
|
|
1668
|
+
const requestConnection = async (retryTransientFailure) => {
|
|
1669
|
+
let response;
|
|
1670
|
+
try {
|
|
1671
|
+
response = await exchangeGrant();
|
|
1672
|
+
}
|
|
1673
|
+
catch (error) {
|
|
1674
|
+
throwIfAborted();
|
|
1675
|
+
if (retryTransientFailure) {
|
|
1676
|
+
throw new RetryablePublishedChatExchangeError();
|
|
1677
|
+
}
|
|
1678
|
+
throw error;
|
|
1679
|
+
}
|
|
1680
|
+
return readConnectionResponse(response, retryTransientFailure);
|
|
1681
|
+
};
|
|
1682
|
+
let connectionData;
|
|
856
1683
|
try {
|
|
857
|
-
|
|
1684
|
+
connectionData = await requestConnection(true);
|
|
858
1685
|
}
|
|
859
1686
|
catch (error) {
|
|
860
1687
|
throwIfAborted();
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
// replay that logical attempt instead of creating a second session.
|
|
864
|
-
exchangeRetried = true;
|
|
865
|
-
response = await exchangeGrant();
|
|
866
|
-
}
|
|
867
|
-
if (!exchangeRetried && response.status >= 500) {
|
|
868
|
-
throwIfAborted();
|
|
869
|
-
response = await exchangeGrant();
|
|
870
|
-
}
|
|
871
|
-
throwIfAborted();
|
|
872
|
-
if (!response.ok) {
|
|
873
|
-
const errorText = await response.text();
|
|
874
|
-
let errorMessage = `HTTP ${response.status}`;
|
|
875
|
-
try {
|
|
876
|
-
const errorData = JSON.parse(errorText);
|
|
877
|
-
this._requestTraceId =
|
|
878
|
-
errorData.request_trace_id ?? errorData.requestTraceId ?? null;
|
|
879
|
-
const raw = errorData.message ?? errorData.error ?? errorData.detail;
|
|
880
|
-
errorMessage =
|
|
881
|
-
typeof raw === "string"
|
|
882
|
-
? raw
|
|
883
|
-
: raw == null
|
|
884
|
-
? errorMessage
|
|
885
|
-
: JSON.stringify(raw);
|
|
886
|
-
}
|
|
887
|
-
catch {
|
|
888
|
-
if (errorText)
|
|
889
|
-
errorMessage = `${errorMessage}: ${errorText}`;
|
|
1688
|
+
if (!(error instanceof RetryablePublishedChatExchangeError)) {
|
|
1689
|
+
throw error;
|
|
890
1690
|
}
|
|
891
|
-
|
|
1691
|
+
// A response can be lost or corrupted after Core consumed the
|
|
1692
|
+
// single-use grant. Retry exactly once with the same attempt key;
|
|
1693
|
+
// Core/Character API replay that logical attempt instead of creating
|
|
1694
|
+
// a second session.
|
|
1695
|
+
connectionData = await requestConnection(false);
|
|
892
1696
|
}
|
|
893
|
-
const connectionData = await response.json();
|
|
894
1697
|
throwIfAborted();
|
|
895
|
-
if (typeof connectionData.room_url !== "string" ||
|
|
896
|
-
typeof connectionData.token !== "string" ||
|
|
897
|
-
typeof connectionData.character_session_id !== "string") {
|
|
898
|
-
throw new Error("Published chat returned an invalid connection response");
|
|
899
|
-
}
|
|
900
1698
|
this._requestTraceId = connectionData.request_trace_id ?? null;
|
|
901
1699
|
this._characterSessionId = connectionData.character_session_id;
|
|
902
1700
|
this._endUserId = connectionData.end_user_id ?? null;
|
|
903
1701
|
this._endUserMetadata = connectionData.end_user_metadata ?? null;
|
|
904
1702
|
await this._room.connect(connectionData.room_url, connectionData.token, {
|
|
905
|
-
rtcConfig: {
|
|
1703
|
+
rtcConfig: {
|
|
1704
|
+
// Hosted Core has TURN, so relay is the safe default. On-prem
|
|
1705
|
+
// deployments without TURN may explicitly allow host/srflx paths.
|
|
1706
|
+
iceTransportPolicy: options.iceTransportPolicy ?? "relay",
|
|
1707
|
+
},
|
|
906
1708
|
});
|
|
907
1709
|
throwIfAborted();
|
|
908
1710
|
this._audioManager.syncStateFromRoom({ emit: true });
|
|
@@ -993,7 +1795,16 @@ export class ConvaiClient extends EventEmitter {
|
|
|
993
1795
|
*/
|
|
994
1796
|
async disconnect() {
|
|
995
1797
|
this._stopClientReadyHandshake();
|
|
996
|
-
|
|
1798
|
+
// Unconditional: the branches below each depend on a transport being
|
|
1799
|
+
// matched, and none of them runs when there is nothing to tear down. A
|
|
1800
|
+
// command in flight must still be settled either way.
|
|
1801
|
+
this._failPendingRosterCommands("Disconnected before the roster command was acknowledged; its outcome is unknown");
|
|
1802
|
+
if (this._activeTransport === "sse" && this._sseSession) {
|
|
1803
|
+
await this._sseSession.disconnect();
|
|
1804
|
+
this._connectionStateHandler.resetConnectionState();
|
|
1805
|
+
this.clearAllManagers();
|
|
1806
|
+
}
|
|
1807
|
+
else if (this._activeTransport === "websocket" && this._wsSession) {
|
|
997
1808
|
this._isDisconnecting = true;
|
|
998
1809
|
try {
|
|
999
1810
|
await this._wsSession.disconnect();
|
|
@@ -1020,6 +1831,15 @@ export class ConvaiClient extends EventEmitter {
|
|
|
1020
1831
|
this.clearAllManagers();
|
|
1021
1832
|
}
|
|
1022
1833
|
}
|
|
1834
|
+
else if (this._state.isConnected || this._state.isConnecting) {
|
|
1835
|
+
// No transport matched, but the client believes it is (or is becoming)
|
|
1836
|
+
// connected -- a connect() that failed after flipping isConnecting, or
|
|
1837
|
+
// was torn down underneath us. Without this branch disconnect() was a
|
|
1838
|
+
// silent no-op here and the flags stayed stuck, so a UI bound to
|
|
1839
|
+
// stateChange kept showing a session that did not exist.
|
|
1840
|
+
this._connectionStateHandler.resetConnectionState();
|
|
1841
|
+
this.clearAllManagers();
|
|
1842
|
+
}
|
|
1023
1843
|
}
|
|
1024
1844
|
/**
|
|
1025
1845
|
* Clear all manager states
|
|
@@ -1028,9 +1848,14 @@ export class ConvaiClient extends EventEmitter {
|
|
|
1028
1848
|
this._connectionType = null;
|
|
1029
1849
|
this._activeTransport = null;
|
|
1030
1850
|
this._wsSession = null;
|
|
1851
|
+
this._failPendingRosterCommands("Disconnected before the roster command was acknowledged; its outcome is unknown");
|
|
1852
|
+
this._roster.reset();
|
|
1853
|
+
this._sseSession = null;
|
|
1031
1854
|
this._apiKey = null;
|
|
1032
1855
|
this._authToken = null;
|
|
1033
1856
|
this._characterId = null;
|
|
1857
|
+
this._characterVersion = null;
|
|
1858
|
+
this._characterReference = null;
|
|
1034
1859
|
this._endUserId = null;
|
|
1035
1860
|
this._endUserMetadata = null;
|
|
1036
1861
|
this._memoryManager = null; // Clear memory manager on disconnect
|
|
@@ -1053,7 +1878,15 @@ export class ConvaiClient extends EventEmitter {
|
|
|
1053
1878
|
* Reset the session ID to start a new conversation
|
|
1054
1879
|
*/
|
|
1055
1880
|
resetSession() {
|
|
1881
|
+
// In a roster room the singular session id is a compatibility mirror of
|
|
1882
|
+
// characters[0], and character sessions are server-owned -- there is no
|
|
1883
|
+
// client-side reset for them. Throwing names the situation; a silent no-op
|
|
1884
|
+
// would look like it worked.
|
|
1885
|
+
if (this._roster.isMultiCharacter) {
|
|
1886
|
+
throw new Error("resetSession() is not supported in a multi-character room; character sessions are server-owned");
|
|
1887
|
+
}
|
|
1056
1888
|
this._characterSessionId = "-1";
|
|
1889
|
+
this.emit("characterSessionId", "-1");
|
|
1057
1890
|
this._messageHandler.reset();
|
|
1058
1891
|
// Clear metrics and disconnect reason when resetting session
|
|
1059
1892
|
this.updateState({ metrics: [], disconnectReason: null });
|
|
@@ -1061,7 +1894,7 @@ export class ConvaiClient extends EventEmitter {
|
|
|
1061
1894
|
/**
|
|
1062
1895
|
* Send a text message to the character
|
|
1063
1896
|
*/
|
|
1064
|
-
sendUserTextMessage(text, options) {
|
|
1897
|
+
sendUserTextMessage(text, options = {}) {
|
|
1065
1898
|
if (!this.isTransportReady())
|
|
1066
1899
|
return;
|
|
1067
1900
|
if (!text || !text.trim())
|
|
@@ -1086,10 +1919,49 @@ export class ConvaiClient extends EventEmitter {
|
|
|
1086
1919
|
userMessage: text.trim(),
|
|
1087
1920
|
timestamp: this._conversationStartTime,
|
|
1088
1921
|
});
|
|
1089
|
-
|
|
1922
|
+
const userTextMessage = {
|
|
1090
1923
|
text: text.trim(),
|
|
1091
1924
|
participant_sid: this._participantSid || this._room.localParticipant?.sid,
|
|
1092
|
-
}
|
|
1925
|
+
};
|
|
1926
|
+
const stateOfMind = normalizeStateOfMind(options.stateOfMind) ?? null;
|
|
1927
|
+
if (stateOfMind || (this._activeTransport === "sse" && options.stateOfMind === null)) {
|
|
1928
|
+
this._stateOfMind = stateOfMind;
|
|
1929
|
+
}
|
|
1930
|
+
if (this._activeTransport === "sse") {
|
|
1931
|
+
const requestedDynamicInfo = options.dynamicInfo?.trim();
|
|
1932
|
+
if (requestedDynamicInfo) {
|
|
1933
|
+
this._sseSession?.updateDynamicInfo(requestedDynamicInfo);
|
|
1934
|
+
}
|
|
1935
|
+
const messages = [];
|
|
1936
|
+
const dynamicInfo = this._sseSession?.getDynamicInfo()?.trim();
|
|
1937
|
+
if (dynamicInfo) {
|
|
1938
|
+
messages.push({
|
|
1939
|
+
type: "update-dynamic-info",
|
|
1940
|
+
data: { dynamic_info: { text: dynamicInfo } },
|
|
1941
|
+
});
|
|
1942
|
+
}
|
|
1943
|
+
if (stateOfMind) {
|
|
1944
|
+
messages.push({ type: "update-emotion", data: { state_of_mind: stateOfMind } });
|
|
1945
|
+
}
|
|
1946
|
+
messages.push({
|
|
1947
|
+
type: "user_text_message",
|
|
1948
|
+
data: userTextMessage,
|
|
1949
|
+
...(logicalTurnId !== undefined ? { id: logicalTurnId } : {}),
|
|
1950
|
+
});
|
|
1951
|
+
this._sseSession?.sendMessages(messages);
|
|
1952
|
+
}
|
|
1953
|
+
else {
|
|
1954
|
+
if (stateOfMind) {
|
|
1955
|
+
this.publishMessage("update-emotion", {
|
|
1956
|
+
state_of_mind: stateOfMind,
|
|
1957
|
+
participant_sid: this._participantSid || this._room.localParticipant?.sid,
|
|
1958
|
+
});
|
|
1959
|
+
}
|
|
1960
|
+
this.publishMessage("user_text_message", userTextMessage, logicalTurnId);
|
|
1961
|
+
}
|
|
1962
|
+
// The submitted line is appended locally on every transport, so it shows
|
|
1963
|
+
// without waiting for a server echo. Sessions that do echo it back as a
|
|
1964
|
+
// final user-transcription are deduplicated in the message handler.
|
|
1093
1965
|
this._messageHandler.addUserTextMessage(text);
|
|
1094
1966
|
}
|
|
1095
1967
|
catch (error) {
|
|
@@ -1100,6 +1972,123 @@ export class ConvaiClient extends EventEmitter {
|
|
|
1100
1972
|
* Return a correlated terminal result for a client-executed tool call.
|
|
1101
1973
|
*/
|
|
1102
1974
|
sendActionResult(result) {
|
|
1975
|
+
const payload = this.buildActionResultPayload(result);
|
|
1976
|
+
this.publishMessage("action-result", payload);
|
|
1977
|
+
}
|
|
1978
|
+
/**
|
|
1979
|
+
* Publish one correlated terminal result and wait for Core's exact
|
|
1980
|
+
* `server-response` acknowledgement. This method performs one publication;
|
|
1981
|
+
* callers own any idempotent retry policy.
|
|
1982
|
+
*/
|
|
1983
|
+
async sendActionResultAndWait(result, options = {}) {
|
|
1984
|
+
const timeoutMs = options.timeoutMs ?? ConvaiClient.ACTION_RESULT_ACK_TIMEOUT_MS;
|
|
1985
|
+
if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
|
|
1986
|
+
throw new Error("Action result acknowledgement timeout must be greater than zero");
|
|
1987
|
+
}
|
|
1988
|
+
if (options.signal?.aborted) {
|
|
1989
|
+
throw new ActionResultAckError("Action result acknowledgement was aborted", {
|
|
1990
|
+
reason: "aborted",
|
|
1991
|
+
toolCallId: result.id,
|
|
1992
|
+
});
|
|
1993
|
+
}
|
|
1994
|
+
const payload = this.buildActionResultPayload(result);
|
|
1995
|
+
const toolCallId = payload.id;
|
|
1996
|
+
if (this._pendingActionResultAcks.has(toolCallId)) {
|
|
1997
|
+
throw new ActionResultAckError(`An action result acknowledgement is already pending for ${toolCallId}`, {
|
|
1998
|
+
reason: "duplicate_in_flight",
|
|
1999
|
+
toolCallId,
|
|
2000
|
+
});
|
|
2001
|
+
}
|
|
2002
|
+
const reservation = Symbol(toolCallId);
|
|
2003
|
+
this._pendingActionResultAcks.set(toolCallId, reservation);
|
|
2004
|
+
return new Promise((resolve, reject) => {
|
|
2005
|
+
let settled = false;
|
|
2006
|
+
let timeout = null;
|
|
2007
|
+
let unsubscribe = null;
|
|
2008
|
+
const cleanup = () => {
|
|
2009
|
+
if (timeout !== null) {
|
|
2010
|
+
clearTimeout(timeout);
|
|
2011
|
+
timeout = null;
|
|
2012
|
+
}
|
|
2013
|
+
if (unsubscribe) {
|
|
2014
|
+
unsubscribe();
|
|
2015
|
+
unsubscribe = null;
|
|
2016
|
+
}
|
|
2017
|
+
options.signal?.removeEventListener("abort", handleAbort);
|
|
2018
|
+
if (this._pendingActionResultAcks.get(toolCallId) === reservation) {
|
|
2019
|
+
this._pendingActionResultAcks.delete(toolCallId);
|
|
2020
|
+
}
|
|
2021
|
+
};
|
|
2022
|
+
const resolveOnce = (ack) => {
|
|
2023
|
+
if (settled)
|
|
2024
|
+
return;
|
|
2025
|
+
settled = true;
|
|
2026
|
+
cleanup();
|
|
2027
|
+
resolve(ack);
|
|
2028
|
+
};
|
|
2029
|
+
const rejectOnce = (error) => {
|
|
2030
|
+
if (settled)
|
|
2031
|
+
return;
|
|
2032
|
+
settled = true;
|
|
2033
|
+
cleanup();
|
|
2034
|
+
reject(error);
|
|
2035
|
+
};
|
|
2036
|
+
const handleAbort = () => {
|
|
2037
|
+
rejectOnce(new ActionResultAckError("Action result acknowledgement was aborted", {
|
|
2038
|
+
reason: "aborted",
|
|
2039
|
+
toolCallId,
|
|
2040
|
+
}));
|
|
2041
|
+
};
|
|
2042
|
+
const handleServerResponse = (response) => {
|
|
2043
|
+
if (!response || typeof response !== "object")
|
|
2044
|
+
return;
|
|
2045
|
+
const candidate = response;
|
|
2046
|
+
if (candidate.event_type !== "action-result")
|
|
2047
|
+
return;
|
|
2048
|
+
const extras = candidate.extras;
|
|
2049
|
+
if (!extras || extras.tool_call_id !== toolCallId)
|
|
2050
|
+
return;
|
|
2051
|
+
const message = typeof candidate.message === "string" ? candidate.message : null;
|
|
2052
|
+
if (candidate.status === "success") {
|
|
2053
|
+
resolveOnce({
|
|
2054
|
+
toolCallId,
|
|
2055
|
+
status: "success",
|
|
2056
|
+
message,
|
|
2057
|
+
idempotent: extras.idempotent === true,
|
|
2058
|
+
});
|
|
2059
|
+
return;
|
|
2060
|
+
}
|
|
2061
|
+
if (candidate.status !== "error")
|
|
2062
|
+
return;
|
|
2063
|
+
const errorCode = typeof extras.error_code === "string" ? extras.error_code : undefined;
|
|
2064
|
+
rejectOnce(new ActionResultAckError(message ?? errorCode ?? "Core rejected the action result", {
|
|
2065
|
+
reason: "server_error",
|
|
2066
|
+
toolCallId,
|
|
2067
|
+
...(errorCode ? { errorCode } : {}),
|
|
2068
|
+
response: candidate,
|
|
2069
|
+
}));
|
|
2070
|
+
};
|
|
2071
|
+
// Register every terminal observer before publication so a synchronous
|
|
2072
|
+
// WebSocket acknowledgement cannot outrun its waiter.
|
|
2073
|
+
unsubscribe = this.on("serverResponse", handleServerResponse);
|
|
2074
|
+
options.signal?.addEventListener("abort", handleAbort, { once: true });
|
|
2075
|
+
timeout = setTimeout(() => {
|
|
2076
|
+
rejectOnce(new ActionResultAckError(`Timed out waiting for action result acknowledgement for ${toolCallId}`, {
|
|
2077
|
+
reason: "timeout",
|
|
2078
|
+
toolCallId,
|
|
2079
|
+
}));
|
|
2080
|
+
}, timeoutMs);
|
|
2081
|
+
void this.publishMessageAndWaitForLocalPublication("action-result", payload).catch((cause) => {
|
|
2082
|
+
const detail = cause instanceof Error ? `: ${cause.message}` : "";
|
|
2083
|
+
rejectOnce(new ActionResultAckError(`Failed to publish action result ${toolCallId}${detail}`, {
|
|
2084
|
+
reason: "publication_error",
|
|
2085
|
+
toolCallId,
|
|
2086
|
+
cause,
|
|
2087
|
+
}));
|
|
2088
|
+
});
|
|
2089
|
+
});
|
|
2090
|
+
}
|
|
2091
|
+
buildActionResultPayload(result) {
|
|
1103
2092
|
if (!this.isTransportReady()) {
|
|
1104
2093
|
throw new Error("Cannot send an action result before the session is ready");
|
|
1105
2094
|
}
|
|
@@ -1119,17 +2108,17 @@ export class ConvaiClient extends EventEmitter {
|
|
|
1119
2108
|
if (result.error !== undefined && !isJsonValue(result.error)) {
|
|
1120
2109
|
throw new Error("Action result error must contain only finite JSON values");
|
|
1121
2110
|
}
|
|
1122
|
-
const
|
|
2111
|
+
const characterSessionId = result.characterSessionId ?? this._characterSessionId;
|
|
2112
|
+
return {
|
|
1123
2113
|
id: result.id,
|
|
1124
2114
|
status: result.status,
|
|
1125
2115
|
...(result.output !== undefined && { output: result.output }),
|
|
1126
2116
|
...(result.error !== undefined && { error: result.error }),
|
|
1127
|
-
...(
|
|
1128
|
-
|
|
1129
|
-
character_session_id:
|
|
2117
|
+
...(characterSessionId &&
|
|
2118
|
+
characterSessionId !== "-1" && {
|
|
2119
|
+
character_session_id: characterSessionId,
|
|
1130
2120
|
}),
|
|
1131
2121
|
};
|
|
1132
|
-
this.publishMessage("action-result", payload);
|
|
1133
2122
|
}
|
|
1134
2123
|
/**
|
|
1135
2124
|
* Send a trigger message to invoke specific character actions
|
|
@@ -1196,9 +2185,15 @@ export class ConvaiClient extends EventEmitter {
|
|
|
1196
2185
|
if (!this.isTransportReady())
|
|
1197
2186
|
return;
|
|
1198
2187
|
try {
|
|
1199
|
-
this.
|
|
1200
|
-
|
|
1201
|
-
|
|
2188
|
+
if (this._activeTransport === "sse" && this._sseSession?.isConnected) {
|
|
2189
|
+
this._sseSession.interrupt();
|
|
2190
|
+
this._messageHandler.finalizeInterruptedResponse(true);
|
|
2191
|
+
}
|
|
2192
|
+
else {
|
|
2193
|
+
this.publishMessage("interrupt-bot", {
|
|
2194
|
+
participant_sid: this._participantSid || this._room.localParticipant?.sid,
|
|
2195
|
+
});
|
|
2196
|
+
}
|
|
1202
2197
|
// Stop local lipsync immediately for every transport. WebSocket can also
|
|
1203
2198
|
// buffer ahead-delivered frames, and waiting for a server cancel leaves
|
|
1204
2199
|
// stale mouth animation visible after the audio stop.
|
|
@@ -1231,8 +2226,16 @@ export class ConvaiClient extends EventEmitter {
|
|
|
1231
2226
|
updateDynamicInfo(dynamicInfo) {
|
|
1232
2227
|
if (!this.isTransportReady() || !dynamicInfo?.trim())
|
|
1233
2228
|
return;
|
|
2229
|
+
const nextDynamicInfo = dynamicInfo.trim();
|
|
2230
|
+
if (this._storedConfig) {
|
|
2231
|
+
this._storedConfig = { ...this._storedConfig, dynamicInfo: nextDynamicInfo };
|
|
2232
|
+
}
|
|
2233
|
+
if (this._activeTransport === "sse" && this._sseSession) {
|
|
2234
|
+
this._sseSession.updateDynamicInfo(nextDynamicInfo);
|
|
2235
|
+
return;
|
|
2236
|
+
}
|
|
1234
2237
|
this.publishMessage("update-dynamic-info", {
|
|
1235
|
-
dynamic_info: { text:
|
|
2238
|
+
dynamic_info: { text: nextDynamicInfo },
|
|
1236
2239
|
participant_sid: this._participantSid || this._room.localParticipant?.sid,
|
|
1237
2240
|
});
|
|
1238
2241
|
}
|
|
@@ -1280,6 +2283,22 @@ export class ConvaiClient extends EventEmitter {
|
|
|
1280
2283
|
if (shouldPreemptLipsync) {
|
|
1281
2284
|
this.startTrackedConversation(`[context-update:${options.mode ?? "append"}]`);
|
|
1282
2285
|
}
|
|
2286
|
+
if (this._activeTransport === "sse" && this._sseSession) {
|
|
2287
|
+
const data = {
|
|
2288
|
+
...(hasText && { text: options.text.trim() }),
|
|
2289
|
+
...(options.mode && { mode: options.mode }),
|
|
2290
|
+
...(options.run_llm && { run_llm: options.run_llm }),
|
|
2291
|
+
...(options.respond_mode && { respond_mode: options.respond_mode }),
|
|
2292
|
+
...(hasAttention && { current_attention_object: options.current_attention_object }),
|
|
2293
|
+
};
|
|
2294
|
+
if (options.run_llm === "false") {
|
|
2295
|
+
this._sseSession.queueMessage("context-update", data);
|
|
2296
|
+
}
|
|
2297
|
+
else {
|
|
2298
|
+
this._sseSession.sendMessage("context-update", data);
|
|
2299
|
+
}
|
|
2300
|
+
return;
|
|
2301
|
+
}
|
|
1283
2302
|
this.publishMessage("context-update", {
|
|
1284
2303
|
...(hasText && { text: options.text.trim() }),
|
|
1285
2304
|
...(options.mode && { mode: options.mode }),
|
|
@@ -1341,6 +2360,8 @@ export class ConvaiClient extends EventEmitter {
|
|
|
1341
2360
|
}
|
|
1342
2361
|
if (!this.isTransportReady())
|
|
1343
2362
|
return;
|
|
2363
|
+
if (this._activeTransport === "sse")
|
|
2364
|
+
return;
|
|
1344
2365
|
this.publishMessage("update-emotion", {
|
|
1345
2366
|
state_of_mind: normalized,
|
|
1346
2367
|
participant_sid: this._participantSid || this._room.localParticipant?.sid,
|
|
@@ -1422,6 +2443,10 @@ export class ConvaiClient extends EventEmitter {
|
|
|
1422
2443
|
* the session from being disconnected due to inactivity.
|
|
1423
2444
|
*/
|
|
1424
2445
|
resetIdleTimer() {
|
|
2446
|
+
// SSE requests are one-turn streams; there is no persistent server-side
|
|
2447
|
+
// realtime session for an idle timer to keep alive.
|
|
2448
|
+
if (this._activeTransport === "sse")
|
|
2449
|
+
return;
|
|
1425
2450
|
if (!this.isTransportReady())
|
|
1426
2451
|
return;
|
|
1427
2452
|
this.publishMessage("reset-idle-timer", {
|
|
@@ -1431,4 +2456,18 @@ export class ConvaiClient extends EventEmitter {
|
|
|
1431
2456
|
}
|
|
1432
2457
|
ConvaiClient.CLIENT_READY_RETRY_MS = 500;
|
|
1433
2458
|
ConvaiClient.CLIENT_READY_TIMEOUT_MS = 45000;
|
|
2459
|
+
ConvaiClient.ACTION_RESULT_ACK_TIMEOUT_MS = 10000;
|
|
2460
|
+
/**
|
|
2461
|
+
* How long to wait for a roster command's ack.
|
|
2462
|
+
*
|
|
2463
|
+
* A timeout is *not* a failure. Every character participant observes the
|
|
2464
|
+
* broadcast and duplicate forwards are response-suppressed after one actor
|
|
2465
|
+
* answers, so a lost ack is an expected outcome. The contract's rule is to
|
|
2466
|
+
* treat it as unknown and reconcile from the next authoritative snapshot,
|
|
2467
|
+
* which is what the rejection below tells the caller to do.
|
|
2468
|
+
*/
|
|
2469
|
+
ConvaiClient.ROSTER_COMMAND_TIMEOUT_MS = 10000;
|
|
2470
|
+
/** Default bounded retry while a roster room is still provisioning. */
|
|
2471
|
+
ConvaiClient.ROSTER_RETRY_ATTEMPTS = 4;
|
|
2472
|
+
ConvaiClient.ROSTER_RETRY_INITIAL_MS = 500;
|
|
1434
2473
|
//# sourceMappingURL=ConvaiClient.js.map
|