@trillet-ai/web-sdk 1.5.2 → 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.
@@ -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 transcripts;
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 { RemoteAudioTrack, Room, RoomEvent, Track, createAudioAnalyser } from 'livekit-client';
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.transcripts.push({
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
- 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);
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
- if (transcriptData.isFinal) {
71
- delete this.currentTranscript[participantId];
72
- const text = transcriptData.text.trim();
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
- });
87
- }
88
- else {
89
- this.currentTranscript[participantId] = transcriptData.text;
57
+ const updated = this.transcriptManager.handleTranscript(participantId, isAgent, transcriptData);
58
+ if (updated) {
59
+ this.emit('transcriptUpdate', this.transcriptManager.getTranscripts());
90
60
  }
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.transcripts.push({
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: process.env.LIVEKIT_WS_URL || 'wss://trillet-ai-xdx0dw5r.livekit.cloud',
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: process.env.LIVEKIT_WS_URL || 'wss://trillet-ai-xdx0dw5r.livekit.cloud',
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,217 +220,84 @@ export class TrilletAgent extends EventEmitter {
230
220
  return this.sdk.isAssistantSpeaking;
231
221
  }
232
222
  getTranscripts() {
233
- return this.transcripts;
223
+ return this.transcriptManager.getTranscripts();
234
224
  }
235
225
  getCurrentTranscript() {
236
- return this.currentTranscript;
226
+ return this.transcriptManager.getCurrentTranscript();
237
227
  }
238
- sendTextMessage(text) {
239
- if (this.config.mode !== 'text') {
240
- console.warn('Cannot send text message in voice mode.');
241
- return;
242
- }
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) {
243
234
  const room = this.sdk.getRoom();
244
- if (!room || !this.sdk.isConnected) {
245
- this.emit('error', new Error('Not connected. Cannot send message.'));
235
+ if (!room) {
236
+ console.warn('Cannot register RPC method: not connected to room');
246
237
  return;
247
238
  }
248
- room.localParticipant.sendText(text);
249
- this.transcripts.push({
250
- role: 'user',
251
- text,
252
- isFinal: true,
253
- timestamp: new Date(),
254
- participantId: room.localParticipant.identity,
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
+ }
255
248
  });
256
- this.emit('transcriptUpdate', this.transcripts);
257
249
  }
258
- }
259
- // Internal SDK class
260
- class TrilletWebSDK extends EventEmitter {
261
- constructor() {
262
- super();
263
- this.isConnected = false;
264
- // Audio state tracking
265
- this.isAssistantSpeaking = false;
266
- }
267
- async initializeCall(config) {
268
- var _a, _b, _c;
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
+ }
269
265
  try {
270
- this.room = new Room({
271
- audioCaptureDefaults: {
272
- autoGainControl: true,
273
- echoCancellation: true,
274
- noiseSuppression: true,
275
- channelCount: 1,
276
- deviceId: (_a = config.audioSettings) === null || _a === void 0 ? void 0 : _a.inputDeviceId,
277
- sampleRate: (_b = config.audioSettings) === null || _b === void 0 ? void 0 : _b.sampleRate,
278
- },
279
- audioOutput: {
280
- deviceId: (_c = config.audioSettings) === null || _c === void 0 ? void 0 : _c.outputDeviceId,
281
- },
266
+ const response = await room.localParticipant.performRpc({
267
+ destinationIdentity: agentParticipant.identity,
268
+ method,
269
+ payload,
270
+ responseTimeout,
282
271
  });
283
- this.setupEventHandlers(config);
284
- await this.room.connect(config.wsUrl, config.token);
285
- console.log('Connected to Trillet room:', this.room.name);
286
- if (config.mode !== 'text') {
287
- this.room.localParticipant.setMicrophoneEnabled(true);
288
- }
289
- this.isConnected = true;
290
- this.emit('connected');
272
+ return response;
291
273
  }
292
274
  catch (error) {
293
- const errorMessage = error instanceof Error ? error.message : 'Failed to initialize call';
294
- this.emit('error', errorMessage);
295
- console.error('Call initialization failed:', error);
296
- this.endCall();
297
- throw error; // Re-throw to let TrilletAgent handle it
275
+ console.error(`RPC call to method ${method} failed:`, error);
276
+ throw error;
298
277
  }
299
278
  }
300
- async enableAudioPlayback() {
301
- var _a;
302
- await ((_a = this.room) === null || _a === void 0 ? void 0 : _a.startAudio());
303
- }
304
- endCall() {
305
- var _a;
306
- if (!this.isConnected)
279
+ sendTextMessage(text) {
280
+ if (this.config.mode !== 'text') {
281
+ console.warn('Cannot send text message in voice mode.');
307
282
  return;
308
- this.isConnected = false;
309
- this.emit('disconnected');
310
- (_a = this.room) === null || _a === void 0 ? void 0 : _a.disconnect();
311
- this.isAssistantSpeaking = false;
312
- if (this.audioAnalyzer) {
313
- this.audioAnalyzer.cleanup();
314
- this.audioAnalyzer = undefined;
315
- }
316
- if (this.audioFrameCapture) {
317
- cancelAnimationFrame(this.audioFrameCapture);
318
- this.audioFrameCapture = undefined;
319
283
  }
320
- this.room = undefined;
321
- }
322
- toggleMicrophone(enabled) {
323
- if (this.isConnected && this.room) {
324
- this.room.localParticipant.setMicrophoneEnabled(enabled);
325
- }
326
- }
327
- captureAudio() {
328
- if (!this.isConnected || !this.audioAnalyzer)
329
- return;
330
- const bufferSize = this.audioAnalyzer.analyser.fftSize;
331
- const audioData = new Float32Array(bufferSize);
332
- this.audioAnalyzer.analyser.getFloatTimeDomainData(audioData);
333
- this.emit('audioData', audioData);
334
- this.audioFrameCapture = requestAnimationFrame(() => this.captureAudio());
335
- }
336
- setupEventHandlers(config) {
337
- let wasAgentSpeaking = false;
338
- 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.'));
339
287
  return;
340
- // Room events
341
- this.room.on(RoomEvent.ParticipantDisconnected, (participant) => {
342
- if ((participant === null || participant === void 0 ? void 0 : participant.identity) === 'assistant') {
343
- this.endCall();
344
- }
345
- });
346
- this.room.on(RoomEvent.Disconnected, () => {
347
- if (this.isConnected)
348
- this.endCall();
349
- });
350
- this.room.registerTextStreamHandler('lk.transcription', async (reader, info) => {
351
- var _a, _b;
352
- const text = await reader.readAll();
353
- const attributes = ((_a = reader.info) === null || _a === void 0 ? void 0 : _a.attributes) || {};
354
- const isFinal = attributes['lk.transcription_final'] === 'true' || attributes['lk.transcribed_track_id'];
355
- if (!info)
356
- return;
357
- const participant = (_b = this.room) === null || _b === void 0 ? void 0 : _b.getParticipantByIdentity(info.identity);
358
- if (!participant)
359
- return;
360
- this.emit('transcript', { text, isFinal }, participant);
361
- });
362
- // Audio events
363
- this.room.on(RoomEvent.TrackSubscribed, (track, publication) => {
364
- var _a;
365
- if (track.kind === Track.Kind.Audio) {
366
- if (publication.trackName === 'assistant_audio' && track instanceof RemoteAudioTrack && ((_a = config.features) === null || _a === void 0 ? void 0 : _a.enableRawAudio)) {
367
- const analyzer = createAudioAnalyser(track);
368
- this.audioAnalyzer = {
369
- calculateVolume: analyzer.calculateVolume,
370
- analyser: analyzer.analyser,
371
- cleanup: analyzer.cleanup,
372
- };
373
- this.audioFrameCapture = requestAnimationFrame(() => this.captureAudio());
374
- }
375
- track.attach();
376
- }
377
- });
378
- // Data events
379
- this.room.on(RoomEvent.DataReceived, (payload, participant) => {
380
- if (!(participant === null || participant === void 0 ? void 0 : participant.identity.startsWith('agent')))
381
- return;
382
- try {
383
- const data = JSON.parse(decoder.decode(payload));
384
- this.handleDataEvent(data, participant);
385
- }
386
- catch (error) {
387
- console.error('Failed to process received data:', error);
388
- }
389
- });
390
- this.room.on(RoomEvent.ActiveSpeakersChanged, (speakers) => {
391
- const isAgentSpeaking = speakers.some((p) => p.identity.startsWith('agent'));
392
- if (isAgentSpeaking && !wasAgentSpeaking) {
393
- this.emit('assistantStartedSpeaking');
394
- }
395
- else if (!isAgentSpeaking && wasAgentSpeaking) {
396
- this.emit('assistantStoppedSpeaking');
397
- }
398
- wasAgentSpeaking = isAgentSpeaking;
399
- });
400
- }
401
- handleDataEvent(event, participant) {
402
- switch (event.type) {
403
- case 'status':
404
- this.emit('status', event);
405
- break;
406
- case 'metadata':
407
- this.emit('metadata', event);
408
- break;
409
- case 'transcript':
410
- // this is for agent-generated transcripts, which we are overriding with lk.transcription
411
- // this.emit('transcript', event.data, participant);
412
- break;
413
- case 'llm_call':
414
- this.emit('toolStarted', { name: event.name, args: event.arguments });
415
- break;
416
- case 'llm_call_response':
417
- this.emit('toolCompleted', {
418
- name: event.details.api_name,
419
- result: event.details.api_response,
420
- isError: event.details.status >= 400,
421
- });
422
- break;
423
- case 'error':
424
- this.emit('toolCompleted', {
425
- name: event.name,
426
- result: event.details,
427
- isError: true,
428
- });
429
- break;
430
- case 'assistant_speaking_started':
431
- this.isAssistantSpeaking = true;
432
- this.emit('assistantStartedSpeaking');
433
- break;
434
- case 'assistant_speaking_ended':
435
- this.isAssistantSpeaking = false;
436
- this.emit('assistantStoppedSpeaking');
437
- break;
438
- case 'agent_message':
439
- this.emit('message', event);
440
- break;
441
288
  }
442
- }
443
- getRoom() {
444
- return this.room;
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
+ });
445
302
  }
446
303
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trillet-ai/web-sdk",
3
- "version": "1.5.2",
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.12.0"
36
+ "livekit-client": "^2.13.4"
37
37
  },
38
38
  "devDependencies": {
39
39
  "@types/jest": "^29.5.12",