@trillet-ai/web-sdk 1.7.1 → 1.9.1

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.
@@ -0,0 +1,718 @@
1
+ import {
2
+ TRILLET_API_URL,
3
+ createCall
4
+ } from "./chunk-3MH6DJZ6.js";
5
+
6
+ // src/index.tsx
7
+ import { EventEmitter as EventEmitter2 } from "eventemitter3";
8
+
9
+ // src/TrilletWebSDK.ts
10
+ import { EventEmitter } from "eventemitter3";
11
+ import { RemoteAudioTrack, Room, RoomEvent, Track, createAudioAnalyser, LocalAudioTrack } from "livekit-client";
12
+ var decoder = new TextDecoder();
13
+ var TrilletWebSDK = class extends EventEmitter {
14
+ constructor() {
15
+ super();
16
+ this.isConnected = false;
17
+ // Audio state tracking
18
+ this.isAssistantSpeaking = false;
19
+ }
20
+ async initializeCall(config) {
21
+ var _a, _b, _c, _d;
22
+ try {
23
+ this.room = new Room({
24
+ audioCaptureDefaults: {
25
+ autoGainControl: true,
26
+ echoCancellation: true,
27
+ noiseSuppression: true,
28
+ channelCount: 1,
29
+ deviceId: (_a = config.audioSettings) == null ? void 0 : _a.inputDeviceId,
30
+ sampleRate: (_b = config.audioSettings) == null ? void 0 : _b.sampleRate
31
+ },
32
+ audioOutput: {
33
+ deviceId: (_c = config.audioSettings) == null ? void 0 : _c.outputDeviceId
34
+ }
35
+ });
36
+ this.setupEventHandlers(config);
37
+ this.room.prepareConnection(config.wsUrl, config.token);
38
+ await this.room.connect(config.wsUrl, config.token);
39
+ console.log("Connected to Trillet room:", this.room.name);
40
+ if (config.mode !== "text") {
41
+ await this.room.localParticipant.setMicrophoneEnabled(true);
42
+ if ((_d = config.features) == null ? void 0 : _d.enableKrispNoiseFilter) {
43
+ await this.setupKrispNoiseFilter();
44
+ }
45
+ }
46
+ this.isConnected = true;
47
+ this.emit("connected");
48
+ } catch (error) {
49
+ const errorMessage = error instanceof Error ? error.message : "Failed to initialize call";
50
+ this.emit("error", errorMessage);
51
+ console.error("Call initialization failed:", error);
52
+ this.endCall();
53
+ throw error;
54
+ }
55
+ }
56
+ async enableAudioPlayback() {
57
+ var _a;
58
+ await ((_a = this.room) == null ? void 0 : _a.startAudio());
59
+ }
60
+ endCall() {
61
+ var _a;
62
+ if (!this.isConnected) return;
63
+ this.isConnected = false;
64
+ this.emit("disconnected");
65
+ (_a = this.room) == null ? void 0 : _a.disconnect();
66
+ this.isAssistantSpeaking = false;
67
+ if (this.audioAnalyzer) {
68
+ this.audioAnalyzer.cleanup();
69
+ this.audioAnalyzer = void 0;
70
+ }
71
+ if (this.audioFrameCapture) {
72
+ cancelAnimationFrame(this.audioFrameCapture);
73
+ this.audioFrameCapture = void 0;
74
+ }
75
+ if (this.krispProcessor) {
76
+ this.krispProcessor = void 0;
77
+ }
78
+ this.room = void 0;
79
+ }
80
+ toggleMicrophone(enabled) {
81
+ if (this.isConnected && this.room) {
82
+ this.room.localParticipant.setMicrophoneEnabled(enabled);
83
+ }
84
+ }
85
+ async setupKrispNoiseFilter() {
86
+ var _a;
87
+ if (!this.room) return;
88
+ try {
89
+ const { KrispNoiseFilter, isKrispNoiseFilterSupported } = await import("@livekit/krisp-noise-filter");
90
+ if (!isKrispNoiseFilterSupported()) {
91
+ console.warn("Krisp noise filter is not supported on this browser");
92
+ this.emit("krispStatus", { enabled: false, supported: false });
93
+ return;
94
+ }
95
+ const microphoneTrack = (_a = this.room.localParticipant.getTrackPublication(Track.Source.Microphone)) == null ? void 0 : _a.track;
96
+ if (microphoneTrack && microphoneTrack instanceof LocalAudioTrack) {
97
+ this.krispProcessor = KrispNoiseFilter();
98
+ await microphoneTrack.setProcessor(this.krispProcessor);
99
+ await this.krispProcessor.setEnabled(true);
100
+ console.log("Krisp noise filter enabled successfully");
101
+ this.emit("krispStatus", { enabled: true, supported: true });
102
+ } else {
103
+ console.warn("Could not find local microphone track to apply Krisp filter");
104
+ this.emit("krispStatus", { enabled: false, supported: true });
105
+ }
106
+ } catch (error) {
107
+ console.error("Failed to setup Krisp noise filter:", error);
108
+ this.emit("krispStatus", { enabled: false, supported: false });
109
+ }
110
+ }
111
+ captureAudio() {
112
+ if (!this.isConnected || !this.audioAnalyzer) return;
113
+ const bufferSize = this.audioAnalyzer.analyser.fftSize;
114
+ const audioData = new Float32Array(bufferSize);
115
+ this.audioAnalyzer.analyser.getFloatTimeDomainData(audioData);
116
+ this.emit("audioData", audioData);
117
+ this.audioFrameCapture = requestAnimationFrame(() => this.captureAudio());
118
+ }
119
+ setupEventHandlers(config) {
120
+ let wasAgentSpeaking = false;
121
+ if (!this.room) return;
122
+ this.room.on(RoomEvent.ParticipantDisconnected, (participant) => {
123
+ if ((participant == null ? void 0 : participant.identity) === "assistant") {
124
+ this.endCall();
125
+ }
126
+ });
127
+ this.room.on(RoomEvent.Disconnected, () => {
128
+ if (this.isConnected) this.endCall();
129
+ });
130
+ this.room.registerTextStreamHandler("lk.transcription", async (reader, info) => {
131
+ var _a, _b;
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";
135
+ if (!info) return;
136
+ const participant = (_b = this.room) == null ? void 0 : _b.getParticipantByIdentity(info.identity);
137
+ if (!participant) return;
138
+ this.emit("transcript", { text, isFinal }, participant);
139
+ });
140
+ this.room.on(RoomEvent.TrackSubscribed, (track, publication) => {
141
+ var _a;
142
+ if (track.kind === Track.Kind.Audio) {
143
+ if (publication.trackName === "assistant_audio" && track instanceof RemoteAudioTrack && ((_a = config.features) == null ? void 0 : _a.enableRawAudio)) {
144
+ const analyzer = createAudioAnalyser(track);
145
+ this.audioAnalyzer = {
146
+ calculateVolume: analyzer.calculateVolume,
147
+ analyser: analyzer.analyser,
148
+ cleanup: analyzer.cleanup
149
+ };
150
+ this.audioFrameCapture = requestAnimationFrame(() => this.captureAudio());
151
+ }
152
+ track.attach();
153
+ }
154
+ });
155
+ this.room.on(RoomEvent.DataReceived, (payload, participant) => {
156
+ if (!(participant == null ? void 0 : participant.identity.startsWith("agent"))) return;
157
+ try {
158
+ const data = JSON.parse(decoder.decode(payload));
159
+ this.handleDataEvent(data, participant);
160
+ } catch (error) {
161
+ console.error("Failed to process received data:", error);
162
+ }
163
+ });
164
+ this.room.on(RoomEvent.ActiveSpeakersChanged, (speakers) => {
165
+ const isAgentSpeaking = speakers.some((p) => p.identity.startsWith("agent"));
166
+ if (isAgentSpeaking && !wasAgentSpeaking) {
167
+ this.emit("assistantStartedSpeaking");
168
+ } else if (!isAgentSpeaking && wasAgentSpeaking) {
169
+ this.emit("assistantStoppedSpeaking");
170
+ }
171
+ wasAgentSpeaking = isAgentSpeaking;
172
+ });
173
+ this.room.on(RoomEvent.ParticipantConnected, (participant) => {
174
+ console.log("Participant connected:", participant.identity);
175
+ if (participant.identity.startsWith("agent")) {
176
+ console.log("Agent connected, RPC communication available");
177
+ }
178
+ });
179
+ }
180
+ handleDataEvent(event, participant) {
181
+ switch (event.type) {
182
+ case "status":
183
+ this.emit("status", event);
184
+ break;
185
+ case "metadata":
186
+ this.emit("metadata", event);
187
+ break;
188
+ case "transcript":
189
+ break;
190
+ case "llm_call":
191
+ this.emit("toolStarted", { name: event.name, args: event.arguments });
192
+ break;
193
+ case "llm_call_response":
194
+ this.emit("toolCompleted", {
195
+ name: event.details.api_name,
196
+ result: event.details.api_response,
197
+ isError: event.details.status >= 400
198
+ });
199
+ break;
200
+ case "error":
201
+ this.emit("toolCompleted", {
202
+ name: event.name,
203
+ result: event.details,
204
+ isError: true
205
+ });
206
+ break;
207
+ case "assistant_speaking_started":
208
+ this.isAssistantSpeaking = true;
209
+ this.emit("assistantStartedSpeaking");
210
+ break;
211
+ case "assistant_speaking_ended":
212
+ this.isAssistantSpeaking = false;
213
+ this.emit("assistantStoppedSpeaking");
214
+ break;
215
+ case "agent_message":
216
+ this.emit("message", event);
217
+ break;
218
+ }
219
+ }
220
+ getRoom() {
221
+ return this.room;
222
+ }
223
+ };
224
+
225
+ // src/TranscriptManager.ts
226
+ var TranscriptManager = class {
227
+ constructor() {
228
+ this.transcripts = [];
229
+ this.currentTranscript = {};
230
+ }
231
+ getTranscripts() {
232
+ return this.transcripts;
233
+ }
234
+ getCurrentTranscript() {
235
+ return this.currentTranscript;
236
+ }
237
+ addToolStarted(toolCall) {
238
+ this.transcripts.push({
239
+ role: "assistant",
240
+ text: `Using tool: ${toolCall.name}`,
241
+ isFinal: true,
242
+ timestamp: /* @__PURE__ */ new Date(),
243
+ toolUsed: { ...toolCall, status: "pending" }
244
+ });
245
+ }
246
+ addToolCompleted(toolResult) {
247
+ const toolTranscriptIndex = this.transcripts.map((t) => {
248
+ var _a, _b;
249
+ return ((_a = t.toolUsed) == null ? void 0 : _a.name) === toolResult.name && ((_b = t.toolUsed) == null ? void 0 : _b.status) === "pending";
250
+ }).lastIndexOf(true);
251
+ if (toolTranscriptIndex > -1) {
252
+ const toolTranscript = this.transcripts[toolTranscriptIndex];
253
+ if (toolTranscript && toolTranscript.toolUsed) {
254
+ toolTranscript.toolUsed.status = toolResult.isError ? "error" : "success";
255
+ }
256
+ }
257
+ }
258
+ handleTranscript(participantId, isAgent, transcriptData) {
259
+ if (transcriptData.isFinal) {
260
+ delete this.currentTranscript[participantId];
261
+ const text = transcriptData.text.trim();
262
+ if (!text) return false;
263
+ const lastMessage = this.transcripts[this.transcripts.length - 1];
264
+ if (lastMessage && lastMessage.text === text && lastMessage.participantId === participantId && Date.now() - lastMessage.timestamp.getTime() < 1e3) {
265
+ return false;
266
+ }
267
+ this.transcripts.push({
268
+ role: isAgent ? "assistant" : "user",
269
+ text,
270
+ isFinal: true,
271
+ timestamp: /* @__PURE__ */ new Date(),
272
+ participantId
273
+ });
274
+ } else {
275
+ this.currentTranscript[participantId] = transcriptData.text;
276
+ }
277
+ return true;
278
+ }
279
+ addMessage(role, text, participantId) {
280
+ this.transcripts.push({
281
+ role,
282
+ text,
283
+ isFinal: true,
284
+ timestamp: /* @__PURE__ */ new Date(),
285
+ participantId
286
+ });
287
+ }
288
+ };
289
+
290
+ // src/BrowserFingerprint.ts
291
+ var STORAGE_KEY = "trillet_dfp";
292
+ var BrowserFingerprint = class {
293
+ /**
294
+ * Generate (or retrieve) a deterministic browser fingerprint.
295
+ * Cached in memory → localStorage → derived from stable hardware signals.
296
+ */
297
+ static async generate() {
298
+ if (this.cachedFingerprint) {
299
+ return this.cachedFingerprint;
300
+ }
301
+ const stored = this.getStored();
302
+ if (stored) {
303
+ this.cachedFingerprint = stored;
304
+ return stored;
305
+ }
306
+ const signals = this.getStableSignals();
307
+ const fingerprint = await this.hashComponents(signals);
308
+ this.persist(fingerprint);
309
+ this.cachedFingerprint = fingerprint;
310
+ return fingerprint;
311
+ }
312
+ /**
313
+ * Collect only hardware / environment signals that do NOT change between
314
+ * tabs, sessions, or browser restarts on the same device.
315
+ *
316
+ * Deliberately excluded (volatile / anti-fingerprint randomised):
317
+ * - canvas.toDataURL() — randomised per origin in many browsers
318
+ * - font detection — noisy across rendering states
319
+ * - screen.availWidth/Height — changes with taskbar / dock resize
320
+ * - navigator.doNotTrack — user can toggle
321
+ * - timezoneOffset — changes with DST
322
+ * - navigator.userAgent — changes on browser update
323
+ */
324
+ static getStableSignals() {
325
+ return {
326
+ // Hardware — fixed for a given device
327
+ screen: {
328
+ width: window.screen.width,
329
+ height: window.screen.height,
330
+ colorDepth: window.screen.colorDepth,
331
+ pixelRatio: window.devicePixelRatio
332
+ },
333
+ hardwareConcurrency: navigator.hardwareConcurrency,
334
+ deviceMemory: navigator.deviceMemory,
335
+ platform: navigator.platform,
336
+ maxTouchPoints: navigator.maxTouchPoints,
337
+ // WebGL vendor/renderer — GPU-based, stable
338
+ webgl: this.getWebGLFingerprint(),
339
+ // Locale — stable unless user changes OS language or moves timezone
340
+ timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
341
+ language: navigator.language
342
+ };
343
+ }
344
+ /**
345
+ * WebGL vendor + renderer string (GPU identifier, very stable)
346
+ */
347
+ static getWebGLFingerprint() {
348
+ try {
349
+ const canvas = document.createElement("canvas");
350
+ const gl = canvas.getContext("webgl") || canvas.getContext("experimental-webgl");
351
+ if (!gl) return "no-webgl";
352
+ const glContext = gl;
353
+ const debugInfo = glContext.getExtension("WEBGL_debug_renderer_info");
354
+ const vendor = debugInfo ? glContext.getParameter(debugInfo.UNMASKED_VENDOR_WEBGL) : glContext.getParameter(glContext.VENDOR);
355
+ const renderer = debugInfo ? glContext.getParameter(debugInfo.UNMASKED_RENDERER_WEBGL) : glContext.getParameter(glContext.RENDERER);
356
+ return `${vendor}~${renderer}`;
357
+ } catch (e) {
358
+ return "webgl-error";
359
+ }
360
+ }
361
+ /**
362
+ * SHA-256 hash of the signals object → hex string
363
+ */
364
+ static async hashComponents(components) {
365
+ const data = new TextEncoder().encode(JSON.stringify(components));
366
+ const hashBuffer = await crypto.subtle.digest("SHA-256", data);
367
+ return Array.from(new Uint8Array(hashBuffer)).map((b) => b.toString(16).padStart(2, "0")).join("");
368
+ }
369
+ // ── localStorage helpers ───────────────────────────────────────────
370
+ static getStored() {
371
+ try {
372
+ return localStorage.getItem(STORAGE_KEY);
373
+ } catch (e) {
374
+ return null;
375
+ }
376
+ }
377
+ static persist(fingerprint) {
378
+ try {
379
+ localStorage.setItem(STORAGE_KEY, fingerprint);
380
+ } catch (e) {
381
+ }
382
+ }
383
+ /**
384
+ * Clear both in-memory and persisted fingerprint (useful for testing)
385
+ */
386
+ static clearCache() {
387
+ this.cachedFingerprint = null;
388
+ try {
389
+ localStorage.removeItem(STORAGE_KEY);
390
+ } catch (e) {
391
+ }
392
+ }
393
+ };
394
+ BrowserFingerprint.cachedFingerprint = null;
395
+
396
+ // src/index.tsx
397
+ var FALLBACK_WS_URL = "wss://trillet-ai-xdx0dw5r.livekit.cloud";
398
+ var decoder2 = new TextDecoder();
399
+ var isBrowser = typeof window !== "undefined";
400
+ var isSecureContext = isBrowser && (window.isSecureContext || window.location.protocol === "https:" || window.location.hostname === "localhost" || window.location.hostname === "127.0.0.1");
401
+ var TrilletAgent = class extends EventEmitter2 {
402
+ constructor(config) {
403
+ super();
404
+ this.sdkToken = null;
405
+ if (!isBrowser) {
406
+ throw new Error("Trillet SDK must be used in a browser environment");
407
+ }
408
+ if (!isSecureContext) {
409
+ throw new Error("Trillet SDK requires a secure context (HTTPS or localhost)");
410
+ }
411
+ if (!config.agentId) {
412
+ throw new Error("agentId is required");
413
+ }
414
+ this.config = {
415
+ ...config,
416
+ mode: config.mode || "voice"
417
+ // Default to voice mode
418
+ };
419
+ this.sdk = new TrilletWebSDK();
420
+ this.transcriptManager = new TranscriptManager();
421
+ this.setupEventForwarding();
422
+ }
423
+ setupEventForwarding() {
424
+ this.sdk.on("disconnected", () => this.emit("disconnected"));
425
+ this.sdk.on("error", (error) => this.emit("error", error));
426
+ this.sdk.on("status", (status) => this.emit("status", status));
427
+ this.sdk.on("metadata", (metadata) => this.emit("metadata", metadata));
428
+ this.sdk.on("assistantStartedSpeaking", () => this.emit("assistantStartedSpeaking"));
429
+ this.sdk.on("assistantStoppedSpeaking", () => this.emit("assistantStoppedSpeaking"));
430
+ this.sdk.on("audioData", (data) => this.emit("audioData", data));
431
+ this.sdk.on("krispStatus", (status) => this.emit("krispStatus", status));
432
+ this.sdk.on("toolStarted", (toolCall) => {
433
+ this.transcriptManager.addToolStarted(toolCall);
434
+ this.emit("toolStarted", toolCall);
435
+ this.emit("transcriptUpdate", this.transcriptManager.getTranscripts());
436
+ });
437
+ this.sdk.on("toolCompleted", (toolResult) => {
438
+ this.transcriptManager.addToolCompleted(toolResult);
439
+ this.emit("toolCompleted", toolResult);
440
+ this.emit("transcriptUpdate", this.transcriptManager.getTranscripts());
441
+ });
442
+ this.sdk.on("transcript", (transcriptData, participant) => {
443
+ const participantId = participant.identity;
444
+ const isAgent = participantId.startsWith("agent");
445
+ const updated = this.transcriptManager.handleTranscript(participantId, isAgent, transcriptData);
446
+ if (updated) {
447
+ this.emit("transcriptUpdate", this.transcriptManager.getTranscripts());
448
+ }
449
+ });
450
+ this.sdk.on("message", (message) => {
451
+ var _a, _b;
452
+ const agentParticipant = Array.from((_b = (_a = this.sdk.getRoom()) == null ? void 0 : _a.remoteParticipants.values()) != null ? _b : []).find((p) => p.identity.startsWith("agent"));
453
+ this.transcriptManager.addMessage("assistant", message.text, agentParticipant == null ? void 0 : agentParticipant.identity);
454
+ this.emit("message", message);
455
+ this.emit("transcriptUpdate", this.transcriptManager.getTranscripts());
456
+ });
457
+ }
458
+ /**
459
+ * Set up default RPC handlers for common agent interactions
460
+ * This should be called after connection is established
461
+ */
462
+ setupDefaultRpcHandlers() {
463
+ this.registerRpcMethod("receiveChatMessage", async (data) => {
464
+ var _a, _b, _c;
465
+ const messageText = typeof data.payload === "string" ? data.payload : ((_a = data.payload) == null ? void 0 : _a.text) || "";
466
+ if (messageText) {
467
+ const agentParticipant = Array.from((_c = (_b = this.sdk.getRoom()) == null ? void 0 : _b.remoteParticipants.values()) != null ? _c : []).find(
468
+ (p) => p.identity.startsWith("agent")
469
+ );
470
+ this.transcriptManager.addMessage("assistant", messageText, agentParticipant == null ? void 0 : agentParticipant.identity);
471
+ this.emit("message", { text: messageText });
472
+ this.emit("transcriptUpdate", this.transcriptManager.getTranscripts());
473
+ }
474
+ return "Message received";
475
+ });
476
+ this.registerRpcMethod("agentStatus", async (data) => {
477
+ this.emit("status", data.payload);
478
+ return "Status received";
479
+ });
480
+ }
481
+ /**
482
+ * **Server-side only — requires an API key, do not call from the browser.**
483
+ *
484
+ * Puts a full-privilege `X-API-KEY` on the request, so this must run where the
485
+ * key is safe. For the secure pattern, mint the room on your backend with
486
+ * `createCall` (from `@trillet-ai/web-sdk/server`) and call {@link joinRoom} in
487
+ * the browser instead. Kept for backward compatibility.
488
+ */
489
+ async startCall() {
490
+ await this.runBeforeCall();
491
+ let data;
492
+ try {
493
+ data = await createCall({
494
+ apiKey: this.config.apiKey,
495
+ agentId: this.config.agentId,
496
+ mode: this.config.mode,
497
+ variables: this.config.variables,
498
+ callbackUrl: this.config.callbackUrl
499
+ });
500
+ } catch (error) {
501
+ console.error("Trillet SDK Error:", error);
502
+ this.emit("error", error instanceof Error ? error : new Error(String(error)));
503
+ throw error;
504
+ }
505
+ await this.connectToRoom(data);
506
+ }
507
+ async startPublicCall() {
508
+ await this.runBeforeCall();
509
+ let data;
510
+ try {
511
+ let browserFingerprint = null;
512
+ try {
513
+ browserFingerprint = await BrowserFingerprint.generate();
514
+ } catch (fpError) {
515
+ console.warn("Trillet SDK: fingerprint generation failed, proceeding without it", fpError);
516
+ }
517
+ const response = await fetch(TRILLET_API_URL.PUBLIC_CONNECT, {
518
+ method: "POST",
519
+ headers: {
520
+ "Content-Type": "application/json",
521
+ Accept: "application/json",
522
+ "x-workspace-id": this.config.workspaceId
523
+ },
524
+ body: JSON.stringify({
525
+ call_agent_id: this.config.agentId,
526
+ mode: this.config.mode,
527
+ dynamic_variables: this.config.variables || {},
528
+ callback_url: this.config.callbackUrl,
529
+ browser_fingerprint: browserFingerprint,
530
+ demo_hash: this.config.demoHash
531
+ // Send demo hash if provided
532
+ })
533
+ });
534
+ if (!response.ok) {
535
+ let errorMessage;
536
+ try {
537
+ const errorData = await response.json();
538
+ errorMessage = errorData.message || errorData.error || "Unknown error";
539
+ } catch (e) {
540
+ errorMessage = await response.text();
541
+ }
542
+ throw new Error(`API Error: ${errorMessage}`);
543
+ }
544
+ data = await response.json();
545
+ } catch (error) {
546
+ console.error("Trillet SDK Error (public call):", error);
547
+ this.emit("error", error instanceof Error ? error : new Error(String(error)));
548
+ throw error;
549
+ }
550
+ await this.connectToRoom(data);
551
+ }
552
+ /**
553
+ * Connect to a pre-minted Trillet room. The secure browser entry point: takes
554
+ * the room details returned by `createCall` (server-side) and joins LiveKit
555
+ * directly — makes NO Trillet API call, so no API key, workspaceId or agentId
556
+ * ever reaches the browser.
557
+ *
558
+ * @param roomDetails - the backend response, e.g. `{ connection: { url, token }, ... }`
559
+ */
560
+ async joinRoom(roomDetails) {
561
+ await this.runBeforeCall();
562
+ await this.connectToRoom(roomDetails);
563
+ }
564
+ /**
565
+ * Run the caller's pre-call gate, if any.
566
+ *
567
+ * Invoked by each public call-start path exactly once. `startCall` and
568
+ * `startPublicCall` therefore delegate to {@link connectToRoom} rather than to the
569
+ * public {@link joinRoom} — routing them through `joinRoom` would fire a customer's
570
+ * hook a second time per call, re-running their challenge or verification request.
571
+ */
572
+ async runBeforeCall() {
573
+ if (!this.config.onBeforeCall) return;
574
+ try {
575
+ await this.config.onBeforeCall();
576
+ } catch (error) {
577
+ console.error("Trillet SDK Error (onBeforeCall):", error);
578
+ this.emit("error", error instanceof Error ? error : new Error(String(error)));
579
+ throw error;
580
+ }
581
+ }
582
+ /** Join LiveKit. Assumes the pre-call gate has already run. */
583
+ async connectToRoom(roomDetails) {
584
+ try {
585
+ const connection = roomDetails == null ? void 0 : roomDetails.connection;
586
+ if (!(connection == null ? void 0 : connection.token)) {
587
+ throw new Error("Invalid room details: missing connection token");
588
+ }
589
+ const wsUrl = connection.url || FALLBACK_WS_URL;
590
+ await this.sdk.initializeCall({
591
+ token: connection.token,
592
+ wsUrl,
593
+ mode: this.config.mode,
594
+ audioSettings: {
595
+ sampleRate: 48e3
596
+ },
597
+ features: {
598
+ enableRawAudio: this.config.mode === "voice",
599
+ // Krisp AI noise cancellation on the local mic for voice calls — cleaner
600
+ // input to STT in noisy environments. Emits `krispStatus` (TRI-629).
601
+ enableKrispNoiseFilter: this.config.mode === "voice"
602
+ }
603
+ });
604
+ if (this.config.mode === "voice") {
605
+ await this.sdk.enableAudioPlayback();
606
+ }
607
+ this.setupDefaultRpcHandlers();
608
+ this.emit("connected", {
609
+ callId: roomDetails.call_id,
610
+ roomName: roomDetails.room_name,
611
+ display: roomDetails.display
612
+ });
613
+ } catch (error) {
614
+ console.error("Trillet SDK Error (joinRoom):", error);
615
+ this.emit("error", error instanceof Error ? error : new Error(String(error)));
616
+ throw error;
617
+ }
618
+ }
619
+ endCall() {
620
+ this.sdk.endCall();
621
+ }
622
+ toggleMicrophone(enabled) {
623
+ this.sdk.toggleMicrophone(enabled);
624
+ }
625
+ get isAssistantSpeaking() {
626
+ return this.sdk.isAssistantSpeaking;
627
+ }
628
+ getTranscripts() {
629
+ return this.transcriptManager.getTranscripts();
630
+ }
631
+ getCurrentTranscript() {
632
+ return this.transcriptManager.getCurrentTranscript();
633
+ }
634
+ /**
635
+ * Register an RPC method handler for receiving calls from the agent
636
+ * @param method - The RPC method name to handle
637
+ * @param handler - The function to handle the RPC call
638
+ */
639
+ registerRpcMethod(method, handler) {
640
+ const room = this.sdk.getRoom();
641
+ if (!room) {
642
+ console.warn("Cannot register RPC method: not connected to room");
643
+ return;
644
+ }
645
+ room.localParticipant.registerRpcMethod(method, async (data) => {
646
+ try {
647
+ const result = await handler(data);
648
+ return result;
649
+ } catch (error) {
650
+ console.error(`RPC method ${method} error:`, error);
651
+ throw error;
652
+ }
653
+ });
654
+ }
655
+ /**
656
+ * Send an RPC call to the agent
657
+ * @param method - The RPC method name
658
+ * @param payload - The data to send
659
+ * @param responseTimeout - Timeout in milliseconds (default: 30000)
660
+ */
661
+ async sendRpcMessage(method, payload, responseTimeout = 3e4) {
662
+ const room = this.sdk.getRoom();
663
+ if (!room || !this.sdk.isConnected) {
664
+ throw new Error("Not connected. Cannot send RPC message.");
665
+ }
666
+ const agentParticipant = Array.from(room.remoteParticipants.values()).find(
667
+ (p) => p.identity.startsWith("agent")
668
+ );
669
+ if (!agentParticipant) {
670
+ throw new Error("No agent found to send RPC message to.");
671
+ }
672
+ try {
673
+ const response = await room.localParticipant.performRpc({
674
+ destinationIdentity: agentParticipant.identity,
675
+ method,
676
+ payload,
677
+ responseTimeout
678
+ });
679
+ return response;
680
+ } catch (error) {
681
+ console.error(`RPC call to method ${method} failed:`, error);
682
+ throw error;
683
+ }
684
+ }
685
+ async sendTextMessage(text) {
686
+ if (this.config.mode !== "text") {
687
+ console.warn("Cannot send text message in voice mode.");
688
+ return;
689
+ }
690
+ const room = this.sdk.getRoom();
691
+ if (!room || !this.sdk.isConnected) {
692
+ this.emit("error", new Error("Not connected. Cannot send message."));
693
+ return;
694
+ }
695
+ this.transcriptManager.addMessage("user", text, room.localParticipant.identity);
696
+ this.emit("transcriptUpdate", this.getTranscripts());
697
+ try {
698
+ await room.localParticipant.sendText(text, { topic: "lk.chat" });
699
+ console.log("Text message sent to agent:", text);
700
+ } catch (error) {
701
+ console.error("Failed to send text message:", error);
702
+ this.emit("error", new Error(`Failed to send message: ${error instanceof Error ? error.message : String(error)}`));
703
+ }
704
+ }
705
+ /**
706
+ * Get the browser fingerprint for this session
707
+ * Useful for demo pages to send fingerprint when checking limits
708
+ */
709
+ async getBrowserFingerprint() {
710
+ return await BrowserFingerprint.generate();
711
+ }
712
+ };
713
+
714
+ export {
715
+ BrowserFingerprint,
716
+ TrilletAgent
717
+ };
718
+ //# sourceMappingURL=chunk-FSJ42TKR.js.map