@trillet-ai/web-sdk 1.5.1 → 1.5.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/TranscriptManager.d.ts +35 -0
- package/dist/TranscriptManager.js +63 -0
- package/dist/TrilletWebSDK.d.ts +35 -0
- package/dist/TrilletWebSDK.js +200 -0
- package/dist/index.d.ts +20 -29
- package/dist/index.js +103 -248
- package/package.json +2 -2
|
@@ -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,35 @@
|
|
|
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
|
+
};
|
|
15
|
+
}
|
|
16
|
+
export declare class TrilletWebSDK extends EventEmitter {
|
|
17
|
+
private room;
|
|
18
|
+
isConnected: boolean;
|
|
19
|
+
isAssistantSpeaking: boolean;
|
|
20
|
+
audioAnalyzer?: {
|
|
21
|
+
calculateVolume: () => number;
|
|
22
|
+
analyser: AnalyserNode;
|
|
23
|
+
cleanup: () => Promise<void>;
|
|
24
|
+
};
|
|
25
|
+
private audioFrameCapture;
|
|
26
|
+
constructor();
|
|
27
|
+
initializeCall(config: TrilletCallConfig): Promise<void>;
|
|
28
|
+
enableAudioPlayback(): Promise<void>;
|
|
29
|
+
endCall(): void;
|
|
30
|
+
toggleMicrophone(enabled: boolean): void;
|
|
31
|
+
private captureAudio;
|
|
32
|
+
private setupEventHandlers;
|
|
33
|
+
private handleDataEvent;
|
|
34
|
+
getRoom(): Room | undefined;
|
|
35
|
+
}
|
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
import { EventEmitter } from 'eventemitter3';
|
|
2
|
+
import { RemoteAudioTrack, Room, RoomEvent, Track, createAudioAnalyser } 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;
|
|
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
|
+
this.room.localParticipant.setMicrophoneEnabled(true);
|
|
34
|
+
}
|
|
35
|
+
this.isConnected = true;
|
|
36
|
+
this.emit('connected');
|
|
37
|
+
}
|
|
38
|
+
catch (error) {
|
|
39
|
+
const errorMessage = error instanceof Error ? error.message : 'Failed to initialize call';
|
|
40
|
+
this.emit('error', errorMessage);
|
|
41
|
+
console.error('Call initialization failed:', error);
|
|
42
|
+
this.endCall();
|
|
43
|
+
throw error; // Re-throw to let TrilletAgent handle it
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
async enableAudioPlayback() {
|
|
47
|
+
var _a;
|
|
48
|
+
await ((_a = this.room) === null || _a === void 0 ? void 0 : _a.startAudio());
|
|
49
|
+
}
|
|
50
|
+
endCall() {
|
|
51
|
+
var _a;
|
|
52
|
+
if (!this.isConnected)
|
|
53
|
+
return;
|
|
54
|
+
this.isConnected = false;
|
|
55
|
+
this.emit('disconnected');
|
|
56
|
+
(_a = this.room) === null || _a === void 0 ? void 0 : _a.disconnect();
|
|
57
|
+
this.isAssistantSpeaking = false;
|
|
58
|
+
if (this.audioAnalyzer) {
|
|
59
|
+
this.audioAnalyzer.cleanup();
|
|
60
|
+
this.audioAnalyzer = undefined;
|
|
61
|
+
}
|
|
62
|
+
if (this.audioFrameCapture) {
|
|
63
|
+
cancelAnimationFrame(this.audioFrameCapture);
|
|
64
|
+
this.audioFrameCapture = undefined;
|
|
65
|
+
}
|
|
66
|
+
this.room = undefined;
|
|
67
|
+
}
|
|
68
|
+
toggleMicrophone(enabled) {
|
|
69
|
+
if (this.isConnected && this.room) {
|
|
70
|
+
this.room.localParticipant.setMicrophoneEnabled(enabled);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
captureAudio() {
|
|
74
|
+
if (!this.isConnected || !this.audioAnalyzer)
|
|
75
|
+
return;
|
|
76
|
+
const bufferSize = this.audioAnalyzer.analyser.fftSize;
|
|
77
|
+
const audioData = new Float32Array(bufferSize);
|
|
78
|
+
this.audioAnalyzer.analyser.getFloatTimeDomainData(audioData);
|
|
79
|
+
this.emit('audioData', audioData);
|
|
80
|
+
this.audioFrameCapture = requestAnimationFrame(() => this.captureAudio());
|
|
81
|
+
}
|
|
82
|
+
setupEventHandlers(config) {
|
|
83
|
+
let wasAgentSpeaking = false;
|
|
84
|
+
if (!this.room)
|
|
85
|
+
return;
|
|
86
|
+
// Room events
|
|
87
|
+
this.room.on(RoomEvent.ParticipantDisconnected, (participant) => {
|
|
88
|
+
if ((participant === null || participant === void 0 ? void 0 : participant.identity) === 'assistant') {
|
|
89
|
+
this.endCall();
|
|
90
|
+
}
|
|
91
|
+
});
|
|
92
|
+
this.room.on(RoomEvent.Disconnected, () => {
|
|
93
|
+
if (this.isConnected)
|
|
94
|
+
this.endCall();
|
|
95
|
+
});
|
|
96
|
+
this.room.registerTextStreamHandler('lk.transcription', async (reader, info) => {
|
|
97
|
+
var _a, _b;
|
|
98
|
+
const text = await reader.readAll();
|
|
99
|
+
const attributes = ((_a = reader.info) === null || _a === void 0 ? void 0 : _a.attributes) || {};
|
|
100
|
+
const isFinal = attributes['lk.transcription_final'] === 'true' || attributes['lk.transcribed_track_id'];
|
|
101
|
+
if (!info)
|
|
102
|
+
return;
|
|
103
|
+
const participant = (_b = this.room) === null || _b === void 0 ? void 0 : _b.getParticipantByIdentity(info.identity);
|
|
104
|
+
if (!participant)
|
|
105
|
+
return;
|
|
106
|
+
this.emit('transcript', { text, isFinal }, participant);
|
|
107
|
+
});
|
|
108
|
+
// Audio events
|
|
109
|
+
this.room.on(RoomEvent.TrackSubscribed, (track, publication) => {
|
|
110
|
+
var _a;
|
|
111
|
+
if (track.kind === Track.Kind.Audio) {
|
|
112
|
+
if (publication.trackName === 'assistant_audio' && track instanceof RemoteAudioTrack && ((_a = config.features) === null || _a === void 0 ? void 0 : _a.enableRawAudio)) {
|
|
113
|
+
const analyzer = createAudioAnalyser(track);
|
|
114
|
+
this.audioAnalyzer = {
|
|
115
|
+
calculateVolume: analyzer.calculateVolume,
|
|
116
|
+
analyser: analyzer.analyser,
|
|
117
|
+
cleanup: analyzer.cleanup,
|
|
118
|
+
};
|
|
119
|
+
this.audioFrameCapture = requestAnimationFrame(() => this.captureAudio());
|
|
120
|
+
}
|
|
121
|
+
track.attach();
|
|
122
|
+
}
|
|
123
|
+
});
|
|
124
|
+
// Data events
|
|
125
|
+
this.room.on(RoomEvent.DataReceived, (payload, participant) => {
|
|
126
|
+
if (!(participant === null || participant === void 0 ? void 0 : participant.identity.startsWith('agent')))
|
|
127
|
+
return;
|
|
128
|
+
try {
|
|
129
|
+
const data = JSON.parse(decoder.decode(payload));
|
|
130
|
+
this.handleDataEvent(data, participant);
|
|
131
|
+
}
|
|
132
|
+
catch (error) {
|
|
133
|
+
console.error('Failed to process received data:', error);
|
|
134
|
+
}
|
|
135
|
+
});
|
|
136
|
+
this.room.on(RoomEvent.ActiveSpeakersChanged, (speakers) => {
|
|
137
|
+
const isAgentSpeaking = speakers.some((p) => p.identity.startsWith('agent'));
|
|
138
|
+
if (isAgentSpeaking && !wasAgentSpeaking) {
|
|
139
|
+
this.emit('assistantStartedSpeaking');
|
|
140
|
+
}
|
|
141
|
+
else if (!isAgentSpeaking && wasAgentSpeaking) {
|
|
142
|
+
this.emit('assistantStoppedSpeaking');
|
|
143
|
+
}
|
|
144
|
+
wasAgentSpeaking = isAgentSpeaking;
|
|
145
|
+
});
|
|
146
|
+
// Handle RPC events if available
|
|
147
|
+
// Note: LiveKit may not have specific RPC events, but we can monitor participant events
|
|
148
|
+
this.room.on(RoomEvent.ParticipantConnected, (participant) => {
|
|
149
|
+
console.log('Participant connected:', participant.identity);
|
|
150
|
+
if (participant.identity.startsWith('agent')) {
|
|
151
|
+
console.log('Agent connected, RPC communication available');
|
|
152
|
+
}
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
handleDataEvent(event, participant) {
|
|
156
|
+
switch (event.type) {
|
|
157
|
+
case 'status':
|
|
158
|
+
this.emit('status', event);
|
|
159
|
+
break;
|
|
160
|
+
case 'metadata':
|
|
161
|
+
this.emit('metadata', event);
|
|
162
|
+
break;
|
|
163
|
+
case 'transcript':
|
|
164
|
+
// this is for agent-generated transcripts, which we are overriding with lk.transcription
|
|
165
|
+
// this.emit('transcript', event.data, participant);
|
|
166
|
+
break;
|
|
167
|
+
case 'llm_call':
|
|
168
|
+
this.emit('toolStarted', { name: event.name, args: event.arguments });
|
|
169
|
+
break;
|
|
170
|
+
case 'llm_call_response':
|
|
171
|
+
this.emit('toolCompleted', {
|
|
172
|
+
name: event.details.api_name,
|
|
173
|
+
result: event.details.api_response,
|
|
174
|
+
isError: event.details.status >= 400,
|
|
175
|
+
});
|
|
176
|
+
break;
|
|
177
|
+
case 'error':
|
|
178
|
+
this.emit('toolCompleted', {
|
|
179
|
+
name: event.name,
|
|
180
|
+
result: event.details,
|
|
181
|
+
isError: true,
|
|
182
|
+
});
|
|
183
|
+
break;
|
|
184
|
+
case 'assistant_speaking_started':
|
|
185
|
+
this.isAssistantSpeaking = true;
|
|
186
|
+
this.emit('assistantStartedSpeaking');
|
|
187
|
+
break;
|
|
188
|
+
case 'assistant_speaking_ended':
|
|
189
|
+
this.isAssistantSpeaking = false;
|
|
190
|
+
this.emit('assistantStoppedSpeaking');
|
|
191
|
+
break;
|
|
192
|
+
case 'agent_message':
|
|
193
|
+
this.emit('message', event);
|
|
194
|
+
break;
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
getRoom() {
|
|
198
|
+
return this.room;
|
|
199
|
+
}
|
|
200
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { EventEmitter } from 'eventemitter3';
|
|
2
|
+
import { Transcript } from './TranscriptManager';
|
|
2
3
|
export interface TrilletAgentConfig {
|
|
3
4
|
apiKey?: string;
|
|
4
5
|
workspaceId?: string;
|
|
@@ -7,40 +8,18 @@ export interface TrilletAgentConfig {
|
|
|
7
8
|
callbackUrl?: string;
|
|
8
9
|
mode?: 'voice' | 'text';
|
|
9
10
|
}
|
|
10
|
-
export interface TrilletCallConfig {
|
|
11
|
-
token: string;
|
|
12
|
-
wsUrl: string;
|
|
13
|
-
audioSettings?: {
|
|
14
|
-
sampleRate?: number;
|
|
15
|
-
inputDeviceId?: string;
|
|
16
|
-
outputDeviceId?: string;
|
|
17
|
-
};
|
|
18
|
-
mode?: 'voice' | 'text';
|
|
19
|
-
features?: {
|
|
20
|
-
enableRawAudio?: boolean;
|
|
21
|
-
};
|
|
22
|
-
}
|
|
23
|
-
interface ToolUsed {
|
|
24
|
-
name: string;
|
|
25
|
-
args?: any;
|
|
26
|
-
status?: 'pending' | 'success' | 'error';
|
|
27
|
-
}
|
|
28
|
-
interface Transcript {
|
|
29
|
-
role: 'user' | 'assistant';
|
|
30
|
-
text: string;
|
|
31
|
-
isFinal: boolean;
|
|
32
|
-
timestamp: Date;
|
|
33
|
-
participantId?: string;
|
|
34
|
-
toolUsed?: ToolUsed;
|
|
35
|
-
}
|
|
36
11
|
export declare class TrilletAgent extends EventEmitter {
|
|
37
12
|
private sdk;
|
|
38
13
|
private config;
|
|
39
14
|
private sdkToken;
|
|
40
|
-
private
|
|
41
|
-
private currentTranscript;
|
|
15
|
+
private transcriptManager;
|
|
42
16
|
constructor(config: TrilletAgentConfig);
|
|
43
17
|
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;
|
|
44
23
|
startCall(): Promise<void>;
|
|
45
24
|
startPublicCall(): Promise<void>;
|
|
46
25
|
endCall(): void;
|
|
@@ -50,6 +29,18 @@ export declare class TrilletAgent extends EventEmitter {
|
|
|
50
29
|
getCurrentTranscript(): {
|
|
51
30
|
[key: string]: string;
|
|
52
31
|
};
|
|
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>;
|
|
53
45
|
sendTextMessage(text: string): void;
|
|
54
46
|
}
|
|
55
|
-
export {};
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { EventEmitter } from 'eventemitter3';
|
|
2
|
-
import {
|
|
2
|
+
import { TrilletWebSDK } from './TrilletWebSDK';
|
|
3
|
+
import { TranscriptManager } from './TranscriptManager';
|
|
3
4
|
const TRILLET_API_URL = {
|
|
4
5
|
CONNECT: 'https://api.trillet.ai/v1/api/web-call',
|
|
5
6
|
PUBLIC_CONNECT: 'https://api.trillet.ai/v1/api/web-call/public',
|
|
@@ -12,8 +13,6 @@ export class TrilletAgent extends EventEmitter {
|
|
|
12
13
|
constructor(config) {
|
|
13
14
|
super();
|
|
14
15
|
this.sdkToken = null;
|
|
15
|
-
this.transcripts = [];
|
|
16
|
-
this.currentTranscript = {};
|
|
17
16
|
// Validate environment
|
|
18
17
|
if (!isBrowser) {
|
|
19
18
|
throw new Error('Trillet SDK must be used in a browser environment');
|
|
@@ -29,11 +28,11 @@ export class TrilletAgent extends EventEmitter {
|
|
|
29
28
|
mode: config.mode || 'voice', // Default to voice mode
|
|
30
29
|
};
|
|
31
30
|
this.sdk = new TrilletWebSDK();
|
|
31
|
+
this.transcriptManager = new TranscriptManager();
|
|
32
32
|
this.setupEventForwarding();
|
|
33
33
|
}
|
|
34
34
|
setupEventForwarding() {
|
|
35
35
|
// Forward all SDK events to agent listeners
|
|
36
|
-
this.sdk.on('connected', () => this.emit('connected'));
|
|
37
36
|
this.sdk.on('disconnected', () => this.emit('disconnected'));
|
|
38
37
|
this.sdk.on('error', (error) => this.emit('error', error));
|
|
39
38
|
this.sdk.on('status', (status) => this.emit('status', status));
|
|
@@ -43,66 +42,53 @@ export class TrilletAgent extends EventEmitter {
|
|
|
43
42
|
this.sdk.on('audioData', (data) => this.emit('audioData', data));
|
|
44
43
|
// Handle incoming tool usage from the agent
|
|
45
44
|
this.sdk.on('toolStarted', (toolCall) => {
|
|
46
|
-
this.
|
|
47
|
-
role: 'assistant',
|
|
48
|
-
text: `Using tool: ${toolCall.name}`,
|
|
49
|
-
isFinal: true,
|
|
50
|
-
timestamp: new Date(),
|
|
51
|
-
toolUsed: { ...toolCall, status: 'pending' },
|
|
52
|
-
});
|
|
45
|
+
this.transcriptManager.addToolStarted(toolCall);
|
|
53
46
|
this.emit('toolStarted', toolCall);
|
|
54
|
-
this.emit('transcriptUpdate', this.getTranscripts());
|
|
47
|
+
this.emit('transcriptUpdate', this.transcriptManager.getTranscripts());
|
|
55
48
|
});
|
|
56
49
|
this.sdk.on('toolCompleted', (toolResult) => {
|
|
57
|
-
|
|
58
|
-
if (toolTranscriptIndex > -1) {
|
|
59
|
-
const toolTranscript = this.transcripts[toolTranscriptIndex];
|
|
60
|
-
if (toolTranscript && toolTranscript.toolUsed) {
|
|
61
|
-
toolTranscript.toolUsed.status = toolResult.isError ? 'error' : 'success';
|
|
62
|
-
}
|
|
63
|
-
}
|
|
50
|
+
this.transcriptManager.addToolCompleted(toolResult);
|
|
64
51
|
this.emit('toolCompleted', toolResult);
|
|
65
|
-
this.emit('transcriptUpdate', this.getTranscripts());
|
|
52
|
+
this.emit('transcriptUpdate', this.transcriptManager.getTranscripts());
|
|
66
53
|
});
|
|
67
54
|
this.sdk.on('transcript', (transcriptData, participant) => {
|
|
68
55
|
const participantId = participant.identity;
|
|
69
56
|
const isAgent = participantId.startsWith('agent');
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
if (!text)
|
|
74
|
-
return;
|
|
75
|
-
// Check for duplicates
|
|
76
|
-
const lastMessage = this.transcripts[this.transcripts.length - 1];
|
|
77
|
-
if (lastMessage && lastMessage.text === text && lastMessage.participantId === participantId && Date.now() - lastMessage.timestamp.getTime() < 1000) {
|
|
78
|
-
return;
|
|
79
|
-
}
|
|
80
|
-
this.transcripts.push({
|
|
81
|
-
role: isAgent ? 'assistant' : 'user',
|
|
82
|
-
text,
|
|
83
|
-
isFinal: true,
|
|
84
|
-
timestamp: new Date(),
|
|
85
|
-
participantId,
|
|
86
|
-
});
|
|
57
|
+
const updated = this.transcriptManager.handleTranscript(participantId, isAgent, transcriptData);
|
|
58
|
+
if (updated) {
|
|
59
|
+
this.emit('transcriptUpdate', this.transcriptManager.getTranscripts());
|
|
87
60
|
}
|
|
88
|
-
else {
|
|
89
|
-
this.currentTranscript[participantId] = transcriptData.text;
|
|
90
|
-
}
|
|
91
|
-
this.emit('transcriptUpdate', this.getTranscripts());
|
|
92
61
|
});
|
|
93
62
|
// Handle incoming text messages from the agent
|
|
94
63
|
this.sdk.on('message', (message) => {
|
|
95
64
|
var _a, _b;
|
|
96
65
|
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'));
|
|
97
|
-
this.
|
|
98
|
-
role: 'assistant',
|
|
99
|
-
text: message.text,
|
|
100
|
-
isFinal: true,
|
|
101
|
-
timestamp: new Date(),
|
|
102
|
-
participantId: agentParticipant === null || agentParticipant === void 0 ? void 0 : agentParticipant.identity,
|
|
103
|
-
});
|
|
66
|
+
this.transcriptManager.addMessage('assistant', message.text, agentParticipant === null || agentParticipant === void 0 ? void 0 : agentParticipant.identity);
|
|
104
67
|
this.emit('message', message);
|
|
105
|
-
this.emit('transcriptUpdate', this.getTranscripts());
|
|
68
|
+
this.emit('transcriptUpdate', this.transcriptManager.getTranscripts());
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Set up default RPC handlers for common agent interactions
|
|
73
|
+
* This should be called after connection is established
|
|
74
|
+
*/
|
|
75
|
+
setupDefaultRpcHandlers() {
|
|
76
|
+
// Register handler for receiving chat messages from agent
|
|
77
|
+
this.registerRpcMethod('receiveChatMessage', async (data) => {
|
|
78
|
+
var _a, _b, _c;
|
|
79
|
+
const messageText = typeof data.payload === 'string' ? data.payload : ((_a = data.payload) === null || _a === void 0 ? void 0 : _a.text) || '';
|
|
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';
|
|
106
92
|
});
|
|
107
93
|
}
|
|
108
94
|
async startCall() {
|
|
@@ -140,7 +126,7 @@ export class TrilletAgent extends EventEmitter {
|
|
|
140
126
|
// Initialize call with LiveKit token
|
|
141
127
|
await this.sdk.initializeCall({
|
|
142
128
|
token: data.token,
|
|
143
|
-
wsUrl:
|
|
129
|
+
wsUrl: 'wss://trillet-ai-xdx0dw5r.livekit.cloud',
|
|
144
130
|
mode: this.config.mode,
|
|
145
131
|
audioSettings: {
|
|
146
132
|
sampleRate: 48000,
|
|
@@ -153,6 +139,8 @@ export class TrilletAgent extends EventEmitter {
|
|
|
153
139
|
if (this.config.mode === 'voice') {
|
|
154
140
|
await this.sdk.enableAudioPlayback();
|
|
155
141
|
}
|
|
142
|
+
// Set up default RPC handlers for text communication
|
|
143
|
+
this.setupDefaultRpcHandlers();
|
|
156
144
|
// Emit additional connection details
|
|
157
145
|
this.emit('connected', {
|
|
158
146
|
callId: data.callId,
|
|
@@ -200,7 +188,7 @@ export class TrilletAgent extends EventEmitter {
|
|
|
200
188
|
// Initialize call with LiveKit token
|
|
201
189
|
await this.sdk.initializeCall({
|
|
202
190
|
token: data.token,
|
|
203
|
-
wsUrl:
|
|
191
|
+
wsUrl: 'wss://trillet-ai-xdx0dw5r.livekit.cloud',
|
|
204
192
|
mode: this.config.mode,
|
|
205
193
|
audioSettings: {
|
|
206
194
|
sampleRate: 48000,
|
|
@@ -213,6 +201,8 @@ export class TrilletAgent extends EventEmitter {
|
|
|
213
201
|
if (this.config.mode === 'voice') {
|
|
214
202
|
await this.sdk.enableAudioPlayback();
|
|
215
203
|
}
|
|
204
|
+
// Set up default RPC handlers for text communication
|
|
205
|
+
this.setupDefaultRpcHandlers();
|
|
216
206
|
// Emit additional connection details
|
|
217
207
|
this.emit('connected', {
|
|
218
208
|
callId: data.callId,
|
|
@@ -230,219 +220,84 @@ export class TrilletAgent extends EventEmitter {
|
|
|
230
220
|
return this.sdk.isAssistantSpeaking;
|
|
231
221
|
}
|
|
232
222
|
getTranscripts() {
|
|
233
|
-
return this.
|
|
223
|
+
return this.transcriptManager.getTranscripts();
|
|
234
224
|
}
|
|
235
225
|
getCurrentTranscript() {
|
|
236
|
-
return this.
|
|
226
|
+
return this.transcriptManager.getCurrentTranscript();
|
|
237
227
|
}
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
228
|
+
/**
|
|
229
|
+
* Register an RPC method handler for receiving calls from the agent
|
|
230
|
+
* @param method - The RPC method name to handle
|
|
231
|
+
* @param handler - The function to handle the RPC call
|
|
232
|
+
*/
|
|
233
|
+
registerRpcMethod(method, handler) {
|
|
234
|
+
const room = this.sdk.getRoom();
|
|
235
|
+
if (!room) {
|
|
236
|
+
console.warn('Cannot register RPC method: not connected to room');
|
|
246
237
|
return;
|
|
247
238
|
}
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
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
|
+
}
|
|
257
248
|
});
|
|
258
|
-
this.emit('transcriptUpdate', this.transcripts);
|
|
259
249
|
}
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
250
|
+
/**
|
|
251
|
+
* Send an RPC call to the agent
|
|
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
|
+
}
|
|
271
265
|
try {
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
channelCount: 1,
|
|
278
|
-
deviceId: (_a = config.audioSettings) === null || _a === void 0 ? void 0 : _a.inputDeviceId,
|
|
279
|
-
sampleRate: (_b = config.audioSettings) === null || _b === void 0 ? void 0 : _b.sampleRate,
|
|
280
|
-
},
|
|
281
|
-
audioOutput: {
|
|
282
|
-
deviceId: (_c = config.audioSettings) === null || _c === void 0 ? void 0 : _c.outputDeviceId,
|
|
283
|
-
},
|
|
266
|
+
const response = await room.localParticipant.performRpc({
|
|
267
|
+
destinationIdentity: agentParticipant.identity,
|
|
268
|
+
method,
|
|
269
|
+
payload,
|
|
270
|
+
responseTimeout,
|
|
284
271
|
});
|
|
285
|
-
|
|
286
|
-
await this.room.connect(config.wsUrl, config.token);
|
|
287
|
-
console.log('Connected to Trillet room:', this.room.name);
|
|
288
|
-
if (config.mode !== 'text') {
|
|
289
|
-
this.room.localParticipant.setMicrophoneEnabled(true);
|
|
290
|
-
}
|
|
291
|
-
this.isConnected = true;
|
|
292
|
-
this.emit('connected');
|
|
272
|
+
return response;
|
|
293
273
|
}
|
|
294
274
|
catch (error) {
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
console.error('Call initialization failed:', error);
|
|
298
|
-
this.endCall();
|
|
299
|
-
throw error; // Re-throw to let TrilletAgent handle it
|
|
275
|
+
console.error(`RPC call to method ${method} failed:`, error);
|
|
276
|
+
throw error;
|
|
300
277
|
}
|
|
301
278
|
}
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
}
|
|
306
|
-
endCall() {
|
|
307
|
-
var _a;
|
|
308
|
-
if (!this.isConnected)
|
|
279
|
+
sendTextMessage(text) {
|
|
280
|
+
if (this.config.mode !== 'text') {
|
|
281
|
+
console.warn('Cannot send text message in voice mode.');
|
|
309
282
|
return;
|
|
310
|
-
this.isConnected = false;
|
|
311
|
-
this.emit('disconnected');
|
|
312
|
-
(_a = this.room) === null || _a === void 0 ? void 0 : _a.disconnect();
|
|
313
|
-
this.isAssistantSpeaking = false;
|
|
314
|
-
if (this.audioAnalyzer) {
|
|
315
|
-
this.audioAnalyzer.cleanup();
|
|
316
|
-
this.audioAnalyzer = undefined;
|
|
317
|
-
}
|
|
318
|
-
if (this.audioFrameCapture) {
|
|
319
|
-
cancelAnimationFrame(this.audioFrameCapture);
|
|
320
|
-
this.audioFrameCapture = undefined;
|
|
321
283
|
}
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
if (this.isConnected && this.room) {
|
|
326
|
-
this.room.localParticipant.setMicrophoneEnabled(enabled);
|
|
327
|
-
}
|
|
328
|
-
}
|
|
329
|
-
captureAudio() {
|
|
330
|
-
if (!this.isConnected || !this.audioAnalyzer)
|
|
331
|
-
return;
|
|
332
|
-
const bufferSize = this.audioAnalyzer.analyser.fftSize;
|
|
333
|
-
const audioData = new Float32Array(bufferSize);
|
|
334
|
-
this.audioAnalyzer.analyser.getFloatTimeDomainData(audioData);
|
|
335
|
-
this.emit('audioData', audioData);
|
|
336
|
-
this.audioFrameCapture = requestAnimationFrame(() => this.captureAudio());
|
|
337
|
-
}
|
|
338
|
-
setupEventHandlers(config) {
|
|
339
|
-
let wasAgentSpeaking = false;
|
|
340
|
-
if (!this.room)
|
|
284
|
+
const room = this.sdk.getRoom();
|
|
285
|
+
if (!room || !this.sdk.isConnected) {
|
|
286
|
+
this.emit('error', new Error('Not connected. Cannot send message.'));
|
|
341
287
|
return;
|
|
342
|
-
// Room events
|
|
343
|
-
this.room.on(RoomEvent.ParticipantDisconnected, (participant) => {
|
|
344
|
-
if ((participant === null || participant === void 0 ? void 0 : participant.identity) === 'assistant') {
|
|
345
|
-
this.endCall();
|
|
346
|
-
}
|
|
347
|
-
});
|
|
348
|
-
this.room.on(RoomEvent.Disconnected, () => {
|
|
349
|
-
if (this.isConnected)
|
|
350
|
-
this.endCall();
|
|
351
|
-
});
|
|
352
|
-
this.room.registerTextStreamHandler('lk.transcription', async (reader, info) => {
|
|
353
|
-
var _a, _b;
|
|
354
|
-
const text = await reader.readAll();
|
|
355
|
-
const attributes = ((_a = reader.info) === null || _a === void 0 ? void 0 : _a.attributes) || {};
|
|
356
|
-
const isFinal = attributes['lk.transcription_final'] === 'true' || attributes['lk.transcribed_track_id'];
|
|
357
|
-
if (!info)
|
|
358
|
-
return;
|
|
359
|
-
const participant = (_b = this.room) === null || _b === void 0 ? void 0 : _b.getParticipantByIdentity(info.identity);
|
|
360
|
-
if (!participant)
|
|
361
|
-
return;
|
|
362
|
-
this.emit('transcript', { text, isFinal }, participant);
|
|
363
|
-
});
|
|
364
|
-
// Audio events
|
|
365
|
-
this.room.on(RoomEvent.TrackSubscribed, (track, publication) => {
|
|
366
|
-
var _a;
|
|
367
|
-
if (track.kind === Track.Kind.Audio) {
|
|
368
|
-
if (publication.trackName === 'assistant_audio' && track instanceof RemoteAudioTrack && ((_a = config.features) === null || _a === void 0 ? void 0 : _a.enableRawAudio)) {
|
|
369
|
-
const analyzer = createAudioAnalyser(track);
|
|
370
|
-
this.audioAnalyzer = {
|
|
371
|
-
calculateVolume: analyzer.calculateVolume,
|
|
372
|
-
analyser: analyzer.analyser,
|
|
373
|
-
cleanup: analyzer.cleanup,
|
|
374
|
-
};
|
|
375
|
-
this.audioFrameCapture = requestAnimationFrame(() => this.captureAudio());
|
|
376
|
-
}
|
|
377
|
-
track.attach();
|
|
378
|
-
}
|
|
379
|
-
});
|
|
380
|
-
// Data events
|
|
381
|
-
this.room.on(RoomEvent.DataReceived, (payload, participant) => {
|
|
382
|
-
if (!(participant === null || participant === void 0 ? void 0 : participant.identity.startsWith('agent')))
|
|
383
|
-
return;
|
|
384
|
-
try {
|
|
385
|
-
const data = JSON.parse(decoder.decode(payload));
|
|
386
|
-
this.handleDataEvent(data, participant);
|
|
387
|
-
}
|
|
388
|
-
catch (error) {
|
|
389
|
-
console.error('Failed to process received data:', error);
|
|
390
|
-
}
|
|
391
|
-
});
|
|
392
|
-
this.room.on(RoomEvent.ActiveSpeakersChanged, (speakers) => {
|
|
393
|
-
const isAgentSpeaking = speakers.some((p) => p.identity.startsWith('agent'));
|
|
394
|
-
if (isAgentSpeaking && !wasAgentSpeaking) {
|
|
395
|
-
this.emit('assistantStartedSpeaking');
|
|
396
|
-
}
|
|
397
|
-
else if (!isAgentSpeaking && wasAgentSpeaking) {
|
|
398
|
-
this.emit('assistantStoppedSpeaking');
|
|
399
|
-
}
|
|
400
|
-
wasAgentSpeaking = isAgentSpeaking;
|
|
401
|
-
});
|
|
402
|
-
}
|
|
403
|
-
handleDataEvent(event, participant) {
|
|
404
|
-
switch (event.type) {
|
|
405
|
-
case 'status':
|
|
406
|
-
this.emit('status', event);
|
|
407
|
-
break;
|
|
408
|
-
case 'metadata':
|
|
409
|
-
this.emit('metadata', event);
|
|
410
|
-
break;
|
|
411
|
-
case 'transcript':
|
|
412
|
-
// this is for agent-generated transcripts, which we are overriding with lk.transcription
|
|
413
|
-
// this.emit('transcript', event.data, participant);
|
|
414
|
-
break;
|
|
415
|
-
case 'llm_call':
|
|
416
|
-
this.emit('toolStarted', { name: event.name, args: event.arguments });
|
|
417
|
-
break;
|
|
418
|
-
case 'llm_call_response':
|
|
419
|
-
this.emit('toolCompleted', {
|
|
420
|
-
name: event.details.api_name,
|
|
421
|
-
result: event.details.api_response,
|
|
422
|
-
isError: event.details.status >= 400,
|
|
423
|
-
});
|
|
424
|
-
break;
|
|
425
|
-
case 'error':
|
|
426
|
-
this.emit('toolCompleted', {
|
|
427
|
-
name: event.name,
|
|
428
|
-
result: event.details,
|
|
429
|
-
isError: true,
|
|
430
|
-
});
|
|
431
|
-
break;
|
|
432
|
-
case 'assistant_speaking_started':
|
|
433
|
-
this.isAssistantSpeaking = true;
|
|
434
|
-
this.emit('assistantStartedSpeaking');
|
|
435
|
-
break;
|
|
436
|
-
case 'assistant_speaking_ended':
|
|
437
|
-
this.isAssistantSpeaking = false;
|
|
438
|
-
this.emit('assistantStoppedSpeaking');
|
|
439
|
-
break;
|
|
440
|
-
case 'agent_message':
|
|
441
|
-
this.emit('message', event);
|
|
442
|
-
break;
|
|
443
288
|
}
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
289
|
+
// Add user message to transcripts immediately
|
|
290
|
+
this.transcriptManager.addMessage('user', text, room.localParticipant.identity);
|
|
291
|
+
this.emit('transcriptUpdate', this.getTranscripts());
|
|
292
|
+
// Send message via RPC
|
|
293
|
+
const history = this.getTranscripts();
|
|
294
|
+
this.sendRpcMessage('send_user_message', { text, history })
|
|
295
|
+
.then(() => {
|
|
296
|
+
console.log('Text message sent to agent via RPC:', text);
|
|
297
|
+
})
|
|
298
|
+
.catch((error) => {
|
|
299
|
+
console.error('Failed to send text message via RPC:', error);
|
|
300
|
+
this.emit('error', new Error(`Failed to send message: ${error instanceof Error ? error.message : String(error)}`));
|
|
301
|
+
});
|
|
447
302
|
}
|
|
448
303
|
}
|
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.3",
|
|
4
4
|
"description": "Trillet Web SDK for real-time audio communication with AI agents",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"types": "dist/index.d.ts",
|
|
@@ -33,7 +33,7 @@
|
|
|
33
33
|
"license": "MIT",
|
|
34
34
|
"dependencies": {
|
|
35
35
|
"eventemitter3": "^5.0.1",
|
|
36
|
-
"livekit-client": "^2.
|
|
36
|
+
"livekit-client": "^2.13.4"
|
|
37
37
|
},
|
|
38
38
|
"devDependencies": {
|
|
39
39
|
"@types/jest": "^29.5.12",
|