@convai/web-sdk 1.9.2 → 1.9.4

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 CHANGED
@@ -10,6 +10,15 @@ TypeScript-first SDK for embedding Convai AI characters into React and vanilla J
10
10
 
11
11
  ---
12
12
 
13
+ ## Fixes in 1.9.1 – 1.9.4
14
+
15
+ - **1.9.4** — The SSE transport sends `authToken` as `API-AUTH-TOKEN`. It sent the token as `Authorization: Bearer`, which the interaction API reads as an API key, so every SSE message made with an `authToken` failed with `401`. [Usage below.](#sse-interaction-transport-beta)
16
+ - **1.9.3** — `audioControls`, `videoControls` and `screenShareControls` follow tracks changed outside them, including a share ended from the browser's "Stop sharing" bar; a disconnected mic reads as muted; the character-info lookup (the widget's name and avatar) sends `CONVAI-API-KEY`; the `mha` lip sync helpers no longer hold a frozen sneer.
17
+ - **1.9.2** — `transport: "websocket"` connects on hosted Convai (`wss://`), and `setCharacterMuted()` silences the character on WebSocket.
18
+ - **1.9.1** — README links point at docs.convai.com.
19
+
20
+ Details in the [CHANGELOG](./CHANGELOG.md).
21
+
13
22
  ## What's new in 1.9.0
14
23
 
15
24
  > **Breaking for 1.8.0 users:** the `<convai-chat>` custom element and the `./embed/browser` entry point (`dist/embed/chat-embed-v1.js`) are removed. The copy/paste published-chat embed is now `<convai-widget>` from [`@convai/web-widget`](https://www.npmjs.com/package/@convai/web-widget); the [CHANGELOG](./CHANGELOG.md) has the before/after snippet.
@@ -331,14 +340,29 @@ Use the interaction API for chat — typed input, with the reply streamed as tex
331
340
  const client = new ConvaiClient({
332
341
  apiKey: "...",
333
342
  characterId: "...",
334
- interactionApiUrl: "https://interaction-api-stg.convai.com/v1/interactions",
343
+ interactionApiUrl: "https://interaction-api.convai.com/v1/interactions",
335
344
  });
336
345
 
337
346
  await client.connect();
338
347
  client.sendUserTextMessage("Hello!");
339
348
  ```
340
349
 
341
- This sends each message as an SSE `POST` with `Authorization: Bearer ...`. Set `transport: "sse"`
350
+ This sends each message as an SSE `POST`. An `apiKey` travels as `Authorization: Bearer ...`.
351
+ To keep the key off the page, mint a short-lived token on your server
352
+ (`POST https://api.convai.com/user/connect` with the `CONVAI-API-KEY` header) and pass it as
353
+ `authToken` instead; the SDK sends it as `API-AUTH-TOKEN` (1.9.4 and later — earlier versions
354
+ sent it as Bearer, which the interaction API rejects with `401`):
355
+
356
+ ```ts
357
+ const { apiAuthToken } = await fetch("/api/convai-token", { method: "POST" }).then((r) => r.json());
358
+ const client = new ConvaiClient({
359
+ authToken: apiAuthToken,
360
+ characterId: "...",
361
+ interactionApiUrl: "https://interaction-api.convai.com/v1/interactions",
362
+ });
363
+ ```
364
+
365
+ Set `transport: "sse"`
342
366
  explicitly if preferred. With `ttsEnabled: true` the reply's speech streams as `audioData`
343
367
  events on the same response; there is no microphone, video, or lipsync. It never calls
344
368
  `/connect`, so `connect()` makes no network request and the session id arrives on the first
@@ -352,7 +376,10 @@ Because it needs neither WebRTC nor a DOM, this is the only transport that runs
352
376
  Import `@convai/web-sdk/core` from Node, SSR, or a serverless function — not the root or `/react`
353
377
  entry points, which pull in browser-only dependencies.
354
378
 
355
- The interaction API is currently reachable at staging only; a production host is planned.
379
+ The interaction API is in beta. It is reachable in production at
380
+ `https://interaction-api.convai.com/v1/interactions`, at staging
381
+ (`https://interaction-api-stg.convai.com/v1/interactions`), and on self-hosted deployments. A token
382
+ works only on the environment that minted it, and a character with Long Term Memory needs `endUserId`.
356
383
  Full guide: [SSE Interaction Transport](https://docs.convai.com/api-docs/plugins-and-integrations/web-plugins/convai-web-sdk/sse-transport).
357
384
 
358
385
  ---
@@ -9,6 +9,8 @@ import type { IWebSocketSession } from "./types.js";
9
9
  */
10
10
  export declare class AudioManager extends EventEmitter implements AudioControls {
11
11
  private room;
12
+ /** Listeners on the current room's local participant, so setRoom can detach them. */
13
+ private listeners;
12
14
  private _wsSession;
13
15
  private _isAudioEnabled;
14
16
  private _isAudioMuted;
@@ -8,6 +8,8 @@ export class AudioManager extends EventEmitter {
8
8
  constructor(room) {
9
9
  super();
10
10
  this.room = null;
11
+ /** Listeners on the current room's local participant, so setRoom can detach them. */
12
+ this.listeners = [];
11
13
  this._wsSession = null;
12
14
  this._isAudioEnabled = false;
13
15
  this._isAudioMuted = false;
@@ -45,8 +47,14 @@ export class AudioManager extends EventEmitter {
45
47
  this.cleanupListeners();
46
48
  }
47
49
  this.room = room;
48
- if (room && room.state !== 'disconnected') {
49
- this.setupListeners();
50
+ if (!room)
51
+ return;
52
+ // Listen even while the room is disconnected: ConvaiClient builds this
53
+ // manager with a fresh Room before connect(), and LiveKit keeps that Room's
54
+ // localParticipant across connections. Gating on a live room meant the
55
+ // listeners were never attached in a real client.
56
+ this.setupListeners();
57
+ if (room.state !== 'disconnected') {
50
58
  this.updateState();
51
59
  }
52
60
  }
@@ -85,10 +93,17 @@ export class AudioManager extends EventEmitter {
85
93
  this.emit('audioStateChange', { isAudioMuted: true, isAudioEnabled: false });
86
94
  }
87
95
  };
88
- localParticipant.on('trackMuted', handleTrackMuted);
89
- localParticipant.on('trackUnmuted', handleTrackUnmuted);
90
- localParticipant.on('trackPublished', handleTrackPublished);
91
- localParticipant.on('trackUnpublished', handleTrackUnpublished);
96
+ // The local participant's publish events are localTrackPublished /
97
+ // localTrackUnpublished; trackPublished / trackUnpublished are emitted
98
+ // only by RemoteParticipant (livekit-client 2.17.3).
99
+ this.listeners = [
100
+ ['trackMuted', handleTrackMuted],
101
+ ['trackUnmuted', handleTrackUnmuted],
102
+ ['localTrackPublished', handleTrackPublished],
103
+ ['localTrackUnpublished', handleTrackUnpublished],
104
+ ];
105
+ for (const [event, handler] of this.listeners)
106
+ localParticipant.on(event, handler);
92
107
  }
93
108
  /**
94
109
  * Clean up event listeners
@@ -96,7 +111,10 @@ export class AudioManager extends EventEmitter {
96
111
  cleanupListeners() {
97
112
  if (!this.room)
98
113
  return;
99
- // LiveKit handles cleanup automatically when participant is removed
114
+ const localParticipant = this.room.localParticipant;
115
+ for (const [event, handler] of this.listeners)
116
+ localParticipant.off(event, handler);
117
+ this.listeners = [];
100
118
  }
101
119
  /**
102
120
  * Force-sync the stored audio state with the underlying LiveKit room.
@@ -275,11 +293,14 @@ export class AudioManager extends EventEmitter {
275
293
  * Reset state on disconnect
276
294
  */
277
295
  reset() {
296
+ // Disconnected means the mic is not transmitting: muted, as
297
+ // syncStateFromRoom already reports for a disconnected room and as
298
+ // useConvaiClient sets on `disconnect` (which this event used to undo).
278
299
  this._isAudioEnabled = false;
279
- this._isAudioMuted = false;
300
+ this._isAudioMuted = true;
280
301
  this._audioLevel = 0;
281
302
  this.emit('audioStateChange', {
282
- isAudioMuted: false,
303
+ isAudioMuted: true,
283
304
  isAudioEnabled: false,
284
305
  audioLevel: 0
285
306
  });
@@ -890,7 +890,8 @@ export class ConvaiClient extends EventEmitter {
890
890
  if (transportType === "sse") {
891
891
  this._sseSession = new SSESession({
892
892
  interactionApiUrl: configWithDefaults.interactionApiUrl,
893
- authorization: configWithDefaults.authToken ?? configWithDefaults.apiKey,
893
+ authorization: configWithDefaults.apiKey ?? "",
894
+ ...(configWithDefaults.authToken && { authToken: configWithDefaults.authToken }),
894
895
  credentialProvider: configWithDefaults.interactionCredentialProvider,
895
896
  characterId: configWithDefaults.characterReference,
896
897
  getCharacterSessionId: () => this._characterSessionId,
@@ -1,7 +1,14 @@
1
1
  import type { ConvaiConfig, SSERequestContext, RawMessageEvent } from "./types.js";
2
2
  export interface SSESessionOptions {
3
3
  interactionApiUrl: string;
4
+ /** API key, sent as `Authorization: Bearer`. */
4
5
  authorization: string;
6
+ /**
7
+ * Auth token, sent as `API-AUTH-TOKEN` and preferred over `authorization`.
8
+ * The interaction API reads a Bearer value as an API key, so a token sent
9
+ * that way is rejected with 401.
10
+ */
11
+ authToken?: string;
5
12
  credentialProvider?: ConvaiConfig["interactionCredentialProvider"];
6
13
  characterId: string;
7
14
  getCharacterSessionId: () => string | null;
@@ -103,9 +103,9 @@ export class SSESession {
103
103
  const controller = new AbortController();
104
104
  this.abortController = controller;
105
105
  try {
106
- let credentialHeaders = {
107
- Authorization: `Bearer ${this.options.authorization}`,
108
- };
106
+ let credentialHeaders = this.options.authToken
107
+ ? { "API-AUTH-TOKEN": this.options.authToken }
108
+ : { Authorization: `Bearer ${this.options.authorization}` };
109
109
  let connectAttemptId;
110
110
  if (this.options.credentialProvider) {
111
111
  const provider = this.options.credentialProvider;
@@ -271,6 +271,10 @@ export class SSESession {
271
271
  let sawTerminal = false;
272
272
  let sawTurnResponse = false;
273
273
  let sawError = false;
274
+ // `done` is the server's last event for this request. Some deployments
275
+ // hold the connection open long after it (prod: ~85 s), and the request
276
+ // queue is serial, so waiting for EOF would stall every following turn.
277
+ let sawDone = false;
274
278
  const dispatch = () => {
275
279
  if (signal.aborted) {
276
280
  eventType = "message";
@@ -385,6 +389,8 @@ export class SSESession {
385
389
  }
386
390
  }
387
391
  if (eventType === "session" || eventType === "done") {
392
+ if (eventType === "done")
393
+ sawDone = true;
388
394
  const sessionId = data
389
395
  ?.character_session_id;
390
396
  if (typeof sessionId === "string")
@@ -410,6 +416,8 @@ export class SSESession {
410
416
  for (const line of lines) {
411
417
  if (signal.aborted)
412
418
  return;
419
+ if (sawDone)
420
+ break;
413
421
  if (!line)
414
422
  dispatch();
415
423
  else if (line.startsWith("event:"))
@@ -418,8 +426,8 @@ export class SSESession {
418
426
  eventData.push(line.slice(5).trimStart());
419
427
  }
420
428
  }
421
- if (done) {
422
- if (buffer) {
429
+ if (done || sawDone) {
430
+ if (done && buffer) {
423
431
  if (buffer.startsWith("event:"))
424
432
  eventType = buffer.slice(6).trim();
425
433
  else if (buffer.startsWith("data:"))
@@ -427,7 +435,7 @@ export class SSESession {
427
435
  }
428
436
  dispatch();
429
437
  this.flushBotLlmText();
430
- // EOF is a request boundary, not proof the model finished the turn.
438
+ // EOF (or `done`) is a request boundary, not proof the model finished the turn.
431
439
  // Preserve partial output and fail only when the response has closed;
432
440
  // no watchdog may cancel an otherwise active long-running stream.
433
441
  if (!signal.aborted &&
@@ -10,6 +10,8 @@ export declare class ScreenShareManager extends EventEmitter implements ScreenSh
10
10
  private room;
11
11
  private _isScreenShareEnabled;
12
12
  private _isScreenShareActive;
13
+ /** Listeners on the current room's local participant, so setRoom can detach them. */
14
+ private listeners;
13
15
  constructor(room?: Room);
14
16
  get isScreenShareEnabled(): boolean;
15
17
  get isScreenShareActive(): boolean;
@@ -18,11 +20,18 @@ export declare class ScreenShareManager extends EventEmitter implements ScreenSh
18
20
  */
19
21
  setRoom(room: Room): void;
20
22
  /**
21
- * Setup event listeners for room
23
+ * Follow the local screen-share track.
24
+ *
25
+ * The local participant emits `localTrackPublished` / `localTrackUnpublished`
26
+ * (livekit-client's `ParticipantEvent.LocalTrack*`). `trackPublished` /
27
+ * `trackUnpublished` are `RemoteParticipant` events and never fire here, which
28
+ * is how a share ended from the browser's own "Stop sharing" bar — LiveKit
29
+ * unpublishes the ended track — used to leave `isScreenShareActive` true.
22
30
  */
23
31
  private setupListeners;
24
32
  /**
25
- * Clean up event listeners
33
+ * Detach from the current room, so a reconnect's new room is the only one
34
+ * driving state.
26
35
  */
27
36
  private cleanupListeners;
28
37
  /**
@@ -11,6 +11,8 @@ export class ScreenShareManager extends EventEmitter {
11
11
  this.room = null;
12
12
  this._isScreenShareEnabled = false;
13
13
  this._isScreenShareActive = false;
14
+ /** Listeners on the current room's local participant, so setRoom can detach them. */
15
+ this.listeners = [];
14
16
  if (room) {
15
17
  this.setRoom(room);
16
18
  }
@@ -30,54 +32,61 @@ export class ScreenShareManager extends EventEmitter {
30
32
  this.cleanupListeners();
31
33
  }
32
34
  this.room = room;
33
- if (room && room.state !== 'disconnected') {
34
- this.setupListeners();
35
+ if (!room)
36
+ return;
37
+ // Listen even while the room is disconnected. ConvaiClient builds this
38
+ // manager with a fresh Room before connect(), and LiveKit keeps that Room's
39
+ // localParticipant across connections — so gating on a live room meant the
40
+ // listeners were never attached in a real client.
41
+ this.setupListeners();
42
+ if (room.state !== 'disconnected') {
35
43
  this.updateState();
36
44
  }
37
45
  }
38
46
  /**
39
- * Setup event listeners for room
47
+ * Follow the local screen-share track.
48
+ *
49
+ * The local participant emits `localTrackPublished` / `localTrackUnpublished`
50
+ * (livekit-client's `ParticipantEvent.LocalTrack*`). `trackPublished` /
51
+ * `trackUnpublished` are `RemoteParticipant` events and never fire here, which
52
+ * is how a share ended from the browser's own "Stop sharing" bar — LiveKit
53
+ * unpublishes the ended track — used to leave `isScreenShareActive` true.
40
54
  */
41
55
  setupListeners() {
42
56
  if (!this.room)
43
57
  return;
44
58
  const localParticipant = this.room.localParticipant;
45
- const handleTrackPublished = (track) => {
46
- if (track.source === 'screen_share') {
47
- this._isScreenShareActive = true;
48
- this.emit('screenShareStateChange', { isScreenShareActive: true });
49
- }
50
- };
51
- const handleTrackUnpublished = (track) => {
52
- if (track.source === 'screen_share') {
53
- this._isScreenShareActive = false;
54
- this.emit('screenShareStateChange', { isScreenShareActive: false });
55
- }
56
- };
57
- const handleTrackMuted = (track) => {
58
- if (track.source === 'screen_share') {
59
- this._isScreenShareActive = false;
60
- this.emit('screenShareStateChange', { isScreenShareActive: false });
61
- }
62
- };
63
- const handleTrackUnmuted = (track) => {
64
- if (track.source === 'screen_share') {
65
- this._isScreenShareActive = true;
66
- this.emit('screenShareStateChange', { isScreenShareActive: true });
67
- }
59
+ const set = (active, enabled = active) => {
60
+ this._isScreenShareActive = active;
61
+ this._isScreenShareEnabled = enabled;
62
+ this.emit('screenShareStateChange', { isScreenShareEnabled: enabled, isScreenShareActive: active });
68
63
  };
69
- localParticipant.on('trackPublished', handleTrackPublished);
70
- localParticipant.on('trackUnpublished', handleTrackUnpublished);
71
- localParticipant.on('trackMuted', handleTrackMuted);
72
- localParticipant.on('trackUnmuted', handleTrackUnmuted);
64
+ const isScreen = (publication) => publication?.source === 'screen_share';
65
+ this.listeners = [
66
+ ['localTrackPublished', (p) => { if (isScreen(p))
67
+ set(true); }],
68
+ ['localTrackUnpublished', (p) => { if (isScreen(p))
69
+ set(false); }],
70
+ // A muted share is still published (enabled), just not showing.
71
+ ['trackMuted', (p) => { if (isScreen(p))
72
+ set(false, this._isScreenShareEnabled); }],
73
+ ['trackUnmuted', (p) => { if (isScreen(p))
74
+ set(true, this._isScreenShareEnabled); }],
75
+ ];
76
+ for (const [event, handler] of this.listeners)
77
+ localParticipant.on(event, handler);
73
78
  }
74
79
  /**
75
- * Clean up event listeners
80
+ * Detach from the current room, so a reconnect's new room is the only one
81
+ * driving state.
76
82
  */
77
83
  cleanupListeners() {
78
84
  if (!this.room)
79
85
  return;
80
- // LiveKit handles cleanup automatically when participant is removed
86
+ const localParticipant = this.room.localParticipant;
87
+ for (const [event, handler] of this.listeners)
88
+ localParticipant.off(event, handler);
89
+ this.listeners = [];
81
90
  }
82
91
  /**
83
92
  * Update screen share state from room
@@ -159,11 +168,12 @@ export class ScreenShareManager extends EventEmitter {
159
168
  surfaceSwitching: "include",
160
169
  systemAudio: "include",
161
170
  });
162
- // Publish each track
163
- tracks.forEach((track) => {
164
- this.room.localParticipant.publishTrack(track);
165
- });
171
+ // Publish every track before reporting the share live: a failed publish
172
+ // rejects here instead of surfacing later as an unhandled rejection.
173
+ await Promise.all(tracks.map((track) => this.room.localParticipant.publishTrack(track)));
166
174
  this._isScreenShareEnabled = true;
175
+ this._isScreenShareActive = true;
176
+ this.emit('screenShareStateChange', { isScreenShareEnabled: true, isScreenShareActive: true });
167
177
  }
168
178
  catch (error) {
169
179
  logger.error("Failed to enable screen share with audio:", error);
@@ -9,6 +9,8 @@ type WebSocketVisionMessageSender = (type: WebSocketVisionMessageType, data: Rec
9
9
  */
10
10
  export declare class VideoManager extends EventEmitter implements VideoControls {
11
11
  private room;
12
+ /** Listeners on the current room's local participant, so setRoom can detach them. */
13
+ private listeners;
12
14
  private _isVideoEnabled;
13
15
  private _isVideoHidden;
14
16
  private _activeVisionSource;
@@ -10,6 +10,8 @@ export class VideoManager extends EventEmitter {
10
10
  constructor(room) {
11
11
  super();
12
12
  this.room = null;
13
+ /** Listeners on the current room's local participant, so setRoom can detach them. */
14
+ this.listeners = [];
13
15
  this._isVideoEnabled = false;
14
16
  this._isVideoHidden = false;
15
17
  this._activeVisionSource = null;
@@ -106,10 +108,18 @@ export class VideoManager extends EventEmitter {
106
108
  });
107
109
  }
108
110
  };
109
- localParticipant.on("trackMuted", handleTrackMuted);
110
- localParticipant.on("trackUnmuted", handleTrackUnmuted);
111
- localParticipant.on("trackPublished", handleTrackPublished);
112
- localParticipant.on("trackUnpublished", handleTrackUnpublished);
111
+ // The local participant's publish events are localTrackPublished /
112
+ // localTrackUnpublished; trackPublished / trackUnpublished are emitted
113
+ // only by RemoteParticipant (livekit-client 2.17.3), so a camera or vision
114
+ // track unpublished outside videoControls never cleared its source.
115
+ this.listeners = [
116
+ ["trackMuted", handleTrackMuted],
117
+ ["trackUnmuted", handleTrackUnmuted],
118
+ ["localTrackPublished", handleTrackPublished],
119
+ ["localTrackUnpublished", handleTrackUnpublished],
120
+ ];
121
+ for (const [event, handler] of this.listeners)
122
+ localParticipant.on(event, handler);
113
123
  }
114
124
  /**
115
125
  * Clean up event listeners
@@ -117,7 +127,10 @@ export class VideoManager extends EventEmitter {
117
127
  cleanupListeners() {
118
128
  if (!this.room)
119
129
  return;
120
- // LiveKit handles cleanup automatically when participant is removed
130
+ const localParticipant = this.room.localParticipant;
131
+ for (const [event, handler] of this.listeners)
132
+ localParticipant.off(event, handler);
133
+ this.listeners = [];
121
134
  }
122
135
  /**
123
136
  * Update video state from room
@@ -21,7 +21,10 @@ export interface CharacterInfo {
21
21
  export declare const FALLBACK_CHARACTER_NAME = "Convi";
22
22
  export interface FetchCharacterInfoOptions {
23
23
  characterId: string;
24
- /** Sent as `X-API-Key`. Ignored when `authToken` is present. */
24
+ /**
25
+ * Sent as `CONVAI-API-KEY`, the header Convai's REST hosts have always taken.
26
+ * Ignored when `authToken` is present.
27
+ */
25
28
  apiKey?: string | null;
26
29
  /** Sent as `API-AUTH-TOKEN`, and preferred over `apiKey`. */
27
30
  authToken?: string | null;
@@ -37,10 +37,14 @@ export async function fetchCharacterInfo(options) {
37
37
  const headers = {
38
38
  "Content-Type": "application/json",
39
39
  };
40
+ // CONVAI-API-KEY, not the X-API-Key that /connect takes. api.convai.com
41
+ // accepts either, but self-hosted deployments authenticate this route the
42
+ // way the legacy convai-web-sdk called it, with CONVAI-API-KEY, and answer
43
+ // X-API-Key with 401.
40
44
  if (authToken)
41
45
  headers["API-AUTH-TOKEN"] = authToken;
42
46
  else if (apiKey)
43
- headers["X-API-Key"] = apiKey;
47
+ headers["CONVAI-API-KEY"] = apiKey;
44
48
  const origin = (baseUrl || DEFAULT_CHARACTER_INFO_URL).replace(/\/+$/, "");
45
49
  const response = await fetch(`${origin}/character/get`, {
46
50
  method: "POST",
@@ -14,6 +14,8 @@ export declare const MHA_LIMIT_DRIVERS: readonly {
14
14
  /**
15
15
  * Apply the MetaHuman limit drivers to a 251-dim frame IN PLACE:
16
16
  * each target channel becomes max(target, source). No-op for other formats.
17
+ * A channel the stream pins at 1.0 (noseWrinkleUpperL/R) is cleared first,
18
+ * so it follows its source instead of holding a sneer.
17
19
  */
18
20
  export declare function applyMhaLimits(frame: Float32Array): void;
19
21
  /** Production-tuned per-channel gains (short control name → gain). */
@@ -1,5 +1,6 @@
1
1
  import { METAHUMAN_ORDER_251 } from "./metahumanOrder251.js";
2
2
  import { MHA_PROFILE, MHA_RECOMMENDED_GAIN_TABLE, mhaChannelIndex, } from "./naturalness/profiles/mha.js";
3
+ import { PINNED_THRESHOLD } from "./naturalness/processor.js";
3
4
  /**
4
5
  * Flat MHA convenience helpers — thin wrappers over the modular
5
6
  * naturalness profile (see `naturalness/`). Prefer
@@ -16,10 +17,16 @@ export const MHA_LIMIT_DRIVERS = MHA_PROFILE.limits.map(([sourceIdx, targetIdx])
16
17
  /**
17
18
  * Apply the MetaHuman limit drivers to a 251-dim frame IN PLACE:
18
19
  * each target channel becomes max(target, source). No-op for other formats.
20
+ * A channel the stream pins at 1.0 (noseWrinkleUpperL/R) is cleared first,
21
+ * so it follows its source instead of holding a sneer.
19
22
  */
20
23
  export function applyMhaLimits(frame) {
21
24
  if (frame.length < METAHUMAN_ORDER_251.length)
22
25
  return;
26
+ for (const i of MHA_PROFILE.pinnedChannels ?? []) {
27
+ if (frame[i] >= PINNED_THRESHOLD)
28
+ frame[i] = 0;
29
+ }
23
30
  for (const [s, t] of MHA_PROFILE.limits) {
24
31
  if (frame[s] > frame[t])
25
32
  frame[t] = frame[s];
@@ -20,4 +20,6 @@ export interface LipsyncProcessor {
20
20
  /** process + apply in one call. */
21
21
  tick(frame: Float32Array | null, deltaSeconds: number, bindings: LipsyncMeshBinding[]): void;
22
22
  }
23
+ /** A pinned channel at or above this value is a stream artifact, not an expression. */
24
+ export declare const PINNED_THRESHOLD = 0.999;
23
25
  export declare function createLipsyncProcessor(formatOrProfile: LipsyncFormat | LipsyncFormatProfile, options?: LipsyncProcessorOptions): LipsyncProcessor;
@@ -28,6 +28,8 @@ export function getLipsyncProfile(format) {
28
28
  }
29
29
  return profile;
30
30
  }
31
+ /** A pinned channel at or above this value is a stream artifact, not an expression. */
32
+ export const PINNED_THRESHOLD = 0.999;
31
33
  export function createLipsyncProcessor(formatOrProfile, options = {}) {
32
34
  const profile = typeof formatOrProfile === "string"
33
35
  ? getLipsyncProfile(formatOrProfile)
@@ -61,6 +63,12 @@ export function createLipsyncProcessor(formatOrProfile, options = {}) {
61
63
  let env = envelope === false ? 1 : 0;
62
64
  const shape = (src) => {
63
65
  work.set(src.subarray(0, dim));
66
+ if (profile.pinnedChannels) {
67
+ for (const i of profile.pinnedChannels) {
68
+ if (work[i] >= PINNED_THRESHOLD)
69
+ work[i] = 0;
70
+ }
71
+ }
64
72
  if (symmetrizeMouth) {
65
73
  for (const [li, ri] of profile.mouthPairs) {
66
74
  const m = (work[li] + work[ri]) / 2;
@@ -28,6 +28,13 @@ const LIMIT_DEFS = [
28
28
  ["jawOpen", "mouthLipsTogetherDL"],
29
29
  ["jawOpen", "mouthLipsTogetherDR"],
30
30
  ];
31
+ /**
32
+ * Channels the stream pins at 1.0 for a whole reply. noseWrinkleUpperL/R
33
+ * arrive at exactly 1.0 on every frame (measured 2026-10-14 on staging and
34
+ * production, 15/15 replies), while the other limit-driver targets arrive
35
+ * near 0 for the rig to derive. Applied raw it is a frozen sneer.
36
+ */
37
+ const PINNED_DEFS = ["noseWrinkleUpperL", "noseWrinkleUpperR"];
31
38
  /** Production-tuned per-channel gains (short name → gain). */
32
39
  export const MHA_RECOMMENDED_GAIN_TABLE = {
33
40
  // Conversational aperture: 0.6 reads mumbled, raw bares the teeth.
@@ -73,6 +80,7 @@ export const MHA_PROFILE = {
73
80
  limits: LIMIT_DEFS.flatMap(([s, t]) => MHA_INDEX[s] !== undefined && MHA_INDEX[t] !== undefined
74
81
  ? [[MHA_INDEX[s], MHA_INDEX[t]]]
75
82
  : []),
83
+ pinnedChannels: new Set(PINNED_DEFS.flatMap((n) => (MHA_INDEX[n] !== undefined ? [MHA_INDEX[n]] : []))),
76
84
  recommendedGains: (() => {
77
85
  const g = new Float32Array(METAHUMAN_ORDER_251.length).fill(1);
78
86
  for (const [name, gain] of Object.entries(MHA_RECOMMENDED_GAIN_TABLE)) {
@@ -18,6 +18,13 @@ export interface LipsyncFormatProfile {
18
18
  * jawOpen → mouthLipsTogether*). Empty for formats without them.
19
19
  */
20
20
  limits: ReadonlyArray<readonly [sourceIdx: number, targetIdx: number]>;
21
+ /**
22
+ * Channels the stream is known to pin at 1.0 as an artifact rather than
23
+ * an expression. A value at or above 0.999 on one of these is treated as
24
+ * 0 before the couplings run, so the coupling derives the channel from its
25
+ * source instead. Omit for formats without such channels.
26
+ */
27
+ pinnedChannels?: ReadonlySet<number>;
21
28
  /** Per-channel production-tuned gains (length = frame dim, default 1). */
22
29
  recommendedGains: Float32Array;
23
30
  /** Channel indices owned by procedural blink/gaze systems. */
@@ -6,7 +6,7 @@ import { type CharacterInfo } from "../../core/characterInfo.js";
6
6
  * the same code rather than a hand-synced copy of it.
7
7
  *
8
8
  * @param characterId - Character to look up
9
- * @param apiKey - Convai API key, sent as `X-API-Key`
9
+ * @param apiKey - Convai API key, sent as `CONVAI-API-KEY`
10
10
  * @param authToken - Preferred over `apiKey`, sent as `API-AUTH-TOKEN`
11
11
  * @param baseUrl - Origin to ask; defaults to `https://api.convai.com`. Pass
12
12
  * `client.characterInfoUrl` so a non-SaaS deployment is not asked to send
@@ -8,7 +8,7 @@ import { fetchCharacterInfo, FALLBACK_CHARACTER_NAME, } from "../../core/charact
8
8
  * the same code rather than a hand-synced copy of it.
9
9
  *
10
10
  * @param characterId - Character to look up
11
- * @param apiKey - Convai API key, sent as `X-API-Key`
11
+ * @param apiKey - Convai API key, sent as `CONVAI-API-KEY`
12
12
  * @param authToken - Preferred over `apiKey`, sent as `API-AUTH-TOKEN`
13
13
  * @param baseUrl - Origin to ask; defaults to `https://api.convai.com`. Pass
14
14
  * `client.characterInfoUrl` so a non-SaaS deployment is not asked to send
@@ -103,18 +103,6 @@ export const useConvaiClient = (config) => {
103
103
  setIsVideoEnabled(false);
104
104
  setIsScreenShareActive(false);
105
105
  });
106
- // WebSocket transport: play bot audio track via a hidden <audio> element
107
- const wsAudioEl = document.createElement("audio");
108
- wsAudioEl.autoplay = true;
109
- wsAudioEl.dataset.convaiWs = "true";
110
- document.body.appendChild(wsAudioEl);
111
- const unsubBotAudioTrack = client.on("botAudioTrack", (track) => {
112
- wsAudioEl.srcObject = new MediaStream([track]);
113
- });
114
- // Disconnect listener also clears WS audio
115
- const unsubDisconnectWsAudio = client.on("disconnect", () => {
116
- wsAudioEl.srcObject = null;
117
- });
118
106
  // Audio controls state change listener
119
107
  const unsubAudioState = client.audioControls.on("audioStateChange", (audioState) => {
120
108
  if (audioState.isAudioMuted !== undefined) {
@@ -142,13 +130,9 @@ export const useConvaiClient = (config) => {
142
130
  unsubBotReady();
143
131
  unsubConnect();
144
132
  unsubDisconnect();
145
- unsubBotAudioTrack();
146
- unsubDisconnectWsAudio();
147
133
  unsubAudioState();
148
134
  unsubVideoState();
149
135
  unsubScreenShareState();
150
- wsAudioEl.srcObject = null;
151
- wsAudioEl.remove();
152
136
  };
153
137
  }, [client]);
154
138
  // Create enhanced connect function that can use stored config
@@ -259,7 +259,7 @@ export function createConvaiWidget(container, options) {
259
259
  // behave identically in both places.
260
260
  //
261
261
  // The two travel in *different* headers, which requestCharacterInfo
262
- // handles: an auth token goes in API-AUTH-TOKEN, an API key in X-API-Key,
262
+ // handles: an auth token goes in API-AUTH-TOKEN, an API key in CONVAI-API-KEY,
263
263
  // and the host answers an API key sent as API-AUTH-TOKEN with `400 Your
264
264
  // session has expired.` The failure is swallowed below, so getting it
265
265
  // wrong showed up only as a header stuck on the fallback name.
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const SDK_VERSION = "1.9.2";
1
+ export declare const SDK_VERSION = "1.9.4";
package/dist/version.js CHANGED
@@ -1,3 +1,3 @@
1
1
  // GENERATED by scripts/sync-version.mjs — do not edit by hand.
2
2
  // Regenerated from package.json on every build.
3
- export const SDK_VERSION = "1.9.2";
3
+ export const SDK_VERSION = "1.9.4";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@convai/web-sdk",
3
- "version": "1.9.2",
3
+ "version": "1.9.4",
4
4
  "description": "Build web apps with lifelike AI characters. The Convai Web SDK gives you real-time voice, lipsync, emotions, and dynamic context — with first-class support for React and vanilla TypeScript.",
5
5
  "private": false,
6
6
  "type": "module",