@trillet-ai/web-sdk 1.1.0 → 1.1.2

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/index.js CHANGED
@@ -3,9 +3,26 @@ import { RemoteAudioTrack, Room, RoomEvent, Track, createAudioAnalyser, } from "
3
3
  const TRILLET_API_URL = "https://api.trillet.ai/v1/api/web-call";
4
4
  const TRILLET_WS_URL = "wss://trilletai-ek0j3un1.livekit.cloud";
5
5
  const decoder = new TextDecoder();
6
+ // Browser compatibility check
7
+ const isBrowser = typeof window !== 'undefined';
8
+ const isSecureContext = isBrowser && window.isSecureContext;
6
9
  export class TrilletAgent extends EventEmitter {
7
10
  constructor(config) {
8
11
  super();
12
+ // Validate environment
13
+ if (!isBrowser) {
14
+ throw new Error('Trillet SDK must be used in a browser environment');
15
+ }
16
+ if (!isSecureContext) {
17
+ throw new Error('Trillet SDK requires a secure context (HTTPS or localhost)');
18
+ }
19
+ // Validate config
20
+ if (!config.apiKey)
21
+ throw new Error('apiKey is required');
22
+ if (!config.workspaceId)
23
+ throw new Error('workspaceId is required');
24
+ if (!config.agentId)
25
+ throw new Error('agentId is required');
9
26
  this.config = config;
10
27
  this.sdk = new TrilletWebSDK();
11
28
  this.setupEventForwarding();
@@ -22,6 +39,7 @@ export class TrilletAgent extends EventEmitter {
22
39
  this.sdk.on('audioData', (data) => this.emit('audioData', data));
23
40
  }
24
41
  async startCall() {
42
+ var _a;
25
43
  try {
26
44
  // 1. Get LiveKit token from Trillet API
27
45
  const response = await fetch(TRILLET_API_URL, {
@@ -30,21 +48,30 @@ export class TrilletAgent extends EventEmitter {
30
48
  'Content-Type': 'application/json',
31
49
  'Accept': 'application/json',
32
50
  'x-workspace-id': this.config.workspaceId,
33
- 'x-api-key': this.config.apiKey,
34
- 'Origin': window.location.origin
51
+ 'x-api-key': this.config.apiKey
35
52
  },
36
53
  mode: 'cors',
37
- credentials: 'omit',
54
+ credentials: 'same-origin',
38
55
  body: JSON.stringify({
39
56
  call_agent_id: this.config.agentId,
40
57
  dynamic_variables: this.config.variables || {}
41
58
  })
42
59
  });
43
60
  if (!response.ok) {
44
- const error = await response.text();
45
- throw new Error(`API Error: ${error}`);
61
+ let errorMessage;
62
+ try {
63
+ const errorData = await response.json();
64
+ errorMessage = errorData.message || errorData.error || 'Unknown error';
65
+ }
66
+ catch (_b) {
67
+ errorMessage = await response.text();
68
+ }
69
+ throw new Error(`API Error: ${errorMessage}`);
46
70
  }
47
71
  const data = await response.json();
72
+ if (!data.token || !((_a = data.connection) === null || _a === void 0 ? void 0 : _a.url)) {
73
+ throw new Error('Invalid response from server: missing token or connection details');
74
+ }
48
75
  // 2. Initialize call with LiveKit token
49
76
  await this.sdk.initializeCall({
50
77
  token: data.token,
@@ -59,6 +86,7 @@ export class TrilletAgent extends EventEmitter {
59
86
  await this.sdk.enableAudioPlayback();
60
87
  }
61
88
  catch (error) {
89
+ console.error('Trillet SDK Error:', error);
62
90
  this.emit('error', error);
63
91
  throw error;
64
92
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trillet-ai/web-sdk",
3
- "version": "1.1.0",
3
+ "version": "1.1.2",
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",
@@ -9,7 +9,8 @@
9
9
  "access": "public"
10
10
  },
11
11
  "scripts": {
12
- "build": "tsc",
12
+ "clean": "rimraf dist",
13
+ "build": "npm run clean && tsc",
13
14
  "dev": "tsc --watch",
14
15
  "lint": "eslint src/**/*.{ts,tsx}",
15
16
  "prepare": "npm run build",
@@ -36,15 +37,16 @@
36
37
  },
37
38
  "devDependencies": {
38
39
  "@types/node": "^20.11.0",
40
+ "@types/react": "^18.2.0",
41
+ "@types/react-dom": "^18.2.0",
39
42
  "@typescript-eslint/eslint-plugin": "^6.18.1",
40
43
  "@typescript-eslint/parser": "^6.18.1",
41
44
  "eslint": "^8.56.0",
42
- "typescript": "^5.3.3",
43
45
  "express": "^4.18.2",
44
- "@types/react": "^18.2.0",
45
- "@types/react-dom": "^18.2.0",
46
46
  "react": "^18.2.0",
47
- "react-dom": "^18.2.0"
47
+ "react-dom": "^18.2.0",
48
+ "rimraf": "^5.0.10",
49
+ "typescript": "^5.3.3"
48
50
  },
49
51
  "files": [
50
52
  "dist",
@@ -1,2 +0,0 @@
1
- declare function App(): any;
2
- export default App;
@@ -1,9 +0,0 @@
1
- import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
- import { TrilletAgent } from './TrilletAgent';
3
- function App() {
4
- return (_jsxs("div", { children: [_jsx("h1", { children: "My Website" }), _jsx(TrilletAgent, { workspaceId: "your_workspace_id", apiKey: "your_api_key", agentId: "your_agent_id", variables: {
5
- customerName: "John Doe",
6
- context: "Website Visit"
7
- }, onStatusChange: (status) => console.log('Agent status:', status), onError: (error) => console.error('Agent error:', error) })] }));
8
- }
9
- export default App;
@@ -1,11 +0,0 @@
1
- import React from 'react';
2
- interface TrilletAgentProps {
3
- workspaceId: string;
4
- apiKey: string;
5
- agentId: string;
6
- variables?: Record<string, any>;
7
- onStatusChange?: (status: string) => void;
8
- onError?: (error: Error) => void;
9
- }
10
- export declare const TrilletAgent: React.FC<TrilletAgentProps>;
11
- export {};
@@ -1,77 +0,0 @@
1
- import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
- import React, { useEffect, useRef, useState } from 'react';
3
- import { TrilletWebSDK } from '@trillet/web-sdk';
4
- export const TrilletAgent = ({ workspaceId, apiKey, agentId, variables = {}, onStatusChange, onError, }) => {
5
- const [isConnected, setIsConnected] = useState(false);
6
- const [isMuted, setIsMuted] = useState(false);
7
- const sdkRef = useRef();
8
- useEffect(() => {
9
- sdkRef.current = new TrilletWebSDK();
10
- setupEventListeners();
11
- return () => {
12
- var _a;
13
- (_a = sdkRef.current) === null || _a === void 0 ? void 0 : _a.endCall();
14
- };
15
- }, []);
16
- const setupEventListeners = () => {
17
- if (!sdkRef.current)
18
- return;
19
- sdkRef.current.on('connected', () => {
20
- setIsConnected(true);
21
- onStatusChange === null || onStatusChange === void 0 ? void 0 : onStatusChange('connected');
22
- });
23
- sdkRef.current.on('disconnected', () => {
24
- setIsConnected(false);
25
- onStatusChange === null || onStatusChange === void 0 ? void 0 : onStatusChange('disconnected');
26
- });
27
- sdkRef.current.on('error', (error) => {
28
- onError === null || onError === void 0 ? void 0 : onError(error);
29
- });
30
- };
31
- const startConversation = async () => {
32
- var _a, _b;
33
- try {
34
- const response = await fetch('https://api.trillet.ai/v1/api/web-call', {
35
- method: 'POST',
36
- headers: {
37
- 'Content-Type': 'application/json',
38
- 'Accept': 'application/json',
39
- 'x-workspace-id': workspaceId,
40
- 'x-api-key': apiKey
41
- },
42
- body: JSON.stringify({
43
- call_agent_id: agentId,
44
- dynamic_variables: variables
45
- })
46
- });
47
- if (!response.ok) {
48
- throw new Error('Failed to initialize conversation');
49
- }
50
- const data = await response.json();
51
- await ((_a = sdkRef.current) === null || _a === void 0 ? void 0 : _a.initializeCall({
52
- token: data.token,
53
- audioSettings: {
54
- sampleRate: 48000
55
- },
56
- features: {
57
- enableRawAudio: true
58
- }
59
- }));
60
- await ((_b = sdkRef.current) === null || _b === void 0 ? void 0 : _b.enableAudioPlayback());
61
- }
62
- catch (error) {
63
- onError === null || onError === void 0 ? void 0 : onError(error);
64
- }
65
- };
66
- const toggleMute = () => {
67
- if (!sdkRef.current)
68
- return;
69
- setIsMuted(!isMuted);
70
- sdkRef.current.toggleMicrophone(!isMuted);
71
- };
72
- const endConversation = () => {
73
- var _a;
74
- (_a = sdkRef.current) === null || _a === void 0 ? void 0 : _a.endCall();
75
- };
76
- return (_jsxs("div", { className: "trillet-controls", children: [_jsxs("div", { className: "status", children: [_jsx("span", { className: `status-indicator ${isConnected ? 'active' : ''}` }), _jsx("span", { children: isConnected ? 'Connected' : 'Disconnected' })] }), _jsx("button", { onClick: startConversation, disabled: isConnected, children: "Start Conversation" }), _jsx("button", { onClick: endConversation, disabled: !isConnected, children: "End Conversation" }), _jsx("button", { onClick: toggleMute, disabled: !isConnected, children: isMuted ? 'Unmute' : 'Mute' })] }));
77
- };
@@ -1,31 +0,0 @@
1
- import { EventEmitter } from "eventemitter3";
2
- export interface TrilletCallConfig {
3
- token: string;
4
- audioSettings?: {
5
- sampleRate?: number;
6
- inputDeviceId?: string;
7
- outputDeviceId?: string;
8
- };
9
- features?: {
10
- enableRawAudio?: boolean;
11
- };
12
- }
13
- export declare class TrilletWebSDK extends EventEmitter {
14
- private room;
15
- private isConnected;
16
- isAssistantSpeaking: boolean;
17
- audioAnalyzer?: {
18
- calculateVolume: () => number;
19
- analyser: AnalyserNode;
20
- cleanup: () => Promise<void>;
21
- };
22
- private audioFrameCapture;
23
- constructor();
24
- initializeCall(config: TrilletCallConfig): Promise<void>;
25
- enableAudioPlayback(): Promise<void>;
26
- endCall(): void;
27
- toggleMicrophone(enabled: boolean): void;
28
- private captureAudio;
29
- private setupEventHandlers;
30
- private handleDataEvent;
31
- }
package/dist/src/index.js DELETED
@@ -1,139 +0,0 @@
1
- import { EventEmitter } from "eventemitter3";
2
- import { RemoteAudioTrack, Room, RoomEvent, Track, createAudioAnalyser, } from "livekit-client";
3
- const TRILLET_WS_URL = "wss://trillet-ai-xdx0dw5r.livekit.cloud";
4
- const decoder = new TextDecoder();
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
- await this.room.connect(TRILLET_WS_URL, config.token);
30
- console.log("Connected to Trillet room:", this.room.name);
31
- this.room.localParticipant.setMicrophoneEnabled(true);
32
- this.isConnected = true;
33
- this.emit("connected");
34
- }
35
- catch (error) {
36
- this.emit("error", "Failed to initialize call");
37
- console.error("Call initialization failed:", error);
38
- this.endCall();
39
- }
40
- }
41
- async enableAudioPlayback() {
42
- var _a;
43
- await ((_a = this.room) === null || _a === void 0 ? void 0 : _a.startAudio());
44
- }
45
- endCall() {
46
- var _a;
47
- if (!this.isConnected)
48
- return;
49
- this.isConnected = false;
50
- this.emit("disconnected");
51
- (_a = this.room) === null || _a === void 0 ? void 0 : _a.disconnect();
52
- this.isAssistantSpeaking = false;
53
- if (this.audioAnalyzer) {
54
- this.audioAnalyzer.cleanup();
55
- this.audioAnalyzer = undefined;
56
- }
57
- if (this.audioFrameCapture) {
58
- cancelAnimationFrame(this.audioFrameCapture);
59
- this.audioFrameCapture = undefined;
60
- }
61
- this.room = undefined;
62
- }
63
- toggleMicrophone(enabled) {
64
- if (this.isConnected && this.room) {
65
- this.room.localParticipant.setMicrophoneEnabled(enabled);
66
- }
67
- }
68
- captureAudio() {
69
- if (!this.isConnected || !this.audioAnalyzer)
70
- return;
71
- const bufferSize = this.audioAnalyzer.analyser.fftSize;
72
- const audioData = new Float32Array(bufferSize);
73
- this.audioAnalyzer.analyser.getFloatTimeDomainData(audioData);
74
- this.emit("audioData", audioData);
75
- this.audioFrameCapture = requestAnimationFrame(() => this.captureAudio());
76
- }
77
- setupEventHandlers(config) {
78
- if (!this.room)
79
- return;
80
- // Room events
81
- this.room.on(RoomEvent.ParticipantDisconnected, (participant) => {
82
- if ((participant === null || participant === void 0 ? void 0 : participant.identity) === "assistant") {
83
- this.endCall();
84
- }
85
- });
86
- this.room.on(RoomEvent.Disconnected, () => {
87
- if (this.isConnected)
88
- this.endCall();
89
- });
90
- // Audio events
91
- this.room.on(RoomEvent.TrackSubscribed, (track, publication) => {
92
- var _a;
93
- if (track.kind === Track.Kind.Audio) {
94
- if (publication.trackName === "assistant_audio" &&
95
- track instanceof RemoteAudioTrack &&
96
- ((_a = config.features) === null || _a === void 0 ? void 0 : _a.enableRawAudio)) {
97
- const analyzer = createAudioAnalyser(track);
98
- this.audioAnalyzer = {
99
- calculateVolume: analyzer.calculateVolume,
100
- analyser: analyzer.analyser,
101
- cleanup: analyzer.cleanup
102
- };
103
- this.audioFrameCapture = requestAnimationFrame(() => this.captureAudio());
104
- }
105
- track.attach();
106
- }
107
- });
108
- // Data events
109
- this.room.on(RoomEvent.DataReceived, (payload, participant) => {
110
- if ((participant === null || participant === void 0 ? void 0 : participant.identity) !== "assistant")
111
- return;
112
- try {
113
- const data = JSON.parse(decoder.decode(payload));
114
- this.handleDataEvent(data);
115
- }
116
- catch (error) {
117
- console.error("Failed to process received data:", error);
118
- }
119
- });
120
- }
121
- handleDataEvent(event) {
122
- switch (event.type) {
123
- case "status":
124
- this.emit("status", event);
125
- break;
126
- case "metadata":
127
- this.emit("metadata", event);
128
- break;
129
- case "assistant_speaking_started":
130
- this.isAssistantSpeaking = true;
131
- this.emit("assistantStartedSpeaking");
132
- break;
133
- case "assistant_speaking_ended":
134
- this.isAssistantSpeaking = false;
135
- this.emit("assistantStoppedSpeaking");
136
- break;
137
- }
138
- }
139
- }