@trillet-ai/web-sdk 1.5.9 → 1.7.0
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 +46 -8
- package/dist/BrowserFingerprint.d.ts +26 -13
- package/dist/BrowserFingerprint.js +82 -129
- package/dist/TranscriptManager.d.ts +35 -0
- package/dist/TranscriptManager.js +63 -0
- package/dist/TrilletWebSDK.d.ts +38 -0
- package/dist/TrilletWebSDK.js +238 -0
- package/dist/index.d.ts +26 -27
- package/dist/index.js +129 -185
- package/package.json +3 -2
package/LICENSE
CHANGED
package/README.md
CHANGED
|
@@ -30,6 +30,7 @@ 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'
|
|
33
34
|
|
|
34
35
|
// Optional parameters
|
|
35
36
|
variables: {
|
|
@@ -51,11 +52,20 @@ agent.on('connected', (details) => {
|
|
|
51
52
|
});
|
|
52
53
|
|
|
53
54
|
agent.on('transcriptionReceived', (transcript) => {
|
|
54
|
-
console.log('New transcript:', transcript);
|
|
55
|
+
console.log('New voice transcript:', transcript);
|
|
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);
|
|
55
64
|
});
|
|
56
65
|
|
|
57
66
|
// Control the call
|
|
58
|
-
agent.toggleMicrophone(true); // Enable/disable microphone
|
|
67
|
+
agent.toggleMicrophone(true); // Enable/disable microphone in voice mode
|
|
68
|
+
agent.sendTextMessage("Hello, agent!"); // Send a text message in text mode
|
|
59
69
|
agent.endCall(); // End the call
|
|
60
70
|
```
|
|
61
71
|
|
|
@@ -78,7 +88,8 @@ The SDK supports two authentication methods:
|
|
|
78
88
|
```typescript
|
|
79
89
|
const agent = new TrilletAgent({
|
|
80
90
|
workspaceId: 'your-workspace-id',
|
|
81
|
-
agentId: 'your-agent-id'
|
|
91
|
+
agentId: 'your-agent-id',
|
|
92
|
+
mode: 'text' // Or 'voice'
|
|
82
93
|
});
|
|
83
94
|
await agent.startPublicCall();
|
|
84
95
|
```
|
|
@@ -99,7 +110,8 @@ The SDK supports two types of calls:
|
|
|
99
110
|
```typescript
|
|
100
111
|
const agent = new TrilletAgent({
|
|
101
112
|
workspaceId: 'your-workspace-id',
|
|
102
|
-
agentId: 'your-agent-id' // Required for both public and regular calls
|
|
113
|
+
agentId: 'your-agent-id', // Required for both public and regular calls
|
|
114
|
+
mode: 'text' // Or 'voice'
|
|
103
115
|
});
|
|
104
116
|
await agent.startPublicCall();
|
|
105
117
|
```
|
|
@@ -122,19 +134,27 @@ agent.on('error', (error) => {
|
|
|
122
134
|
});
|
|
123
135
|
|
|
124
136
|
agent.on('transcriptionReceived', (segments, participant) => {
|
|
125
|
-
// Called when new transcription is available
|
|
137
|
+
// Called when new transcription is available (voice mode)
|
|
126
138
|
});
|
|
127
139
|
|
|
128
140
|
agent.on('assistantStartedSpeaking', () => {
|
|
129
|
-
// Called when the AI agent starts speaking
|
|
141
|
+
// Called when the AI agent starts speaking (voice mode)
|
|
130
142
|
});
|
|
131
143
|
|
|
132
144
|
agent.on('assistantStoppedSpeaking', () => {
|
|
133
|
-
// Called when the AI agent stops speaking
|
|
145
|
+
// Called when the AI agent stops speaking (voice mode)
|
|
134
146
|
});
|
|
135
147
|
|
|
136
148
|
agent.on('audioData', (data) => {
|
|
137
|
-
// Raw audio data for visualization
|
|
149
|
+
// Raw audio data for visualization (voice mode)
|
|
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)
|
|
138
158
|
});
|
|
139
159
|
```
|
|
140
160
|
|
|
@@ -151,6 +171,24 @@ const allTranscripts = agent.getTranscripts();
|
|
|
151
171
|
const currentTranscript = agent.getCurrentTranscript();
|
|
152
172
|
```
|
|
153
173
|
|
|
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
|
+
|
|
154
192
|
## Requirements
|
|
155
193
|
|
|
156
194
|
- Modern web browser with secure context (HTTPS or localhost)
|
|
@@ -1,33 +1,46 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Browser Fingerprinting Utility
|
|
3
|
-
* Generates a
|
|
4
|
-
*
|
|
3
|
+
* Generates a deterministic fingerprint based on stable browser/hardware characteristics.
|
|
4
|
+
* Used for demo link usage limit tracking.
|
|
5
|
+
*
|
|
6
|
+
* Strategy:
|
|
7
|
+
* 1. localStorage persistence — generate once, reuse across tabs/sessions forever
|
|
8
|
+
* 2. Stable hardware-only seed — if storage is cleared, the same hardware signals
|
|
9
|
+
* produce the same hash, so the fingerprint stays consistent
|
|
10
|
+
* 3. Server-side IP fallback — handled by the backend when no fingerprint is sent
|
|
5
11
|
*/
|
|
6
12
|
export declare class BrowserFingerprint {
|
|
7
13
|
private static cachedFingerprint;
|
|
8
14
|
/**
|
|
9
|
-
* Generate a
|
|
10
|
-
*
|
|
15
|
+
* Generate (or retrieve) a deterministic browser fingerprint.
|
|
16
|
+
* Cached in memory → localStorage → derived from stable hardware signals.
|
|
11
17
|
*/
|
|
12
18
|
static generate(): Promise<string>;
|
|
13
19
|
/**
|
|
14
|
-
*
|
|
20
|
+
* Collect only hardware / environment signals that do NOT change between
|
|
21
|
+
* tabs, sessions, or browser restarts on the same device.
|
|
22
|
+
*
|
|
23
|
+
* Deliberately excluded (volatile / anti-fingerprint randomised):
|
|
24
|
+
* - canvas.toDataURL() — randomised per origin in many browsers
|
|
25
|
+
* - font detection — noisy across rendering states
|
|
26
|
+
* - screen.availWidth/Height — changes with taskbar / dock resize
|
|
27
|
+
* - navigator.doNotTrack — user can toggle
|
|
28
|
+
* - timezoneOffset — changes with DST
|
|
29
|
+
* - navigator.userAgent — changes on browser update
|
|
15
30
|
*/
|
|
16
|
-
private static
|
|
31
|
+
private static getStableSignals;
|
|
17
32
|
/**
|
|
18
|
-
* WebGL
|
|
33
|
+
* WebGL vendor + renderer string (GPU identifier, very stable)
|
|
19
34
|
*/
|
|
20
35
|
private static getWebGLFingerprint;
|
|
21
36
|
/**
|
|
22
|
-
*
|
|
23
|
-
*/
|
|
24
|
-
private static getInstalledFonts;
|
|
25
|
-
/**
|
|
26
|
-
* Hash all components into a single fingerprint
|
|
37
|
+
* SHA-256 hash of the signals object → hex string
|
|
27
38
|
*/
|
|
28
39
|
private static hashComponents;
|
|
40
|
+
private static getStored;
|
|
41
|
+
private static persist;
|
|
29
42
|
/**
|
|
30
|
-
* Clear
|
|
43
|
+
* Clear both in-memory and persisted fingerprint (useful for testing)
|
|
31
44
|
*/
|
|
32
45
|
static clearCache(): void;
|
|
33
46
|
}
|
|
@@ -1,101 +1,72 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Browser Fingerprinting Utility
|
|
3
|
-
* Generates a
|
|
4
|
-
*
|
|
3
|
+
* Generates a deterministic fingerprint based on stable browser/hardware characteristics.
|
|
4
|
+
* Used for demo link usage limit tracking.
|
|
5
|
+
*
|
|
6
|
+
* Strategy:
|
|
7
|
+
* 1. localStorage persistence — generate once, reuse across tabs/sessions forever
|
|
8
|
+
* 2. Stable hardware-only seed — if storage is cleared, the same hardware signals
|
|
9
|
+
* produce the same hash, so the fingerprint stays consistent
|
|
10
|
+
* 3. Server-side IP fallback — handled by the backend when no fingerprint is sent
|
|
5
11
|
*/
|
|
12
|
+
const STORAGE_KEY = 'trillet_dfp';
|
|
6
13
|
export class BrowserFingerprint {
|
|
7
14
|
/**
|
|
8
|
-
* Generate a
|
|
9
|
-
*
|
|
15
|
+
* Generate (or retrieve) a deterministic browser fingerprint.
|
|
16
|
+
* Cached in memory → localStorage → derived from stable hardware signals.
|
|
10
17
|
*/
|
|
11
18
|
static async generate() {
|
|
12
|
-
//
|
|
19
|
+
// 1. In-memory cache (fastest)
|
|
13
20
|
if (this.cachedFingerprint) {
|
|
14
21
|
return this.cachedFingerprint;
|
|
15
22
|
}
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
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);
|
|
23
|
+
// 2. Persisted in localStorage (survives tab close / browser restart)
|
|
24
|
+
const stored = this.getStored();
|
|
25
|
+
if (stored) {
|
|
26
|
+
this.cachedFingerprint = stored;
|
|
27
|
+
return stored;
|
|
28
|
+
}
|
|
29
|
+
// 3. Derive from stable hardware signals and persist
|
|
30
|
+
const signals = this.getStableSignals();
|
|
31
|
+
const fingerprint = await this.hashComponents(signals);
|
|
32
|
+
this.persist(fingerprint);
|
|
62
33
|
this.cachedFingerprint = fingerprint;
|
|
63
34
|
return fingerprint;
|
|
64
35
|
}
|
|
65
36
|
/**
|
|
66
|
-
*
|
|
37
|
+
* Collect only hardware / environment signals that do NOT change between
|
|
38
|
+
* tabs, sessions, or browser restarts on the same device.
|
|
39
|
+
*
|
|
40
|
+
* Deliberately excluded (volatile / anti-fingerprint randomised):
|
|
41
|
+
* - canvas.toDataURL() — randomised per origin in many browsers
|
|
42
|
+
* - font detection — noisy across rendering states
|
|
43
|
+
* - screen.availWidth/Height — changes with taskbar / dock resize
|
|
44
|
+
* - navigator.doNotTrack — user can toggle
|
|
45
|
+
* - timezoneOffset — changes with DST
|
|
46
|
+
* - navigator.userAgent — changes on browser update
|
|
67
47
|
*/
|
|
68
|
-
static
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
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
|
-
}
|
|
48
|
+
static getStableSignals() {
|
|
49
|
+
return {
|
|
50
|
+
// Hardware — fixed for a given device
|
|
51
|
+
screen: {
|
|
52
|
+
width: window.screen.width,
|
|
53
|
+
height: window.screen.height,
|
|
54
|
+
colorDepth: window.screen.colorDepth,
|
|
55
|
+
pixelRatio: window.devicePixelRatio,
|
|
56
|
+
},
|
|
57
|
+
hardwareConcurrency: navigator.hardwareConcurrency,
|
|
58
|
+
deviceMemory: navigator.deviceMemory,
|
|
59
|
+
platform: navigator.platform,
|
|
60
|
+
maxTouchPoints: navigator.maxTouchPoints,
|
|
61
|
+
// WebGL vendor/renderer — GPU-based, stable
|
|
62
|
+
webgl: this.getWebGLFingerprint(),
|
|
63
|
+
// Locale — stable unless user changes OS language or moves timezone
|
|
64
|
+
timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
|
|
65
|
+
language: navigator.language,
|
|
66
|
+
};
|
|
96
67
|
}
|
|
97
68
|
/**
|
|
98
|
-
* WebGL
|
|
69
|
+
* WebGL vendor + renderer string (GPU identifier, very stable)
|
|
99
70
|
*/
|
|
100
71
|
static getWebGLFingerprint() {
|
|
101
72
|
try {
|
|
@@ -113,66 +84,48 @@ export class BrowserFingerprint {
|
|
|
113
84
|
: glContext.getParameter(glContext.RENDERER);
|
|
114
85
|
return `${vendor}~${renderer}`;
|
|
115
86
|
}
|
|
116
|
-
catch (
|
|
87
|
+
catch (_a) {
|
|
117
88
|
return 'webgl-error';
|
|
118
89
|
}
|
|
119
90
|
}
|
|
120
91
|
/**
|
|
121
|
-
*
|
|
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
|
|
92
|
+
* SHA-256 hash of the signals object → hex string
|
|
160
93
|
*/
|
|
161
94
|
static async hashComponents(components) {
|
|
162
|
-
const
|
|
163
|
-
const encoder = new TextEncoder();
|
|
164
|
-
const data = encoder.encode(jsonString);
|
|
165
|
-
// Use SubtleCrypto for hashing
|
|
95
|
+
const data = new TextEncoder().encode(JSON.stringify(components));
|
|
166
96
|
const hashBuffer = await crypto.subtle.digest('SHA-256', data);
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
97
|
+
return Array.from(new Uint8Array(hashBuffer))
|
|
98
|
+
.map((b) => b.toString(16).padStart(2, '0'))
|
|
99
|
+
.join('');
|
|
100
|
+
}
|
|
101
|
+
// ── localStorage helpers ───────────────────────────────────────────
|
|
102
|
+
static getStored() {
|
|
103
|
+
try {
|
|
104
|
+
return localStorage.getItem(STORAGE_KEY);
|
|
105
|
+
}
|
|
106
|
+
catch (_a) {
|
|
107
|
+
return null;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
static persist(fingerprint) {
|
|
111
|
+
try {
|
|
112
|
+
localStorage.setItem(STORAGE_KEY, fingerprint);
|
|
113
|
+
}
|
|
114
|
+
catch (_a) {
|
|
115
|
+
// Storage full or disabled — fingerprint still works in-memory
|
|
116
|
+
}
|
|
170
117
|
}
|
|
171
118
|
/**
|
|
172
|
-
* Clear
|
|
119
|
+
* Clear both in-memory and persisted fingerprint (useful for testing)
|
|
173
120
|
*/
|
|
174
121
|
static clearCache() {
|
|
175
122
|
this.cachedFingerprint = null;
|
|
123
|
+
try {
|
|
124
|
+
localStorage.removeItem(STORAGE_KEY);
|
|
125
|
+
}
|
|
126
|
+
catch (_a) {
|
|
127
|
+
// Ignore
|
|
128
|
+
}
|
|
176
129
|
}
|
|
177
130
|
}
|
|
178
131
|
BrowserFingerprint.cachedFingerprint = null;
|
|
@@ -0,0 +1,35 @@
|
|
|
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
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
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
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
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
|
+
}
|
|
@@ -0,0 +1,238 @@
|
|
|
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
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { EventEmitter } from 'eventemitter3';
|
|
2
|
+
import { Transcript } from './TranscriptManager.js';
|
|
2
3
|
import { BrowserFingerprint } from './BrowserFingerprint.js';
|
|
3
4
|
export { BrowserFingerprint };
|
|
4
5
|
export interface TrilletAgentConfig {
|
|
@@ -10,39 +11,18 @@ export interface TrilletAgentConfig {
|
|
|
10
11
|
mode?: 'voice' | 'text';
|
|
11
12
|
demoHash?: string;
|
|
12
13
|
}
|
|
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;
|
|
37
|
-
}
|
|
38
14
|
export declare class TrilletAgent extends EventEmitter {
|
|
39
15
|
private sdk;
|
|
40
16
|
private config;
|
|
41
17
|
private sdkToken;
|
|
42
|
-
private
|
|
43
|
-
private currentTranscript;
|
|
18
|
+
private transcriptManager;
|
|
44
19
|
constructor(config: TrilletAgentConfig);
|
|
45
20
|
private setupEventForwarding;
|
|
21
|
+
/**
|
|
22
|
+
* Set up default RPC handlers for common agent interactions
|
|
23
|
+
* This should be called after connection is established
|
|
24
|
+
*/
|
|
25
|
+
private setupDefaultRpcHandlers;
|
|
46
26
|
startCall(): Promise<void>;
|
|
47
27
|
startPublicCall(): Promise<void>;
|
|
48
28
|
endCall(): void;
|
|
@@ -52,4 +32,23 @@ export declare class TrilletAgent extends EventEmitter {
|
|
|
52
32
|
getCurrentTranscript(): {
|
|
53
33
|
[key: string]: string;
|
|
54
34
|
};
|
|
35
|
+
/**
|
|
36
|
+
* Register an RPC method handler for receiving calls from the agent
|
|
37
|
+
* @param method - The RPC method name to handle
|
|
38
|
+
* @param handler - The function to handle the RPC call
|
|
39
|
+
*/
|
|
40
|
+
registerRpcMethod(method: string, handler: (data: any) => Promise<any> | any): void;
|
|
41
|
+
/**
|
|
42
|
+
* Send an RPC call to the agent
|
|
43
|
+
* @param method - The RPC method name
|
|
44
|
+
* @param payload - The data to send
|
|
45
|
+
* @param responseTimeout - Timeout in milliseconds (default: 30000)
|
|
46
|
+
*/
|
|
47
|
+
sendRpcMessage(method: string, payload: any, responseTimeout?: number): Promise<any>;
|
|
48
|
+
sendTextMessage(text: string): Promise<void>;
|
|
49
|
+
/**
|
|
50
|
+
* Get the browser fingerprint for this session
|
|
51
|
+
* Useful for demo pages to send fingerprint when checking limits
|
|
52
|
+
*/
|
|
53
|
+
getBrowserFingerprint(): Promise<string>;
|
|
55
54
|
}
|
package/dist/index.js
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
import { EventEmitter } from 'eventemitter3';
|
|
2
|
-
import {
|
|
2
|
+
import { TrilletWebSDK } from './TrilletWebSDK.js';
|
|
3
|
+
import { TranscriptManager } from './TranscriptManager.js';
|
|
3
4
|
import { BrowserFingerprint } from './BrowserFingerprint.js';
|
|
4
5
|
// Export BrowserFingerprint for external use
|
|
5
6
|
export { BrowserFingerprint };
|
|
6
7
|
const TRILLET_API_URL = {
|
|
7
|
-
CONNECT: 'https://api
|
|
8
|
-
PUBLIC_CONNECT: 'https://api
|
|
8
|
+
CONNECT: 'https://api.trillet.ai/v1/api/web-call',
|
|
9
|
+
PUBLIC_CONNECT: 'https://api.trillet.ai/v1/api/web-call/public',
|
|
9
10
|
};
|
|
10
11
|
const decoder = new TextDecoder();
|
|
11
12
|
// Browser compatibility check
|
|
@@ -15,8 +16,6 @@ export class TrilletAgent extends EventEmitter {
|
|
|
15
16
|
constructor(config) {
|
|
16
17
|
super();
|
|
17
18
|
this.sdkToken = null;
|
|
18
|
-
this.transcripts = [];
|
|
19
|
-
this.currentTranscript = {};
|
|
20
19
|
// Validate environment
|
|
21
20
|
if (!isBrowser) {
|
|
22
21
|
throw new Error('Trillet SDK must be used in a browser environment');
|
|
@@ -32,12 +31,11 @@ export class TrilletAgent extends EventEmitter {
|
|
|
32
31
|
mode: config.mode || 'voice', // Default to voice mode
|
|
33
32
|
};
|
|
34
33
|
this.sdk = new TrilletWebSDK();
|
|
34
|
+
this.transcriptManager = new TranscriptManager();
|
|
35
35
|
this.setupEventForwarding();
|
|
36
36
|
}
|
|
37
37
|
setupEventForwarding() {
|
|
38
|
-
var _a;
|
|
39
38
|
// Forward all SDK events to agent listeners
|
|
40
|
-
this.sdk.on('connected', () => this.emit('connected'));
|
|
41
39
|
this.sdk.on('disconnected', () => this.emit('disconnected'));
|
|
42
40
|
this.sdk.on('error', (error) => this.emit('error', error));
|
|
43
41
|
this.sdk.on('status', (status) => this.emit('status', status));
|
|
@@ -45,43 +43,55 @@ export class TrilletAgent extends EventEmitter {
|
|
|
45
43
|
this.sdk.on('assistantStartedSpeaking', () => this.emit('assistantStartedSpeaking'));
|
|
46
44
|
this.sdk.on('assistantStoppedSpeaking', () => this.emit('assistantStoppedSpeaking'));
|
|
47
45
|
this.sdk.on('audioData', (data) => this.emit('audioData', data));
|
|
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
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
46
|
+
// Handle incoming tool usage from the agent
|
|
47
|
+
this.sdk.on('toolStarted', (toolCall) => {
|
|
48
|
+
this.transcriptManager.addToolStarted(toolCall);
|
|
49
|
+
this.emit('toolStarted', toolCall);
|
|
50
|
+
this.emit('transcriptUpdate', this.transcriptManager.getTranscripts());
|
|
51
|
+
});
|
|
52
|
+
this.sdk.on('toolCompleted', (toolResult) => {
|
|
53
|
+
this.transcriptManager.addToolCompleted(toolResult);
|
|
54
|
+
this.emit('toolCompleted', toolResult);
|
|
55
|
+
this.emit('transcriptUpdate', this.transcriptManager.getTranscripts());
|
|
56
|
+
});
|
|
57
|
+
this.sdk.on('transcript', (transcriptData, participant) => {
|
|
58
|
+
const participantId = participant.identity;
|
|
59
|
+
const isAgent = participantId.startsWith('agent');
|
|
60
|
+
const updated = this.transcriptManager.handleTranscript(participantId, isAgent, transcriptData);
|
|
61
|
+
if (updated) {
|
|
62
|
+
this.emit('transcriptUpdate', this.transcriptManager.getTranscripts());
|
|
63
|
+
}
|
|
64
|
+
});
|
|
65
|
+
// Handle incoming text messages from the agent
|
|
66
|
+
this.sdk.on('message', (message) => {
|
|
67
|
+
var _a, _b;
|
|
68
|
+
const agentParticipant = Array.from((_b = (_a = this.sdk.getRoom()) === null || _a === void 0 ? void 0 : _a.remoteParticipants.values()) !== null && _b !== void 0 ? _b : []).find((p) => p.identity.startsWith('agent'));
|
|
69
|
+
this.transcriptManager.addMessage('assistant', message.text, agentParticipant === null || agentParticipant === void 0 ? void 0 : agentParticipant.identity);
|
|
70
|
+
this.emit('message', message);
|
|
71
|
+
this.emit('transcriptUpdate', this.transcriptManager.getTranscripts());
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Set up default RPC handlers for common agent interactions
|
|
76
|
+
* This should be called after connection is established
|
|
77
|
+
*/
|
|
78
|
+
setupDefaultRpcHandlers() {
|
|
79
|
+
// Register handler for receiving chat messages from agent
|
|
80
|
+
this.registerRpcMethod('receiveChatMessage', async (data) => {
|
|
81
|
+
var _a, _b, _c;
|
|
82
|
+
const messageText = typeof data.payload === 'string' ? data.payload : ((_a = data.payload) === null || _a === void 0 ? void 0 : _a.text) || '';
|
|
83
|
+
if (messageText) {
|
|
84
|
+
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'));
|
|
85
|
+
this.transcriptManager.addMessage('assistant', messageText, agentParticipant === null || agentParticipant === void 0 ? void 0 : agentParticipant.identity);
|
|
86
|
+
this.emit('message', { text: messageText });
|
|
87
|
+
this.emit('transcriptUpdate', this.transcriptManager.getTranscripts());
|
|
88
|
+
}
|
|
89
|
+
return 'Message received';
|
|
90
|
+
});
|
|
91
|
+
// Register handler for agent status updates
|
|
92
|
+
this.registerRpcMethod('agentStatus', async (data) => {
|
|
93
|
+
this.emit('status', data.payload);
|
|
94
|
+
return 'Status received';
|
|
85
95
|
});
|
|
86
96
|
}
|
|
87
97
|
async startCall() {
|
|
@@ -122,7 +132,8 @@ export class TrilletAgent extends EventEmitter {
|
|
|
122
132
|
// Initialize call with LiveKit token
|
|
123
133
|
await this.sdk.initializeCall({
|
|
124
134
|
token: data.token,
|
|
125
|
-
wsUrl:
|
|
135
|
+
wsUrl: 'wss://trillet-ai-xdx0dw5r.livekit.cloud',
|
|
136
|
+
mode: this.config.mode,
|
|
126
137
|
audioSettings: {
|
|
127
138
|
sampleRate: 48000,
|
|
128
139
|
},
|
|
@@ -134,6 +145,8 @@ export class TrilletAgent extends EventEmitter {
|
|
|
134
145
|
if (this.config.mode === 'voice') {
|
|
135
146
|
await this.sdk.enableAudioPlayback();
|
|
136
147
|
}
|
|
148
|
+
// Set up default RPC handlers for text communication
|
|
149
|
+
this.setupDefaultRpcHandlers();
|
|
137
150
|
// Emit additional connection details
|
|
138
151
|
this.emit('connected', {
|
|
139
152
|
callId: data.callId,
|
|
@@ -185,7 +198,8 @@ export class TrilletAgent extends EventEmitter {
|
|
|
185
198
|
// Initialize call with LiveKit token
|
|
186
199
|
await this.sdk.initializeCall({
|
|
187
200
|
token: data.token,
|
|
188
|
-
wsUrl:
|
|
201
|
+
wsUrl: 'wss://trillet-ai-xdx0dw5r.livekit.cloud',
|
|
202
|
+
mode: this.config.mode,
|
|
189
203
|
audioSettings: {
|
|
190
204
|
sampleRate: 48000,
|
|
191
205
|
},
|
|
@@ -197,6 +211,8 @@ export class TrilletAgent extends EventEmitter {
|
|
|
197
211
|
if (this.config.mode === 'voice') {
|
|
198
212
|
await this.sdk.enableAudioPlayback();
|
|
199
213
|
}
|
|
214
|
+
// Set up default RPC handlers for text communication
|
|
215
|
+
this.setupDefaultRpcHandlers();
|
|
200
216
|
// Emit additional connection details
|
|
201
217
|
this.emit('connected', {
|
|
202
218
|
callId: data.callId,
|
|
@@ -214,161 +230,89 @@ export class TrilletAgent extends EventEmitter {
|
|
|
214
230
|
return this.sdk.isAssistantSpeaking;
|
|
215
231
|
}
|
|
216
232
|
getTranscripts() {
|
|
217
|
-
return this.
|
|
233
|
+
return this.transcriptManager.getTranscripts();
|
|
218
234
|
}
|
|
219
235
|
getCurrentTranscript() {
|
|
220
|
-
return this.
|
|
236
|
+
return this.transcriptManager.getCurrentTranscript();
|
|
221
237
|
}
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
238
|
+
/**
|
|
239
|
+
* Register an RPC method handler for receiving calls from the agent
|
|
240
|
+
* @param method - The RPC method name to handle
|
|
241
|
+
* @param handler - The function to handle the RPC call
|
|
242
|
+
*/
|
|
243
|
+
registerRpcMethod(method, handler) {
|
|
244
|
+
const room = this.sdk.getRoom();
|
|
245
|
+
if (!room) {
|
|
246
|
+
console.warn('Cannot register RPC method: not connected to room');
|
|
247
|
+
return;
|
|
248
|
+
}
|
|
249
|
+
room.localParticipant.registerRpcMethod(method, async (data) => {
|
|
250
|
+
try {
|
|
251
|
+
const result = await handler(data);
|
|
252
|
+
return result;
|
|
253
|
+
}
|
|
254
|
+
catch (error) {
|
|
255
|
+
console.error(`RPC method ${method} error:`, error);
|
|
256
|
+
throw error;
|
|
257
|
+
}
|
|
258
|
+
});
|
|
230
259
|
}
|
|
231
|
-
|
|
232
|
-
|
|
260
|
+
/**
|
|
261
|
+
* Send an RPC call to the agent
|
|
262
|
+
* @param method - The RPC method name
|
|
263
|
+
* @param payload - The data to send
|
|
264
|
+
* @param responseTimeout - Timeout in milliseconds (default: 30000)
|
|
265
|
+
*/
|
|
266
|
+
async sendRpcMessage(method, payload, responseTimeout = 30000) {
|
|
267
|
+
const room = this.sdk.getRoom();
|
|
268
|
+
if (!room || !this.sdk.isConnected) {
|
|
269
|
+
throw new Error('Not connected. Cannot send RPC message.');
|
|
270
|
+
}
|
|
271
|
+
const agentParticipant = Array.from(room.remoteParticipants.values()).find((p) => p.identity.startsWith('agent'));
|
|
272
|
+
if (!agentParticipant) {
|
|
273
|
+
throw new Error('No agent found to send RPC message to.');
|
|
274
|
+
}
|
|
233
275
|
try {
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
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
|
-
},
|
|
276
|
+
const response = await room.localParticipant.performRpc({
|
|
277
|
+
destinationIdentity: agentParticipant.identity,
|
|
278
|
+
method,
|
|
279
|
+
payload,
|
|
280
|
+
responseTimeout,
|
|
246
281
|
});
|
|
247
|
-
|
|
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');
|
|
282
|
+
return response;
|
|
253
283
|
}
|
|
254
284
|
catch (error) {
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
console.error('Call initialization failed:', error);
|
|
258
|
-
this.endCall();
|
|
259
|
-
throw error; // Re-throw to let TrilletAgent handle it
|
|
285
|
+
console.error(`RPC call to method ${method} failed:`, error);
|
|
286
|
+
throw error;
|
|
260
287
|
}
|
|
261
288
|
}
|
|
262
|
-
async
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
}
|
|
266
|
-
endCall() {
|
|
267
|
-
var _a;
|
|
268
|
-
if (!this.isConnected)
|
|
289
|
+
async sendTextMessage(text) {
|
|
290
|
+
if (this.config.mode !== 'text') {
|
|
291
|
+
console.warn('Cannot send text message in voice mode.');
|
|
269
292
|
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;
|
|
277
293
|
}
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
this.
|
|
294
|
+
const room = this.sdk.getRoom();
|
|
295
|
+
if (!room || !this.sdk.isConnected) {
|
|
296
|
+
this.emit('error', new Error('Not connected. Cannot send message.'));
|
|
297
|
+
return;
|
|
281
298
|
}
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
299
|
+
// Add user message to transcripts immediately
|
|
300
|
+
this.transcriptManager.addMessage('user', text, room.localParticipant.identity);
|
|
301
|
+
this.emit('transcriptUpdate', this.getTranscripts());
|
|
302
|
+
// Send the text message using LiveKit's sendText API with topic 'lk.chat'.
|
|
303
|
+
try {
|
|
304
|
+
await room.localParticipant.sendText(text, { topic: 'lk.chat' });
|
|
305
|
+
console.log('Text message sent to agent:', text);
|
|
287
306
|
}
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
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;
|
|
307
|
+
catch (error) {
|
|
308
|
+
console.error('Failed to send text message:', error);
|
|
309
|
+
this.emit('error', new Error(`Failed to send message: ${error instanceof Error ? error.message : String(error)}`));
|
|
367
310
|
}
|
|
368
311
|
}
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
312
|
+
/**
|
|
313
|
+
* Get the browser fingerprint for this session
|
|
314
|
+
* Useful for demo pages to send fingerprint when checking limits
|
|
315
|
+
*/
|
|
372
316
|
async getBrowserFingerprint() {
|
|
373
317
|
return await BrowserFingerprint.generate();
|
|
374
318
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@trillet-ai/web-sdk",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.7.0",
|
|
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,8 +32,9 @@
|
|
|
32
32
|
"author": "Trillet AI",
|
|
33
33
|
"license": "MIT",
|
|
34
34
|
"dependencies": {
|
|
35
|
+
"@livekit/krisp-noise-filter": "^0.3.4",
|
|
35
36
|
"eventemitter3": "^5.0.1",
|
|
36
|
-
"livekit-client": "^2.
|
|
37
|
+
"livekit-client": "^2.13.4"
|
|
37
38
|
},
|
|
38
39
|
"devDependencies": {
|
|
39
40
|
"@types/jest": "^29.5.12",
|