@trillet-ai/web-sdk 1.2.8 → 1.2.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,93 +1,167 @@
1
- # Trillet AI Web SDK
1
+ # Trillet Web SDK
2
2
 
3
- Official Web SDK for integrating Trillet AI voice agents into your web applications. This SDK enables real-time voice communication with Trillet AI agents directly in your frontend application.
3
+ The Trillet Web SDK enables you to integrate voice AI agents into your web applications. This SDK provides a simple interface for initiating and managing voice calls with Trillet AI agents.
4
4
 
5
5
  ## Installation
6
6
 
7
7
  ```bash
8
- npm install @trillet-ai/web-sdk
8
+ npm install @trillet/web-sdk
9
9
  ```
10
10
 
11
- ## Quick Start
12
-
13
- ### React Integration
14
-
15
- ```tsx
16
- import { TrilletAgent } from '@trillet-ai/web-sdk';
17
- import { useState } from 'react';
18
-
19
- function VoiceAgent() {
20
- const [agent] = useState(() => new TrilletAgent({
21
- apiKey: 'your-api-key',
22
- workspaceId: 'your-workspace-id',
23
- agentId: 'your-agent-id'
24
- }));
25
-
26
- return (
27
- <div>
28
- <button onClick={() => agent.startCall()}>Start Call</button>
29
- <button onClick={() => agent.endCall()}>End Call</button>
30
- <button onClick={() => agent.toggleMicrophone(false)}>Mute</button>
31
- </div>
32
- );
33
- }
11
+ ## Authentication
12
+
13
+ There are two methods to authenticate with the Trillet API:
14
+
15
+ ### 1. Server-Side Authentication (Recommended)
16
+
17
+ For production environments, we strongly recommend using server-side authentication to keep your API keys secure. Here's how to implement it:
18
+
19
+ 1. First, generate a token on your backend server:
20
+
21
+ ```javascript
22
+ // Backend (Node.js example)
23
+ app.post('/get-trillet-token', async (req, res) => {
24
+ try {
25
+ const response = await fetch('https://api.trillet.ai/v1/api/calls/sdk/auth', {
26
+ method: 'POST',
27
+ headers: {
28
+ 'Content-Type': 'application/json',
29
+ },
30
+ body: JSON.stringify({
31
+ api_key: process.env.TRILLET_API_KEY,
32
+ workspace_id: process.env.TRILLET_WORKSPACE_ID
33
+ })
34
+ });
35
+
36
+ const { sdk_token } = await response.json();
37
+ res.json({ token: sdk_token });
38
+ } catch (error) {
39
+ res.status(500).json({ error: 'Failed to generate token' });
40
+ }
41
+ });
34
42
  ```
35
43
 
36
- ### Vanilla JavaScript
44
+ 2. Then use the token in your frontend code:
37
45
 
38
46
  ```javascript
39
- import { TrilletAgent } from '@trillet-ai/web-sdk';
47
+ // Frontend
48
+ const response = await fetch('/get-trillet-token');
49
+ const { token } = await response.json();
40
50
 
41
51
  const agent = new TrilletAgent({
42
- apiKey: 'your-api-key',
43
- workspaceId: 'your-workspace-id',
52
+ connectionToken: token, // Use the token from your backend
44
53
  agentId: 'your-agent-id'
45
54
  });
46
55
 
47
- // Add event listeners
48
- agent.on('connected', () => console.log('Connected to agent'));
49
- agent.on('disconnected', () => console.log('Disconnected from agent'));
50
- agent.on('error', (error) => console.error('Error:', error));
56
+ await agent.startCall();
57
+ ```
58
+
59
+ ### 2. Direct Authentication (Development Only)
60
+
61
+ For development and testing purposes only, you can authenticate directly:
62
+
63
+ ```javascript
64
+ const agent = new TrilletAgent({
65
+ apiKey: 'your-api-key', // Not recommended in production
66
+ workspaceId: 'your-workspace-id', // Not recommended in production
67
+ agentId: 'your-agent-id'
68
+ });
51
69
 
52
- // Control the call
53
70
  await agent.startCall();
54
- await agent.endCall();
55
- agent.toggleMicrophone(false); // mute
56
71
  ```
57
72
 
58
- ## Required Parameters
73
+ ⚠️ **Security Warning**: Never expose your API keys in frontend code in production. Always use server-side token generation for production environments.
74
+
75
+ ## Basic Usage
76
+
77
+ ```javascript
78
+ import { TrilletAgent } from '@trillet/web-sdk';
79
+
80
+ // Initialize the agent
81
+ const agent = new TrilletAgent({
82
+ connectionToken: 'token-from-your-backend',
83
+ agentId: 'your-agent-id',
84
+ variables: {
85
+ // Optional variables to customize agent behavior
86
+ customerName: 'John Doe',
87
+ context: 'support'
88
+ },
89
+ callbackUrl: 'https://your-server.com/webhooks/calls' // Optional webhook URL for call events
90
+ });
91
+
92
+ // Start a call
93
+ await agent.startCall();
94
+
95
+ // Listen for events
96
+ agent.on('connected', () => {
97
+ console.log('Connected to agent');
98
+ });
99
+
100
+ agent.on('disconnected', () => {
101
+ console.log('Disconnected from agent');
102
+ });
103
+
104
+ agent.on('error', (error) => {
105
+ console.error('Error:', error);
106
+ });
107
+
108
+ // End the call
109
+ agent.endCall();
110
+ ```
59
111
 
60
- - `apiKey`: Your Trillet API key for authentication
61
- - `agentId`: The unique identifier of the Trillet AI agent you want to connect to
62
- - `workspaceId`: Your Trillet workspace identifier
112
+ ## API Endpoints
63
113
 
64
- ## Features
114
+ The SDK uses the following endpoints:
65
115
 
66
- - 🎯 Frontend-only integration - no backend required
67
- - 🔒 Secure WebRTC communication
68
- - 🎤 High-quality audio streaming
69
- - ⚛️ React support out of the box
70
- - 📱 Mobile browser support
71
- - 🔊 Audio device control (mute/unmute)
116
+ - Authentication: `https://api.trillet.ai/v1/api/calls/sdk/auth`
117
+ - Connection: `https://api.trillet.ai/v1/api/calls/web/connect`
72
118
 
73
119
  ## Events
74
120
 
75
- The SDK emits several events you can listen to:
121
+ The SDK emits various events you can listen to:
122
+
123
+ - `connected`: Fired when successfully connected to the agent
124
+ - `disconnected`: Fired when disconnected from the agent
125
+ - `error`: Fired when an error occurs
126
+ - `status`: Provides status updates about the call
127
+ - `metadata`: Provides additional data about the call
128
+ - `assistantStartedSpeaking`: Fired when the AI agent starts speaking
129
+ - `assistantStoppedSpeaking`: Fired when the AI agent stops speaking
130
+ - `audioData`: Provides raw audio data (if enabled)
131
+
132
+ ## Advanced Configuration
133
+
134
+ You can customize various aspects of the call:
135
+
136
+ ```javascript
137
+ const agent = new TrilletAgent({
138
+ connectionToken: 'your-token',
139
+ agentId: 'your-agent-id',
140
+ variables: {
141
+ // Custom variables for your agent
142
+ },
143
+ callbackUrl: 'https://your-webhook-url.com',
144
+ });
145
+
146
+ await agent.startCall();
147
+
148
+ // Toggle microphone
149
+ agent.toggleMicrophone(false); // Mute
150
+ agent.toggleMicrophone(true); // Unmute
76
151
 
77
- ```typescript
78
- agent.on('connected', () => {}); // Call connected
79
- agent.on('disconnected', () => {}); // Call ended
80
- agent.on('error', (error) => {}); // Error occurred
81
- agent.on('assistantStartedSpeaking', () => {}); // AI started speaking
82
- agent.on('assistantStoppedSpeaking', () => {}); // AI stopped speaking
152
+ // Check if assistant is speaking
153
+ const isSpeaking = agent.isAssistantSpeaking;
83
154
  ```
84
155
 
85
- ## Documentation
156
+ ## Browser Support
86
157
 
87
- For detailed documentation and integration examples, visit:
88
- - [API Documentation](https://docs.trillet.ai/sdk)
89
- - [Example Repository](https://github.com/trillet-ai/webcalls-examples)
158
+ The SDK requires a secure context (HTTPS or localhost) and modern browser features. Supported browsers:
159
+ - Chrome (recommended)
160
+ - Firefox
161
+ - Safari
162
+ - Edge
90
163
 
91
- ## License
164
+ ## Need Help?
92
165
 
93
- MIT License - see LICENSE file for details
166
+ - Documentation: [https://docs.trillet.ai](https://docs.trillet.ai)
167
+ - Support: [support@trillet.ai](mailto:support@trillet.ai)
package/dist/index.d.ts CHANGED
@@ -1,9 +1,12 @@
1
1
  import { EventEmitter } from "eventemitter3";
2
2
  export interface TrilletAgentConfig {
3
- apiKey: string;
4
- workspaceId: string;
3
+ connectionToken?: string;
4
+ apiKey?: string;
5
+ workspaceId?: string;
5
6
  agentId: string;
6
7
  variables?: Record<string, any>;
8
+ callbackUrl?: string;
9
+ mode?: 'voice' | 'text';
7
10
  }
8
11
  export interface TrilletCallConfig {
9
12
  token: string;
@@ -20,8 +23,10 @@ export interface TrilletCallConfig {
20
23
  export declare class TrilletAgent extends EventEmitter {
21
24
  private sdk;
22
25
  private config;
26
+ private sdkToken;
23
27
  constructor(config: TrilletAgentConfig);
24
28
  private setupEventForwarding;
29
+ private authenticate;
25
30
  startCall(): Promise<void>;
26
31
  endCall(): void;
27
32
  toggleMicrophone(enabled: boolean): void;
package/dist/index.js CHANGED
@@ -1,7 +1,9 @@
1
1
  import { EventEmitter } from "eventemitter3";
2
2
  import { RemoteAudioTrack, Room, RoomEvent, Track, createAudioAnalyser, } from "livekit-client";
3
- const TRILLET_API_URL = "https://api.trillet.ai/v1/api/calls/web/connect";
4
- const TRILLET_LIVEKIT_WS_URL = "wss://trillet-ai-xdx0dw5r.livekit.cloud";
3
+ const TRILLET_API_URL = {
4
+ AUTH: "https://api.trillet.ai/v1/api/calls/sdk/auth",
5
+ CONNECT: "https://api.trillet.ai/v1/api/calls/web/connect"
6
+ };
5
7
  const decoder = new TextDecoder();
6
8
  // Browser compatibility check
7
9
  const isBrowser = typeof window !== 'undefined';
@@ -9,6 +11,7 @@ const isSecureContext = isBrowser && window.isSecureContext;
9
11
  export class TrilletAgent extends EventEmitter {
10
12
  constructor(config) {
11
13
  super();
14
+ this.sdkToken = null;
12
15
  // Validate environment
13
16
  if (!isBrowser) {
14
17
  throw new Error('Trillet SDK must be used in a browser environment');
@@ -17,13 +20,16 @@ export class TrilletAgent extends EventEmitter {
17
20
  throw new Error('Trillet SDK requires a secure context (HTTPS or localhost)');
18
21
  }
19
22
  // Validate config
20
- if (!config.apiKey)
21
- throw new Error('apiKey is required');
22
- if (!config.workspaceId)
23
- throw new Error('workspaceId is required');
24
- if (!config.agentId)
23
+ if (!config.connectionToken && (!config.apiKey || !config.workspaceId)) {
24
+ throw new Error('Either connectionToken OR (apiKey AND workspaceId) must be provided');
25
+ }
26
+ if (!config.agentId) {
25
27
  throw new Error('agentId is required');
26
- this.config = config;
28
+ }
29
+ this.config = {
30
+ ...config,
31
+ mode: config.mode || 'voice' // Default to voice mode
32
+ };
27
33
  this.sdk = new TrilletWebSDK();
28
34
  this.setupEventForwarding();
29
35
  }
@@ -38,23 +44,60 @@ export class TrilletAgent extends EventEmitter {
38
44
  this.sdk.on('assistantStoppedSpeaking', () => this.emit('assistantStoppedSpeaking'));
39
45
  this.sdk.on('audioData', (data) => this.emit('audioData', data));
40
46
  }
47
+ async authenticate() {
48
+ if (this.config.connectionToken) {
49
+ return this.config.connectionToken;
50
+ }
51
+ try {
52
+ console.warn('WARNING: Using API key authentication directly from the browser is not recommended for production. ' +
53
+ 'Please consider implementing server-side token generation.');
54
+ const response = await fetch(TRILLET_API_URL.AUTH, {
55
+ method: 'POST',
56
+ headers: {
57
+ 'Content-Type': 'application/json',
58
+ 'Accept': 'application/json'
59
+ },
60
+ body: JSON.stringify({
61
+ api_key: this.config.apiKey,
62
+ workspace_id: this.config.workspaceId
63
+ })
64
+ });
65
+ if (!response.ok) {
66
+ let errorMessage;
67
+ try {
68
+ const errorData = await response.json();
69
+ errorMessage = errorData.message || errorData.error || 'Unknown error';
70
+ }
71
+ catch (_a) {
72
+ errorMessage = await response.text();
73
+ }
74
+ throw new Error(`Authentication Error: ${errorMessage}`);
75
+ }
76
+ const data = await response.json();
77
+ return data.sdk_token;
78
+ }
79
+ catch (error) {
80
+ console.error('Trillet SDK Authentication Error:', error);
81
+ throw error;
82
+ }
83
+ }
41
84
  async startCall() {
42
85
  try {
43
- // 1. Get LiveKit token from Trillet API
44
- const response = await fetch(TRILLET_API_URL, {
86
+ // 1. Get or use connection token
87
+ const token = await this.authenticate();
88
+ // 2. Initialize call with LiveKit token
89
+ const response = await fetch(TRILLET_API_URL.CONNECT, {
45
90
  method: 'POST',
46
91
  headers: {
47
92
  'Content-Type': 'application/json',
48
93
  'Accept': 'application/json',
49
- 'x-workspace-id': this.config.workspaceId,
50
- 'x-api-key': this.config.apiKey,
51
- 'Origin': window.location.origin // Explicitly set origin
94
+ 'Authorization': `Bearer ${token}`
52
95
  },
53
- mode: 'cors', // Explicitly request CORS
54
- credentials: 'include', // Include credentials if needed
55
96
  body: JSON.stringify({
56
97
  agentId: this.config.agentId,
57
- dynamic_variables: this.config.variables || {}
98
+ mode: this.config.mode,
99
+ dynamic_variables: this.config.variables || {},
100
+ callback_url: this.config.callbackUrl
58
101
  })
59
102
  });
60
103
  if (!response.ok) {
@@ -69,22 +112,30 @@ export class TrilletAgent extends EventEmitter {
69
112
  throw new Error(`API Error: ${errorMessage}`);
70
113
  }
71
114
  const data = await response.json();
72
- if (!data.token) {
73
- throw new Error('Invalid response from server: missing token');
115
+ if (!data.token || !data.roomName) {
116
+ throw new Error('Invalid response from server: missing token or room name');
74
117
  }
75
- // 2. Initialize call with LiveKit token
118
+ // 3. Initialize call with LiveKit token
76
119
  await this.sdk.initializeCall({
77
120
  token: data.token,
78
- wsUrl: TRILLET_LIVEKIT_WS_URL,
121
+ wsUrl: process.env.LIVEKIT_WS_URL || 'wss://trillet-ai-xdx0dw5r.livekit.cloud',
79
122
  audioSettings: {
80
123
  sampleRate: 48000
81
124
  },
82
125
  features: {
83
- enableRawAudio: true
126
+ enableRawAudio: this.config.mode === 'voice'
84
127
  }
85
128
  });
86
- // 3. Enable audio playback
87
- await this.sdk.enableAudioPlayback();
129
+ // 4. Enable audio playback for voice mode
130
+ if (this.config.mode === 'voice') {
131
+ await this.sdk.enableAudioPlayback();
132
+ }
133
+ // Emit additional connection details
134
+ this.emit('connected', {
135
+ callId: data.callId,
136
+ roomName: data.roomName,
137
+ agent: data.agent
138
+ });
88
139
  }
89
140
  catch (error) {
90
141
  console.error('Trillet SDK Error:', error);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trillet-ai/web-sdk",
3
- "version": "1.2.8",
3
+ "version": "1.2.10",
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",
@@ -31,6 +31,7 @@
31
31
  "author": "Trillet AI",
32
32
  "license": "MIT",
33
33
  "dependencies": {
34
+ "@trillet-ai/web-sdk": "file:",
34
35
  "eventemitter3": "^5.0.1",
35
36
  "livekit-client": "^1.15.5"
36
37
  },