@trillet-ai/web-sdk 1.3.5 → 1.3.6

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/dist/index.d.ts CHANGED
@@ -1,11 +1,11 @@
1
- import { EventEmitter } from "eventemitter3";
1
+ import { EventEmitter } from 'eventemitter3';
2
2
  export interface TrilletAgentConfig {
3
3
  apiKey?: string;
4
4
  workspaceId?: string;
5
5
  agentId: string;
6
6
  variables?: Record<string, any>;
7
7
  callbackUrl?: string;
8
- mode?: "voice" | "text";
8
+ mode?: 'voice' | 'text';
9
9
  }
10
10
  export interface TrilletCallConfig {
11
11
  token: string;
@@ -22,10 +22,10 @@ export interface TrilletCallConfig {
22
22
  interface ToolUsed {
23
23
  name: string;
24
24
  args?: any;
25
- status?: "pending" | "success" | "error";
25
+ status?: 'pending' | 'success' | 'error';
26
26
  }
27
27
  interface Transcript {
28
- role: "user" | "assistant";
28
+ role: 'user' | 'assistant';
29
29
  text: string;
30
30
  isFinal: boolean;
31
31
  timestamp: Date;
package/dist/index.js CHANGED
@@ -1,12 +1,12 @@
1
- import { EventEmitter } from "eventemitter3";
2
- import { RemoteAudioTrack, Room, RoomEvent, Track, createAudioAnalyser, } from "livekit-client";
1
+ import { EventEmitter } from 'eventemitter3';
2
+ import { RemoteAudioTrack, Room, RoomEvent, Track, createAudioAnalyser } from 'livekit-client';
3
3
  const TRILLET_API_URL = {
4
- CONNECT: "https://api.trillet.ai/v1/api/web-call",
5
- PUBLIC_CONNECT: "https://api.trillet.ai/v1/api/web-call/public",
4
+ CONNECT: 'https://api.trillet.ai/v1/api/web-call',
5
+ PUBLIC_CONNECT: 'https://api.trillet.ai/v1/api/web-call/public',
6
6
  };
7
7
  const decoder = new TextDecoder();
8
8
  // Browser compatibility check
9
- const isBrowser = typeof window !== "undefined";
9
+ const isBrowser = typeof window !== 'undefined';
10
10
  const isSecureContext = isBrowser && window.isSecureContext;
11
11
  export class TrilletAgent extends EventEmitter {
12
12
  constructor(config) {
@@ -16,17 +16,17 @@ export class TrilletAgent extends EventEmitter {
16
16
  this.currentTranscript = {};
17
17
  // Validate environment
18
18
  if (!isBrowser) {
19
- throw new Error("Trillet SDK must be used in a browser environment");
19
+ throw new Error('Trillet SDK must be used in a browser environment');
20
20
  }
21
21
  if (!isSecureContext) {
22
- throw new Error("Trillet SDK requires a secure context (HTTPS or localhost)");
22
+ throw new Error('Trillet SDK requires a secure context (HTTPS or localhost)');
23
23
  }
24
24
  if (!config.agentId) {
25
- throw new Error("agentId is required");
25
+ throw new Error('agentId is required');
26
26
  }
27
27
  this.config = {
28
28
  ...config,
29
- mode: config.mode || "voice", // Default to voice mode
29
+ mode: config.mode || 'voice', // Default to voice mode
30
30
  };
31
31
  this.sdk = new TrilletWebSDK();
32
32
  this.setupEventForwarding();
@@ -34,23 +34,21 @@ export class TrilletAgent extends EventEmitter {
34
34
  setupEventForwarding() {
35
35
  var _a;
36
36
  // Forward all SDK events to agent listeners
37
- this.sdk.on("connected", () => this.emit("connected"));
38
- this.sdk.on("disconnected", () => this.emit("disconnected"));
39
- this.sdk.on("error", (error) => this.emit("error", error));
40
- this.sdk.on("status", (status) => this.emit("status", status));
41
- this.sdk.on("metadata", (metadata) => this.emit("metadata", metadata));
42
- this.sdk.on("assistantStartedSpeaking", () => this.emit("assistantStartedSpeaking"));
43
- this.sdk.on("assistantStoppedSpeaking", () => this.emit("assistantStoppedSpeaking"));
44
- this.sdk.on("audioData", (data) => this.emit("audioData", data));
37
+ this.sdk.on('connected', () => this.emit('connected'));
38
+ this.sdk.on('disconnected', () => this.emit('disconnected'));
39
+ this.sdk.on('error', (error) => this.emit('error', error));
40
+ this.sdk.on('status', (status) => this.emit('status', status));
41
+ this.sdk.on('metadata', (metadata) => this.emit('metadata', metadata));
42
+ this.sdk.on('assistantStartedSpeaking', () => this.emit('assistantStartedSpeaking'));
43
+ this.sdk.on('assistantStoppedSpeaking', () => this.emit('assistantStoppedSpeaking'));
44
+ this.sdk.on('audioData', (data) => this.emit('audioData', data));
45
45
  // Forward Room events to agent listeners
46
- (_a = this.sdk
47
- .getRoom()) === null || _a === void 0 ? void 0 : _a.on(RoomEvent.TranscriptionReceived, (segments, participant) => {
46
+ (_a = this.sdk.getRoom()) === null || _a === void 0 ? void 0 : _a.on(RoomEvent.TranscriptionReceived, (segments, participant) => {
48
47
  const room = this.sdk.getRoom();
49
48
  if (!room)
50
49
  return;
51
50
  const participantId = (participant === null || participant === void 0 ? void 0 : participant.identity) || room.localParticipant.identity;
52
- const isAgent = participantId.startsWith("agent-") ||
53
- participantId.startsWith("web-agent");
51
+ const isAgent = participantId.startsWith('agent-') || participantId.startsWith('web-agent');
54
52
  segments.forEach((segment) => {
55
53
  var _a;
56
54
  if (segment.final) {
@@ -58,23 +56,20 @@ export class TrilletAgent extends EventEmitter {
58
56
  const text = segment.text.trim();
59
57
  // Check for duplicates
60
58
  const lastMessage = this.transcripts[this.transcripts.length - 1];
61
- if (lastMessage &&
62
- lastMessage.text === text &&
63
- lastMessage.participantId === participantId &&
64
- Date.now() - lastMessage.timestamp.getTime() < 1000) {
59
+ if (lastMessage && lastMessage.text === text && lastMessage.participantId === participantId && Date.now() - lastMessage.timestamp.getTime() < 1000) {
65
60
  return;
66
61
  }
67
62
  this.transcripts.push({
68
- role: isAgent ? "assistant" : "user",
63
+ role: isAgent ? 'assistant' : 'user',
69
64
  text,
70
65
  isFinal: true,
71
66
  timestamp: new Date(),
72
67
  participantId,
73
- toolUsed: text.includes("Using tool:")
68
+ toolUsed: text.includes('Using tool:')
74
69
  ? {
75
- name: text.split("Using tool:")[1].split(" ")[1],
76
- args: (_a = text.split("Arguments:")[1]) === null || _a === void 0 ? void 0 : _a.trim(),
77
- status: "pending",
70
+ name: text.split('Using tool:')[1].split(' ')[1],
71
+ args: (_a = text.split('Arguments:')[1]) === null || _a === void 0 ? void 0 : _a.trim(),
72
+ status: 'pending',
78
73
  }
79
74
  : undefined,
80
75
  });
@@ -90,11 +85,11 @@ export class TrilletAgent extends EventEmitter {
90
85
  try {
91
86
  // 2. Initialize call with API KEY
92
87
  const response = await fetch(TRILLET_API_URL.CONNECT, {
93
- method: "POST",
88
+ method: 'POST',
94
89
  headers: {
95
- "Content-Type": "application/json",
96
- Accept: "application/json",
97
- "X-API-KEY": this.config.apiKey,
90
+ 'Content-Type': 'application/json',
91
+ Accept: 'application/json',
92
+ 'X-API-KEY': this.config.apiKey,
98
93
  },
99
94
  body: JSON.stringify({
100
95
  call_agent_id: this.config.agentId,
@@ -107,8 +102,7 @@ export class TrilletAgent extends EventEmitter {
107
102
  let errorMessage;
108
103
  try {
109
104
  const errorData = await response.json();
110
- errorMessage =
111
- errorData.message || errorData.error || "Unknown error";
105
+ errorMessage = errorData.message || errorData.error || 'Unknown error';
112
106
  }
113
107
  catch (_a) {
114
108
  errorMessage = await response.text();
@@ -117,45 +111,44 @@ export class TrilletAgent extends EventEmitter {
117
111
  }
118
112
  const data = await response.json();
119
113
  if (!data.token || !data.roomName) {
120
- throw new Error("Invalid response from server: missing token or room name");
114
+ throw new Error('Invalid response from server: missing token or room name');
121
115
  }
122
116
  // Initialize call with LiveKit token
123
117
  await this.sdk.initializeCall({
124
118
  token: data.token,
125
- wsUrl: process.env.LIVEKIT_WS_URL ||
126
- "wss://trillet-ai-xdx0dw5r.livekit.cloud",
119
+ wsUrl: process.env.LIVEKIT_WS_URL || 'wss://trillet-ai-xdx0dw5r.livekit.cloud',
127
120
  audioSettings: {
128
121
  sampleRate: 48000,
129
122
  },
130
123
  features: {
131
- enableRawAudio: this.config.mode === "voice",
124
+ enableRawAudio: this.config.mode === 'voice',
132
125
  },
133
126
  });
134
127
  // Enable audio playback for voice mode
135
- if (this.config.mode === "voice") {
128
+ if (this.config.mode === 'voice') {
136
129
  await this.sdk.enableAudioPlayback();
137
130
  }
138
131
  // Emit additional connection details
139
- this.emit("connected", {
132
+ this.emit('connected', {
140
133
  callId: data.callId,
141
134
  roomName: data.roomName,
142
135
  agent: data.agent,
143
136
  });
144
137
  }
145
138
  catch (error) {
146
- console.error("Trillet SDK Error:", error);
147
- this.emit("error", error instanceof Error ? error : new Error(String(error)));
139
+ console.error('Trillet SDK Error:', error);
140
+ this.emit('error', error instanceof Error ? error : new Error(String(error)));
148
141
  throw error;
149
142
  }
150
143
  }
151
144
  async startPublicCall() {
152
145
  // 2. Initialize public call
153
146
  const response = await fetch(TRILLET_API_URL.PUBLIC_CONNECT, {
154
- method: "POST",
147
+ method: 'POST',
155
148
  headers: {
156
- "Content-Type": "application/json",
157
- Accept: "application/json",
158
- 'x-workspace-id': this.config.workspaceId
149
+ 'Content-Type': 'application/json',
150
+ Accept: 'application/json',
151
+ 'x-workspace-id': this.config.workspaceId,
159
152
  },
160
153
  body: JSON.stringify({
161
154
  call_agent_id: this.config.agentId,
@@ -168,7 +161,7 @@ export class TrilletAgent extends EventEmitter {
168
161
  let errorMessage;
169
162
  try {
170
163
  const errorData = await response.json();
171
- errorMessage = errorData.message || errorData.error || "Unknown error";
164
+ errorMessage = errorData.message || errorData.error || 'Unknown error';
172
165
  }
173
166
  catch (_a) {
174
167
  errorMessage = await response.text();
@@ -177,25 +170,25 @@ export class TrilletAgent extends EventEmitter {
177
170
  }
178
171
  const data = await response.json();
179
172
  if (!data.token || !data.roomName) {
180
- throw new Error("Invalid response from server: missing token or room name");
173
+ throw new Error('Invalid response from server: missing token or room name');
181
174
  }
182
175
  // Initialize call with LiveKit token
183
176
  await this.sdk.initializeCall({
184
177
  token: data.token,
185
- wsUrl: process.env.LIVEKIT_WS_URL || "wss://trillet-ai-xdx0dw5r.livekit.cloud",
178
+ wsUrl: process.env.LIVEKIT_WS_URL || 'wss://trillet-ai-xdx0dw5r.livekit.cloud',
186
179
  audioSettings: {
187
180
  sampleRate: 48000,
188
181
  },
189
182
  features: {
190
- enableRawAudio: this.config.mode === "voice",
183
+ enableRawAudio: this.config.mode === 'voice',
191
184
  },
192
185
  });
193
186
  // Enable audio playback for voice mode
194
- if (this.config.mode === "voice") {
187
+ if (this.config.mode === 'voice') {
195
188
  await this.sdk.enableAudioPlayback();
196
189
  }
197
190
  // Emit additional connection details
198
- this.emit("connected", {
191
+ this.emit('connected', {
199
192
  callId: data.callId,
200
193
  roomName: data.roomName,
201
194
  agent: data.agent,
@@ -243,15 +236,15 @@ class TrilletWebSDK extends EventEmitter {
243
236
  });
244
237
  this.setupEventHandlers(config);
245
238
  await this.room.connect(config.wsUrl, config.token);
246
- console.log("Connected to Trillet room:", this.room.name);
239
+ console.log('Connected to Trillet room:', this.room.name);
247
240
  this.room.localParticipant.setMicrophoneEnabled(true);
248
241
  this.isConnected = true;
249
- this.emit("connected");
242
+ this.emit('connected');
250
243
  }
251
244
  catch (error) {
252
- const errorMessage = error instanceof Error ? error.message : "Failed to initialize call";
253
- this.emit("error", errorMessage);
254
- console.error("Call initialization failed:", error);
245
+ const errorMessage = error instanceof Error ? error.message : 'Failed to initialize call';
246
+ this.emit('error', errorMessage);
247
+ console.error('Call initialization failed:', error);
255
248
  this.endCall();
256
249
  throw error; // Re-throw to let TrilletAgent handle it
257
250
  }
@@ -265,7 +258,7 @@ class TrilletWebSDK extends EventEmitter {
265
258
  if (!this.isConnected)
266
259
  return;
267
260
  this.isConnected = false;
268
- this.emit("disconnected");
261
+ this.emit('disconnected');
269
262
  (_a = this.room) === null || _a === void 0 ? void 0 : _a.disconnect();
270
263
  this.isAssistantSpeaking = false;
271
264
  if (this.audioAnalyzer) {
@@ -289,15 +282,16 @@ class TrilletWebSDK extends EventEmitter {
289
282
  const bufferSize = this.audioAnalyzer.analyser.fftSize;
290
283
  const audioData = new Float32Array(bufferSize);
291
284
  this.audioAnalyzer.analyser.getFloatTimeDomainData(audioData);
292
- this.emit("audioData", audioData);
285
+ this.emit('audioData', audioData);
293
286
  this.audioFrameCapture = requestAnimationFrame(() => this.captureAudio());
294
287
  }
295
288
  setupEventHandlers(config) {
289
+ let wasAgentSpeaking = false;
296
290
  if (!this.room)
297
291
  return;
298
292
  // Room events
299
293
  this.room.on(RoomEvent.ParticipantDisconnected, (participant) => {
300
- if ((participant === null || participant === void 0 ? void 0 : participant.identity) === "assistant") {
294
+ if ((participant === null || participant === void 0 ? void 0 : participant.identity) === 'assistant') {
301
295
  this.endCall();
302
296
  }
303
297
  });
@@ -309,9 +303,7 @@ class TrilletWebSDK extends EventEmitter {
309
303
  this.room.on(RoomEvent.TrackSubscribed, (track, publication) => {
310
304
  var _a;
311
305
  if (track.kind === Track.Kind.Audio) {
312
- if (publication.trackName === "assistant_audio" &&
313
- track instanceof RemoteAudioTrack &&
314
- ((_a = config.features) === null || _a === void 0 ? void 0 : _a.enableRawAudio)) {
306
+ if (publication.trackName === 'assistant_audio' && track instanceof RemoteAudioTrack && ((_a = config.features) === null || _a === void 0 ? void 0 : _a.enableRawAudio)) {
315
307
  const analyzer = createAudioAnalyser(track);
316
308
  this.audioAnalyzer = {
317
309
  calculateVolume: analyzer.calculateVolume,
@@ -325,32 +317,42 @@ class TrilletWebSDK extends EventEmitter {
325
317
  });
326
318
  // Data events
327
319
  this.room.on(RoomEvent.DataReceived, (payload, participant) => {
328
- if ((participant === null || participant === void 0 ? void 0 : participant.identity) !== "assistant")
320
+ if ((participant === null || participant === void 0 ? void 0 : participant.identity) !== 'agent')
329
321
  return;
330
322
  try {
331
323
  const data = JSON.parse(decoder.decode(payload));
332
324
  this.handleDataEvent(data);
333
325
  }
334
326
  catch (error) {
335
- console.error("Failed to process received data:", error);
327
+ console.error('Failed to process received data:', error);
336
328
  }
337
329
  });
330
+ this.room.on(RoomEvent.ActiveSpeakersChanged, (speakers) => {
331
+ const isAgentSpeaking = speakers.some((p) => p.identity.startsWith('agent'));
332
+ if (isAgentSpeaking && !wasAgentSpeaking) {
333
+ this.emit('assistantStartedSpeaking');
334
+ }
335
+ else if (!isAgentSpeaking && wasAgentSpeaking) {
336
+ this.emit('assistantStoppedSpeaking');
337
+ }
338
+ wasAgentSpeaking = isAgentSpeaking;
339
+ });
338
340
  }
339
341
  handleDataEvent(event) {
340
342
  switch (event.type) {
341
- case "status":
342
- this.emit("status", event);
343
+ case 'status':
344
+ this.emit('status', event);
343
345
  break;
344
- case "metadata":
345
- this.emit("metadata", event);
346
+ case 'metadata':
347
+ this.emit('metadata', event);
346
348
  break;
347
- case "assistant_speaking_started":
349
+ case 'assistant_speaking_started':
348
350
  this.isAssistantSpeaking = true;
349
- this.emit("assistantStartedSpeaking");
351
+ this.emit('assistantStartedSpeaking');
350
352
  break;
351
- case "assistant_speaking_ended":
353
+ case 'assistant_speaking_ended':
352
354
  this.isAssistantSpeaking = false;
353
- this.emit("assistantStoppedSpeaking");
355
+ this.emit('assistantStoppedSpeaking');
354
356
  break;
355
357
  }
356
358
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trillet-ai/web-sdk",
3
- "version": "1.3.5",
3
+ "version": "1.3.6",
4
4
  "description": "Trillet Web SDK for real-time audio communication with AI agents",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -33,7 +33,7 @@
33
33
  "license": "MIT",
34
34
  "dependencies": {
35
35
  "eventemitter3": "^5.0.1",
36
- "livekit-client": "^2.8.1"
36
+ "livekit-client": "^2.12.0"
37
37
  },
38
38
  "devDependencies": {
39
39
  "@types/jest": "^29.5.12",