@trillet-ai/web-sdk 1.5.8 → 1.5.9
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 +1 -1
- package/README.md +8 -46
- package/dist/BrowserFingerprint.d.ts +33 -0
- package/dist/BrowserFingerprint.js +178 -0
- package/dist/index.d.ts +30 -21
- package/dist/index.js +198 -125
- package/package.json +2 -3
- package/dist/TranscriptManager.d.ts +0 -35
- package/dist/TranscriptManager.js +0 -63
- package/dist/TrilletWebSDK.d.ts +0 -38
- package/dist/TrilletWebSDK.js +0 -238
package/LICENSE
CHANGED
package/README.md
CHANGED
|
@@ -30,7 +30,6 @@ const agent = new TrilletAgent({
|
|
|
30
30
|
apiKey: 'your-api-key',
|
|
31
31
|
workspaceId: 'your-workspace-id',
|
|
32
32
|
agentId: 'your-agent-id',
|
|
33
|
-
mode: 'voice', // 'voice' or 'text'
|
|
34
33
|
|
|
35
34
|
// Optional parameters
|
|
36
35
|
variables: {
|
|
@@ -52,20 +51,11 @@ agent.on('connected', (details) => {
|
|
|
52
51
|
});
|
|
53
52
|
|
|
54
53
|
agent.on('transcriptionReceived', (transcript) => {
|
|
55
|
-
console.log('New
|
|
56
|
-
});
|
|
57
|
-
|
|
58
|
-
agent.on('message', (message) => {
|
|
59
|
-
console.log('New text message from agent:', message);
|
|
60
|
-
});
|
|
61
|
-
|
|
62
|
-
agent.on('transcriptUpdate', (transcripts) => {
|
|
63
|
-
console.log('Transcript updated:', transcripts);
|
|
54
|
+
console.log('New transcript:', transcript);
|
|
64
55
|
});
|
|
65
56
|
|
|
66
57
|
// Control the call
|
|
67
|
-
agent.toggleMicrophone(true); // Enable/disable microphone
|
|
68
|
-
agent.sendTextMessage("Hello, agent!"); // Send a text message in text mode
|
|
58
|
+
agent.toggleMicrophone(true); // Enable/disable microphone
|
|
69
59
|
agent.endCall(); // End the call
|
|
70
60
|
```
|
|
71
61
|
|
|
@@ -88,8 +78,7 @@ The SDK supports two authentication methods:
|
|
|
88
78
|
```typescript
|
|
89
79
|
const agent = new TrilletAgent({
|
|
90
80
|
workspaceId: 'your-workspace-id',
|
|
91
|
-
agentId: 'your-agent-id'
|
|
92
|
-
mode: 'text' // Or 'voice'
|
|
81
|
+
agentId: 'your-agent-id'
|
|
93
82
|
});
|
|
94
83
|
await agent.startPublicCall();
|
|
95
84
|
```
|
|
@@ -110,8 +99,7 @@ The SDK supports two types of calls:
|
|
|
110
99
|
```typescript
|
|
111
100
|
const agent = new TrilletAgent({
|
|
112
101
|
workspaceId: 'your-workspace-id',
|
|
113
|
-
agentId: 'your-agent-id'
|
|
114
|
-
mode: 'text' // Or 'voice'
|
|
102
|
+
agentId: 'your-agent-id' // Required for both public and regular calls
|
|
115
103
|
});
|
|
116
104
|
await agent.startPublicCall();
|
|
117
105
|
```
|
|
@@ -134,27 +122,19 @@ agent.on('error', (error) => {
|
|
|
134
122
|
});
|
|
135
123
|
|
|
136
124
|
agent.on('transcriptionReceived', (segments, participant) => {
|
|
137
|
-
// Called when new transcription is available
|
|
125
|
+
// Called when new transcription is available
|
|
138
126
|
});
|
|
139
127
|
|
|
140
128
|
agent.on('assistantStartedSpeaking', () => {
|
|
141
|
-
// Called when the AI agent starts speaking
|
|
129
|
+
// Called when the AI agent starts speaking
|
|
142
130
|
});
|
|
143
131
|
|
|
144
132
|
agent.on('assistantStoppedSpeaking', () => {
|
|
145
|
-
// Called when the AI agent stops speaking
|
|
133
|
+
// Called when the AI agent stops speaking
|
|
146
134
|
});
|
|
147
135
|
|
|
148
136
|
agent.on('audioData', (data) => {
|
|
149
|
-
// Raw audio data for visualization
|
|
150
|
-
});
|
|
151
|
-
|
|
152
|
-
agent.on('message', (message) => {
|
|
153
|
-
// Called when a text message is received from the agent (text mode)
|
|
154
|
-
});
|
|
155
|
-
|
|
156
|
-
agent.on('transcriptUpdate', (transcripts) => {
|
|
157
|
-
// Called whenever the transcript is updated (voice or text)
|
|
137
|
+
// Raw audio data for visualization
|
|
158
138
|
});
|
|
159
139
|
```
|
|
160
140
|
|
|
@@ -171,24 +151,6 @@ const allTranscripts = agent.getTranscripts();
|
|
|
171
151
|
const currentTranscript = agent.getCurrentTranscript();
|
|
172
152
|
```
|
|
173
153
|
|
|
174
|
-
## Text Mode Features
|
|
175
|
-
|
|
176
|
-
When using text mode, you can send and receive text messages.
|
|
177
|
-
|
|
178
|
-
```typescript
|
|
179
|
-
// Send a message to the agent
|
|
180
|
-
agent.sendTextMessage("Hello, how are you?");
|
|
181
|
-
|
|
182
|
-
// Listen for messages from the agent
|
|
183
|
-
agent.on('message', (message) => {
|
|
184
|
-
console.log('Agent says:', message.text);
|
|
185
|
-
});
|
|
186
|
-
|
|
187
|
-
// The full conversation transcript is available for both modes
|
|
188
|
-
const fullConversation = agent.getTranscripts();
|
|
189
|
-
console.log(fullConversation);
|
|
190
|
-
```
|
|
191
|
-
|
|
192
154
|
## Requirements
|
|
193
155
|
|
|
194
156
|
- Modern web browser with secure context (HTTPS or localhost)
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Browser Fingerprinting Utility
|
|
3
|
+
* Generates a unique fingerprint based on browser characteristics
|
|
4
|
+
* Tracking for demo link usage limits
|
|
5
|
+
*/
|
|
6
|
+
export declare class BrowserFingerprint {
|
|
7
|
+
private static cachedFingerprint;
|
|
8
|
+
/**
|
|
9
|
+
* Generate a unique browser fingerprint
|
|
10
|
+
* Combines multiple browser characteristics to create a unique identifier
|
|
11
|
+
*/
|
|
12
|
+
static generate(): Promise<string>;
|
|
13
|
+
/**
|
|
14
|
+
* Canvas fingerprinting - draws shapes and text, then hashes the result
|
|
15
|
+
*/
|
|
16
|
+
private static getCanvasFingerprint;
|
|
17
|
+
/**
|
|
18
|
+
* WebGL fingerprinting
|
|
19
|
+
*/
|
|
20
|
+
private static getWebGLFingerprint;
|
|
21
|
+
/**
|
|
22
|
+
* Check for common installed fonts
|
|
23
|
+
*/
|
|
24
|
+
private static getInstalledFonts;
|
|
25
|
+
/**
|
|
26
|
+
* Hash all components into a single fingerprint
|
|
27
|
+
*/
|
|
28
|
+
private static hashComponents;
|
|
29
|
+
/**
|
|
30
|
+
* Clear cached fingerprint (useful for testing)
|
|
31
|
+
*/
|
|
32
|
+
static clearCache(): void;
|
|
33
|
+
}
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Browser Fingerprinting Utility
|
|
3
|
+
* Generates a unique fingerprint based on browser characteristics
|
|
4
|
+
* Tracking for demo link usage limits
|
|
5
|
+
*/
|
|
6
|
+
export class BrowserFingerprint {
|
|
7
|
+
/**
|
|
8
|
+
* Generate a unique browser fingerprint
|
|
9
|
+
* Combines multiple browser characteristics to create a unique identifier
|
|
10
|
+
*/
|
|
11
|
+
static async generate() {
|
|
12
|
+
// Return cached fingerprint if already generated
|
|
13
|
+
if (this.cachedFingerprint) {
|
|
14
|
+
return this.cachedFingerprint;
|
|
15
|
+
}
|
|
16
|
+
const components = {};
|
|
17
|
+
// 1. Canvas fingerprinting (most unique)
|
|
18
|
+
components.canvas = await this.getCanvasFingerprint();
|
|
19
|
+
// 2. WebGL fingerprinting
|
|
20
|
+
components.webgl = this.getWebGLFingerprint();
|
|
21
|
+
// 3. Screen characteristics
|
|
22
|
+
components.screen = {
|
|
23
|
+
width: window.screen.width,
|
|
24
|
+
height: window.screen.height,
|
|
25
|
+
colorDepth: window.screen.colorDepth,
|
|
26
|
+
pixelRatio: window.devicePixelRatio,
|
|
27
|
+
availWidth: window.screen.availWidth,
|
|
28
|
+
availHeight: window.screen.availHeight,
|
|
29
|
+
};
|
|
30
|
+
// 4. Timezone
|
|
31
|
+
components.timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
|
|
32
|
+
components.timezoneOffset = new Date().getTimezoneOffset();
|
|
33
|
+
// 5. Language preferences
|
|
34
|
+
components.languages = navigator.languages || [navigator.language];
|
|
35
|
+
components.language = navigator.language;
|
|
36
|
+
// 6. Platform and user agent
|
|
37
|
+
components.platform = navigator.platform;
|
|
38
|
+
components.userAgent = navigator.userAgent;
|
|
39
|
+
// 7. Hardware concurrency (CPU cores)
|
|
40
|
+
components.hardwareConcurrency = navigator.hardwareConcurrency;
|
|
41
|
+
// 8. Device memory (if available)
|
|
42
|
+
components.deviceMemory = navigator.deviceMemory;
|
|
43
|
+
// 9. Installed fonts (quick check)
|
|
44
|
+
components.fonts = await this.getInstalledFonts();
|
|
45
|
+
// 10. Touch support
|
|
46
|
+
components.touchSupport = {
|
|
47
|
+
maxTouchPoints: navigator.maxTouchPoints,
|
|
48
|
+
touchEvent: 'ontouchstart' in window,
|
|
49
|
+
touchPoints: navigator.msMaxTouchPoints,
|
|
50
|
+
};
|
|
51
|
+
// 11. Browser features
|
|
52
|
+
components.features = {
|
|
53
|
+
localStorage: !!window.localStorage,
|
|
54
|
+
sessionStorage: !!window.sessionStorage,
|
|
55
|
+
indexedDB: !!window.indexedDB,
|
|
56
|
+
openDatabase: !!window.openDatabase,
|
|
57
|
+
cpuClass: navigator.cpuClass,
|
|
58
|
+
doNotTrack: navigator.doNotTrack,
|
|
59
|
+
};
|
|
60
|
+
// Generate hash from all components
|
|
61
|
+
const fingerprint = await this.hashComponents(components);
|
|
62
|
+
this.cachedFingerprint = fingerprint;
|
|
63
|
+
return fingerprint;
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Canvas fingerprinting - draws shapes and text, then hashes the result
|
|
67
|
+
*/
|
|
68
|
+
static async getCanvasFingerprint() {
|
|
69
|
+
try {
|
|
70
|
+
const canvas = document.createElement('canvas');
|
|
71
|
+
canvas.width = 200;
|
|
72
|
+
canvas.height = 50;
|
|
73
|
+
const ctx = canvas.getContext('2d');
|
|
74
|
+
if (!ctx)
|
|
75
|
+
return 'no-canvas';
|
|
76
|
+
// Draw text with specific styling
|
|
77
|
+
ctx.textBaseline = 'top';
|
|
78
|
+
ctx.font = '14px Arial';
|
|
79
|
+
ctx.textBaseline = 'alphabetic';
|
|
80
|
+
ctx.fillStyle = '#f60';
|
|
81
|
+
ctx.fillRect(125, 1, 62, 20);
|
|
82
|
+
ctx.fillStyle = '#069';
|
|
83
|
+
ctx.fillText('Trillet 🎯', 2, 15);
|
|
84
|
+
ctx.fillStyle = 'rgba(102, 204, 0, 0.7)';
|
|
85
|
+
ctx.fillText('Trillet 🎯', 4, 17);
|
|
86
|
+
// Draw some shapes
|
|
87
|
+
ctx.beginPath();
|
|
88
|
+
ctx.arc(50, 25, 20, 0, Math.PI * 2, true);
|
|
89
|
+
ctx.closePath();
|
|
90
|
+
ctx.fill();
|
|
91
|
+
return canvas.toDataURL();
|
|
92
|
+
}
|
|
93
|
+
catch (e) {
|
|
94
|
+
return 'canvas-error';
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* WebGL fingerprinting
|
|
99
|
+
*/
|
|
100
|
+
static getWebGLFingerprint() {
|
|
101
|
+
try {
|
|
102
|
+
const canvas = document.createElement('canvas');
|
|
103
|
+
const gl = canvas.getContext('webgl') || canvas.getContext('experimental-webgl');
|
|
104
|
+
if (!gl)
|
|
105
|
+
return 'no-webgl';
|
|
106
|
+
const glContext = gl;
|
|
107
|
+
const debugInfo = glContext.getExtension('WEBGL_debug_renderer_info');
|
|
108
|
+
const vendor = debugInfo
|
|
109
|
+
? glContext.getParameter(debugInfo.UNMASKED_VENDOR_WEBGL)
|
|
110
|
+
: glContext.getParameter(glContext.VENDOR);
|
|
111
|
+
const renderer = debugInfo
|
|
112
|
+
? glContext.getParameter(debugInfo.UNMASKED_RENDERER_WEBGL)
|
|
113
|
+
: glContext.getParameter(glContext.RENDERER);
|
|
114
|
+
return `${vendor}~${renderer}`;
|
|
115
|
+
}
|
|
116
|
+
catch (e) {
|
|
117
|
+
return 'webgl-error';
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* Check for common installed fonts
|
|
122
|
+
*/
|
|
123
|
+
static async getInstalledFonts() {
|
|
124
|
+
const baseFonts = ['monospace', 'sans-serif', 'serif'];
|
|
125
|
+
const testFonts = [
|
|
126
|
+
'Arial',
|
|
127
|
+
'Courier New',
|
|
128
|
+
'Georgia',
|
|
129
|
+
'Times New Roman',
|
|
130
|
+
'Verdana',
|
|
131
|
+
'Comic Sans MS',
|
|
132
|
+
'Impact',
|
|
133
|
+
'Trebuchet MS',
|
|
134
|
+
];
|
|
135
|
+
const detected = [];
|
|
136
|
+
const canvas = document.createElement('canvas');
|
|
137
|
+
const ctx = canvas.getContext('2d');
|
|
138
|
+
if (!ctx)
|
|
139
|
+
return detected;
|
|
140
|
+
for (const font of testFonts) {
|
|
141
|
+
let detected_font = false;
|
|
142
|
+
for (const baseFont of baseFonts) {
|
|
143
|
+
ctx.font = `72px ${baseFont}`;
|
|
144
|
+
const baseWidth = ctx.measureText('mmmmmmmmmmlli').width;
|
|
145
|
+
ctx.font = `72px ${font}, ${baseFont}`;
|
|
146
|
+
const testWidth = ctx.measureText('mmmmmmmmmmlli').width;
|
|
147
|
+
if (baseWidth !== testWidth) {
|
|
148
|
+
detected_font = true;
|
|
149
|
+
break;
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
if (detected_font) {
|
|
153
|
+
detected.push(font);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
return detected;
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* Hash all components into a single fingerprint
|
|
160
|
+
*/
|
|
161
|
+
static async hashComponents(components) {
|
|
162
|
+
const jsonString = JSON.stringify(components);
|
|
163
|
+
const encoder = new TextEncoder();
|
|
164
|
+
const data = encoder.encode(jsonString);
|
|
165
|
+
// Use SubtleCrypto for hashing
|
|
166
|
+
const hashBuffer = await crypto.subtle.digest('SHA-256', data);
|
|
167
|
+
const hashArray = Array.from(new Uint8Array(hashBuffer));
|
|
168
|
+
const hashHex = hashArray.map((b) => b.toString(16).padStart(2, '0')).join('');
|
|
169
|
+
return hashHex;
|
|
170
|
+
}
|
|
171
|
+
/**
|
|
172
|
+
* Clear cached fingerprint (useful for testing)
|
|
173
|
+
*/
|
|
174
|
+
static clearCache() {
|
|
175
|
+
this.cachedFingerprint = null;
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
BrowserFingerprint.cachedFingerprint = null;
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { EventEmitter } from 'eventemitter3';
|
|
2
|
-
import {
|
|
2
|
+
import { BrowserFingerprint } from './BrowserFingerprint.js';
|
|
3
|
+
export { BrowserFingerprint };
|
|
3
4
|
export interface TrilletAgentConfig {
|
|
4
5
|
apiKey?: string;
|
|
5
6
|
workspaceId?: string;
|
|
@@ -7,19 +8,41 @@ export interface TrilletAgentConfig {
|
|
|
7
8
|
variables?: Record<string, any>;
|
|
8
9
|
callbackUrl?: string;
|
|
9
10
|
mode?: 'voice' | 'text';
|
|
11
|
+
demoHash?: string;
|
|
12
|
+
}
|
|
13
|
+
export interface TrilletCallConfig {
|
|
14
|
+
token: string;
|
|
15
|
+
wsUrl: string;
|
|
16
|
+
audioSettings?: {
|
|
17
|
+
sampleRate?: number;
|
|
18
|
+
inputDeviceId?: string;
|
|
19
|
+
outputDeviceId?: string;
|
|
20
|
+
};
|
|
21
|
+
features?: {
|
|
22
|
+
enableRawAudio?: boolean;
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
interface ToolUsed {
|
|
26
|
+
name: string;
|
|
27
|
+
args?: any;
|
|
28
|
+
status?: 'pending' | 'success' | 'error';
|
|
29
|
+
}
|
|
30
|
+
interface Transcript {
|
|
31
|
+
role: 'user' | 'assistant';
|
|
32
|
+
text: string;
|
|
33
|
+
isFinal: boolean;
|
|
34
|
+
timestamp: Date;
|
|
35
|
+
participantId?: string;
|
|
36
|
+
toolUsed?: ToolUsed;
|
|
10
37
|
}
|
|
11
38
|
export declare class TrilletAgent extends EventEmitter {
|
|
12
39
|
private sdk;
|
|
13
40
|
private config;
|
|
14
41
|
private sdkToken;
|
|
15
|
-
private
|
|
42
|
+
private transcripts;
|
|
43
|
+
private currentTranscript;
|
|
16
44
|
constructor(config: TrilletAgentConfig);
|
|
17
45
|
private setupEventForwarding;
|
|
18
|
-
/**
|
|
19
|
-
* Set up default RPC handlers for common agent interactions
|
|
20
|
-
* This should be called after connection is established
|
|
21
|
-
*/
|
|
22
|
-
private setupDefaultRpcHandlers;
|
|
23
46
|
startCall(): Promise<void>;
|
|
24
47
|
startPublicCall(): Promise<void>;
|
|
25
48
|
endCall(): void;
|
|
@@ -29,18 +52,4 @@ export declare class TrilletAgent extends EventEmitter {
|
|
|
29
52
|
getCurrentTranscript(): {
|
|
30
53
|
[key: string]: string;
|
|
31
54
|
};
|
|
32
|
-
/**
|
|
33
|
-
* Register an RPC method handler for receiving calls from the agent
|
|
34
|
-
* @param method - The RPC method name to handle
|
|
35
|
-
* @param handler - The function to handle the RPC call
|
|
36
|
-
*/
|
|
37
|
-
registerRpcMethod(method: string, handler: (data: any) => Promise<any> | any): void;
|
|
38
|
-
/**
|
|
39
|
-
* Send an RPC call to the agent
|
|
40
|
-
* @param method - The RPC method name
|
|
41
|
-
* @param payload - The data to send
|
|
42
|
-
* @param responseTimeout - Timeout in milliseconds (default: 30000)
|
|
43
|
-
*/
|
|
44
|
-
sendRpcMessage(method: string, payload: any, responseTimeout?: number): Promise<any>;
|
|
45
|
-
sendTextMessage(text: string): Promise<void>;
|
|
46
55
|
}
|
package/dist/index.js
CHANGED
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
import { EventEmitter } from 'eventemitter3';
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
2
|
+
import { RemoteAudioTrack, Room, RoomEvent, Track, createAudioAnalyser } from 'livekit-client';
|
|
3
|
+
import { BrowserFingerprint } from './BrowserFingerprint.js';
|
|
4
|
+
// Export BrowserFingerprint for external use
|
|
5
|
+
export { BrowserFingerprint };
|
|
4
6
|
const TRILLET_API_URL = {
|
|
5
|
-
CONNECT: 'https://api
|
|
6
|
-
PUBLIC_CONNECT: 'https://api
|
|
7
|
+
CONNECT: 'https://api-trillet.verlatai.com/v1/api/web-call',
|
|
8
|
+
PUBLIC_CONNECT: 'https://api-trillet.verlatai.com/v1/api/web-call/public',
|
|
7
9
|
};
|
|
8
10
|
const decoder = new TextDecoder();
|
|
9
11
|
// Browser compatibility check
|
|
@@ -13,6 +15,8 @@ export class TrilletAgent extends EventEmitter {
|
|
|
13
15
|
constructor(config) {
|
|
14
16
|
super();
|
|
15
17
|
this.sdkToken = null;
|
|
18
|
+
this.transcripts = [];
|
|
19
|
+
this.currentTranscript = {};
|
|
16
20
|
// Validate environment
|
|
17
21
|
if (!isBrowser) {
|
|
18
22
|
throw new Error('Trillet SDK must be used in a browser environment');
|
|
@@ -28,11 +32,12 @@ export class TrilletAgent extends EventEmitter {
|
|
|
28
32
|
mode: config.mode || 'voice', // Default to voice mode
|
|
29
33
|
};
|
|
30
34
|
this.sdk = new TrilletWebSDK();
|
|
31
|
-
this.transcriptManager = new TranscriptManager();
|
|
32
35
|
this.setupEventForwarding();
|
|
33
36
|
}
|
|
34
37
|
setupEventForwarding() {
|
|
38
|
+
var _a;
|
|
35
39
|
// Forward all SDK events to agent listeners
|
|
40
|
+
this.sdk.on('connected', () => this.emit('connected'));
|
|
36
41
|
this.sdk.on('disconnected', () => this.emit('disconnected'));
|
|
37
42
|
this.sdk.on('error', (error) => this.emit('error', error));
|
|
38
43
|
this.sdk.on('status', (status) => this.emit('status', status));
|
|
@@ -40,59 +45,49 @@ export class TrilletAgent extends EventEmitter {
|
|
|
40
45
|
this.sdk.on('assistantStartedSpeaking', () => this.emit('assistantStartedSpeaking'));
|
|
41
46
|
this.sdk.on('assistantStoppedSpeaking', () => this.emit('assistantStoppedSpeaking'));
|
|
42
47
|
this.sdk.on('audioData', (data) => this.emit('audioData', data));
|
|
43
|
-
//
|
|
44
|
-
this.sdk.on(
|
|
45
|
-
this.
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
if (messageText) {
|
|
81
|
-
const agentParticipant = Array.from((_c = (_b = this.sdk.getRoom()) === null || _b === void 0 ? void 0 : _b.remoteParticipants.values()) !== null && _c !== void 0 ? _c : []).find((p) => p.identity.startsWith('agent'));
|
|
82
|
-
this.transcriptManager.addMessage('assistant', messageText, agentParticipant === null || agentParticipant === void 0 ? void 0 : agentParticipant.identity);
|
|
83
|
-
this.emit('message', { text: messageText });
|
|
84
|
-
this.emit('transcriptUpdate', this.transcriptManager.getTranscripts());
|
|
85
|
-
}
|
|
86
|
-
return 'Message received';
|
|
87
|
-
});
|
|
88
|
-
// Register handler for agent status updates
|
|
89
|
-
this.registerRpcMethod('agentStatus', async (data) => {
|
|
90
|
-
this.emit('status', data.payload);
|
|
91
|
-
return 'Status received';
|
|
48
|
+
// Forward Room events to agent listeners
|
|
49
|
+
(_a = this.sdk.getRoom()) === null || _a === void 0 ? void 0 : _a.on(RoomEvent.TranscriptionReceived, (segments, participant) => {
|
|
50
|
+
const room = this.sdk.getRoom();
|
|
51
|
+
if (!room)
|
|
52
|
+
return;
|
|
53
|
+
const participantId = (participant === null || participant === void 0 ? void 0 : participant.identity) || room.localParticipant.identity;
|
|
54
|
+
const isAgent = participantId.startsWith('agent-') || participantId.startsWith('web-agent');
|
|
55
|
+
segments.forEach((segment) => {
|
|
56
|
+
var _a;
|
|
57
|
+
if (segment.final) {
|
|
58
|
+
delete this.currentTranscript[participantId];
|
|
59
|
+
const text = segment.text.trim();
|
|
60
|
+
// Check for duplicates
|
|
61
|
+
const lastMessage = this.transcripts[this.transcripts.length - 1];
|
|
62
|
+
if (lastMessage && lastMessage.text === text && lastMessage.participantId === participantId && Date.now() - lastMessage.timestamp.getTime() < 1000) {
|
|
63
|
+
return;
|
|
64
|
+
}
|
|
65
|
+
this.transcripts.push({
|
|
66
|
+
role: isAgent ? 'assistant' : 'user',
|
|
67
|
+
text,
|
|
68
|
+
isFinal: true,
|
|
69
|
+
timestamp: new Date(),
|
|
70
|
+
participantId,
|
|
71
|
+
toolUsed: text.includes('Using tool:')
|
|
72
|
+
? {
|
|
73
|
+
name: text.split('Using tool:')[1].split(' ')[1],
|
|
74
|
+
args: (_a = text.split('Arguments:')[1]) === null || _a === void 0 ? void 0 : _a.trim(),
|
|
75
|
+
status: 'pending',
|
|
76
|
+
}
|
|
77
|
+
: undefined,
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
else {
|
|
81
|
+
this.currentTranscript[participantId] = segment.text;
|
|
82
|
+
}
|
|
83
|
+
});
|
|
84
|
+
this.emit(RoomEvent.TranscriptionReceived, segments, participant);
|
|
92
85
|
});
|
|
93
86
|
}
|
|
94
87
|
async startCall() {
|
|
95
88
|
try {
|
|
89
|
+
// Generate browser fingerprint before making the call
|
|
90
|
+
const browserFingerprint = await BrowserFingerprint.generate();
|
|
96
91
|
// 2. Initialize call with API KEY
|
|
97
92
|
const response = await fetch(TRILLET_API_URL.CONNECT, {
|
|
98
93
|
method: 'POST',
|
|
@@ -106,6 +101,7 @@ export class TrilletAgent extends EventEmitter {
|
|
|
106
101
|
mode: this.config.mode,
|
|
107
102
|
dynamic_variables: this.config.variables || {},
|
|
108
103
|
callback_url: this.config.callbackUrl,
|
|
104
|
+
browser_fingerprint: browserFingerprint,
|
|
109
105
|
}),
|
|
110
106
|
});
|
|
111
107
|
if (!response.ok) {
|
|
@@ -126,8 +122,7 @@ export class TrilletAgent extends EventEmitter {
|
|
|
126
122
|
// Initialize call with LiveKit token
|
|
127
123
|
await this.sdk.initializeCall({
|
|
128
124
|
token: data.token,
|
|
129
|
-
wsUrl: 'wss://trillet-ai-xdx0dw5r.livekit.cloud',
|
|
130
|
-
mode: this.config.mode,
|
|
125
|
+
wsUrl: process.env.LIVEKIT_WS_URL || 'wss://trillet-ai-xdx0dw5r.livekit.cloud',
|
|
131
126
|
audioSettings: {
|
|
132
127
|
sampleRate: 48000,
|
|
133
128
|
},
|
|
@@ -139,8 +134,6 @@ export class TrilletAgent extends EventEmitter {
|
|
|
139
134
|
if (this.config.mode === 'voice') {
|
|
140
135
|
await this.sdk.enableAudioPlayback();
|
|
141
136
|
}
|
|
142
|
-
// Set up default RPC handlers for text communication
|
|
143
|
-
this.setupDefaultRpcHandlers();
|
|
144
137
|
// Emit additional connection details
|
|
145
138
|
this.emit('connected', {
|
|
146
139
|
callId: data.callId,
|
|
@@ -155,6 +148,8 @@ export class TrilletAgent extends EventEmitter {
|
|
|
155
148
|
}
|
|
156
149
|
}
|
|
157
150
|
async startPublicCall() {
|
|
151
|
+
// Generate browser fingerprint before making the call
|
|
152
|
+
const browserFingerprint = await BrowserFingerprint.generate();
|
|
158
153
|
// 2. Initialize public call
|
|
159
154
|
const response = await fetch(TRILLET_API_URL.PUBLIC_CONNECT, {
|
|
160
155
|
method: 'POST',
|
|
@@ -168,6 +163,8 @@ export class TrilletAgent extends EventEmitter {
|
|
|
168
163
|
mode: this.config.mode,
|
|
169
164
|
dynamic_variables: this.config.variables || {},
|
|
170
165
|
callback_url: this.config.callbackUrl,
|
|
166
|
+
browser_fingerprint: browserFingerprint,
|
|
167
|
+
demo_hash: this.config.demoHash, // Send demo hash if provided
|
|
171
168
|
}),
|
|
172
169
|
});
|
|
173
170
|
if (!response.ok) {
|
|
@@ -188,8 +185,7 @@ export class TrilletAgent extends EventEmitter {
|
|
|
188
185
|
// Initialize call with LiveKit token
|
|
189
186
|
await this.sdk.initializeCall({
|
|
190
187
|
token: data.token,
|
|
191
|
-
wsUrl: 'wss://trillet-ai-xdx0dw5r.livekit.cloud',
|
|
192
|
-
mode: this.config.mode,
|
|
188
|
+
wsUrl: process.env.LIVEKIT_WS_URL || 'wss://trillet-ai-xdx0dw5r.livekit.cloud',
|
|
193
189
|
audioSettings: {
|
|
194
190
|
sampleRate: 48000,
|
|
195
191
|
},
|
|
@@ -201,8 +197,6 @@ export class TrilletAgent extends EventEmitter {
|
|
|
201
197
|
if (this.config.mode === 'voice') {
|
|
202
198
|
await this.sdk.enableAudioPlayback();
|
|
203
199
|
}
|
|
204
|
-
// Set up default RPC handlers for text communication
|
|
205
|
-
this.setupDefaultRpcHandlers();
|
|
206
200
|
// Emit additional connection details
|
|
207
201
|
this.emit('connected', {
|
|
208
202
|
callId: data.callId,
|
|
@@ -220,83 +214,162 @@ export class TrilletAgent extends EventEmitter {
|
|
|
220
214
|
return this.sdk.isAssistantSpeaking;
|
|
221
215
|
}
|
|
222
216
|
getTranscripts() {
|
|
223
|
-
return this.
|
|
217
|
+
return this.transcripts;
|
|
224
218
|
}
|
|
225
219
|
getCurrentTranscript() {
|
|
226
|
-
return this.
|
|
220
|
+
return this.currentTranscript;
|
|
227
221
|
}
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
console.warn('Cannot register RPC method: not connected to room');
|
|
237
|
-
return;
|
|
238
|
-
}
|
|
239
|
-
room.localParticipant.registerRpcMethod(method, async (data) => {
|
|
240
|
-
try {
|
|
241
|
-
const result = await handler(data);
|
|
242
|
-
return result;
|
|
243
|
-
}
|
|
244
|
-
catch (error) {
|
|
245
|
-
console.error(`RPC method ${method} error:`, error);
|
|
246
|
-
throw error;
|
|
247
|
-
}
|
|
248
|
-
});
|
|
222
|
+
}
|
|
223
|
+
// Internal SDK class
|
|
224
|
+
class TrilletWebSDK extends EventEmitter {
|
|
225
|
+
constructor() {
|
|
226
|
+
super();
|
|
227
|
+
this.isConnected = false;
|
|
228
|
+
// Audio state tracking
|
|
229
|
+
this.isAssistantSpeaking = false;
|
|
249
230
|
}
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
* @param method - The RPC method name
|
|
253
|
-
* @param payload - The data to send
|
|
254
|
-
* @param responseTimeout - Timeout in milliseconds (default: 30000)
|
|
255
|
-
*/
|
|
256
|
-
async sendRpcMessage(method, payload, responseTimeout = 30000) {
|
|
257
|
-
const room = this.sdk.getRoom();
|
|
258
|
-
if (!room || !this.sdk.isConnected) {
|
|
259
|
-
throw new Error('Not connected. Cannot send RPC message.');
|
|
260
|
-
}
|
|
261
|
-
const agentParticipant = Array.from(room.remoteParticipants.values()).find((p) => p.identity.startsWith('agent'));
|
|
262
|
-
if (!agentParticipant) {
|
|
263
|
-
throw new Error('No agent found to send RPC message to.');
|
|
264
|
-
}
|
|
231
|
+
async initializeCall(config) {
|
|
232
|
+
var _a, _b, _c;
|
|
265
233
|
try {
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
234
|
+
this.room = new Room({
|
|
235
|
+
audioCaptureDefaults: {
|
|
236
|
+
autoGainControl: true,
|
|
237
|
+
echoCancellation: true,
|
|
238
|
+
noiseSuppression: true,
|
|
239
|
+
channelCount: 1,
|
|
240
|
+
deviceId: (_a = config.audioSettings) === null || _a === void 0 ? void 0 : _a.inputDeviceId,
|
|
241
|
+
sampleRate: (_b = config.audioSettings) === null || _b === void 0 ? void 0 : _b.sampleRate,
|
|
242
|
+
},
|
|
243
|
+
audioOutput: {
|
|
244
|
+
deviceId: (_c = config.audioSettings) === null || _c === void 0 ? void 0 : _c.outputDeviceId,
|
|
245
|
+
},
|
|
271
246
|
});
|
|
272
|
-
|
|
247
|
+
this.setupEventHandlers(config);
|
|
248
|
+
await this.room.connect(config.wsUrl, config.token);
|
|
249
|
+
console.log('Connected to Trillet room:', this.room.name);
|
|
250
|
+
this.room.localParticipant.setMicrophoneEnabled(true);
|
|
251
|
+
this.isConnected = true;
|
|
252
|
+
this.emit('connected');
|
|
273
253
|
}
|
|
274
254
|
catch (error) {
|
|
275
|
-
|
|
276
|
-
|
|
255
|
+
const errorMessage = error instanceof Error ? error.message : 'Failed to initialize call';
|
|
256
|
+
this.emit('error', errorMessage);
|
|
257
|
+
console.error('Call initialization failed:', error);
|
|
258
|
+
this.endCall();
|
|
259
|
+
throw error; // Re-throw to let TrilletAgent handle it
|
|
277
260
|
}
|
|
278
261
|
}
|
|
279
|
-
async
|
|
280
|
-
|
|
281
|
-
|
|
262
|
+
async enableAudioPlayback() {
|
|
263
|
+
var _a;
|
|
264
|
+
await ((_a = this.room) === null || _a === void 0 ? void 0 : _a.startAudio());
|
|
265
|
+
}
|
|
266
|
+
endCall() {
|
|
267
|
+
var _a;
|
|
268
|
+
if (!this.isConnected)
|
|
282
269
|
return;
|
|
270
|
+
this.isConnected = false;
|
|
271
|
+
this.emit('disconnected');
|
|
272
|
+
(_a = this.room) === null || _a === void 0 ? void 0 : _a.disconnect();
|
|
273
|
+
this.isAssistantSpeaking = false;
|
|
274
|
+
if (this.audioAnalyzer) {
|
|
275
|
+
this.audioAnalyzer.cleanup();
|
|
276
|
+
this.audioAnalyzer = undefined;
|
|
283
277
|
}
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
this.
|
|
287
|
-
return;
|
|
278
|
+
if (this.audioFrameCapture) {
|
|
279
|
+
cancelAnimationFrame(this.audioFrameCapture);
|
|
280
|
+
this.audioFrameCapture = undefined;
|
|
288
281
|
}
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
await room.localParticipant.sendText(text, { topic: 'lk.chat' });
|
|
295
|
-
console.log('Text message sent to agent:', text);
|
|
282
|
+
this.room = undefined;
|
|
283
|
+
}
|
|
284
|
+
toggleMicrophone(enabled) {
|
|
285
|
+
if (this.isConnected && this.room) {
|
|
286
|
+
this.room.localParticipant.setMicrophoneEnabled(enabled);
|
|
296
287
|
}
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
288
|
+
}
|
|
289
|
+
captureAudio() {
|
|
290
|
+
if (!this.isConnected || !this.audioAnalyzer)
|
|
291
|
+
return;
|
|
292
|
+
const bufferSize = this.audioAnalyzer.analyser.fftSize;
|
|
293
|
+
const audioData = new Float32Array(bufferSize);
|
|
294
|
+
this.audioAnalyzer.analyser.getFloatTimeDomainData(audioData);
|
|
295
|
+
this.emit('audioData', audioData);
|
|
296
|
+
this.audioFrameCapture = requestAnimationFrame(() => this.captureAudio());
|
|
297
|
+
}
|
|
298
|
+
setupEventHandlers(config) {
|
|
299
|
+
let wasAgentSpeaking = false;
|
|
300
|
+
if (!this.room)
|
|
301
|
+
return;
|
|
302
|
+
// Room events
|
|
303
|
+
this.room.on(RoomEvent.ParticipantDisconnected, (participant) => {
|
|
304
|
+
if ((participant === null || participant === void 0 ? void 0 : participant.identity) === 'assistant') {
|
|
305
|
+
this.endCall();
|
|
306
|
+
}
|
|
307
|
+
});
|
|
308
|
+
this.room.on(RoomEvent.Disconnected, () => {
|
|
309
|
+
if (this.isConnected)
|
|
310
|
+
this.endCall();
|
|
311
|
+
});
|
|
312
|
+
// Audio events
|
|
313
|
+
this.room.on(RoomEvent.TrackSubscribed, (track, publication) => {
|
|
314
|
+
var _a;
|
|
315
|
+
if (track.kind === Track.Kind.Audio) {
|
|
316
|
+
if (publication.trackName === 'assistant_audio' && track instanceof RemoteAudioTrack && ((_a = config.features) === null || _a === void 0 ? void 0 : _a.enableRawAudio)) {
|
|
317
|
+
const analyzer = createAudioAnalyser(track);
|
|
318
|
+
this.audioAnalyzer = {
|
|
319
|
+
calculateVolume: analyzer.calculateVolume,
|
|
320
|
+
analyser: analyzer.analyser,
|
|
321
|
+
cleanup: analyzer.cleanup,
|
|
322
|
+
};
|
|
323
|
+
this.audioFrameCapture = requestAnimationFrame(() => this.captureAudio());
|
|
324
|
+
}
|
|
325
|
+
track.attach();
|
|
326
|
+
}
|
|
327
|
+
});
|
|
328
|
+
// Data events
|
|
329
|
+
this.room.on(RoomEvent.DataReceived, (payload, participant) => {
|
|
330
|
+
if ((participant === null || participant === void 0 ? void 0 : participant.identity) !== 'agent')
|
|
331
|
+
return;
|
|
332
|
+
try {
|
|
333
|
+
const data = JSON.parse(decoder.decode(payload));
|
|
334
|
+
this.handleDataEvent(data);
|
|
335
|
+
}
|
|
336
|
+
catch (error) {
|
|
337
|
+
console.error('Failed to process received data:', error);
|
|
338
|
+
}
|
|
339
|
+
});
|
|
340
|
+
this.room.on(RoomEvent.ActiveSpeakersChanged, (speakers) => {
|
|
341
|
+
const isAgentSpeaking = speakers.some((p) => p.identity.startsWith('agent'));
|
|
342
|
+
if (isAgentSpeaking && !wasAgentSpeaking) {
|
|
343
|
+
this.emit('assistantStartedSpeaking');
|
|
344
|
+
}
|
|
345
|
+
else if (!isAgentSpeaking && wasAgentSpeaking) {
|
|
346
|
+
this.emit('assistantStoppedSpeaking');
|
|
347
|
+
}
|
|
348
|
+
wasAgentSpeaking = isAgentSpeaking;
|
|
349
|
+
});
|
|
350
|
+
}
|
|
351
|
+
handleDataEvent(event) {
|
|
352
|
+
switch (event.type) {
|
|
353
|
+
case 'status':
|
|
354
|
+
this.emit('status', event);
|
|
355
|
+
break;
|
|
356
|
+
case 'metadata':
|
|
357
|
+
this.emit('metadata', event);
|
|
358
|
+
break;
|
|
359
|
+
case 'assistant_speaking_started':
|
|
360
|
+
this.isAssistantSpeaking = true;
|
|
361
|
+
this.emit('assistantStartedSpeaking');
|
|
362
|
+
break;
|
|
363
|
+
case 'assistant_speaking_ended':
|
|
364
|
+
this.isAssistantSpeaking = false;
|
|
365
|
+
this.emit('assistantStoppedSpeaking');
|
|
366
|
+
break;
|
|
300
367
|
}
|
|
301
368
|
}
|
|
369
|
+
getRoom() {
|
|
370
|
+
return this.room;
|
|
371
|
+
}
|
|
372
|
+
async getBrowserFingerprint() {
|
|
373
|
+
return await BrowserFingerprint.generate();
|
|
374
|
+
}
|
|
302
375
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@trillet-ai/web-sdk",
|
|
3
|
-
"version": "1.5.
|
|
3
|
+
"version": "1.5.9",
|
|
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",
|
|
@@ -32,9 +32,8 @@
|
|
|
32
32
|
"author": "Trillet AI",
|
|
33
33
|
"license": "MIT",
|
|
34
34
|
"dependencies": {
|
|
35
|
-
"@livekit/krisp-noise-filter": "^0.3.4",
|
|
36
35
|
"eventemitter3": "^5.0.1",
|
|
37
|
-
"livekit-client": "^2.
|
|
36
|
+
"livekit-client": "^2.12.0"
|
|
38
37
|
},
|
|
39
38
|
"devDependencies": {
|
|
40
39
|
"@types/jest": "^29.5.12",
|
|
@@ -1,35 +0,0 @@
|
|
|
1
|
-
export interface ToolUsed {
|
|
2
|
-
name: string;
|
|
3
|
-
args?: any;
|
|
4
|
-
status?: 'pending' | 'success' | 'error';
|
|
5
|
-
}
|
|
6
|
-
export interface Transcript {
|
|
7
|
-
role: 'user' | 'assistant';
|
|
8
|
-
text: string;
|
|
9
|
-
isFinal: boolean;
|
|
10
|
-
timestamp: Date;
|
|
11
|
-
participantId?: string;
|
|
12
|
-
toolUsed?: ToolUsed;
|
|
13
|
-
}
|
|
14
|
-
export declare class TranscriptManager {
|
|
15
|
-
private transcripts;
|
|
16
|
-
private currentTranscript;
|
|
17
|
-
getTranscripts(): Transcript[];
|
|
18
|
-
getCurrentTranscript(): {
|
|
19
|
-
[key: string]: string;
|
|
20
|
-
};
|
|
21
|
-
addToolStarted(toolCall: {
|
|
22
|
-
name: string;
|
|
23
|
-
args: any;
|
|
24
|
-
}): void;
|
|
25
|
-
addToolCompleted(toolResult: {
|
|
26
|
-
name: string;
|
|
27
|
-
result: any;
|
|
28
|
-
isError: boolean;
|
|
29
|
-
}): void;
|
|
30
|
-
handleTranscript(participantId: string, isAgent: boolean, transcriptData: {
|
|
31
|
-
text: string;
|
|
32
|
-
isFinal: boolean;
|
|
33
|
-
}): boolean;
|
|
34
|
-
addMessage(role: 'user' | 'assistant', text: string, participantId?: string): void;
|
|
35
|
-
}
|
|
@@ -1,63 +0,0 @@
|
|
|
1
|
-
export class TranscriptManager {
|
|
2
|
-
constructor() {
|
|
3
|
-
this.transcripts = [];
|
|
4
|
-
this.currentTranscript = {};
|
|
5
|
-
}
|
|
6
|
-
getTranscripts() {
|
|
7
|
-
return this.transcripts;
|
|
8
|
-
}
|
|
9
|
-
getCurrentTranscript() {
|
|
10
|
-
return this.currentTranscript;
|
|
11
|
-
}
|
|
12
|
-
addToolStarted(toolCall) {
|
|
13
|
-
this.transcripts.push({
|
|
14
|
-
role: 'assistant',
|
|
15
|
-
text: `Using tool: ${toolCall.name}`,
|
|
16
|
-
isFinal: true,
|
|
17
|
-
timestamp: new Date(),
|
|
18
|
-
toolUsed: { ...toolCall, status: 'pending' },
|
|
19
|
-
});
|
|
20
|
-
}
|
|
21
|
-
addToolCompleted(toolResult) {
|
|
22
|
-
const toolTranscriptIndex = this.transcripts.map((t) => { var _a, _b; return ((_a = t.toolUsed) === null || _a === void 0 ? void 0 : _a.name) === toolResult.name && ((_b = t.toolUsed) === null || _b === void 0 ? void 0 : _b.status) === 'pending'; }).lastIndexOf(true);
|
|
23
|
-
if (toolTranscriptIndex > -1) {
|
|
24
|
-
const toolTranscript = this.transcripts[toolTranscriptIndex];
|
|
25
|
-
if (toolTranscript && toolTranscript.toolUsed) {
|
|
26
|
-
toolTranscript.toolUsed.status = toolResult.isError ? 'error' : 'success';
|
|
27
|
-
}
|
|
28
|
-
}
|
|
29
|
-
}
|
|
30
|
-
handleTranscript(participantId, isAgent, transcriptData) {
|
|
31
|
-
if (transcriptData.isFinal) {
|
|
32
|
-
delete this.currentTranscript[participantId];
|
|
33
|
-
const text = transcriptData.text.trim();
|
|
34
|
-
if (!text)
|
|
35
|
-
return false;
|
|
36
|
-
// Check for duplicates
|
|
37
|
-
const lastMessage = this.transcripts[this.transcripts.length - 1];
|
|
38
|
-
if (lastMessage && lastMessage.text === text && lastMessage.participantId === participantId && Date.now() - lastMessage.timestamp.getTime() < 1000) {
|
|
39
|
-
return false;
|
|
40
|
-
}
|
|
41
|
-
this.transcripts.push({
|
|
42
|
-
role: isAgent ? 'assistant' : 'user',
|
|
43
|
-
text,
|
|
44
|
-
isFinal: true,
|
|
45
|
-
timestamp: new Date(),
|
|
46
|
-
participantId,
|
|
47
|
-
});
|
|
48
|
-
}
|
|
49
|
-
else {
|
|
50
|
-
this.currentTranscript[participantId] = transcriptData.text;
|
|
51
|
-
}
|
|
52
|
-
return true;
|
|
53
|
-
}
|
|
54
|
-
addMessage(role, text, participantId) {
|
|
55
|
-
this.transcripts.push({
|
|
56
|
-
role,
|
|
57
|
-
text,
|
|
58
|
-
isFinal: true,
|
|
59
|
-
timestamp: new Date(),
|
|
60
|
-
participantId,
|
|
61
|
-
});
|
|
62
|
-
}
|
|
63
|
-
}
|
package/dist/TrilletWebSDK.d.ts
DELETED
|
@@ -1,38 +0,0 @@
|
|
|
1
|
-
import { EventEmitter } from 'eventemitter3';
|
|
2
|
-
import { Room } from 'livekit-client';
|
|
3
|
-
export interface TrilletCallConfig {
|
|
4
|
-
token: string;
|
|
5
|
-
wsUrl: string;
|
|
6
|
-
audioSettings?: {
|
|
7
|
-
sampleRate?: number;
|
|
8
|
-
inputDeviceId?: string;
|
|
9
|
-
outputDeviceId?: string;
|
|
10
|
-
};
|
|
11
|
-
mode?: 'voice' | 'text';
|
|
12
|
-
features?: {
|
|
13
|
-
enableRawAudio?: boolean;
|
|
14
|
-
enableKrispNoiseFilter?: boolean;
|
|
15
|
-
};
|
|
16
|
-
}
|
|
17
|
-
export declare class TrilletWebSDK extends EventEmitter {
|
|
18
|
-
private room;
|
|
19
|
-
isConnected: boolean;
|
|
20
|
-
isAssistantSpeaking: boolean;
|
|
21
|
-
audioAnalyzer?: {
|
|
22
|
-
calculateVolume: () => number;
|
|
23
|
-
analyser: AnalyserNode;
|
|
24
|
-
cleanup: () => Promise<void>;
|
|
25
|
-
};
|
|
26
|
-
private krispProcessor?;
|
|
27
|
-
private audioFrameCapture;
|
|
28
|
-
constructor();
|
|
29
|
-
initializeCall(config: TrilletCallConfig): Promise<void>;
|
|
30
|
-
enableAudioPlayback(): Promise<void>;
|
|
31
|
-
endCall(): void;
|
|
32
|
-
toggleMicrophone(enabled: boolean): void;
|
|
33
|
-
private setupKrispNoiseFilter;
|
|
34
|
-
private captureAudio;
|
|
35
|
-
private setupEventHandlers;
|
|
36
|
-
private handleDataEvent;
|
|
37
|
-
getRoom(): Room | undefined;
|
|
38
|
-
}
|
package/dist/TrilletWebSDK.js
DELETED
|
@@ -1,238 +0,0 @@
|
|
|
1
|
-
import { EventEmitter } from 'eventemitter3';
|
|
2
|
-
import { RemoteAudioTrack, Room, RoomEvent, Track, createAudioAnalyser, LocalAudioTrack } from 'livekit-client';
|
|
3
|
-
const decoder = new TextDecoder();
|
|
4
|
-
// Internal SDK class
|
|
5
|
-
export class TrilletWebSDK extends EventEmitter {
|
|
6
|
-
constructor() {
|
|
7
|
-
super();
|
|
8
|
-
this.isConnected = false;
|
|
9
|
-
// Audio state tracking
|
|
10
|
-
this.isAssistantSpeaking = false;
|
|
11
|
-
}
|
|
12
|
-
async initializeCall(config) {
|
|
13
|
-
var _a, _b, _c, _d;
|
|
14
|
-
try {
|
|
15
|
-
this.room = new Room({
|
|
16
|
-
audioCaptureDefaults: {
|
|
17
|
-
autoGainControl: true,
|
|
18
|
-
echoCancellation: true,
|
|
19
|
-
noiseSuppression: true,
|
|
20
|
-
channelCount: 1,
|
|
21
|
-
deviceId: (_a = config.audioSettings) === null || _a === void 0 ? void 0 : _a.inputDeviceId,
|
|
22
|
-
sampleRate: (_b = config.audioSettings) === null || _b === void 0 ? void 0 : _b.sampleRate,
|
|
23
|
-
},
|
|
24
|
-
audioOutput: {
|
|
25
|
-
deviceId: (_c = config.audioSettings) === null || _c === void 0 ? void 0 : _c.outputDeviceId,
|
|
26
|
-
},
|
|
27
|
-
});
|
|
28
|
-
this.setupEventHandlers(config);
|
|
29
|
-
this.room.prepareConnection(config.wsUrl, config.token);
|
|
30
|
-
await this.room.connect(config.wsUrl, config.token);
|
|
31
|
-
console.log('Connected to Trillet room:', this.room.name);
|
|
32
|
-
if (config.mode !== 'text') {
|
|
33
|
-
await this.room.localParticipant.setMicrophoneEnabled(true);
|
|
34
|
-
// Apply Krisp noise filter if enabled
|
|
35
|
-
if ((_d = config.features) === null || _d === void 0 ? void 0 : _d.enableKrispNoiseFilter) {
|
|
36
|
-
await this.setupKrispNoiseFilter();
|
|
37
|
-
}
|
|
38
|
-
}
|
|
39
|
-
this.isConnected = true;
|
|
40
|
-
this.emit('connected');
|
|
41
|
-
}
|
|
42
|
-
catch (error) {
|
|
43
|
-
const errorMessage = error instanceof Error ? error.message : 'Failed to initialize call';
|
|
44
|
-
this.emit('error', errorMessage);
|
|
45
|
-
console.error('Call initialization failed:', error);
|
|
46
|
-
this.endCall();
|
|
47
|
-
throw error; // Re-throw to let TrilletAgent handle it
|
|
48
|
-
}
|
|
49
|
-
}
|
|
50
|
-
async enableAudioPlayback() {
|
|
51
|
-
var _a;
|
|
52
|
-
await ((_a = this.room) === null || _a === void 0 ? void 0 : _a.startAudio());
|
|
53
|
-
}
|
|
54
|
-
endCall() {
|
|
55
|
-
var _a;
|
|
56
|
-
if (!this.isConnected)
|
|
57
|
-
return;
|
|
58
|
-
this.isConnected = false;
|
|
59
|
-
this.emit('disconnected');
|
|
60
|
-
(_a = this.room) === null || _a === void 0 ? void 0 : _a.disconnect();
|
|
61
|
-
this.isAssistantSpeaking = false;
|
|
62
|
-
if (this.audioAnalyzer) {
|
|
63
|
-
this.audioAnalyzer.cleanup();
|
|
64
|
-
this.audioAnalyzer = undefined;
|
|
65
|
-
}
|
|
66
|
-
if (this.audioFrameCapture) {
|
|
67
|
-
cancelAnimationFrame(this.audioFrameCapture);
|
|
68
|
-
this.audioFrameCapture = undefined;
|
|
69
|
-
}
|
|
70
|
-
// Cleanup Krisp processor
|
|
71
|
-
if (this.krispProcessor) {
|
|
72
|
-
this.krispProcessor = undefined;
|
|
73
|
-
}
|
|
74
|
-
this.room = undefined;
|
|
75
|
-
}
|
|
76
|
-
toggleMicrophone(enabled) {
|
|
77
|
-
if (this.isConnected && this.room) {
|
|
78
|
-
this.room.localParticipant.setMicrophoneEnabled(enabled);
|
|
79
|
-
}
|
|
80
|
-
}
|
|
81
|
-
async setupKrispNoiseFilter() {
|
|
82
|
-
var _a;
|
|
83
|
-
if (!this.room)
|
|
84
|
-
return;
|
|
85
|
-
try {
|
|
86
|
-
// Dynamically import Krisp noise filter
|
|
87
|
-
const { KrispNoiseFilter, isKrispNoiseFilterSupported } = await import('@livekit/krisp-noise-filter');
|
|
88
|
-
// Check browser compatibility
|
|
89
|
-
if (!isKrispNoiseFilterSupported()) {
|
|
90
|
-
console.warn('Krisp noise filter is not supported on this browser');
|
|
91
|
-
return;
|
|
92
|
-
}
|
|
93
|
-
// Get the local microphone track
|
|
94
|
-
const microphoneTrack = (_a = this.room.localParticipant.getTrackPublication(Track.Source.Microphone)) === null || _a === void 0 ? void 0 : _a.track;
|
|
95
|
-
if (microphoneTrack && microphoneTrack instanceof LocalAudioTrack) {
|
|
96
|
-
// Initialize the Krisp processor
|
|
97
|
-
this.krispProcessor = KrispNoiseFilter();
|
|
98
|
-
await microphoneTrack.setProcessor(this.krispProcessor);
|
|
99
|
-
// Enable the noise filter
|
|
100
|
-
await this.krispProcessor.setEnabled(true);
|
|
101
|
-
console.log('Krisp noise filter enabled successfully');
|
|
102
|
-
}
|
|
103
|
-
else {
|
|
104
|
-
console.warn('Could not find local microphone track to apply Krisp filter');
|
|
105
|
-
}
|
|
106
|
-
}
|
|
107
|
-
catch (error) {
|
|
108
|
-
console.error('Failed to setup Krisp noise filter:', error);
|
|
109
|
-
}
|
|
110
|
-
}
|
|
111
|
-
captureAudio() {
|
|
112
|
-
if (!this.isConnected || !this.audioAnalyzer)
|
|
113
|
-
return;
|
|
114
|
-
const bufferSize = this.audioAnalyzer.analyser.fftSize;
|
|
115
|
-
const audioData = new Float32Array(bufferSize);
|
|
116
|
-
this.audioAnalyzer.analyser.getFloatTimeDomainData(audioData);
|
|
117
|
-
this.emit('audioData', audioData);
|
|
118
|
-
this.audioFrameCapture = requestAnimationFrame(() => this.captureAudio());
|
|
119
|
-
}
|
|
120
|
-
setupEventHandlers(config) {
|
|
121
|
-
let wasAgentSpeaking = false;
|
|
122
|
-
if (!this.room)
|
|
123
|
-
return;
|
|
124
|
-
// Room events
|
|
125
|
-
this.room.on(RoomEvent.ParticipantDisconnected, (participant) => {
|
|
126
|
-
if ((participant === null || participant === void 0 ? void 0 : participant.identity) === 'assistant') {
|
|
127
|
-
this.endCall();
|
|
128
|
-
}
|
|
129
|
-
});
|
|
130
|
-
this.room.on(RoomEvent.Disconnected, () => {
|
|
131
|
-
if (this.isConnected)
|
|
132
|
-
this.endCall();
|
|
133
|
-
});
|
|
134
|
-
this.room.registerTextStreamHandler('lk.transcription', async (reader, info) => {
|
|
135
|
-
var _a, _b;
|
|
136
|
-
const text = await reader.readAll();
|
|
137
|
-
const attributes = ((_a = reader.info) === null || _a === void 0 ? void 0 : _a.attributes) || {};
|
|
138
|
-
const isFinal = attributes['lk.transcription_final'] === 'true';
|
|
139
|
-
if (!info)
|
|
140
|
-
return;
|
|
141
|
-
const participant = (_b = this.room) === null || _b === void 0 ? void 0 : _b.getParticipantByIdentity(info.identity);
|
|
142
|
-
if (!participant)
|
|
143
|
-
return;
|
|
144
|
-
this.emit('transcript', { text, isFinal }, participant);
|
|
145
|
-
});
|
|
146
|
-
// Audio events
|
|
147
|
-
this.room.on(RoomEvent.TrackSubscribed, (track, publication) => {
|
|
148
|
-
var _a;
|
|
149
|
-
if (track.kind === Track.Kind.Audio) {
|
|
150
|
-
if (publication.trackName === 'assistant_audio' && track instanceof RemoteAudioTrack && ((_a = config.features) === null || _a === void 0 ? void 0 : _a.enableRawAudio)) {
|
|
151
|
-
const analyzer = createAudioAnalyser(track);
|
|
152
|
-
this.audioAnalyzer = {
|
|
153
|
-
calculateVolume: analyzer.calculateVolume,
|
|
154
|
-
analyser: analyzer.analyser,
|
|
155
|
-
cleanup: analyzer.cleanup,
|
|
156
|
-
};
|
|
157
|
-
this.audioFrameCapture = requestAnimationFrame(() => this.captureAudio());
|
|
158
|
-
}
|
|
159
|
-
track.attach();
|
|
160
|
-
}
|
|
161
|
-
});
|
|
162
|
-
// Data events
|
|
163
|
-
this.room.on(RoomEvent.DataReceived, (payload, participant) => {
|
|
164
|
-
if (!(participant === null || participant === void 0 ? void 0 : participant.identity.startsWith('agent')))
|
|
165
|
-
return;
|
|
166
|
-
try {
|
|
167
|
-
const data = JSON.parse(decoder.decode(payload));
|
|
168
|
-
this.handleDataEvent(data, participant);
|
|
169
|
-
}
|
|
170
|
-
catch (error) {
|
|
171
|
-
console.error('Failed to process received data:', error);
|
|
172
|
-
}
|
|
173
|
-
});
|
|
174
|
-
this.room.on(RoomEvent.ActiveSpeakersChanged, (speakers) => {
|
|
175
|
-
const isAgentSpeaking = speakers.some((p) => p.identity.startsWith('agent'));
|
|
176
|
-
if (isAgentSpeaking && !wasAgentSpeaking) {
|
|
177
|
-
this.emit('assistantStartedSpeaking');
|
|
178
|
-
}
|
|
179
|
-
else if (!isAgentSpeaking && wasAgentSpeaking) {
|
|
180
|
-
this.emit('assistantStoppedSpeaking');
|
|
181
|
-
}
|
|
182
|
-
wasAgentSpeaking = isAgentSpeaking;
|
|
183
|
-
});
|
|
184
|
-
// Handle RPC events if available
|
|
185
|
-
// Note: LiveKit may not have specific RPC events, but we can monitor participant events
|
|
186
|
-
this.room.on(RoomEvent.ParticipantConnected, (participant) => {
|
|
187
|
-
console.log('Participant connected:', participant.identity);
|
|
188
|
-
if (participant.identity.startsWith('agent')) {
|
|
189
|
-
console.log('Agent connected, RPC communication available');
|
|
190
|
-
}
|
|
191
|
-
});
|
|
192
|
-
}
|
|
193
|
-
handleDataEvent(event, participant) {
|
|
194
|
-
switch (event.type) {
|
|
195
|
-
case 'status':
|
|
196
|
-
this.emit('status', event);
|
|
197
|
-
break;
|
|
198
|
-
case 'metadata':
|
|
199
|
-
this.emit('metadata', event);
|
|
200
|
-
break;
|
|
201
|
-
case 'transcript':
|
|
202
|
-
// this is for agent-generated transcripts, which we are overriding with lk.transcription
|
|
203
|
-
// this.emit('transcript', event.data, participant);
|
|
204
|
-
break;
|
|
205
|
-
case 'llm_call':
|
|
206
|
-
this.emit('toolStarted', { name: event.name, args: event.arguments });
|
|
207
|
-
break;
|
|
208
|
-
case 'llm_call_response':
|
|
209
|
-
this.emit('toolCompleted', {
|
|
210
|
-
name: event.details.api_name,
|
|
211
|
-
result: event.details.api_response,
|
|
212
|
-
isError: event.details.status >= 400,
|
|
213
|
-
});
|
|
214
|
-
break;
|
|
215
|
-
case 'error':
|
|
216
|
-
this.emit('toolCompleted', {
|
|
217
|
-
name: event.name,
|
|
218
|
-
result: event.details,
|
|
219
|
-
isError: true,
|
|
220
|
-
});
|
|
221
|
-
break;
|
|
222
|
-
case 'assistant_speaking_started':
|
|
223
|
-
this.isAssistantSpeaking = true;
|
|
224
|
-
this.emit('assistantStartedSpeaking');
|
|
225
|
-
break;
|
|
226
|
-
case 'assistant_speaking_ended':
|
|
227
|
-
this.isAssistantSpeaking = false;
|
|
228
|
-
this.emit('assistantStoppedSpeaking');
|
|
229
|
-
break;
|
|
230
|
-
case 'agent_message':
|
|
231
|
-
this.emit('message', event);
|
|
232
|
-
break;
|
|
233
|
-
}
|
|
234
|
-
}
|
|
235
|
-
getRoom() {
|
|
236
|
-
return this.room;
|
|
237
|
-
}
|
|
238
|
-
}
|