@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
|
@@ -1,8 +1,24 @@
|
|
|
1
1
|
import { RoomEvent } from "livekit-client";
|
|
2
2
|
import { EventEmitter } from "./EventEmitter.js";
|
|
3
3
|
import { extractModelOutputPayload, parseModelOutputMessage, } from "./modelOutput.js";
|
|
4
|
-
import { isValidLogicalTurnId } from "./logicalTurn.js";
|
|
4
|
+
import { isValidLogicalTurnId, isValidOutputId } from "./logicalTurn.js";
|
|
5
5
|
import { BlendshapeQueue, } from "./BlendshapeQueue.js";
|
|
6
|
+
function stableJsonFingerprint(value) {
|
|
7
|
+
if (Array.isArray(value)) {
|
|
8
|
+
return `[${value.map(stableJsonFingerprint).join(",")}]`;
|
|
9
|
+
}
|
|
10
|
+
if (value && typeof value === "object") {
|
|
11
|
+
const entries = Object.entries(value)
|
|
12
|
+
.sort(([left], [right]) => left.localeCompare(right))
|
|
13
|
+
.map(([key, item]) => `${JSON.stringify(key)}:${stableJsonFingerprint(item)}`);
|
|
14
|
+
return `{${entries.join(",")}}`;
|
|
15
|
+
}
|
|
16
|
+
return JSON.stringify(value);
|
|
17
|
+
}
|
|
18
|
+
const MAX_MODEL_OUTPUT_REPLAY_FINGERPRINTS = 400;
|
|
19
|
+
// Preserve exact replay matching instead of accepting hash collisions, while
|
|
20
|
+
// bounding the aggregate strings retained by a long-lived v2 session.
|
|
21
|
+
const MAX_MODEL_OUTPUT_REPLAY_RETAINED_CHARS = 4 * 1024 * 1024;
|
|
6
22
|
/**
|
|
7
23
|
* Handles incoming messages from Convai
|
|
8
24
|
* Processes various message types from the AI assistant and updates chat history
|
|
@@ -12,6 +28,7 @@ export class MessageHandler extends EventEmitter {
|
|
|
12
28
|
super();
|
|
13
29
|
this.room = null;
|
|
14
30
|
this.chatMessages = [];
|
|
31
|
+
this.activeBotLlmMessageId = null;
|
|
15
32
|
this.userTranscription = "";
|
|
16
33
|
this.logRtviMessages = true;
|
|
17
34
|
this.isBotResponding = false;
|
|
@@ -20,7 +37,8 @@ export class MessageHandler extends EventEmitter {
|
|
|
20
37
|
this.totalBlendshapesReceived = 0;
|
|
21
38
|
this._currentEmotion = null;
|
|
22
39
|
this.modelOutputVersion = 1;
|
|
23
|
-
this.
|
|
40
|
+
this.seenModelOutputPayloads = new Set();
|
|
41
|
+
this.seenModelOutputPayloadCharacters = 0;
|
|
24
42
|
// bot-output segments already added to the chat. The server re-sends the
|
|
25
43
|
// same segment (full text) as TTS progress advances (spoken_status
|
|
26
44
|
// in-progress → completed); only the first sighting may touch the chat.
|
|
@@ -46,7 +64,7 @@ export class MessageHandler extends EventEmitter {
|
|
|
46
64
|
/** Select the server-negotiated canonical output version for this session. */
|
|
47
65
|
setModelOutputVersion(version) {
|
|
48
66
|
this.modelOutputVersion = version;
|
|
49
|
-
this.
|
|
67
|
+
this._clearModelOutputReplayLedger();
|
|
50
68
|
}
|
|
51
69
|
/**
|
|
52
70
|
* Get current chat messages
|
|
@@ -98,6 +116,52 @@ export class MessageHandler extends EventEmitter {
|
|
|
98
116
|
this.emit("speakingChange", false);
|
|
99
117
|
}
|
|
100
118
|
}
|
|
119
|
+
/**
|
|
120
|
+
* Finalize local response state after the client intentionally aborts a
|
|
121
|
+
* transport before the server can deliver its terminal response frame.
|
|
122
|
+
*/
|
|
123
|
+
finalizeInterruptedResponse(finalizeAll = false) {
|
|
124
|
+
const finalizedMessages = this.finalizeStreamingBotMessages(finalizeAll);
|
|
125
|
+
this.isBotResponding = false;
|
|
126
|
+
this.emit("botRespondingChange", false);
|
|
127
|
+
if (finalizedMessages.length > 0) {
|
|
128
|
+
this.emit("messagesChange", this.chatMessages, undefined, finalizedMessages);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
finalizeStreamingBotMessages(finalizeAll = this.modelOutputVersion === 2) {
|
|
132
|
+
const finalizedMessages = [];
|
|
133
|
+
if (finalizeAll) {
|
|
134
|
+
for (let index = 0; index < this.chatMessages.length; index++) {
|
|
135
|
+
const message = this.chatMessages[index];
|
|
136
|
+
if ((message.type === "bot-llm-text" || message.type === "bot-output") &&
|
|
137
|
+
message.isStreaming) {
|
|
138
|
+
const finalizedMessage = {
|
|
139
|
+
...message,
|
|
140
|
+
isStreaming: false,
|
|
141
|
+
};
|
|
142
|
+
this.chatMessages[index] = finalizedMessage;
|
|
143
|
+
finalizedMessages.push(finalizedMessage);
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
else {
|
|
148
|
+
let stopIndex = this.activeBotLlmMessageId
|
|
149
|
+
? this.chatMessages.findIndex((message) => message.id === this.activeBotLlmMessageId)
|
|
150
|
+
: -1;
|
|
151
|
+
if (stopIndex === -1)
|
|
152
|
+
stopIndex = this.chatMessages.length - 1;
|
|
153
|
+
const lastBotMsg = this.chatMessages[stopIndex];
|
|
154
|
+
if (lastBotMsg &&
|
|
155
|
+
(lastBotMsg.type === "bot-llm-text" ||
|
|
156
|
+
lastBotMsg.type === "bot-output") &&
|
|
157
|
+
lastBotMsg.isStreaming) {
|
|
158
|
+
const finalizedMessage = { ...lastBotMsg, isStreaming: false };
|
|
159
|
+
this.chatMessages[stopIndex] = finalizedMessage;
|
|
160
|
+
finalizedMessages.push(finalizedMessage);
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
return finalizedMessages;
|
|
164
|
+
}
|
|
101
165
|
/**
|
|
102
166
|
* Set the LiveKit room instance
|
|
103
167
|
*/
|
|
@@ -128,7 +192,7 @@ export class MessageHandler extends EventEmitter {
|
|
|
128
192
|
/**
|
|
129
193
|
* Handle incoming data message
|
|
130
194
|
*/
|
|
131
|
-
handleDataReceived(payload, _participant,
|
|
195
|
+
handleDataReceived(payload, _participant, transport = "livekit") {
|
|
132
196
|
let messageString = "";
|
|
133
197
|
let parsed = false;
|
|
134
198
|
try {
|
|
@@ -148,6 +212,23 @@ export class MessageHandler extends EventEmitter {
|
|
|
148
212
|
// Extract and categorize messages for chat display
|
|
149
213
|
const timestamp = new Date().toISOString();
|
|
150
214
|
const messageId = `${messageData.type}-${Date.now()}-${Math.random()}`;
|
|
215
|
+
// Multi-character routing identity, carried inline on every
|
|
216
|
+
// character-originated event. Undefined in single-character sessions, so
|
|
217
|
+
// these spread to nothing and every existing message keeps its shape.
|
|
218
|
+
const attribution = {
|
|
219
|
+
...(messageData.data?.membership_id && {
|
|
220
|
+
membershipId: messageData.data.membership_id,
|
|
221
|
+
}),
|
|
222
|
+
...(messageData.data?.character_id && {
|
|
223
|
+
characterId: messageData.data.character_id,
|
|
224
|
+
}),
|
|
225
|
+
};
|
|
226
|
+
/**
|
|
227
|
+
* Two instances must never share a streaming bubble. Without this a
|
|
228
|
+
* target switch mid-turn splices one character's text onto another's,
|
|
229
|
+
* because the merge would only be checking `isStreaming`.
|
|
230
|
+
*/
|
|
231
|
+
const sameSpeaker = (msg) => !!msg && msg.membershipId === attribution.membershipId;
|
|
151
232
|
// Handle different message types
|
|
152
233
|
switch (messageData.type) {
|
|
153
234
|
// Submitted text is appended locally by sendUserTextMessage. Ignore
|
|
@@ -164,21 +245,40 @@ export class MessageHandler extends EventEmitter {
|
|
|
164
245
|
break;
|
|
165
246
|
// Bot Ready - Bot is ready, connection should be true
|
|
166
247
|
case "bot-ready":
|
|
167
|
-
this
|
|
248
|
+
// `about` carries this instance's routing identity in a roster room,
|
|
249
|
+
// and the same fields are also flattened onto `data`. Prefer `about`,
|
|
250
|
+
// fall back to the flattened copy, and pass undefined for a
|
|
251
|
+
// single-character session.
|
|
252
|
+
this.emit("botReady", messageData.data?.about ??
|
|
253
|
+
(messageData.data?.membership_id ? messageData.data : undefined));
|
|
168
254
|
break;
|
|
169
255
|
// Bot LLM Started - Begin streaming response
|
|
170
256
|
case "bot-llm-started":
|
|
171
257
|
this.isBotResponding = true;
|
|
172
258
|
this.emit("botRespondingChange", true);
|
|
173
259
|
this.seenBotOutputSegments.clear();
|
|
174
|
-
//
|
|
260
|
+
// Lifecycle frames do not carry output_id. In v2 or SSE, keep at most one
|
|
261
|
+
// unowned placeholder so concurrent starts cannot create anonymous
|
|
262
|
+
// rows that later get adopted in reverse order. Invocation-correlated
|
|
263
|
+
// chunks establish additional rows in authoritative arrival order.
|
|
264
|
+
const hasUnownedCorrelatedStarter = (this.modelOutputVersion === 2 || transport === "sse") &&
|
|
265
|
+
this.chatMessages.some((message) => message.type === "bot-llm-text" &&
|
|
266
|
+
message.isStreaming &&
|
|
267
|
+
message.content === "" &&
|
|
268
|
+
message.outputId === undefined &&
|
|
269
|
+
message.logicalTurnId === undefined);
|
|
270
|
+
if (hasUnownedCorrelatedStarter)
|
|
271
|
+
break;
|
|
272
|
+
// Add initial streaming message to chat.
|
|
175
273
|
const streamingMessage = {
|
|
176
274
|
id: messageId,
|
|
177
275
|
type: "bot-llm-text",
|
|
178
276
|
content: "",
|
|
179
277
|
timestamp: timestamp,
|
|
180
278
|
isStreaming: true,
|
|
279
|
+
...attribution,
|
|
181
280
|
};
|
|
281
|
+
this.activeBotLlmMessageId = messageId;
|
|
182
282
|
this.chatMessages.push(streamingMessage);
|
|
183
283
|
this.emit("messagesChange", this.chatMessages);
|
|
184
284
|
break;
|
|
@@ -205,17 +305,24 @@ export class MessageHandler extends EventEmitter {
|
|
|
205
305
|
break;
|
|
206
306
|
this.seenBotOutputSegments.add(segmentId);
|
|
207
307
|
}
|
|
308
|
+
const activeBotLlmMessage = this.activeBotLlmMessageId
|
|
309
|
+
? this.chatMessages.find((message) => message.id === this.activeBotLlmMessageId)
|
|
310
|
+
: undefined;
|
|
208
311
|
const lastMsg = this.chatMessages[this.chatMessages.length - 1];
|
|
209
312
|
// When the reply is rendered by the LLM text stream
|
|
210
313
|
// (bot-llm-text), the TTS echo adds nothing — never mix
|
|
211
314
|
// bot-output into an LLM bubble (streaming or complete).
|
|
315
|
+
if (activeBotLlmMessage?.type === "bot-llm-text")
|
|
316
|
+
break;
|
|
212
317
|
if (lastMsg?.type === "bot-llm-text")
|
|
213
318
|
break;
|
|
214
319
|
if (lastMsg?.type === "bot-output" &&
|
|
215
320
|
lastMsg.content.includes(newText)) {
|
|
216
321
|
break;
|
|
217
322
|
}
|
|
218
|
-
if (lastMsg?.type === "bot-output" &&
|
|
323
|
+
if (lastMsg?.type === "bot-output" &&
|
|
324
|
+
lastMsg.isStreaming &&
|
|
325
|
+
sameSpeaker(lastMsg)) {
|
|
219
326
|
this.chatMessages[this.chatMessages.length - 1] = {
|
|
220
327
|
...lastMsg,
|
|
221
328
|
content: lastMsg.content + newText,
|
|
@@ -228,6 +335,7 @@ export class MessageHandler extends EventEmitter {
|
|
|
228
335
|
content: newText,
|
|
229
336
|
timestamp: new Date().toISOString(),
|
|
230
337
|
isStreaming: true,
|
|
338
|
+
...attribution,
|
|
231
339
|
});
|
|
232
340
|
}
|
|
233
341
|
this.emit("messagesChange", this.chatMessages);
|
|
@@ -237,42 +345,175 @@ export class MessageHandler extends EventEmitter {
|
|
|
237
345
|
case "bot-llm-text":
|
|
238
346
|
if (messageData.data?.text) {
|
|
239
347
|
const newChunk = messageData.data.text;
|
|
240
|
-
//
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
348
|
+
// Core's Interaction API/SSE path can carry logical-turn metadata
|
|
349
|
+
// before hosts opt into the full model-output v2 contract. Preserve
|
|
350
|
+
// it for SSE rows so callers can correlate legacy/default text
|
|
351
|
+
// completions without changing LiveKit's historical v1 shape.
|
|
352
|
+
const acceptsSseCorrelation = transport === "sse";
|
|
353
|
+
const outputId = (this.modelOutputVersion === 2 || acceptsSseCorrelation) &&
|
|
354
|
+
isValidOutputId(messageData.data.output_id)
|
|
355
|
+
? messageData.data.output_id
|
|
356
|
+
: undefined;
|
|
357
|
+
const logicalTurnId = (this.modelOutputVersion === 2 || acceptsSseCorrelation) &&
|
|
358
|
+
isValidLogicalTurnId(messageData.data.logical_turn_id)
|
|
359
|
+
? messageData.data.logical_turn_id
|
|
360
|
+
: undefined;
|
|
361
|
+
// A logical turn can contain multiple provider invocations (for
|
|
362
|
+
// example, the response before a tool call and the continuation
|
|
363
|
+
// after its result). Prefer the invocation id, then fall back to
|
|
364
|
+
// the older v2 logical-turn id when Core does not send one.
|
|
365
|
+
let targetMessageIndex = -1;
|
|
366
|
+
if (outputId !== undefined) {
|
|
367
|
+
for (let index = this.chatMessages.length - 1; index >= 0; index--) {
|
|
368
|
+
const message = this.chatMessages[index];
|
|
369
|
+
if (message.type === "bot-llm-text" &&
|
|
370
|
+
message.isStreaming &&
|
|
371
|
+
message.outputId === outputId &&
|
|
372
|
+
sameSpeaker(message)) {
|
|
373
|
+
targetMessageIndex = index;
|
|
374
|
+
break;
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
// bot-llm-started has no correlation metadata. Let one empty,
|
|
378
|
+
// unowned row adopt the first authoritative invocation id.
|
|
379
|
+
if (targetMessageIndex === -1) {
|
|
380
|
+
for (let index = this.chatMessages.length - 1; index >= 0; index--) {
|
|
381
|
+
const message = this.chatMessages[index];
|
|
382
|
+
if (message.type === "bot-llm-text" &&
|
|
383
|
+
message.isStreaming &&
|
|
384
|
+
message.content === "" &&
|
|
385
|
+
message.outputId === undefined &&
|
|
386
|
+
message.logicalTurnId === undefined &&
|
|
387
|
+
sameSpeaker(message)) {
|
|
388
|
+
targetMessageIndex = index;
|
|
389
|
+
break;
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
else if (logicalTurnId !== undefined) {
|
|
395
|
+
for (let index = this.chatMessages.length - 1; index >= 0; index--) {
|
|
396
|
+
const message = this.chatMessages[index];
|
|
397
|
+
if (message.type === "bot-llm-text" &&
|
|
398
|
+
message.isStreaming &&
|
|
399
|
+
message.outputId === undefined &&
|
|
400
|
+
message.logicalTurnId === logicalTurnId &&
|
|
401
|
+
sameSpeaker(message)) {
|
|
402
|
+
targetMessageIndex = index;
|
|
403
|
+
break;
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
// Older v2 Core still needs the starter-row behavior that was
|
|
407
|
+
// introduced with logical-turn correlation.
|
|
408
|
+
if (targetMessageIndex === -1) {
|
|
409
|
+
const lastIndex = this.chatMessages.length - 1;
|
|
410
|
+
const lastMessage = this.chatMessages[lastIndex];
|
|
411
|
+
if (lastMessage?.type === "bot-llm-text" &&
|
|
412
|
+
lastMessage.isStreaming &&
|
|
413
|
+
lastMessage.content === "" &&
|
|
414
|
+
lastMessage.outputId === undefined &&
|
|
415
|
+
lastMessage.logicalTurnId === undefined &&
|
|
416
|
+
sameSpeaker(lastMessage)) {
|
|
417
|
+
targetMessageIndex = lastIndex;
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
else {
|
|
422
|
+
// Uncorrelated (v1) chunk: it belongs to the bubble bot-llm-started
|
|
423
|
+
// opened for this speaker. Only when no such bubble exists does the
|
|
424
|
+
// historical "last streaming row" rule apply -- and still only for
|
|
425
|
+
// the same speaker, so a target switch mid-turn cannot splice one
|
|
426
|
+
// member's text onto another's row.
|
|
427
|
+
// Ownership applies among uncorrelated rows only: an uncorrelated
|
|
428
|
+
// chunk must never join a row that carries an output or turn id,
|
|
429
|
+
// or a v2 correlated stream would absorb legacy text.
|
|
430
|
+
if (this.activeBotLlmMessageId) {
|
|
431
|
+
targetMessageIndex = this.chatMessages.findIndex((message) => message.id === this.activeBotLlmMessageId &&
|
|
432
|
+
message.type === "bot-llm-text" &&
|
|
433
|
+
message.isStreaming &&
|
|
434
|
+
!message.outputId &&
|
|
435
|
+
!message.logicalTurnId &&
|
|
436
|
+
sameSpeaker(message));
|
|
437
|
+
}
|
|
438
|
+
if (targetMessageIndex === -1) {
|
|
439
|
+
const lastIndex = this.chatMessages.length - 1;
|
|
440
|
+
const lastMessage = this.chatMessages[lastIndex];
|
|
441
|
+
if (lastMessage &&
|
|
442
|
+
lastMessage.type === "bot-llm-text" &&
|
|
443
|
+
lastMessage.isStreaming &&
|
|
444
|
+
!lastMessage.outputId &&
|
|
445
|
+
!lastMessage.logicalTurnId &&
|
|
446
|
+
sameSpeaker(lastMessage)) {
|
|
447
|
+
targetMessageIndex = lastIndex;
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
let updatedMessage;
|
|
452
|
+
if (targetMessageIndex !== -1) {
|
|
453
|
+
const targetMessage = this.chatMessages[targetMessageIndex];
|
|
454
|
+
updatedMessage = {
|
|
455
|
+
...targetMessage,
|
|
456
|
+
content: targetMessage.content + newChunk,
|
|
457
|
+
...(outputId !== undefined &&
|
|
458
|
+
targetMessage.outputId === undefined
|
|
459
|
+
? { outputId }
|
|
460
|
+
: {}),
|
|
461
|
+
...(logicalTurnId !== undefined &&
|
|
462
|
+
targetMessage.logicalTurnId === undefined
|
|
463
|
+
? { logicalTurnId }
|
|
464
|
+
: {}),
|
|
246
465
|
};
|
|
466
|
+
this.chatMessages[targetMessageIndex] = updatedMessage;
|
|
247
467
|
}
|
|
248
468
|
else {
|
|
249
469
|
// If no streaming message exists yet, create one
|
|
250
|
-
|
|
470
|
+
updatedMessage = {
|
|
251
471
|
id: `${messageData.type}-${Date.now()}-${Math.random()}`,
|
|
252
472
|
type: "bot-llm-text",
|
|
253
473
|
content: newChunk,
|
|
254
474
|
timestamp: new Date().toISOString(),
|
|
255
475
|
isStreaming: true,
|
|
476
|
+
...(outputId ? { outputId } : {}),
|
|
477
|
+
...(logicalTurnId ? { logicalTurnId } : {}),
|
|
478
|
+
...attribution,
|
|
256
479
|
};
|
|
257
|
-
this.
|
|
480
|
+
this.activeBotLlmMessageId = updatedMessage.id;
|
|
481
|
+
this.chatMessages.push(updatedMessage);
|
|
258
482
|
}
|
|
259
|
-
this.emit("messagesChange", this.chatMessages);
|
|
483
|
+
this.emit("messagesChange", this.chatMessages, updatedMessage);
|
|
260
484
|
}
|
|
261
485
|
break;
|
|
486
|
+
// Parallel diagnostics-only provider output. This must never affect
|
|
487
|
+
// normal chat, speech, TTS, or response lifecycle state.
|
|
488
|
+
case "bot-llm-text-raw":
|
|
489
|
+
this._handleBotLlmTextRaw(messageData.data);
|
|
490
|
+
break;
|
|
262
491
|
// Bot LLM Stopped - Complete streaming response
|
|
263
|
-
case "bot-llm-stopped":
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
...lastBotMsg,
|
|
268
|
-
isStreaming: false,
|
|
269
|
-
};
|
|
270
|
-
}
|
|
492
|
+
case "bot-llm-stopped": {
|
|
493
|
+
// A v2 response can have interleaved correlated rows. The stop event
|
|
494
|
+
// is response-scoped, so none may remain open for later chunks.
|
|
495
|
+
const finalizedMessages = this.finalizeStreamingBotMessages();
|
|
271
496
|
// Clear streaming state
|
|
272
497
|
this.isBotResponding = false;
|
|
273
498
|
this.emit("botRespondingChange", false);
|
|
274
|
-
|
|
499
|
+
// Keep the full-list event at one emission per stop while carrying
|
|
500
|
+
// every v2 terminal delta for singular-message consumers.
|
|
501
|
+
this.emit("messagesChange", this.chatMessages, undefined, finalizedMessages);
|
|
502
|
+
break;
|
|
503
|
+
}
|
|
504
|
+
// Text-only Interactions API terminal marker. This is deliberately a
|
|
505
|
+
// separate event: a completed REST turn must not be represented as a
|
|
506
|
+
// synthetic bot-llm-stopped message.
|
|
507
|
+
case "bot-turn-completed": {
|
|
508
|
+
const finalizedMessages = this.finalizeStreamingBotMessages(transport === "sse");
|
|
509
|
+
if (finalizedMessages.length > 0) {
|
|
510
|
+
this.emit("messagesChange", this.chatMessages, undefined, finalizedMessages);
|
|
511
|
+
}
|
|
512
|
+
this.isBotResponding = false;
|
|
513
|
+
this.emit("botRespondingChange", false);
|
|
514
|
+
this.emit("botTurnCompleted", messageData.data ?? {});
|
|
275
515
|
break;
|
|
516
|
+
}
|
|
276
517
|
// User Transcription Messages
|
|
277
518
|
case "user-transcription":
|
|
278
519
|
if (messageData.data?.text) {
|
|
@@ -281,6 +522,14 @@ export class MessageHandler extends EventEmitter {
|
|
|
281
522
|
const logicalTurnId = this.transcriptionLogicalTurnId(messageData.data.logical_turn_id);
|
|
282
523
|
// Final transcription - accumulate in single bubble until bot responds
|
|
283
524
|
const lastUserMsg = this.chatMessages[this.chatMessages.length - 1];
|
|
525
|
+
// A final transcription identical to the line appended locally on send is
|
|
526
|
+
// the server echoing that send back: drop it, or the user sees it twice.
|
|
527
|
+
if (lastUserMsg?.type === "user-llm-text" &&
|
|
528
|
+
lastUserMsg.content.trim() === String(messageContent).trim()) {
|
|
529
|
+
this.userTranscription = "";
|
|
530
|
+
this.emit("userTranscriptionChange", "");
|
|
531
|
+
break;
|
|
532
|
+
}
|
|
284
533
|
// Check if last message is an accumulating user message (isStreaming=true)
|
|
285
534
|
if (lastUserMsg &&
|
|
286
535
|
lastUserMsg.type === "user-transcription" &&
|
|
@@ -325,7 +574,8 @@ export class MessageHandler extends EventEmitter {
|
|
|
325
574
|
emotion: messageData.data.emotion,
|
|
326
575
|
scale: messageData.data.scale,
|
|
327
576
|
};
|
|
328
|
-
|
|
577
|
+
if (this.logRtviMessages)
|
|
578
|
+
console.log("[SDK bot-emotion]", messageData.data);
|
|
329
579
|
this.emit("emotionChange", this._currentEmotion);
|
|
330
580
|
const emotionMessage = {
|
|
331
581
|
id: messageId,
|
|
@@ -399,6 +649,14 @@ export class MessageHandler extends EventEmitter {
|
|
|
399
649
|
this.emit("metrics", messageData.data);
|
|
400
650
|
}
|
|
401
651
|
break;
|
|
652
|
+
// Per-turn usage/cost breakdown. Informational only: the server streams
|
|
653
|
+
// it once the client opts in with usage-toggle, and it never affects
|
|
654
|
+
// server-side usage tracking or billing.
|
|
655
|
+
case "usage-update":
|
|
656
|
+
if (messageData.data) {
|
|
657
|
+
this.emit("usageUpdate", messageData.data);
|
|
658
|
+
}
|
|
659
|
+
break;
|
|
402
660
|
// Behavior Tree Response Messages
|
|
403
661
|
case "behavior-tree-response":
|
|
404
662
|
if (messageData.data?.narrative_section_id) {
|
|
@@ -417,11 +675,22 @@ export class MessageHandler extends EventEmitter {
|
|
|
417
675
|
if (messageData.data) {
|
|
418
676
|
const serverData = messageData.data;
|
|
419
677
|
switch (serverData.type) {
|
|
678
|
+
case "bot-llm-text-raw":
|
|
679
|
+
this._handleBotLlmTextRaw(serverData.data ?? serverData);
|
|
680
|
+
break;
|
|
420
681
|
case "final-user-transcription":
|
|
421
682
|
if (serverData.text) {
|
|
422
683
|
const finalText = serverData.text;
|
|
423
684
|
const logicalTurnId = this.transcriptionLogicalTurnId(serverData.logical_turn_id);
|
|
424
685
|
const lastUserMsg = this.chatMessages[this.chatMessages.length - 1];
|
|
686
|
+
// A final transcription identical to the line appended locally on send is
|
|
687
|
+
// the server echoing that send back: drop it, or the user sees it twice.
|
|
688
|
+
if (lastUserMsg?.type === "user-llm-text" &&
|
|
689
|
+
lastUserMsg.content.trim() === String(finalText).trim()) {
|
|
690
|
+
this.userTranscription = "";
|
|
691
|
+
this.emit("userTranscriptionChange", "");
|
|
692
|
+
break;
|
|
693
|
+
}
|
|
425
694
|
if (lastUserMsg &&
|
|
426
695
|
lastUserMsg.type === "user-transcription" &&
|
|
427
696
|
lastUserMsg.isStreaming === true) {
|
|
@@ -459,7 +728,8 @@ export class MessageHandler extends EventEmitter {
|
|
|
459
728
|
emotion: serverData.emotion,
|
|
460
729
|
scale: serverData.scale,
|
|
461
730
|
};
|
|
462
|
-
|
|
731
|
+
if (this.logRtviMessages)
|
|
732
|
+
console.log("[SDK bot-emotion (ws)]", serverData);
|
|
463
733
|
this.emit("emotionChange", this._currentEmotion);
|
|
464
734
|
}
|
|
465
735
|
break;
|
|
@@ -546,6 +816,35 @@ export class MessageHandler extends EventEmitter {
|
|
|
546
816
|
this.emit("serverResponse", serverResponse);
|
|
547
817
|
break;
|
|
548
818
|
}
|
|
819
|
+
/**
|
|
820
|
+
* Lifecycle of one roster member. Emitted when a member is added
|
|
821
|
+
* at runtime, becomes ready, or fails after /connect already
|
|
822
|
+
* returned 200. `bot-ready` stays the readiness authority --
|
|
823
|
+
* a `character-status` of "ready" must not enable interaction on
|
|
824
|
+
* its own -- but this is the only way a background dispatch
|
|
825
|
+
* failure is ever reported.
|
|
826
|
+
*/
|
|
827
|
+
case "character-status": {
|
|
828
|
+
const status = {
|
|
829
|
+
status: serverData.status ?? "starting",
|
|
830
|
+
membershipId: serverData.membership_id ?? "",
|
|
831
|
+
characterId: serverData.character_id ?? "",
|
|
832
|
+
characterSessionId: serverData.character_session_id ?? null,
|
|
833
|
+
participantIdentity: serverData.participant_identity ??
|
|
834
|
+
(serverData.membership_id
|
|
835
|
+
? `character:${serverData.membership_id}`
|
|
836
|
+
: ""),
|
|
837
|
+
roomSessionId: serverData.room_session_id ?? null,
|
|
838
|
+
rosterEpoch: typeof serverData.roster_epoch === "number"
|
|
839
|
+
? serverData.roster_epoch
|
|
840
|
+
: null,
|
|
841
|
+
failureCode: serverData.failure_code ?? null,
|
|
842
|
+
};
|
|
843
|
+
// Unattributable status is dropped rather than guessed at.
|
|
844
|
+
if (status.membershipId)
|
|
845
|
+
this.emit("characterStatus", status);
|
|
846
|
+
break;
|
|
847
|
+
}
|
|
549
848
|
// interaction-created: session IDs for analytics/tracking
|
|
550
849
|
case "interaction-created": {
|
|
551
850
|
const interactionCreated = {
|
|
@@ -613,11 +912,55 @@ export class MessageHandler extends EventEmitter {
|
|
|
613
912
|
});
|
|
614
913
|
return;
|
|
615
914
|
}
|
|
616
|
-
|
|
915
|
+
// output_id identifies a provider invocation, not a serialized envelope.
|
|
916
|
+
// One invocation can produce distinct text and tool-call projections with
|
|
917
|
+
// the same id, and consumers must receive both in transport arrival order.
|
|
918
|
+
// Suppress only an exact transport replay of an already delivered payload.
|
|
919
|
+
const fingerprint = stableJsonFingerprint(output);
|
|
920
|
+
if (this.seenModelOutputPayloads.has(fingerprint))
|
|
921
|
+
return;
|
|
922
|
+
if (fingerprint.length > MAX_MODEL_OUTPUT_REPLAY_RETAINED_CHARS) {
|
|
923
|
+
this.emit("modelOutputProtocolError", {
|
|
924
|
+
code: "invalid_model_output",
|
|
925
|
+
message: "Core sent an oversized model-output envelope",
|
|
926
|
+
});
|
|
617
927
|
return;
|
|
618
|
-
|
|
928
|
+
}
|
|
929
|
+
this.seenModelOutputPayloads.add(fingerprint);
|
|
930
|
+
this.seenModelOutputPayloadCharacters += fingerprint.length;
|
|
931
|
+
while (this.seenModelOutputPayloads.size > MAX_MODEL_OUTPUT_REPLAY_FINGERPRINTS ||
|
|
932
|
+
this.seenModelOutputPayloadCharacters >
|
|
933
|
+
MAX_MODEL_OUTPUT_REPLAY_RETAINED_CHARS) {
|
|
934
|
+
const oldestFingerprint = this.seenModelOutputPayloads.values().next()
|
|
935
|
+
.value;
|
|
936
|
+
if (!oldestFingerprint)
|
|
937
|
+
break;
|
|
938
|
+
this.seenModelOutputPayloads.delete(oldestFingerprint);
|
|
939
|
+
this.seenModelOutputPayloadCharacters -= oldestFingerprint.length;
|
|
940
|
+
}
|
|
619
941
|
this.emit("modelOutput", output);
|
|
620
942
|
}
|
|
943
|
+
_clearModelOutputReplayLedger() {
|
|
944
|
+
this.seenModelOutputPayloads.clear();
|
|
945
|
+
this.seenModelOutputPayloadCharacters = 0;
|
|
946
|
+
}
|
|
947
|
+
_handleBotLlmTextRaw(value) {
|
|
948
|
+
if (this.modelOutputVersion !== 2 || !value || typeof value !== "object") {
|
|
949
|
+
return;
|
|
950
|
+
}
|
|
951
|
+
const data = value;
|
|
952
|
+
if (typeof data.text !== "string" ||
|
|
953
|
+
!isValidLogicalTurnId(data.logical_turn_id)) {
|
|
954
|
+
return;
|
|
955
|
+
}
|
|
956
|
+
this.emit("botLlmTextRaw", {
|
|
957
|
+
text: data.text,
|
|
958
|
+
logical_turn_id: data.logical_turn_id,
|
|
959
|
+
...(isValidOutputId(data.output_id)
|
|
960
|
+
? { output_id: data.output_id }
|
|
961
|
+
: {}),
|
|
962
|
+
});
|
|
963
|
+
}
|
|
621
964
|
lifecycleOwner(data) {
|
|
622
965
|
if (!data) {
|
|
623
966
|
return {};
|
|
@@ -643,8 +986,8 @@ export class MessageHandler extends EventEmitter {
|
|
|
643
986
|
/**
|
|
644
987
|
* Public entry point for WebSocket transport to inject messages into the same pipeline.
|
|
645
988
|
*/
|
|
646
|
-
handleDataReceivedPublic(payload) {
|
|
647
|
-
this.handleDataReceived(payload, null,
|
|
989
|
+
handleDataReceivedPublic(payload, transport = "websocket") {
|
|
990
|
+
this.handleDataReceived(payload, null, transport);
|
|
648
991
|
}
|
|
649
992
|
/** Append a submitted text message without waiting for a server echo. */
|
|
650
993
|
addUserTextMessage(text) {
|
|
@@ -659,19 +1002,41 @@ export class MessageHandler extends EventEmitter {
|
|
|
659
1002
|
});
|
|
660
1003
|
this.emit("messagesChange", this.chatMessages);
|
|
661
1004
|
}
|
|
1005
|
+
/**
|
|
1006
|
+
* Insert a message into the transcript locally. Nothing is transmitted and
|
|
1007
|
+
* no LLM turn is billed -- this is for client-side lines (a greeting, a
|
|
1008
|
+
* system notice, a replayed history entry) that must appear in the chat.
|
|
1009
|
+
*
|
|
1010
|
+
* Subscribers see it through the same `messagesChange` as a live message,
|
|
1011
|
+
* so React and the widgets pick it up with no special casing.
|
|
1012
|
+
*/
|
|
1013
|
+
appendLocalMessage(message) {
|
|
1014
|
+
const chatMessage = {
|
|
1015
|
+
id: `local-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`,
|
|
1016
|
+
type: message.sender === "user" ? "user-llm-text" : "bot-llm-text",
|
|
1017
|
+
content: message.content,
|
|
1018
|
+
timestamp: new Date().toISOString(),
|
|
1019
|
+
...(message.membershipId && { membershipId: message.membershipId }),
|
|
1020
|
+
...(message.characterId && { characterId: message.characterId }),
|
|
1021
|
+
};
|
|
1022
|
+
this.chatMessages.push(chatMessage);
|
|
1023
|
+
this.emit("messagesChange", this.chatMessages);
|
|
1024
|
+
return chatMessage;
|
|
1025
|
+
}
|
|
662
1026
|
/**
|
|
663
1027
|
* Reset message state
|
|
664
1028
|
*/
|
|
665
1029
|
reset() {
|
|
666
1030
|
this.chatMessages = [];
|
|
1031
|
+
this.activeBotLlmMessageId = null;
|
|
667
1032
|
this.userTranscription = "";
|
|
668
1033
|
this.isBotResponding = false;
|
|
669
1034
|
this.isSpeaking = false;
|
|
670
1035
|
this.isListening = false;
|
|
671
1036
|
this.totalBlendshapesReceived = 0;
|
|
672
1037
|
this._currentEmotion = null;
|
|
673
|
-
this.seenModelOutputIds.clear();
|
|
674
1038
|
this.seenBotOutputSegments.clear();
|
|
1039
|
+
this._clearModelOutputReplayLedger();
|
|
675
1040
|
this.blendshapeQueue.reset();
|
|
676
1041
|
this.emit("messagesChange", this.chatMessages);
|
|
677
1042
|
this.emit("userTranscriptionChange", "");
|