@trillet-ai/web-sdk 1.9.1 → 1.10.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 +2 -0
- package/dist/{chunk-3MH6DJZ6.js → chunk-CVTVHUNZ.js} +12 -5
- package/dist/chunk-CVTVHUNZ.js.map +1 -0
- package/dist/{chunk-FSJ42TKR.js → chunk-IASKK2IK.js} +155 -23
- package/dist/chunk-IASKK2IK.js.map +1 -0
- package/dist/index.d.ts +34 -1
- package/dist/index.js +2 -2
- package/dist/server.d.ts +5 -1
- package/dist/server.js +1 -1
- package/dist/widget/index.d.ts +194 -37
- package/dist/widget/index.js +1526 -644
- package/dist/widget/index.js.map +1 -1
- package/dist/widget.umd.js +492 -361
- package/dist/widget.umd.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-3MH6DJZ6.js.map +0 -1
- package/dist/chunk-FSJ42TKR.js.map +0 -1
package/README.md
CHANGED
|
@@ -97,6 +97,8 @@ agent.on('transcriptUpdate', (transcripts) => {
|
|
|
97
97
|
|
|
98
98
|
// Control the call
|
|
99
99
|
agent.toggleMicrophone(true); // Enable/disable microphone in voice mode
|
|
100
|
+
await agent.setMuted(true); // Mute (awaitable); agent.isMuted reflects state
|
|
101
|
+
agent.on('muteChanged', (muted) => console.log('muted?', muted));
|
|
100
102
|
agent.sendTextMessage("Hello, agent!"); // Send a text message in text mode
|
|
101
103
|
agent.endCall(); // End the call
|
|
102
104
|
```
|
|
@@ -1,11 +1,17 @@
|
|
|
1
1
|
// src/createCall.ts
|
|
2
|
+
var DEFAULT_API_BASE = "https://api.trillet.ai";
|
|
2
3
|
var TRILLET_API_URL = {
|
|
3
|
-
CONNECT:
|
|
4
|
-
PUBLIC_CONNECT:
|
|
4
|
+
CONNECT: `${DEFAULT_API_BASE}/v1/api/web-call`,
|
|
5
|
+
PUBLIC_CONNECT: `${DEFAULT_API_BASE}/v1/api/web-call/public`,
|
|
6
|
+
WIDGET_CONFIG: `${DEFAULT_API_BASE}/v1/api/web-call/public/widget-config`
|
|
5
7
|
};
|
|
8
|
+
function apiUrl(path, apiBase) {
|
|
9
|
+
const base = (apiBase || DEFAULT_API_BASE).replace(/\/+$/, "");
|
|
10
|
+
return `${base}${path}`;
|
|
11
|
+
}
|
|
6
12
|
async function createCall(config) {
|
|
7
13
|
var _a, _b;
|
|
8
|
-
const response = await fetch(
|
|
14
|
+
const response = await fetch(apiUrl("/v1/api/web-call", config.apiBaseUrl), {
|
|
9
15
|
method: "POST",
|
|
10
16
|
headers: {
|
|
11
17
|
"Content-Type": "application/json",
|
|
@@ -15,6 +21,7 @@ async function createCall(config) {
|
|
|
15
21
|
body: JSON.stringify({
|
|
16
22
|
call_agent_id: config.agentId,
|
|
17
23
|
mode: config.mode,
|
|
24
|
+
...config.initialModality ? { initial_modality: config.initialModality } : {},
|
|
18
25
|
dynamic_variables: config.variables || {},
|
|
19
26
|
callback_url: config.callbackUrl,
|
|
20
27
|
// browser_fingerprint is a browser-only concern; omitted here so this runs
|
|
@@ -40,7 +47,7 @@ async function createCall(config) {
|
|
|
40
47
|
}
|
|
41
48
|
|
|
42
49
|
export {
|
|
43
|
-
|
|
50
|
+
apiUrl,
|
|
44
51
|
createCall
|
|
45
52
|
};
|
|
46
|
-
//# sourceMappingURL=chunk-
|
|
53
|
+
//# sourceMappingURL=chunk-CVTVHUNZ.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/createCall.ts"],"sourcesContent":["// Shared, browser-agnostic call-creation logic.\n//\n// This module performs ONLY the authenticated `POST /v1/api/web-call` fetch and\n// returns the room details keyed off the `connection` object that the backend\n// returns. It deliberately contains no `window`/DOM access and no secure-context\n// guard, so it can run in Node (the server entry point) as well as in the browser\n// (the `TrilletAgent.startCall` internals). Keeping this here means index.tsx and\n// server.ts share one request/response implementation and cannot drift.\n\nexport const DEFAULT_API_BASE = 'https://api.trillet.ai';\n\nexport const TRILLET_API_URL = {\n CONNECT: `${DEFAULT_API_BASE}/v1/api/web-call`,\n PUBLIC_CONNECT: `${DEFAULT_API_BASE}/v1/api/web-call/public`,\n WIDGET_CONFIG: `${DEFAULT_API_BASE}/v1/api/web-call/public/widget-config`,\n};\n\n/**\n * Resolve an endpoint against an optional API base (whitelabel API host, or a local\n * backend in development). Trailing slashes on the base are ignored.\n */\nexport function apiUrl(path: string, apiBase?: string): string {\n const base = (apiBase || DEFAULT_API_BASE).replace(/\\/+$/, '');\n return `${base}${path}`;\n}\n\n/**\n * Room connection details returned by the Trillet web-call endpoints and consumed\n * by `TrilletAgent.joinRoom`. The `connection` object is the stable contract that\n * both the authenticated and public endpoints return.\n */\nexport interface TrilletRoomDetails {\n connection: { url: string; token: string };\n call_id?: string;\n room_name?: string;\n status?: string;\n /**\n * Human-facing identity of who the caller is talking to. Returned by both the\n * authenticated and public web-call endpoints. All three keys are always present;\n * any individual value may be `null`. Consumed by the widget header.\n */\n display?: {\n agent_name?: string | null;\n call_flow_name?: string | null;\n workspace_name?: string | null;\n };\n}\n\nexport interface CreateCallConfig {\n apiKey: string;\n agentId: string;\n mode?: 'voice' | 'text' | 'multimodal';\n /** Multimodal only: which side the conversation starts on. */\n initialModality?: 'voice' | 'text';\n variables?: Record<string, any>;\n callbackUrl?: string;\n /** Override the API host (defaults to https://api.trillet.ai). */\n apiBaseUrl?: string;\n}\n\n/**\n * **Server-side only — requires an API key, do not call from the browser.**\n *\n * Performs the authenticated `POST /v1/api/web-call` request with the `X-API-KEY`\n * header and returns the room {@link TrilletRoomDetails}. Makes no LiveKit\n * connection, requests no microphone, and touches no browser APIs — safe to run\n * in Node on the customer's backend. Pass the returned `connection` object to the\n * browser and call `agent.joinRoom(roomDetails)` there.\n */\nexport async function createCall(config: CreateCallConfig): Promise<TrilletRoomDetails> {\n const response = await fetch(apiUrl('/v1/api/web-call', config.apiBaseUrl), {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n 'X-API-KEY': config.apiKey,\n },\n body: JSON.stringify({\n call_agent_id: config.agentId,\n mode: config.mode,\n ...(config.initialModality ? { initial_modality: config.initialModality } : {}),\n dynamic_variables: config.variables || {},\n callback_url: config.callbackUrl,\n // browser_fingerprint is a browser-only concern; omitted here so this runs\n // cleanly server-side. The backend degrades to IP-based tracking.\n browser_fingerprint: null,\n }),\n });\n\n if (!response.ok) {\n let errorMessage;\n try {\n const errorData = await response.json();\n errorMessage = errorData.message || errorData.error || 'Unknown error';\n } catch {\n errorMessage = await response.text();\n }\n throw new Error(`API Error: ${errorMessage}`);\n }\n\n const data: TrilletRoomDetails = await response.json();\n\n if (!data.connection?.url || !data.connection?.token) {\n throw new Error('Invalid response from server: missing connection url or token');\n }\n\n return data;\n}\n"],"mappings":";AASO,IAAM,mBAAmB;AAEzB,IAAM,kBAAkB;AAAA,EAC7B,SAAS,GAAG,gBAAgB;AAAA,EAC5B,gBAAgB,GAAG,gBAAgB;AAAA,EACnC,eAAe,GAAG,gBAAgB;AACpC;AAMO,SAAS,OAAO,MAAc,SAA0B;AAC7D,QAAM,QAAQ,WAAW,kBAAkB,QAAQ,QAAQ,EAAE;AAC7D,SAAO,GAAG,IAAI,GAAG,IAAI;AACvB;AA6CA,eAAsB,WAAW,QAAuD;AArExF;AAsEE,QAAM,WAAW,MAAM,MAAM,OAAO,oBAAoB,OAAO,UAAU,GAAG;AAAA,IAC1E,QAAQ;AAAA,IACR,SAAS;AAAA,MACP,gBAAgB;AAAA,MAChB,QAAQ;AAAA,MACR,aAAa,OAAO;AAAA,IACtB;AAAA,IACA,MAAM,KAAK,UAAU;AAAA,MACnB,eAAe,OAAO;AAAA,MACtB,MAAM,OAAO;AAAA,MACb,GAAI,OAAO,kBAAkB,EAAE,kBAAkB,OAAO,gBAAgB,IAAI,CAAC;AAAA,MAC7E,mBAAmB,OAAO,aAAa,CAAC;AAAA,MACxC,cAAc,OAAO;AAAA;AAAA;AAAA,MAGrB,qBAAqB;AAAA,IACvB,CAAC;AAAA,EACH,CAAC;AAED,MAAI,CAAC,SAAS,IAAI;AAChB,QAAI;AACJ,QAAI;AACF,YAAM,YAAY,MAAM,SAAS,KAAK;AACtC,qBAAe,UAAU,WAAW,UAAU,SAAS;AAAA,IACzD,SAAQ;AACN,qBAAe,MAAM,SAAS,KAAK;AAAA,IACrC;AACA,UAAM,IAAI,MAAM,cAAc,YAAY,EAAE;AAAA,EAC9C;AAEA,QAAM,OAA2B,MAAM,SAAS,KAAK;AAErD,MAAI,GAAC,UAAK,eAAL,mBAAiB,QAAO,GAAC,UAAK,eAAL,mBAAiB,QAAO;AACpD,UAAM,IAAI,MAAM,+DAA+D;AAAA,EACjF;AAEA,SAAO;AACT;","names":[]}
|
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
import {
|
|
2
|
-
|
|
2
|
+
apiUrl,
|
|
3
3
|
createCall
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-CVTVHUNZ.js";
|
|
5
5
|
|
|
6
6
|
// src/index.tsx
|
|
7
7
|
import { EventEmitter as EventEmitter2 } from "eventemitter3";
|
|
8
|
+
import { RoomEvent as RoomEvent2 } from "livekit-client";
|
|
8
9
|
|
|
9
10
|
// src/TrilletWebSDK.ts
|
|
10
11
|
import { EventEmitter } from "eventemitter3";
|
|
@@ -16,6 +17,7 @@ var TrilletWebSDK = class extends EventEmitter {
|
|
|
16
17
|
this.isConnected = false;
|
|
17
18
|
// Audio state tracking
|
|
18
19
|
this.isAssistantSpeaking = false;
|
|
20
|
+
this.krispWanted = false;
|
|
19
21
|
}
|
|
20
22
|
async initializeCall(config) {
|
|
21
23
|
var _a, _b, _c, _d;
|
|
@@ -37,11 +39,10 @@ var TrilletWebSDK = class extends EventEmitter {
|
|
|
37
39
|
this.room.prepareConnection(config.wsUrl, config.token);
|
|
38
40
|
await this.room.connect(config.wsUrl, config.token);
|
|
39
41
|
console.log("Connected to Trillet room:", this.room.name);
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
}
|
|
42
|
+
this.krispWanted = Boolean((_d = config.features) == null ? void 0 : _d.enableKrispNoiseFilter);
|
|
43
|
+
const micAtStart = config.mode === "voice" || config.mode === "multimodal" && config.startWithVoice;
|
|
44
|
+
if (micAtStart) {
|
|
45
|
+
await this.setMicrophone(true);
|
|
45
46
|
}
|
|
46
47
|
this.isConnected = true;
|
|
47
48
|
this.emit("connected");
|
|
@@ -77,6 +78,17 @@ var TrilletWebSDK = class extends EventEmitter {
|
|
|
77
78
|
}
|
|
78
79
|
this.room = void 0;
|
|
79
80
|
}
|
|
81
|
+
/**
|
|
82
|
+
* Turn the microphone on or off and wait for it. Used for a multimodal session's
|
|
83
|
+
* switch to and from voice; Krisp is attached the first time the mic comes on.
|
|
84
|
+
*/
|
|
85
|
+
async setMicrophone(enabled) {
|
|
86
|
+
if (!this.room) return;
|
|
87
|
+
await this.room.localParticipant.setMicrophoneEnabled(enabled);
|
|
88
|
+
if (enabled && this.krispWanted && !this.krispProcessor) {
|
|
89
|
+
await this.setupKrispNoiseFilter();
|
|
90
|
+
}
|
|
91
|
+
}
|
|
80
92
|
toggleMicrophone(enabled) {
|
|
81
93
|
if (this.isConnected && this.room) {
|
|
82
94
|
this.room.localParticipant.setMicrophoneEnabled(enabled);
|
|
@@ -128,14 +140,20 @@ var TrilletWebSDK = class extends EventEmitter {
|
|
|
128
140
|
if (this.isConnected) this.endCall();
|
|
129
141
|
});
|
|
130
142
|
this.room.registerTextStreamHandler("lk.transcription", async (reader, info) => {
|
|
131
|
-
var _a
|
|
132
|
-
const text = await reader.readAll();
|
|
133
|
-
const attributes = ((_a = reader.info) == null ? void 0 : _a.attributes) || {};
|
|
134
|
-
const isFinal = attributes["lk.transcription_final"] === "true";
|
|
143
|
+
var _a;
|
|
135
144
|
if (!info) return;
|
|
136
|
-
const participant = (
|
|
145
|
+
const participant = (_a = this.room) == null ? void 0 : _a.getParticipantByIdentity(info.identity);
|
|
137
146
|
if (!participant) return;
|
|
138
|
-
|
|
147
|
+
let text = "";
|
|
148
|
+
try {
|
|
149
|
+
for await (const chunk of reader) {
|
|
150
|
+
text += chunk;
|
|
151
|
+
if (text.trim()) this.emit("transcript", { text, isFinal: false }, participant);
|
|
152
|
+
}
|
|
153
|
+
} catch (error) {
|
|
154
|
+
console.warn("Trillet SDK: transcription stream ended early", error);
|
|
155
|
+
}
|
|
156
|
+
this.emit("transcript", { text, isFinal: true }, participant);
|
|
139
157
|
});
|
|
140
158
|
this.room.on(RoomEvent.TrackSubscribed, (track, publication) => {
|
|
141
159
|
var _a;
|
|
@@ -257,12 +275,13 @@ var TranscriptManager = class {
|
|
|
257
275
|
}
|
|
258
276
|
handleTranscript(participantId, isAgent, transcriptData) {
|
|
259
277
|
if (transcriptData.isFinal) {
|
|
278
|
+
const hadPartial = participantId in this.currentTranscript;
|
|
260
279
|
delete this.currentTranscript[participantId];
|
|
261
280
|
const text = transcriptData.text.trim();
|
|
262
|
-
if (!text) return
|
|
281
|
+
if (!text) return hadPartial;
|
|
263
282
|
const lastMessage = this.transcripts[this.transcripts.length - 1];
|
|
264
283
|
if (lastMessage && lastMessage.text === text && lastMessage.participantId === participantId && Date.now() - lastMessage.timestamp.getTime() < 1e3) {
|
|
265
|
-
return
|
|
284
|
+
return hadPartial;
|
|
266
285
|
}
|
|
267
286
|
this.transcripts.push({
|
|
268
287
|
role: isAgent ? "assistant" : "user",
|
|
@@ -402,6 +421,10 @@ var TrilletAgent = class extends EventEmitter2 {
|
|
|
402
421
|
constructor(config) {
|
|
403
422
|
super();
|
|
404
423
|
this.sdkToken = null;
|
|
424
|
+
this.muted = false;
|
|
425
|
+
this.voiceEnabled = false;
|
|
426
|
+
// Typed messages the agent will echo back as transcription; see the transcript handler.
|
|
427
|
+
this.recentTyped = [];
|
|
405
428
|
if (!isBrowser) {
|
|
406
429
|
throw new Error("Trillet SDK must be used in a browser environment");
|
|
407
430
|
}
|
|
@@ -421,7 +444,10 @@ var TrilletAgent = class extends EventEmitter2 {
|
|
|
421
444
|
this.setupEventForwarding();
|
|
422
445
|
}
|
|
423
446
|
setupEventForwarding() {
|
|
424
|
-
this.sdk.on("disconnected", () =>
|
|
447
|
+
this.sdk.on("disconnected", () => {
|
|
448
|
+
this.muted = false;
|
|
449
|
+
this.emit("disconnected");
|
|
450
|
+
});
|
|
425
451
|
this.sdk.on("error", (error) => this.emit("error", error));
|
|
426
452
|
this.sdk.on("status", (status) => this.emit("status", status));
|
|
427
453
|
this.sdk.on("metadata", (metadata) => this.emit("metadata", metadata));
|
|
@@ -440,7 +466,21 @@ var TrilletAgent = class extends EventEmitter2 {
|
|
|
440
466
|
this.emit("transcriptUpdate", this.transcriptManager.getTranscripts());
|
|
441
467
|
});
|
|
442
468
|
this.sdk.on("transcript", (transcriptData, participant) => {
|
|
469
|
+
var _a;
|
|
443
470
|
const participantId = participant.identity;
|
|
471
|
+
if (participantId === ((_a = this.sdk.getRoom()) == null ? void 0 : _a.localParticipant.identity)) {
|
|
472
|
+
if (this.config.mode === "text") return;
|
|
473
|
+
if (this.config.mode === "multimodal") {
|
|
474
|
+
const now = Date.now();
|
|
475
|
+
this.recentTyped = this.recentTyped.filter((t) => now - t.at < 15e3);
|
|
476
|
+
const typed = transcriptData.text.trim();
|
|
477
|
+
const match = this.recentTyped.findIndex((t) => t.text === typed || t.text.startsWith(typed));
|
|
478
|
+
if (match !== -1) {
|
|
479
|
+
if (transcriptData.isFinal) this.recentTyped.splice(match, 1);
|
|
480
|
+
return;
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
}
|
|
444
484
|
const isAgent = participantId.startsWith("agent");
|
|
445
485
|
const updated = this.transcriptManager.handleTranscript(participantId, isAgent, transcriptData);
|
|
446
486
|
if (updated) {
|
|
@@ -495,7 +535,8 @@ var TrilletAgent = class extends EventEmitter2 {
|
|
|
495
535
|
agentId: this.config.agentId,
|
|
496
536
|
mode: this.config.mode,
|
|
497
537
|
variables: this.config.variables,
|
|
498
|
-
callbackUrl: this.config.callbackUrl
|
|
538
|
+
callbackUrl: this.config.callbackUrl,
|
|
539
|
+
apiBaseUrl: this.config.apiBaseUrl
|
|
499
540
|
});
|
|
500
541
|
} catch (error) {
|
|
501
542
|
console.error("Trillet SDK Error:", error);
|
|
@@ -514,7 +555,7 @@ var TrilletAgent = class extends EventEmitter2 {
|
|
|
514
555
|
} catch (fpError) {
|
|
515
556
|
console.warn("Trillet SDK: fingerprint generation failed, proceeding without it", fpError);
|
|
516
557
|
}
|
|
517
|
-
const response = await fetch(
|
|
558
|
+
const response = await fetch(apiUrl("/v1/api/web-call/public", this.config.apiBaseUrl), {
|
|
518
559
|
method: "POST",
|
|
519
560
|
headers: {
|
|
520
561
|
"Content-Type": "application/json",
|
|
@@ -524,6 +565,7 @@ var TrilletAgent = class extends EventEmitter2 {
|
|
|
524
565
|
body: JSON.stringify({
|
|
525
566
|
call_agent_id: this.config.agentId,
|
|
526
567
|
mode: this.config.mode,
|
|
568
|
+
...this.config.mode === "multimodal" ? { initial_modality: this.config.startWithVoice ? "voice" : "text" } : {},
|
|
527
569
|
dynamic_variables: this.config.variables || {},
|
|
528
570
|
callback_url: this.config.callbackUrl,
|
|
529
571
|
browser_fingerprint: browserFingerprint,
|
|
@@ -591,17 +633,19 @@ var TrilletAgent = class extends EventEmitter2 {
|
|
|
591
633
|
token: connection.token,
|
|
592
634
|
wsUrl,
|
|
593
635
|
mode: this.config.mode,
|
|
636
|
+
startWithVoice: this.config.startWithVoice,
|
|
594
637
|
audioSettings: {
|
|
595
638
|
sampleRate: 48e3
|
|
596
639
|
},
|
|
597
640
|
features: {
|
|
598
|
-
enableRawAudio: this.config.mode
|
|
641
|
+
enableRawAudio: this.config.mode !== "text",
|
|
599
642
|
// Krisp AI noise cancellation on the local mic for voice calls — cleaner
|
|
600
643
|
// input to STT in noisy environments. Emits `krispStatus` (TRI-629).
|
|
601
|
-
enableKrispNoiseFilter: this.config.mode
|
|
644
|
+
enableKrispNoiseFilter: this.config.mode !== "text"
|
|
602
645
|
}
|
|
603
646
|
});
|
|
604
|
-
|
|
647
|
+
this.voiceEnabled = this.config.mode === "voice" || this.config.mode === "multimodal" && Boolean(this.config.startWithVoice);
|
|
648
|
+
if (this.config.mode !== "text") {
|
|
605
649
|
await this.sdk.enableAudioPlayback();
|
|
606
650
|
}
|
|
607
651
|
this.setupDefaultRpcHandlers();
|
|
@@ -621,6 +665,25 @@ var TrilletAgent = class extends EventEmitter2 {
|
|
|
621
665
|
}
|
|
622
666
|
toggleMicrophone(enabled) {
|
|
623
667
|
this.sdk.toggleMicrophone(enabled);
|
|
668
|
+
this.updateMuted(!enabled);
|
|
669
|
+
}
|
|
670
|
+
/** True while the visitor's microphone is muted on a live voice call. */
|
|
671
|
+
get isMuted() {
|
|
672
|
+
return this.muted;
|
|
673
|
+
}
|
|
674
|
+
/**
|
|
675
|
+
* Mute or unmute the visitor's microphone and wait for LiveKit to apply it.
|
|
676
|
+
* Emits `muteChanged` (boolean). A no-op when no call is connected.
|
|
677
|
+
*/
|
|
678
|
+
async setMuted(muted) {
|
|
679
|
+
if (!this.sdk.isConnected) return;
|
|
680
|
+
await this.sdk.setMicrophone(!muted);
|
|
681
|
+
this.updateMuted(muted);
|
|
682
|
+
}
|
|
683
|
+
updateMuted(muted) {
|
|
684
|
+
if (this.muted === muted) return;
|
|
685
|
+
this.muted = muted;
|
|
686
|
+
this.emit("muteChanged", muted);
|
|
624
687
|
}
|
|
625
688
|
get isAssistantSpeaking() {
|
|
626
689
|
return this.sdk.isAssistantSpeaking;
|
|
@@ -682,8 +745,70 @@ var TrilletAgent = class extends EventEmitter2 {
|
|
|
682
745
|
throw error;
|
|
683
746
|
}
|
|
684
747
|
}
|
|
748
|
+
/** Multimodal: whether the microphone/voice side is currently on. */
|
|
749
|
+
get isVoiceEnabled() {
|
|
750
|
+
return this.voiceEnabled;
|
|
751
|
+
}
|
|
752
|
+
/**
|
|
753
|
+
* Multimodal only: switch the SAME conversation between typing and talking. Turns
|
|
754
|
+
* the mic on/off and tells the agent, which turns its speech on/off and keeps the
|
|
755
|
+
* whole conversation in context. Emits `modalityChanged` with 'voice' | 'text'.
|
|
756
|
+
*/
|
|
757
|
+
async setVoiceEnabled(enabled) {
|
|
758
|
+
if (this.config.mode !== "multimodal") {
|
|
759
|
+
console.warn("setVoiceEnabled is only available in multimodal mode.");
|
|
760
|
+
return;
|
|
761
|
+
}
|
|
762
|
+
const room = this.sdk.getRoom();
|
|
763
|
+
if (!room || !this.sdk.isConnected) throw new Error("Not connected.");
|
|
764
|
+
if (enabled === this.voiceEnabled) return;
|
|
765
|
+
await this.sdk.setMicrophone(enabled);
|
|
766
|
+
if (enabled) await this.sdk.enableAudioPlayback();
|
|
767
|
+
try {
|
|
768
|
+
await this.waitForAgent(15e3);
|
|
769
|
+
await this.sendRpcMessage("trillet.set_modality", JSON.stringify({ mode: enabled ? "voice" : "text" }), 8e3);
|
|
770
|
+
} catch (error) {
|
|
771
|
+
await this.sdk.setMicrophone(!enabled).catch(() => void 0);
|
|
772
|
+
throw error;
|
|
773
|
+
}
|
|
774
|
+
this.voiceEnabled = enabled;
|
|
775
|
+
this.emit("modalityChanged", enabled ? "voice" : "text");
|
|
776
|
+
}
|
|
777
|
+
/**
|
|
778
|
+
* Resolve once the agent's session is ready to receive (its `lk.agent.state` has
|
|
779
|
+
* moved past "initializing"), or reject after `timeoutMs`. Joining the room is not
|
|
780
|
+
* enough: a text message sent before the session listens is silently dropped.
|
|
781
|
+
*/
|
|
782
|
+
waitForAgent(timeoutMs) {
|
|
783
|
+
const room = this.sdk.getRoom();
|
|
784
|
+
const ready = () => {
|
|
785
|
+
var _a;
|
|
786
|
+
return Array.from((_a = room == null ? void 0 : room.remoteParticipants.values()) != null ? _a : []).some((p) => {
|
|
787
|
+
var _a2;
|
|
788
|
+
if (!p.identity.startsWith("agent")) return false;
|
|
789
|
+
const state = (_a2 = p.attributes) == null ? void 0 : _a2["lk.agent.state"];
|
|
790
|
+
return !state || state !== "initializing";
|
|
791
|
+
});
|
|
792
|
+
};
|
|
793
|
+
if (!room || ready()) return Promise.resolve();
|
|
794
|
+
return new Promise((resolve, reject) => {
|
|
795
|
+
const done = (ok) => {
|
|
796
|
+
clearTimeout(timer);
|
|
797
|
+
room.off(RoomEvent2.ParticipantConnected, check);
|
|
798
|
+
room.off(RoomEvent2.ParticipantAttributesChanged, check);
|
|
799
|
+
if (ok) resolve();
|
|
800
|
+
else reject(new Error("The agent is not ready yet. Please try again."));
|
|
801
|
+
};
|
|
802
|
+
const check = () => {
|
|
803
|
+
if (ready()) done(true);
|
|
804
|
+
};
|
|
805
|
+
const timer = setTimeout(() => done(ready()), timeoutMs);
|
|
806
|
+
room.on(RoomEvent2.ParticipantConnected, check);
|
|
807
|
+
room.on(RoomEvent2.ParticipantAttributesChanged, check);
|
|
808
|
+
});
|
|
809
|
+
}
|
|
685
810
|
async sendTextMessage(text) {
|
|
686
|
-
if (this.config.mode
|
|
811
|
+
if (this.config.mode === "voice") {
|
|
687
812
|
console.warn("Cannot send text message in voice mode.");
|
|
688
813
|
return;
|
|
689
814
|
}
|
|
@@ -692,7 +817,14 @@ var TrilletAgent = class extends EventEmitter2 {
|
|
|
692
817
|
this.emit("error", new Error("Not connected. Cannot send message."));
|
|
693
818
|
return;
|
|
694
819
|
}
|
|
820
|
+
try {
|
|
821
|
+
await this.waitForAgent(3e4);
|
|
822
|
+
} catch (error) {
|
|
823
|
+
this.emit("error", error instanceof Error ? error : new Error(String(error)));
|
|
824
|
+
return;
|
|
825
|
+
}
|
|
695
826
|
this.transcriptManager.addMessage("user", text, room.localParticipant.identity);
|
|
827
|
+
this.recentTyped.push({ text: text.trim(), at: Date.now() });
|
|
696
828
|
this.emit("transcriptUpdate", this.getTranscripts());
|
|
697
829
|
try {
|
|
698
830
|
await room.localParticipant.sendText(text, { topic: "lk.chat" });
|
|
@@ -715,4 +847,4 @@ export {
|
|
|
715
847
|
BrowserFingerprint,
|
|
716
848
|
TrilletAgent
|
|
717
849
|
};
|
|
718
|
-
//# sourceMappingURL=chunk-
|
|
850
|
+
//# sourceMappingURL=chunk-IASKK2IK.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.tsx","../src/TrilletWebSDK.ts","../src/TranscriptManager.ts","../src/BrowserFingerprint.ts"],"sourcesContent":["import { EventEmitter } from 'eventemitter3';\nimport { Participant, RoomEvent } from 'livekit-client';\nimport { TrilletWebSDK } from './TrilletWebSDK.js';\nimport { TranscriptManager, Transcript } from './TranscriptManager.js';\nimport { BrowserFingerprint } from './BrowserFingerprint.js';\nimport { createCall, apiUrl, TrilletRoomDetails } from './createCall.js';\n\n// Export BrowserFingerprint for external use\nexport { BrowserFingerprint };\n\n// Shared room-details type (see ./createCall.ts). Re-exported so consumers can\n// import it from the package root as well as from the `/server` subpath.\nexport type { TrilletRoomDetails };\n\n// Fallback LiveKit cluster URL. Used only when the server response omits\n// connection.url — the server-provided url is always preferred.\nconst FALLBACK_WS_URL = 'wss://trillet-ai-xdx0dw5r.livekit.cloud';\n\nconst decoder = new TextDecoder();\n\n// Browser compatibility check\nconst isBrowser = typeof window !== 'undefined';\n// Safari iOS in private mode (and some proxy configs) returns isSecureContext=false\n// even on HTTPS. Fall back to protocol/hostname so we don't block valid contexts.\nconst isSecureContext =\n isBrowser &&\n (window.isSecureContext ||\n window.location.protocol === 'https:' ||\n window.location.hostname === 'localhost' ||\n window.location.hostname === '127.0.0.1');\n\nexport interface TrilletAgentConfig {\n // Direct authentication (not recommended for production)\n apiKey?: string;\n workspaceId?: string;\n\n // Required parameters\n agentId: string;\n variables?: Record<string, any>;\n callbackUrl?: string;\n /**\n * `voice` and `text` are single-modality sessions. `multimodal` is one conversation\n * the visitor can type in or talk in, switching any time with {@link setVoiceEnabled}.\n */\n mode?: 'voice' | 'text' | 'multimodal';\n /** Multimodal only: start with the microphone on (the visitor chose to call). */\n startWithVoice?: boolean;\n /** Override the API host (whitelabel API domain, or a local backend in development). */\n apiBaseUrl?: string;\n\n // Demo link tracking\n demoHash?: string; // Optional hash for demo link tracking\n\n /**\n * Pre-call gate. Awaited once at the top of every call-start path — before any\n * network request or LiveKit connection — so a rejection aborts the call cleanly\n * with nothing minted and nothing connected.\n *\n * Plug your own verification in here: a reCAPTCHA challenge you verify on your\n * server, a login check, a quota lookup. Throw (or reject) to block the call; the\n * error propagates to the caller and is emitted on the `error` event.\n *\n * @example\n * const agent = new TrilletAgent({\n * agentId,\n * onBeforeCall: async () => {\n * const ok = await myServer.verifyHuman();\n * if (!ok) throw new Error('Verification failed');\n * },\n * });\n */\n onBeforeCall?: () => Promise<void>;\n}\n\ninterface RpcInvocationData {\n requestId: string;\n callerIdentity: string;\n payload: any;\n responseTimeout: number;\n}\n\ninterface RpcMethodCall {\n method: string;\n payload: any;\n participant: any;\n}\n\nexport class TrilletAgent extends EventEmitter {\n private sdk: TrilletWebSDK;\n private config: TrilletAgentConfig;\n private sdkToken: string | null = null;\n private transcriptManager: TranscriptManager;\n\n constructor(config: TrilletAgentConfig) {\n super();\n\n // Validate environment\n if (!isBrowser) {\n throw new Error('Trillet SDK must be used in a browser environment');\n }\n\n if (!isSecureContext) {\n throw new Error('Trillet SDK requires a secure context (HTTPS or localhost)');\n }\n\n if (!config.agentId) {\n throw new Error('agentId is required');\n }\n\n this.config = {\n ...config,\n mode: config.mode || 'voice', // Default to voice mode\n };\n\n this.sdk = new TrilletWebSDK();\n this.transcriptManager = new TranscriptManager();\n this.setupEventForwarding();\n }\n\n private setupEventForwarding(): void {\n // Forward all SDK events to agent listeners\n this.sdk.on('disconnected', () => {\n // A new call always starts unmuted.\n this.muted = false;\n this.emit('disconnected');\n });\n this.sdk.on('error', (error) => this.emit('error', error));\n this.sdk.on('status', (status) => this.emit('status', status));\n this.sdk.on('metadata', (metadata) => this.emit('metadata', metadata));\n this.sdk.on('assistantStartedSpeaking', () => this.emit('assistantStartedSpeaking'));\n this.sdk.on('assistantStoppedSpeaking', () => this.emit('assistantStoppedSpeaking'));\n this.sdk.on('audioData', (data) => this.emit('audioData', data));\n this.sdk.on('krispStatus', (status) => this.emit('krispStatus', status));\n\n // Handle incoming tool usage from the agent\n this.sdk.on('toolStarted', (toolCall: { name: string; args: any }) => {\n this.transcriptManager.addToolStarted(toolCall);\n this.emit('toolStarted', toolCall);\n this.emit('transcriptUpdate', this.transcriptManager.getTranscripts());\n });\n\n this.sdk.on('toolCompleted', (toolResult: { name: string; result: any; isError: boolean }) => {\n this.transcriptManager.addToolCompleted(toolResult);\n this.emit('toolCompleted', toolResult);\n this.emit('transcriptUpdate', this.transcriptManager.getTranscripts());\n });\n\n this.sdk.on('transcript', (transcriptData: { text: string; isFinal: boolean }, participant: Participant) => {\n const participantId = participant.identity;\n // The agent echoes the visitor's own typed turns back as transcription, and\n // sendTextMessage already added them. Text mode: skip every echo. Multimodal:\n // the visitor's SPOKEN turns arrive the same way and must stay, so only skip an\n // echo that matches something just typed.\n if (participantId === this.sdk.getRoom()?.localParticipant.identity) {\n if (this.config.mode === 'text') return;\n if (this.config.mode === 'multimodal') {\n const now = Date.now();\n this.recentTyped = this.recentTyped.filter((t) => now - t.at < 15000);\n const typed = transcriptData.text.trim();\n const match = this.recentTyped.findIndex((t) => t.text === typed || t.text.startsWith(typed));\n if (match !== -1) {\n if (transcriptData.isFinal) this.recentTyped.splice(match, 1);\n return;\n }\n }\n }\n const isAgent = participantId.startsWith('agent');\n\n const updated = this.transcriptManager.handleTranscript(participantId, isAgent, transcriptData);\n if (updated) {\n this.emit('transcriptUpdate', this.transcriptManager.getTranscripts());\n }\n });\n\n // Handle incoming text messages from the agent\n this.sdk.on('message', (message: { text: string; [key: string]: any }) => {\n const agentParticipant = Array.from(this.sdk.getRoom()?.remoteParticipants.values() ?? []).find((p) => p.identity.startsWith('agent'));\n this.transcriptManager.addMessage('assistant', message.text, agentParticipant?.identity);\n this.emit('message', message);\n this.emit('transcriptUpdate', this.transcriptManager.getTranscripts());\n });\n }\n\n /**\n * Set up default RPC handlers for common agent interactions\n * This should be called after connection is established\n */\n private setupDefaultRpcHandlers(): void {\n // Register handler for receiving chat messages from agent\n this.registerRpcMethod('receiveChatMessage', async (data: any) => {\n const messageText = typeof data.payload === 'string' ? data.payload : data.payload?.text || '';\n \n if (messageText) {\n const agentParticipant = Array.from(this.sdk.getRoom()?.remoteParticipants.values() ?? []).find((p) =>\n p.identity.startsWith('agent')\n );\n \n this.transcriptManager.addMessage('assistant', messageText, agentParticipant?.identity);\n \n this.emit('message', { text: messageText });\n this.emit('transcriptUpdate', this.transcriptManager.getTranscripts());\n }\n \n return 'Message received';\n });\n\n // Register handler for agent status updates\n this.registerRpcMethod('agentStatus', async (data: any) => {\n this.emit('status', data.payload);\n return 'Status received';\n });\n }\n\n /**\n * **Server-side only — requires an API key, do not call from the browser.**\n *\n * Puts a full-privilege `X-API-KEY` on the request, so this must run where the\n * key is safe. For the secure pattern, mint the room on your backend with\n * `createCall` (from `@trillet-ai/web-sdk/server`) and call {@link joinRoom} in\n * the browser instead. Kept for backward compatibility.\n */\n public async startCall(): Promise<void> {\n // Gate first: a rejection here must cost nothing — no room minted, no connection.\n await this.runBeforeCall();\n\n let data: TrilletRoomDetails;\n try {\n // Performs the authenticated POST /v1/api/web-call and returns room details\n // keyed off `connection`. Shared with the `/server` createCall export.\n data = await createCall({\n apiKey: this.config.apiKey!,\n agentId: this.config.agentId,\n mode: this.config.mode,\n variables: this.config.variables,\n callbackUrl: this.config.callbackUrl,\n apiBaseUrl: this.config.apiBaseUrl,\n });\n } catch (error) {\n console.error('Trillet SDK Error:', error);\n this.emit('error', error instanceof Error ? error : new Error(String(error)));\n throw error;\n }\n\n // connectToRoom owns its own error emission + rethrow. Called instead of the\n // public joinRoom so onBeforeCall is not run a second time.\n await this.connectToRoom(data);\n }\n\n public async startPublicCall(): Promise<void> {\n // Gate first: a rejection here must cost nothing — no room minted, no connection.\n await this.runBeforeCall();\n\n let data: TrilletRoomDetails;\n try {\n // Generate browser fingerprint before making the call.\n // Non-fatal: if it fails (Safari iOS quirks with crypto.subtle / canvas.toDataURL\n // in private mode or restricted contexts), fall back to null so the fetch still\n // happens. Backend's per-user limit tracking degrades gracefully.\n let browserFingerprint: string | null = null;\n try {\n browserFingerprint = await BrowserFingerprint.generate();\n } catch (fpError) {\n console.warn('Trillet SDK: fingerprint generation failed, proceeding without it', fpError);\n }\n\n // 2. Initialize public call\n const response = await fetch(apiUrl('/v1/api/web-call/public', this.config.apiBaseUrl), {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n 'x-workspace-id': this.config.workspaceId!,\n },\n body: JSON.stringify({\n call_agent_id: this.config.agentId,\n mode: this.config.mode,\n ...(this.config.mode === 'multimodal'\n ? { initial_modality: this.config.startWithVoice ? 'voice' : 'text' }\n : {}),\n dynamic_variables: this.config.variables || {},\n callback_url: this.config.callbackUrl,\n browser_fingerprint: browserFingerprint,\n demo_hash: this.config.demoHash, // Send demo hash if provided\n }),\n });\n\n if (!response.ok) {\n let errorMessage;\n try {\n const errorData = await response.json();\n errorMessage = errorData.message || errorData.error || 'Unknown error';\n } catch {\n errorMessage = await response.text();\n }\n throw new Error(`API Error: ${errorMessage}`);\n }\n\n data = await response.json();\n } catch (error) {\n console.error('Trillet SDK Error (public call):', error);\n this.emit('error', error instanceof Error ? error : new Error(String(error)));\n throw error;\n }\n\n // Key off the `connection` object (consistent across both endpoints) rather\n // than the inconsistent top-level token/roomName fields. connectToRoom owns its\n // own error emission + rethrow, and skips the already-run onBeforeCall gate.\n await this.connectToRoom(data);\n }\n\n /**\n * Connect to a pre-minted Trillet room. The secure browser entry point: takes\n * the room details returned by `createCall` (server-side) and joins LiveKit\n * directly — makes NO Trillet API call, so no API key, workspaceId or agentId\n * ever reaches the browser.\n *\n * @param roomDetails - the backend response, e.g. `{ connection: { url, token }, ... }`\n */\n public async joinRoom(roomDetails: TrilletRoomDetails): Promise<void> {\n await this.runBeforeCall();\n await this.connectToRoom(roomDetails);\n }\n\n /**\n * Run the caller's pre-call gate, if any.\n *\n * Invoked by each public call-start path exactly once. `startCall` and\n * `startPublicCall` therefore delegate to {@link connectToRoom} rather than to the\n * public {@link joinRoom} — routing them through `joinRoom` would fire a customer's\n * hook a second time per call, re-running their challenge or verification request.\n */\n private async runBeforeCall(): Promise<void> {\n if (!this.config.onBeforeCall) return;\n\n try {\n await this.config.onBeforeCall();\n } catch (error) {\n console.error('Trillet SDK Error (onBeforeCall):', error);\n this.emit('error', error instanceof Error ? error : new Error(String(error)));\n throw error;\n }\n }\n\n /** Join LiveKit. Assumes the pre-call gate has already run. */\n private async connectToRoom(roomDetails: TrilletRoomDetails): Promise<void> {\n try {\n const connection = roomDetails?.connection;\n if (!connection?.token) {\n throw new Error('Invalid room details: missing connection token');\n }\n\n // Prefer the server-provided WebSocket URL; fall back to the cluster default\n // only when it is missing.\n const wsUrl = connection.url || FALLBACK_WS_URL;\n\n await this.sdk.initializeCall({\n token: connection.token,\n wsUrl,\n mode: this.config.mode,\n startWithVoice: this.config.startWithVoice,\n audioSettings: {\n sampleRate: 48000,\n },\n features: {\n enableRawAudio: this.config.mode !== 'text',\n // Krisp AI noise cancellation on the local mic for voice calls — cleaner\n // input to STT in noisy environments. Emits `krispStatus` (TRI-629).\n enableKrispNoiseFilter: this.config.mode !== 'text',\n },\n });\n this.voiceEnabled =\n this.config.mode === 'voice' || (this.config.mode === 'multimodal' && Boolean(this.config.startWithVoice));\n\n // Audio playback for anything that can speak. Must run inside the visitor's\n // click (browsers block autoplay), which is why multimodal starts it up front.\n if (this.config.mode !== 'text') {\n await this.sdk.enableAudioPlayback();\n }\n\n // Set up default RPC handlers for text communication\n this.setupDefaultRpcHandlers();\n\n // Emit connection details, guarding fields that may be undefined.\n this.emit('connected', {\n callId: roomDetails.call_id,\n roomName: roomDetails.room_name,\n display: roomDetails.display,\n });\n } catch (error) {\n console.error('Trillet SDK Error (joinRoom):', error);\n this.emit('error', error instanceof Error ? error : new Error(String(error)));\n throw error;\n }\n }\n\n public endCall(): void {\n this.sdk.endCall();\n }\n\n public toggleMicrophone(enabled: boolean): void {\n this.sdk.toggleMicrophone(enabled);\n this.updateMuted(!enabled);\n }\n\n private muted = false;\n\n /** True while the visitor's microphone is muted on a live voice call. */\n public get isMuted(): boolean {\n return this.muted;\n }\n\n /**\n * Mute or unmute the visitor's microphone and wait for LiveKit to apply it.\n * Emits `muteChanged` (boolean). A no-op when no call is connected.\n */\n public async setMuted(muted: boolean): Promise<void> {\n if (!this.sdk.isConnected) return;\n await this.sdk.setMicrophone(!muted);\n this.updateMuted(muted);\n }\n\n private updateMuted(muted: boolean): void {\n if (this.muted === muted) return;\n this.muted = muted;\n this.emit('muteChanged', muted);\n }\n\n public get isAssistantSpeaking(): boolean {\n return this.sdk.isAssistantSpeaking;\n }\n\n public getTranscripts(): Transcript[] {\n return this.transcriptManager.getTranscripts();\n }\n\n public getCurrentTranscript(): { [key: string]: string } {\n return this.transcriptManager.getCurrentTranscript();\n }\n\n /**\n * Register an RPC method handler for receiving calls from the agent\n * @param method - The RPC method name to handle\n * @param handler - The function to handle the RPC call\n */\n public registerRpcMethod(method: string, handler: (data: any) => Promise<any> | any): void {\n const room = this.sdk.getRoom();\n if (!room) {\n console.warn('Cannot register RPC method: not connected to room');\n return;\n }\n\n room.localParticipant.registerRpcMethod(method, async (data: any) => {\n try {\n const result = await handler(data);\n return result;\n } catch (error) {\n console.error(`RPC method ${method} error:`, error);\n throw error;\n }\n });\n }\n\n /**\n * Send an RPC call to the agent\n * @param method - The RPC method name\n * @param payload - The data to send\n * @param responseTimeout - Timeout in milliseconds (default: 30000)\n */\n public async sendRpcMessage(method: string, payload: any, responseTimeout: number = 30000): Promise<any> {\n const room = this.sdk.getRoom();\n if (!room || !this.sdk.isConnected) {\n throw new Error('Not connected. Cannot send RPC message.');\n }\n\n const agentParticipant = Array.from(room.remoteParticipants.values()).find((p) =>\n p.identity.startsWith('agent')\n );\n\n if (!agentParticipant) {\n throw new Error('No agent found to send RPC message to.');\n }\n\n try {\n const response = await room.localParticipant.performRpc({\n destinationIdentity: agentParticipant.identity,\n method,\n payload,\n responseTimeout,\n });\n return response;\n } catch (error) {\n console.error(`RPC call to method ${method} failed:`, error);\n throw error;\n }\n }\n\n private voiceEnabled = false;\n // Typed messages the agent will echo back as transcription; see the transcript handler.\n private recentTyped: { text: string; at: number }[] = [];\n\n /** Multimodal: whether the microphone/voice side is currently on. */\n public get isVoiceEnabled(): boolean {\n return this.voiceEnabled;\n }\n\n /**\n * Multimodal only: switch the SAME conversation between typing and talking. Turns\n * the mic on/off and tells the agent, which turns its speech on/off and keeps the\n * whole conversation in context. Emits `modalityChanged` with 'voice' | 'text'.\n */\n public async setVoiceEnabled(enabled: boolean): Promise<void> {\n if (this.config.mode !== 'multimodal') {\n console.warn('setVoiceEnabled is only available in multimodal mode.');\n return;\n }\n const room = this.sdk.getRoom();\n if (!room || !this.sdk.isConnected) throw new Error('Not connected.');\n if (enabled === this.voiceEnabled) return;\n\n // Mic first: if permission is refused, the agent never switches and the\n // conversation stays in text.\n await this.sdk.setMicrophone(enabled);\n if (enabled) await this.sdk.enableAudioPlayback();\n try {\n // The agent can still be joining (a switch tapped in the first seconds).\n await this.waitForAgent(15000);\n await this.sendRpcMessage('trillet.set_modality', JSON.stringify({ mode: enabled ? 'voice' : 'text' }), 8000);\n } catch (error) {\n await this.sdk.setMicrophone(!enabled).catch(() => undefined);\n throw error;\n }\n this.voiceEnabled = enabled;\n this.emit('modalityChanged', enabled ? 'voice' : 'text');\n }\n\n /**\n * Resolve once the agent's session is ready to receive (its `lk.agent.state` has\n * moved past \"initializing\"), or reject after `timeoutMs`. Joining the room is not\n * enough: a text message sent before the session listens is silently dropped.\n */\n private waitForAgent(timeoutMs: number): Promise<void> {\n const room = this.sdk.getRoom();\n const ready = () =>\n Array.from(room?.remoteParticipants.values() ?? []).some((p) => {\n if (!p.identity.startsWith('agent')) return false;\n const state = p.attributes?.['lk.agent.state'];\n // Older agents never set the attribute: being present is the best signal.\n return !state || state !== 'initializing';\n });\n if (!room || ready()) return Promise.resolve();\n return new Promise((resolve, reject) => {\n const done = (ok: boolean) => {\n clearTimeout(timer);\n room.off(RoomEvent.ParticipantConnected, check);\n room.off(RoomEvent.ParticipantAttributesChanged, check);\n if (ok) resolve();\n else reject(new Error('The agent is not ready yet. Please try again.'));\n };\n const check = () => {\n if (ready()) done(true);\n };\n const timer = setTimeout(() => done(ready()), timeoutMs);\n room.on(RoomEvent.ParticipantConnected, check);\n room.on(RoomEvent.ParticipantAttributesChanged, check);\n });\n }\n\n public async sendTextMessage(text: string): Promise<void> {\n if (this.config.mode === 'voice') {\n console.warn('Cannot send text message in voice mode.');\n return;\n }\n\n const room = this.sdk.getRoom();\n if (!room || !this.sdk.isConnected) {\n this.emit('error', new Error('Not connected. Cannot send message.'));\n return;\n }\n\n // Text streams only reach participants already in the room, so a message sent\n // before the agent joins would be lost.\n try {\n await this.waitForAgent(30000);\n } catch (error) {\n this.emit('error', error instanceof Error ? error : new Error(String(error)));\n return;\n }\n\n // Add user message to transcripts immediately\n this.transcriptManager.addMessage('user', text, room.localParticipant.identity);\n this.recentTyped.push({ text: text.trim(), at: Date.now() });\n this.emit('transcriptUpdate', this.getTranscripts());\n\n // Send the text message using LiveKit's sendText API with topic 'lk.chat'.\n try {\n await room.localParticipant.sendText(text, { topic: 'lk.chat' });\n console.log('Text message sent to agent:', text);\n } catch (error) {\n console.error('Failed to send text message:', error);\n this.emit('error', new Error(`Failed to send message: ${error instanceof Error ? error.message : String(error)}`));\n }\n }\n\n /**\n * Get the browser fingerprint for this session\n * Useful for demo pages to send fingerprint when checking limits\n */\n public async getBrowserFingerprint(): Promise<string> {\n return await BrowserFingerprint.generate();\n }\n}\n","import { EventEmitter } from 'eventemitter3';\nimport { RemoteParticipant, RemoteTrack, RemoteAudioTrack, RemoteTrackPublication, Room, RoomEvent, Track, createAudioAnalyser, Participant, LocalAudioTrack } from 'livekit-client';\nimport type { KrispNoiseFilterProcessor } from '@livekit/krisp-noise-filter';\n\nconst decoder = new TextDecoder();\n\nexport interface TrilletCallConfig {\n token: string;\n wsUrl: string; // LiveKit WebSocket URL\n audioSettings?: {\n sampleRate?: number;\n inputDeviceId?: string; // Device ID for audio input\n outputDeviceId?: string; // Device ID for audio output\n };\n mode?: 'voice' | 'text' | 'multimodal';\n /** Multimodal sessions: turn the microphone on at connect (visitor chose Call). */\n startWithVoice?: boolean;\n features?: {\n enableRawAudio?: boolean; // Enable raw audio sampling for visualizations\n enableKrispNoiseFilter?: boolean; // Enable Krisp AI noise cancellation for local microphone\n };\n}\n\n// Internal SDK class\nexport class TrilletWebSDK extends EventEmitter {\n private room: Room | undefined;\n public isConnected: boolean = false;\n\n // Audio state tracking\n public isAssistantSpeaking: boolean = false;\n\n // Audio analysis tools\n public audioAnalyzer?: {\n calculateVolume: () => number;\n analyser: AnalyserNode;\n cleanup: () => Promise<void>;\n };\n\n // Krisp noise filter processor\n private krispProcessor?: KrispNoiseFilterProcessor;\n\n private audioFrameCapture: number | undefined;\n\n constructor() {\n super();\n }\n\n public async initializeCall(config: TrilletCallConfig): Promise<void> {\n try {\n this.room = new Room({\n audioCaptureDefaults: {\n autoGainControl: true,\n echoCancellation: true,\n noiseSuppression: true,\n channelCount: 1,\n deviceId: config.audioSettings?.inputDeviceId,\n sampleRate: config.audioSettings?.sampleRate,\n },\n audioOutput: {\n deviceId: config.audioSettings?.outputDeviceId,\n },\n });\n\n this.setupEventHandlers(config);\n\n this.room.prepareConnection(config.wsUrl, config.token);\n await this.room.connect(config.wsUrl, config.token);\n console.log('Connected to Trillet room:', this.room.name);\n\n this.krispWanted = Boolean(config.features?.enableKrispNoiseFilter);\n const micAtStart = config.mode === 'voice' || (config.mode === 'multimodal' && config.startWithVoice);\n if (micAtStart) {\n await this.setMicrophone(true);\n }\n this.isConnected = true;\n this.emit('connected');\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Failed to initialize call';\n this.emit('error', errorMessage);\n console.error('Call initialization failed:', error);\n this.endCall();\n throw error; // Re-throw to let TrilletAgent handle it\n }\n }\n\n public async enableAudioPlayback(): Promise<void> {\n await this.room?.startAudio();\n }\n\n public endCall(): void {\n if (!this.isConnected) return;\n\n this.isConnected = false;\n this.emit('disconnected');\n this.room?.disconnect();\n\n this.isAssistantSpeaking = false;\n\n if (this.audioAnalyzer) {\n this.audioAnalyzer.cleanup();\n this.audioAnalyzer = undefined;\n }\n\n if (this.audioFrameCapture) {\n cancelAnimationFrame(this.audioFrameCapture);\n this.audioFrameCapture = undefined;\n }\n\n // Cleanup Krisp processor\n if (this.krispProcessor) {\n this.krispProcessor = undefined;\n }\n\n this.room = undefined;\n }\n\n private krispWanted = false;\n\n /**\n * Turn the microphone on or off and wait for it. Used for a multimodal session's\n * switch to and from voice; Krisp is attached the first time the mic comes on.\n */\n public async setMicrophone(enabled: boolean): Promise<void> {\n if (!this.room) return;\n await this.room.localParticipant.setMicrophoneEnabled(enabled);\n if (enabled && this.krispWanted && !this.krispProcessor) {\n await this.setupKrispNoiseFilter();\n }\n }\n\n public toggleMicrophone(enabled: boolean): void {\n if (this.isConnected && this.room) {\n this.room.localParticipant.setMicrophoneEnabled(enabled);\n }\n }\n\n private async setupKrispNoiseFilter(): Promise<void> {\n if (!this.room) return;\n\n try {\n // Dynamically import Krisp noise filter\n const { KrispNoiseFilter, isKrispNoiseFilterSupported } = await import('@livekit/krisp-noise-filter');\n\n // Check browser compatibility\n if (!isKrispNoiseFilterSupported()) {\n console.warn('Krisp noise filter is not supported on this browser');\n this.emit('krispStatus', { enabled: false, supported: false });\n return;\n }\n\n // Get the local microphone track\n const microphoneTrack = this.room.localParticipant.getTrackPublication(Track.Source.Microphone)?.track;\n\n if (microphoneTrack && microphoneTrack instanceof LocalAudioTrack) {\n // Initialize the Krisp processor\n this.krispProcessor = KrispNoiseFilter();\n await microphoneTrack.setProcessor(this.krispProcessor);\n\n // Enable the noise filter\n await this.krispProcessor.setEnabled(true);\n console.log('Krisp noise filter enabled successfully');\n this.emit('krispStatus', { enabled: true, supported: true });\n } else {\n console.warn('Could not find local microphone track to apply Krisp filter');\n this.emit('krispStatus', { enabled: false, supported: true });\n }\n } catch (error) {\n console.error('Failed to setup Krisp noise filter:', error);\n this.emit('krispStatus', { enabled: false, supported: false });\n }\n }\n\n private captureAudio(): void {\n if (!this.isConnected || !this.audioAnalyzer) return;\n\n const bufferSize = this.audioAnalyzer.analyser.fftSize;\n const audioData = new Float32Array(bufferSize);\n this.audioAnalyzer.analyser.getFloatTimeDomainData(audioData);\n this.emit('audioData', audioData);\n\n this.audioFrameCapture = requestAnimationFrame(() => this.captureAudio());\n }\n\n private setupEventHandlers(config: TrilletCallConfig): void {\n let wasAgentSpeaking = false;\n if (!this.room) return;\n\n // Room events\n this.room.on(RoomEvent.ParticipantDisconnected, (participant: RemoteParticipant) => {\n if (participant?.identity === 'assistant') {\n this.endCall();\n }\n });\n\n this.room.on(RoomEvent.Disconnected, () => {\n if (this.isConnected) this.endCall();\n });\n\n // One text stream = one transcript segment. The worker opens every segment with\n // `lk.transcription_final=false` in the stream HEADER and only finishes it by\n // closing the stream, so the header attribute is never a usable finality signal.\n // Close of stream is the end of the segment. Chunks are read as they arrive so text\n // replies render progressively (partials), then once more as final on close.\n this.room.registerTextStreamHandler('lk.transcription', async (reader, info) => {\n if (!info) return;\n const participant = this.room?.getParticipantByIdentity(info.identity);\n if (!participant) return;\n\n let text = '';\n try {\n for await (const chunk of reader) {\n text += chunk;\n if (text.trim()) this.emit('transcript', { text, isFinal: false }, participant);\n }\n } catch (error) {\n console.warn('Trillet SDK: transcription stream ended early', error);\n }\n this.emit('transcript', { text, isFinal: true }, participant);\n });\n\n // Audio events\n this.room.on(RoomEvent.TrackSubscribed, (track: RemoteTrack, publication: RemoteTrackPublication) => {\n if (track.kind === Track.Kind.Audio) {\n if (publication.trackName === 'assistant_audio' && track instanceof RemoteAudioTrack && config.features?.enableRawAudio) {\n const analyzer = createAudioAnalyser(track);\n this.audioAnalyzer = {\n calculateVolume: analyzer.calculateVolume,\n analyser: analyzer.analyser,\n cleanup: analyzer.cleanup,\n };\n this.audioFrameCapture = requestAnimationFrame(() => this.captureAudio());\n }\n track.attach();\n }\n });\n\n // Data events\n this.room.on(RoomEvent.DataReceived, (payload: Uint8Array, participant?: RemoteParticipant) => {\n if (!participant?.identity.startsWith('agent')) return;\n\n try {\n const data = JSON.parse(decoder.decode(payload));\n this.handleDataEvent(data, participant);\n } catch (error) {\n console.error('Failed to process received data:', error);\n }\n });\n\n this.room.on(RoomEvent.ActiveSpeakersChanged, (speakers: Participant[]) => {\n const isAgentSpeaking = speakers.some((p) => p.identity.startsWith('agent'));\n\n if (isAgentSpeaking && !wasAgentSpeaking) {\n this.emit('assistantStartedSpeaking');\n } else if (!isAgentSpeaking && wasAgentSpeaking) {\n this.emit('assistantStoppedSpeaking');\n }\n\n wasAgentSpeaking = isAgentSpeaking;\n });\n\n // Handle RPC events if available\n // Note: LiveKit may not have specific RPC events, but we can monitor participant events\n this.room.on(RoomEvent.ParticipantConnected, (participant: RemoteParticipant) => {\n console.log('Participant connected:', participant.identity);\n if (participant.identity.startsWith('agent')) {\n console.log('Agent connected, RPC communication available');\n }\n });\n }\n\n private handleDataEvent(event: any, participant: RemoteParticipant): void {\n switch (event.type) {\n case 'status':\n this.emit('status', event);\n break;\n case 'metadata':\n this.emit('metadata', event);\n break;\n case 'transcript':\n // this is for agent-generated transcripts, which we are overriding with lk.transcription\n // this.emit('transcript', event.data, participant);\n break;\n case 'llm_call':\n this.emit('toolStarted', { name: event.name, args: event.arguments });\n break;\n case 'llm_call_response':\n this.emit('toolCompleted', {\n name: event.details.api_name,\n result: event.details.api_response,\n isError: event.details.status >= 400,\n });\n break;\n case 'error':\n this.emit('toolCompleted', {\n name: event.name,\n result: event.details,\n isError: true,\n });\n break;\n case 'assistant_speaking_started':\n this.isAssistantSpeaking = true;\n this.emit('assistantStartedSpeaking');\n break;\n case 'assistant_speaking_ended':\n this.isAssistantSpeaking = false;\n this.emit('assistantStoppedSpeaking');\n break;\n case 'agent_message':\n this.emit('message', event);\n break;\n }\n }\n\n public getRoom(): Room | undefined {\n return this.room;\n }\n} ","export interface ToolUsed {\n name: string;\n args?: any;\n status?: 'pending' | 'success' | 'error';\n}\n\nexport interface Transcript {\n role: 'user' | 'assistant';\n text: string;\n isFinal: boolean;\n timestamp: Date;\n participantId?: string;\n toolUsed?: ToolUsed;\n}\n\nexport class TranscriptManager {\n private transcripts: Transcript[] = [];\n private currentTranscript: { [key: string]: string } = {};\n\n public getTranscripts(): Transcript[] {\n return this.transcripts;\n }\n\n public getCurrentTranscript(): { [key: string]: string } {\n return this.currentTranscript;\n }\n\n public addToolStarted(toolCall: { name: string; args: any }): void {\n this.transcripts.push({\n role: 'assistant',\n text: `Using tool: ${toolCall.name}`,\n isFinal: true,\n timestamp: new Date(),\n toolUsed: { ...toolCall, status: 'pending' },\n });\n }\n\n public addToolCompleted(toolResult: { name: string; result: any; isError: boolean }): void {\n const toolTranscriptIndex = this.transcripts.map((t) => t.toolUsed?.name === toolResult.name && t.toolUsed?.status === 'pending').lastIndexOf(true);\n if (toolTranscriptIndex > -1) {\n const toolTranscript = this.transcripts[toolTranscriptIndex];\n if (toolTranscript && toolTranscript.toolUsed) {\n toolTranscript.toolUsed.status = toolResult.isError ? 'error' : 'success';\n }\n }\n }\n\n public handleTranscript(participantId: string, isAgent: boolean, transcriptData: { text: string; isFinal: boolean }): boolean {\n if (transcriptData.isFinal) {\n const hadPartial = participantId in this.currentTranscript;\n delete this.currentTranscript[participantId];\n\n const text = transcriptData.text.trim();\n // An empty final still clears a visible partial, so report that as a change.\n if (!text) return hadPartial;\n\n // Check for duplicates\n const lastMessage = this.transcripts[this.transcripts.length - 1];\n if (lastMessage && lastMessage.text === text && lastMessage.participantId === participantId && Date.now() - lastMessage.timestamp.getTime() < 1000) {\n return hadPartial;\n }\n\n this.transcripts.push({\n role: isAgent ? 'assistant' : 'user',\n text,\n isFinal: true,\n timestamp: new Date(),\n participantId,\n });\n } else {\n this.currentTranscript[participantId] = transcriptData.text;\n }\n return true;\n }\n\n public addMessage(role: 'user' | 'assistant', text: string, participantId?: string) {\n this.transcripts.push({\n role,\n text,\n isFinal: true,\n timestamp: new Date(),\n participantId,\n });\n }\n} ","/**\r\n * Browser Fingerprinting Utility\r\n * Generates a deterministic fingerprint based on stable browser/hardware characteristics.\r\n * Used for demo link usage limit tracking.\r\n *\r\n * Strategy:\r\n * 1. localStorage persistence — generate once, reuse across tabs/sessions forever\r\n * 2. Stable hardware-only seed — if storage is cleared, the same hardware signals\r\n * produce the same hash, so the fingerprint stays consistent\r\n * 3. Server-side IP fallback — handled by the backend when no fingerprint is sent\r\n */\r\n\r\nconst STORAGE_KEY = 'trillet_dfp';\r\n\r\nexport class BrowserFingerprint {\r\n private static cachedFingerprint: string | null = null;\r\n\r\n /**\r\n * Generate (or retrieve) a deterministic browser fingerprint.\r\n * Cached in memory → localStorage → derived from stable hardware signals.\r\n */\r\n public static async generate(): Promise<string> {\r\n // 1. In-memory cache (fastest)\r\n if (this.cachedFingerprint) {\r\n return this.cachedFingerprint;\r\n }\r\n\r\n // 2. Persisted in localStorage (survives tab close / browser restart)\r\n const stored = this.getStored();\r\n if (stored) {\r\n this.cachedFingerprint = stored;\r\n return stored;\r\n }\r\n\r\n // 3. Derive from stable hardware signals and persist\r\n const signals = this.getStableSignals();\r\n const fingerprint = await this.hashComponents(signals);\r\n\r\n this.persist(fingerprint);\r\n this.cachedFingerprint = fingerprint;\r\n\r\n return fingerprint;\r\n }\r\n\r\n /**\r\n * Collect only hardware / environment signals that do NOT change between\r\n * tabs, sessions, or browser restarts on the same device.\r\n *\r\n * Deliberately excluded (volatile / anti-fingerprint randomised):\r\n * - canvas.toDataURL() — randomised per origin in many browsers\r\n * - font detection — noisy across rendering states\r\n * - screen.availWidth/Height — changes with taskbar / dock resize\r\n * - navigator.doNotTrack — user can toggle\r\n * - timezoneOffset — changes with DST\r\n * - navigator.userAgent — changes on browser update\r\n */\r\n private static getStableSignals(): Record<string, unknown> {\r\n return {\r\n // Hardware — fixed for a given device\r\n screen: {\r\n width: window.screen.width,\r\n height: window.screen.height,\r\n colorDepth: window.screen.colorDepth,\r\n pixelRatio: window.devicePixelRatio,\r\n },\r\n hardwareConcurrency: navigator.hardwareConcurrency,\r\n deviceMemory: (navigator as any).deviceMemory,\r\n platform: navigator.platform,\r\n maxTouchPoints: navigator.maxTouchPoints,\r\n\r\n // WebGL vendor/renderer — GPU-based, stable\r\n webgl: this.getWebGLFingerprint(),\r\n\r\n // Locale — stable unless user changes OS language or moves timezone\r\n timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,\r\n language: navigator.language,\r\n };\r\n }\r\n\r\n /**\r\n * WebGL vendor + renderer string (GPU identifier, very stable)\r\n */\r\n private static getWebGLFingerprint(): string {\r\n try {\r\n const canvas = document.createElement('canvas');\r\n const gl = canvas.getContext('webgl') || canvas.getContext('experimental-webgl');\r\n\r\n if (!gl) return 'no-webgl';\r\n\r\n const glContext = gl as WebGLRenderingContext;\r\n const debugInfo = glContext.getExtension('WEBGL_debug_renderer_info');\r\n\r\n const vendor = debugInfo\r\n ? glContext.getParameter(debugInfo.UNMASKED_VENDOR_WEBGL)\r\n : glContext.getParameter(glContext.VENDOR);\r\n const renderer = debugInfo\r\n ? glContext.getParameter(debugInfo.UNMASKED_RENDERER_WEBGL)\r\n : glContext.getParameter(glContext.RENDERER);\r\n\r\n return `${vendor}~${renderer}`;\r\n } catch {\r\n return 'webgl-error';\r\n }\r\n }\r\n\r\n /**\r\n * SHA-256 hash of the signals object → hex string\r\n */\r\n private static async hashComponents(components: Record<string, unknown>): Promise<string> {\r\n const data = new TextEncoder().encode(JSON.stringify(components));\r\n const hashBuffer = await crypto.subtle.digest('SHA-256', data);\r\n return Array.from(new Uint8Array(hashBuffer))\r\n .map((b) => b.toString(16).padStart(2, '0'))\r\n .join('');\r\n }\r\n\r\n // ── localStorage helpers ───────────────────────────────────────────\r\n\r\n private static getStored(): string | null {\r\n try {\r\n return localStorage.getItem(STORAGE_KEY);\r\n } catch {\r\n return null;\r\n }\r\n }\r\n\r\n private static persist(fingerprint: string): void {\r\n try {\r\n localStorage.setItem(STORAGE_KEY, fingerprint);\r\n } catch {\r\n // Storage full or disabled — fingerprint still works in-memory\r\n }\r\n }\r\n\r\n /**\r\n * Clear both in-memory and persisted fingerprint (useful for testing)\r\n */\r\n public static clearCache(): void {\r\n this.cachedFingerprint = null;\r\n try {\r\n localStorage.removeItem(STORAGE_KEY);\r\n } catch {\r\n // Ignore\r\n }\r\n }\r\n}\r\n"],"mappings":";;;;;;AAAA,SAAS,gBAAAA,qBAAoB;AAC7B,SAAsB,aAAAC,kBAAiB;;;ACDvC,SAAS,oBAAoB;AAC7B,SAAyC,kBAA0C,MAAM,WAAW,OAAO,qBAAkC,uBAAuB;AAGpK,IAAM,UAAU,IAAI,YAAY;AAoBzB,IAAM,gBAAN,cAA4B,aAAa;AAAA,EAmB9C,cAAc;AACZ,UAAM;AAlBR,SAAO,cAAuB;AAG9B;AAAA,SAAO,sBAA+B;AAuFtC,SAAQ,cAAc;AAAA,EAvEtB;AAAA,EAEA,MAAa,eAAe,QAA0C;AA/CxE;AAgDI,QAAI;AACF,WAAK,OAAO,IAAI,KAAK;AAAA,QACnB,sBAAsB;AAAA,UACpB,iBAAiB;AAAA,UACjB,kBAAkB;AAAA,UAClB,kBAAkB;AAAA,UAClB,cAAc;AAAA,UACd,WAAU,YAAO,kBAAP,mBAAsB;AAAA,UAChC,aAAY,YAAO,kBAAP,mBAAsB;AAAA,QACpC;AAAA,QACA,aAAa;AAAA,UACX,WAAU,YAAO,kBAAP,mBAAsB;AAAA,QAClC;AAAA,MACF,CAAC;AAED,WAAK,mBAAmB,MAAM;AAE9B,WAAK,KAAK,kBAAkB,OAAO,OAAO,OAAO,KAAK;AACtD,YAAM,KAAK,KAAK,QAAQ,OAAO,OAAO,OAAO,KAAK;AAClD,cAAQ,IAAI,8BAA8B,KAAK,KAAK,IAAI;AAExD,WAAK,cAAc,SAAQ,YAAO,aAAP,mBAAiB,sBAAsB;AAClE,YAAM,aAAa,OAAO,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AAGA,SAAK,kBAAkB,WAAW,QAAQ,MAAM,KAAK,iBAAiB,QAAQ;AAC9E,SAAK,YAAY,KAAK,EAAE,MAAM,KAAK,KAAK,GAAG,IAAI,KAAK,IAAI,EAAE,CAAC;AAC3D,SAAK,KAAK,oBAAoB,KAAK,eAAe,CAAC;AAGnD,QAAI;AACF,YAAM,KAAK,iBAAiB,SAAS,MAAM,EAAE,OAAO,UAAU,CAAC;AAC/D,cAAQ,IAAI,+BAA+B,IAAI;AAAA,IACjD,SAAS,OAAO;AACd,cAAQ,MAAM,gCAAgC,KAAK;AACnD,WAAK,KAAK,SAAS,IAAI,MAAM,2BAA2B,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC,EAAE,CAAC;AAAA,IACnH;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,MAAa,wBAAyC;AACpD,WAAO,MAAM,mBAAmB,SAAS;AAAA,EAC3C;AACF;","names":["EventEmitter","RoomEvent","decoder","EventEmitter","_a","RoomEvent"]}
|
package/dist/index.d.ts
CHANGED
|
@@ -55,7 +55,15 @@ interface TrilletAgentConfig {
|
|
|
55
55
|
agentId: string;
|
|
56
56
|
variables?: Record<string, any>;
|
|
57
57
|
callbackUrl?: string;
|
|
58
|
-
|
|
58
|
+
/**
|
|
59
|
+
* `voice` and `text` are single-modality sessions. `multimodal` is one conversation
|
|
60
|
+
* the visitor can type in or talk in, switching any time with {@link setVoiceEnabled}.
|
|
61
|
+
*/
|
|
62
|
+
mode?: 'voice' | 'text' | 'multimodal';
|
|
63
|
+
/** Multimodal only: start with the microphone on (the visitor chose to call). */
|
|
64
|
+
startWithVoice?: boolean;
|
|
65
|
+
/** Override the API host (whitelabel API domain, or a local backend in development). */
|
|
66
|
+
apiBaseUrl?: string;
|
|
59
67
|
demoHash?: string;
|
|
60
68
|
/**
|
|
61
69
|
* Pre-call gate. Awaited once at the top of every call-start path — before any
|
|
@@ -121,6 +129,15 @@ declare class TrilletAgent extends EventEmitter {
|
|
|
121
129
|
private connectToRoom;
|
|
122
130
|
endCall(): void;
|
|
123
131
|
toggleMicrophone(enabled: boolean): void;
|
|
132
|
+
private muted;
|
|
133
|
+
/** True while the visitor's microphone is muted on a live voice call. */
|
|
134
|
+
get isMuted(): boolean;
|
|
135
|
+
/**
|
|
136
|
+
* Mute or unmute the visitor's microphone and wait for LiveKit to apply it.
|
|
137
|
+
* Emits `muteChanged` (boolean). A no-op when no call is connected.
|
|
138
|
+
*/
|
|
139
|
+
setMuted(muted: boolean): Promise<void>;
|
|
140
|
+
private updateMuted;
|
|
124
141
|
get isAssistantSpeaking(): boolean;
|
|
125
142
|
getTranscripts(): Transcript[];
|
|
126
143
|
getCurrentTranscript(): {
|
|
@@ -139,6 +156,22 @@ declare class TrilletAgent extends EventEmitter {
|
|
|
139
156
|
* @param responseTimeout - Timeout in milliseconds (default: 30000)
|
|
140
157
|
*/
|
|
141
158
|
sendRpcMessage(method: string, payload: any, responseTimeout?: number): Promise<any>;
|
|
159
|
+
private voiceEnabled;
|
|
160
|
+
private recentTyped;
|
|
161
|
+
/** Multimodal: whether the microphone/voice side is currently on. */
|
|
162
|
+
get isVoiceEnabled(): boolean;
|
|
163
|
+
/**
|
|
164
|
+
* Multimodal only: switch the SAME conversation between typing and talking. Turns
|
|
165
|
+
* the mic on/off and tells the agent, which turns its speech on/off and keeps the
|
|
166
|
+
* whole conversation in context. Emits `modalityChanged` with 'voice' | 'text'.
|
|
167
|
+
*/
|
|
168
|
+
setVoiceEnabled(enabled: boolean): Promise<void>;
|
|
169
|
+
/**
|
|
170
|
+
* Resolve once the agent's session is ready to receive (its `lk.agent.state` has
|
|
171
|
+
* moved past "initializing"), or reject after `timeoutMs`. Joining the room is not
|
|
172
|
+
* enough: a text message sent before the session listens is silently dropped.
|
|
173
|
+
*/
|
|
174
|
+
private waitForAgent;
|
|
142
175
|
sendTextMessage(text: string): Promise<void>;
|
|
143
176
|
/**
|
|
144
177
|
* Get the browser fingerprint for this session
|
package/dist/index.js
CHANGED
package/dist/server.d.ts
CHANGED
|
@@ -25,9 +25,13 @@ interface TrilletRoomDetails {
|
|
|
25
25
|
interface CreateCallConfig {
|
|
26
26
|
apiKey: string;
|
|
27
27
|
agentId: string;
|
|
28
|
-
mode?: 'voice' | 'text';
|
|
28
|
+
mode?: 'voice' | 'text' | 'multimodal';
|
|
29
|
+
/** Multimodal only: which side the conversation starts on. */
|
|
30
|
+
initialModality?: 'voice' | 'text';
|
|
29
31
|
variables?: Record<string, any>;
|
|
30
32
|
callbackUrl?: string;
|
|
33
|
+
/** Override the API host (defaults to https://api.trillet.ai). */
|
|
34
|
+
apiBaseUrl?: string;
|
|
31
35
|
}
|
|
32
36
|
/**
|
|
33
37
|
* **Server-side only — requires an API key, do not call from the browser.**
|