@trillet-ai/web-sdk 1.3.4 → 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/LICENSE CHANGED
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2024 Trillet AI
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Trillet AI
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
21
  SOFTWARE.
package/README.md CHANGED
@@ -1,184 +1,184 @@
1
- # Trillet AI Web Calls SDK
2
-
3
- The Trillet AI Web Calls SDK enables seamless integration of AI-powered voice and text interactions into web applications. This SDK provides a simple interface to connect with Trillet AI agents for real-time communication.
4
-
5
- ## Features
6
-
7
- - 🎙️ Real-time voice interactions with AI agents
8
- - 💬 Text-based conversations
9
- - 🔒 Secure authentication options
10
- - 📊 Audio visualization capabilities
11
- - 🎯 Event-driven architecture
12
- - 🔄 Real-time transcription
13
- - 🌐 Browser compatibility checks
14
-
15
- ## Installation
16
-
17
- ```bash
18
- npm install @trillet/webcalls-sdk
19
- # or
20
- yarn add @trillet/webcalls-sdk
21
- ```
22
-
23
- ## Quick Start
24
-
25
- ```typescript
26
- import { TrilletAgent } from '@trillet/webcalls-sdk';
27
-
28
- // Initialize the agent with API Key (Standard Method)
29
- const agent = new TrilletAgent({
30
- apiKey: 'your-api-key',
31
- workspaceId: 'your-workspace-id',
32
- agentId: 'your-agent-id',
33
-
34
- // Optional parameters
35
- variables: {
36
- customVar1: 'value1',
37
- customVar2: 'value2'
38
- },
39
- callbackUrl: 'https://your-callback-url.com'
40
- });
41
-
42
- // Start a regular call
43
- await agent.startCall();
44
-
45
- // Or start a public call
46
- await agent.startPublicCall();
47
-
48
- // Listen for events
49
- agent.on('connected', (details) => {
50
- console.log('Connected to call:', details);
51
- });
52
-
53
- agent.on('transcriptionReceived', (transcript) => {
54
- console.log('New transcript:', transcript);
55
- });
56
-
57
- // Control the call
58
- agent.toggleMicrophone(true); // Enable/disable microphone
59
- agent.endCall(); // End the call
60
- ```
61
-
62
- ## Authentication
63
-
64
- The SDK supports two authentication methods:
65
-
66
- 1. **API Key Authentication (Standard Method)**
67
- ```typescript
68
- const agent = new TrilletAgent({
69
- apiKey: 'your-api-key',
70
- workspaceId: 'your-workspace-id',
71
- agentId: 'your-agent-id'
72
- });
73
- ```
74
-
75
- 2. **Public Access**
76
- - For public-facing applications
77
- - Uses `startPublicCall()` method
78
- ```typescript
79
- const agent = new TrilletAgent({
80
- workspaceId: 'your-workspace-id',
81
- agentId: 'your-agent-id'
82
- });
83
- await agent.startPublicCall();
84
- ```
85
-
86
- ## Call Types
87
-
88
- The SDK supports two types of calls:
89
-
90
- 1. **Regular Call** - Using `startCall()`
91
- - Requires full authentication with API Key
92
- - Suitable for authenticated users
93
-
94
- 2. **Public Call** - Using `startPublicCall()`
95
- - Requires workspace ID and agent ID
96
- - Suitable for public-facing applications
97
- - No API key needed in client-side code
98
- - Example:
99
- ```typescript
100
- const agent = new TrilletAgent({
101
- workspaceId: 'your-workspace-id',
102
- agentId: 'your-agent-id' // Required for both public and regular calls
103
- });
104
- await agent.startPublicCall();
105
- ```
106
-
107
- ## Events
108
-
109
- The SDK emits various events that you can listen to:
110
-
111
- ```typescript
112
- agent.on('connected', (details) => {
113
- // Called when successfully connected to a call
114
- });
115
-
116
- agent.on('disconnected', () => {
117
- // Called when the call ends
118
- });
119
-
120
- agent.on('error', (error) => {
121
- // Called when an error occurs
122
- });
123
-
124
- agent.on('transcriptionReceived', (segments, participant) => {
125
- // Called when new transcription is available
126
- });
127
-
128
- agent.on('assistantStartedSpeaking', () => {
129
- // Called when the AI agent starts speaking
130
- });
131
-
132
- agent.on('assistantStoppedSpeaking', () => {
133
- // Called when the AI agent stops speaking
134
- });
135
-
136
- agent.on('audioData', (data) => {
137
- // Raw audio data for visualization
138
- });
139
- ```
140
-
141
- ## Voice Mode Features
142
-
143
- When using voice mode, the SDK provides additional audio-related features:
144
-
145
- ```typescript
146
- // Check if the assistant is currently speaking
147
- const isSpeaking = agent.isAssistantSpeaking;
148
-
149
- // Access transcripts
150
- const allTranscripts = agent.getTranscripts();
151
- const currentTranscript = agent.getCurrentTranscript();
152
- ```
153
-
154
- ## Requirements
155
-
156
- - Modern web browser with secure context (HTTPS or localhost)
157
- - WebRTC support
158
- - Microphone access (for voice mode)
159
-
160
- ## Browser Support
161
-
162
- The SDK is compatible with modern browsers that support WebRTC:
163
- - Chrome (recommended)
164
- - Firefox
165
- - Safari
166
- - Edge
167
-
168
- ## Error Handling
169
-
170
- The SDK includes comprehensive error handling:
171
-
172
- ```typescript
173
- agent.on('error', (error) => {
174
- console.error('Trillet SDK Error:', error);
175
- });
176
- ```
177
-
178
- ## License
179
-
180
- [License details here]
181
-
182
- ## Support
183
-
184
- For support, please contact [support contact information].
1
+ # Trillet AI Web Calls SDK
2
+
3
+ The Trillet AI Web Calls SDK enables seamless integration of AI-powered voice and text interactions into web applications. This SDK provides a simple interface to connect with Trillet AI agents for real-time communication.
4
+
5
+ ## Features
6
+
7
+ - 🎙️ Real-time voice interactions with AI agents
8
+ - 💬 Text-based conversations
9
+ - 🔒 Secure authentication options
10
+ - 📊 Audio visualization capabilities
11
+ - 🎯 Event-driven architecture
12
+ - 🔄 Real-time transcription
13
+ - 🌐 Browser compatibility checks
14
+
15
+ ## Installation
16
+
17
+ ```bash
18
+ npm install @trillet-ai/web-sdk
19
+ # or
20
+ yarn add @trillet-ai/web-sdk
21
+ ```
22
+
23
+ ## Quick Start
24
+
25
+ ```typescript
26
+ import { TrilletAgent } from '@trillet-ai/web-sdk';
27
+
28
+ // Initialize the agent with API Key (Standard Method)
29
+ const agent = new TrilletAgent({
30
+ apiKey: 'your-api-key',
31
+ workspaceId: 'your-workspace-id',
32
+ agentId: 'your-agent-id',
33
+
34
+ // Optional parameters
35
+ variables: {
36
+ customVar1: 'value1',
37
+ customVar2: 'value2'
38
+ },
39
+ callbackUrl: 'https://your-callback-url.com'
40
+ });
41
+
42
+ // Start a regular call
43
+ await agent.startCall();
44
+
45
+ // Or start a public call
46
+ await agent.startPublicCall();
47
+
48
+ // Listen for events
49
+ agent.on('connected', (details) => {
50
+ console.log('Connected to call:', details);
51
+ });
52
+
53
+ agent.on('transcriptionReceived', (transcript) => {
54
+ console.log('New transcript:', transcript);
55
+ });
56
+
57
+ // Control the call
58
+ agent.toggleMicrophone(true); // Enable/disable microphone
59
+ agent.endCall(); // End the call
60
+ ```
61
+
62
+ ## Authentication
63
+
64
+ The SDK supports two authentication methods:
65
+
66
+ 1. **API Key Authentication (Standard Method)**
67
+ ```typescript
68
+ const agent = new TrilletAgent({
69
+ apiKey: 'your-api-key',
70
+ workspaceId: 'your-workspace-id',
71
+ agentId: 'your-agent-id'
72
+ });
73
+ ```
74
+
75
+ 2. **Public Access**
76
+ - For public-facing applications
77
+ - Uses `startPublicCall()` method
78
+ ```typescript
79
+ const agent = new TrilletAgent({
80
+ workspaceId: 'your-workspace-id',
81
+ agentId: 'your-agent-id'
82
+ });
83
+ await agent.startPublicCall();
84
+ ```
85
+
86
+ ## Call Types
87
+
88
+ The SDK supports two types of calls:
89
+
90
+ 1. **Regular Call** - Using `startCall()`
91
+ - Requires full authentication with API Key
92
+ - Suitable for authenticated users
93
+
94
+ 2. **Public Call** - Using `startPublicCall()`
95
+ - Requires workspace ID and agent ID
96
+ - Suitable for public-facing applications
97
+ - No API key needed in client-side code
98
+ - Example:
99
+ ```typescript
100
+ const agent = new TrilletAgent({
101
+ workspaceId: 'your-workspace-id',
102
+ agentId: 'your-agent-id' // Required for both public and regular calls
103
+ });
104
+ await agent.startPublicCall();
105
+ ```
106
+
107
+ ## Events
108
+
109
+ The SDK emits various events that you can listen to:
110
+
111
+ ```typescript
112
+ agent.on('connected', (details) => {
113
+ // Called when successfully connected to a call
114
+ });
115
+
116
+ agent.on('disconnected', () => {
117
+ // Called when the call ends
118
+ });
119
+
120
+ agent.on('error', (error) => {
121
+ // Called when an error occurs
122
+ });
123
+
124
+ agent.on('transcriptionReceived', (segments, participant) => {
125
+ // Called when new transcription is available
126
+ });
127
+
128
+ agent.on('assistantStartedSpeaking', () => {
129
+ // Called when the AI agent starts speaking
130
+ });
131
+
132
+ agent.on('assistantStoppedSpeaking', () => {
133
+ // Called when the AI agent stops speaking
134
+ });
135
+
136
+ agent.on('audioData', (data) => {
137
+ // Raw audio data for visualization
138
+ });
139
+ ```
140
+
141
+ ## Voice Mode Features
142
+
143
+ When using voice mode, the SDK provides additional audio-related features:
144
+
145
+ ```typescript
146
+ // Check if the assistant is currently speaking
147
+ const isSpeaking = agent.isAssistantSpeaking;
148
+
149
+ // Access transcripts
150
+ const allTranscripts = agent.getTranscripts();
151
+ const currentTranscript = agent.getCurrentTranscript();
152
+ ```
153
+
154
+ ## Requirements
155
+
156
+ - Modern web browser with secure context (HTTPS or localhost)
157
+ - WebRTC support
158
+ - Microphone access (for voice mode)
159
+
160
+ ## Browser Support
161
+
162
+ The SDK is compatible with modern browsers that support WebRTC:
163
+ - Chrome (recommended)
164
+ - Firefox
165
+ - Safari
166
+ - Edge
167
+
168
+ ## Error Handling
169
+
170
+ The SDK includes comprehensive error handling:
171
+
172
+ ```typescript
173
+ agent.on('error', (error) => {
174
+ console.error('Trillet SDK Error:', error);
175
+ });
176
+ ```
177
+
178
+ ## License
179
+
180
+ [License details here]
181
+
182
+ ## Support
183
+
184
+ For support, please contact [support contact information].
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,14 +85,14 @@ 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
- agentId: this.config.agentId,
95
+ call_agent_id: this.config.agentId,
101
96
  mode: this.config.mode,
102
97
  dynamic_variables: this.config.variables || {},
103
98
  callback_url: this.config.callbackUrl,
@@ -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,56 +1,56 @@
1
- {
2
- "name": "@trillet-ai/web-sdk",
3
- "version": "1.3.4",
4
- "description": "Trillet Web SDK for real-time audio communication with AI agents",
5
- "main": "dist/index.js",
6
- "types": "dist/index.d.ts",
7
- "type": "module",
8
- "publishConfig": {
9
- "access": "public"
10
- },
11
- "scripts": {
12
- "clean": "rimraf dist",
13
- "build": "npm run clean && tsc",
14
- "dev": "tsc --watch",
15
- "lint": "eslint src/**/*.{ts,tsx}",
16
- "prepare": "npm run build",
17
- "test": "node --experimental-vm-modules node_modules/jest/bin/jest.js"
18
- },
19
- "peerDependencies": {
20
- "react": ">=16.8.0",
21
- "react-dom": ">=16.8.0"
22
- },
23
- "keywords": [
24
- "trillet",
25
- "ai",
26
- "voice",
27
- "audio",
28
- "sdk",
29
- "webrtc",
30
- "react"
31
- ],
32
- "author": "Trillet AI",
33
- "license": "MIT",
34
- "dependencies": {
35
- "eventemitter3": "^5.0.1",
36
- "livekit-client": "^2.8.1"
37
- },
38
- "devDependencies": {
39
- "@types/jest": "^29.5.12",
40
- "@types/node": "^20.11.0",
41
- "@types/react": "^18.2.0",
42
- "@types/react-dom": "^18.2.0",
43
- "@typescript-eslint/eslint-plugin": "^6.18.1",
44
- "@typescript-eslint/parser": "^6.18.1",
45
- "eslint": "^8.56.0",
46
- "jest": "^29.7.0",
47
- "rimraf": "^5.0.10",
48
- "ts-jest": "^29.1.2",
49
- "typescript": "^5.3.3"
50
- },
51
- "files": [
52
- "dist",
53
- "README.md",
54
- "LICENSE"
55
- ]
56
- }
1
+ {
2
+ "name": "@trillet-ai/web-sdk",
3
+ "version": "1.3.6",
4
+ "description": "Trillet Web SDK for real-time audio communication with AI agents",
5
+ "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
7
+ "type": "module",
8
+ "publishConfig": {
9
+ "access": "public"
10
+ },
11
+ "scripts": {
12
+ "clean": "rimraf dist",
13
+ "build": "npm run clean && tsc",
14
+ "dev": "tsc --watch",
15
+ "lint": "eslint src/**/*.{ts,tsx}",
16
+ "prepare": "npm run build",
17
+ "test": "node --experimental-vm-modules node_modules/jest/bin/jest.js"
18
+ },
19
+ "peerDependencies": {
20
+ "react": ">=16.8.0",
21
+ "react-dom": ">=16.8.0"
22
+ },
23
+ "keywords": [
24
+ "trillet",
25
+ "ai",
26
+ "voice",
27
+ "audio",
28
+ "sdk",
29
+ "webrtc",
30
+ "react"
31
+ ],
32
+ "author": "Trillet AI",
33
+ "license": "MIT",
34
+ "dependencies": {
35
+ "eventemitter3": "^5.0.1",
36
+ "livekit-client": "^2.12.0"
37
+ },
38
+ "devDependencies": {
39
+ "@types/jest": "^29.5.12",
40
+ "@types/node": "^20.11.0",
41
+ "@types/react": "^18.2.0",
42
+ "@types/react-dom": "^18.2.0",
43
+ "@typescript-eslint/eslint-plugin": "^6.18.1",
44
+ "@typescript-eslint/parser": "^6.18.1",
45
+ "eslint": "^8.56.0",
46
+ "jest": "^29.7.0",
47
+ "rimraf": "^5.0.10",
48
+ "ts-jest": "^29.1.2",
49
+ "typescript": "^5.3.3"
50
+ },
51
+ "files": [
52
+ "dist",
53
+ "README.md",
54
+ "LICENSE"
55
+ ]
56
+ }