@trillet-ai/web-sdk 1.14.1 → 1.15.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.
@@ -476,6 +476,17 @@ var BrowserFingerprint = class {
476
476
  };
477
477
  BrowserFingerprint.cachedFingerprint = null;
478
478
 
479
+ // src/greetingSignal.ts
480
+ var GREETING_ATTRIBUTE = "trillet.greeting";
481
+ var NO_GREETING = "none";
482
+ function agentSkipsGreeting(participants) {
483
+ var _a;
484
+ for (const p of participants) {
485
+ if (p.identity.startsWith("agent") && ((_a = p.attributes) == null ? void 0 : _a[GREETING_ATTRIBUTE]) === NO_GREETING) return true;
486
+ }
487
+ return false;
488
+ }
489
+
479
490
  // src/index.tsx
480
491
  var FALLBACK_WS_URL = "wss://trillet-ai-xdx0dw5r.livekit.cloud";
481
492
  var decoder2 = new TextDecoder();
@@ -718,6 +729,7 @@ var TrilletAgent = class extends EventEmitter2 {
718
729
  roomName: roomDetails.room_name,
719
730
  display: roomDetails.display
720
731
  });
732
+ this.watchGreeting();
721
733
  } catch (error) {
722
734
  console.error("Trillet SDK Error (joinRoom):", error);
723
735
  this.emit("error", error instanceof Error ? error : new Error(String(error)));
@@ -843,6 +855,23 @@ var TrilletAgent = class extends EventEmitter2 {
843
855
  this.voiceEnabled = enabled;
844
856
  this.emit("modalityChanged", enabled ? "voice" : "text");
845
857
  }
858
+ /**
859
+ * Emit `greetingSkipped` once the agent says it will not greet (participant attribute
860
+ * `trillet.greeting=none`, TRI-2230), so a message held for the greeting can go now.
861
+ */
862
+ watchGreeting() {
863
+ const room = this.sdk.getRoom();
864
+ if (!room) return;
865
+ const check = () => {
866
+ if (!agentSkipsGreeting(room.remoteParticipants.values())) return;
867
+ room.off(RoomEvent2.ParticipantConnected, check);
868
+ room.off(RoomEvent2.ParticipantAttributesChanged, check);
869
+ this.emit("greetingSkipped");
870
+ };
871
+ room.on(RoomEvent2.ParticipantConnected, check);
872
+ room.on(RoomEvent2.ParticipantAttributesChanged, check);
873
+ check();
874
+ }
846
875
  /**
847
876
  * Resolve once the agent's session is ready to receive (its `lk.agent.state` has
848
877
  * moved past "initializing"), or reject after `timeoutMs`. Joining the room is not
@@ -916,4 +945,4 @@ export {
916
945
  BrowserFingerprint,
917
946
  TrilletAgent
918
947
  };
919
- //# sourceMappingURL=chunk-GUAIVASQ.js.map
948
+ //# sourceMappingURL=chunk-WSOSR3UF.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.tsx","../src/TrilletWebSDK.ts","../src/TranscriptManager.ts","../src/BrowserFingerprint.ts","../src/greetingSignal.ts"],"sourcesContent":["import { EventEmitter } from 'eventemitter3';\nimport { Participant, RoomEvent } from 'livekit-client';\nimport { TrilletWebSDK } from './TrilletWebSDK.js';\nimport { TranscriptManager, Transcript } from './TranscriptManager.js';\nimport { BrowserFingerprint } from './BrowserFingerprint.js';\nimport { createCall, apiUrl, TrilletRoomDetails } from './createCall.js';\nimport { agentSkipsGreeting } from './greetingSignal.js';\n\n// Export BrowserFingerprint for external use\nexport { BrowserFingerprint };\n\n// Shared room-details type (see ./createCall.ts). Re-exported so consumers can\n// import it from the package root as well as from the `/server` subpath.\nexport type { TrilletRoomDetails };\n\n// Fallback LiveKit cluster URL. Used only when the server response omits\n// connection.url — the server-provided url is always preferred.\nconst FALLBACK_WS_URL = 'wss://trillet-ai-xdx0dw5r.livekit.cloud';\n\nconst decoder = new TextDecoder();\n\n// Browser compatibility check\nconst isBrowser = typeof window !== 'undefined';\n// Safari iOS in private mode (and some proxy configs) returns isSecureContext=false\n// even on HTTPS. Fall back to protocol/hostname so we don't block valid contexts.\nconst isSecureContext =\n isBrowser &&\n (window.isSecureContext ||\n window.location.protocol === 'https:' ||\n window.location.hostname === 'localhost' ||\n window.location.hostname === '127.0.0.1');\n\nexport interface TrilletAgentConfig {\n // Direct authentication (not recommended for production)\n apiKey?: string;\n workspaceId?: string;\n\n // Required parameters\n agentId: string;\n variables?: Record<string, any>;\n callbackUrl?: string;\n /**\n * `voice` and `text` are single-modality sessions. `multimodal` is one conversation\n * the visitor can type in or talk in, switching any time with {@link setVoiceEnabled}.\n */\n mode?: 'voice' | 'text' | 'multimodal';\n /** Multimodal only: start with the microphone on (the visitor chose to call). */\n startWithVoice?: boolean;\n /** Override the API host (whitelabel API domain, or a local backend in development). */\n apiBaseUrl?: string;\n\n // Demo link tracking\n demoHash?: string; // Optional hash for demo link tracking\n\n /**\n * Pre-call gate. Awaited once at the top of every call-start path — before any\n * network request or LiveKit connection — so a rejection aborts the call cleanly\n * with nothing minted and nothing connected.\n *\n * Plug your own verification in here: a reCAPTCHA challenge you verify on your\n * server, a login check, a quota lookup. Throw (or reject) to block the call; the\n * error propagates to the caller and is emitted on the `error` event.\n *\n * @example\n * const agent = new TrilletAgent({\n * agentId,\n * onBeforeCall: async () => {\n * const ok = await myServer.verifyHuman();\n * if (!ok) throw new Error('Verification failed');\n * },\n * });\n */\n onBeforeCall?: () => Promise<void>;\n}\n\ninterface RpcInvocationData {\n requestId: string;\n callerIdentity: string;\n payload: any;\n responseTimeout: number;\n}\n\ninterface RpcMethodCall {\n method: string;\n payload: any;\n participant: any;\n}\n\nexport class TrilletAgent extends EventEmitter {\n private sdk: TrilletWebSDK;\n private config: TrilletAgentConfig;\n private sdkToken: string | null = null;\n private transcriptManager: TranscriptManager;\n\n constructor(config: TrilletAgentConfig) {\n super();\n\n // Validate environment\n if (!isBrowser) {\n throw new Error('Trillet SDK must be used in a browser environment');\n }\n\n if (!isSecureContext) {\n throw new Error('Trillet SDK requires a secure context (HTTPS or localhost)');\n }\n\n if (!config.agentId) {\n throw new Error('agentId is required');\n }\n\n this.config = {\n ...config,\n mode: config.mode || 'voice', // Default to voice mode\n };\n\n this.sdk = new TrilletWebSDK();\n this.transcriptManager = new TranscriptManager();\n this.setupEventForwarding();\n }\n\n private setupEventForwarding(): void {\n // Forward all SDK events to agent listeners\n this.sdk.on('disconnected', () => {\n // A new call always starts unmuted.\n this.muted = false;\n this.emit('disconnected');\n });\n this.sdk.on('error', (error) => this.emit('error', error));\n this.sdk.on('status', (status) => this.emit('status', status));\n this.sdk.on('metadata', (metadata) => this.emit('metadata', metadata));\n this.sdk.on('assistantStartedSpeaking', () => this.emit('assistantStartedSpeaking'));\n this.sdk.on('assistantStoppedSpeaking', () => this.emit('assistantStoppedSpeaking'));\n this.sdk.on('audioData', (data) => this.emit('audioData', data));\n this.sdk.on('krispStatus', (status) => this.emit('krispStatus', status));\n\n // Handle incoming tool usage from the agent\n this.sdk.on('toolStarted', (toolCall: { name: string; args: any }) => {\n this.transcriptManager.addToolStarted(toolCall);\n this.emit('toolStarted', toolCall);\n this.emit('transcriptUpdate', this.transcriptManager.getLiveTranscripts());\n });\n\n this.sdk.on('toolCompleted', (toolResult: { name: string; result: any; isError: boolean }) => {\n this.transcriptManager.addToolCompleted(toolResult);\n this.emit('toolCompleted', toolResult);\n this.emit('transcriptUpdate', this.transcriptManager.getLiveTranscripts());\n });\n\n this.sdk.on('transcript', (transcriptData: { text: string; isFinal: boolean }, participant: Participant) => {\n const participantId = participant.identity;\n // The agent echoes the visitor's own typed turns back as transcription, and\n // sendTextMessage already added them. Text mode: skip every echo. Multimodal:\n // the visitor's SPOKEN turns arrive the same way and must stay, so only skip an\n // echo that matches something just typed.\n if (participantId === this.sdk.getRoom()?.localParticipant.identity) {\n if (this.config.mode === 'text') return;\n if (this.config.mode === 'multimodal') {\n const now = Date.now();\n this.recentTyped = this.recentTyped.filter((t) => now - t.at < 15000);\n const typed = transcriptData.text.trim();\n const match = this.recentTyped.findIndex((t) => t.text === typed || t.text.startsWith(typed));\n if (match !== -1) {\n if (transcriptData.isFinal) this.recentTyped.splice(match, 1);\n return;\n }\n }\n }\n const isAgent = participantId.startsWith('agent');\n\n const updated = this.transcriptManager.handleTranscript(participantId, isAgent, transcriptData);\n if (updated) {\n this.emit('transcriptUpdate', this.transcriptManager.getLiveTranscripts());\n }\n });\n\n // Handle incoming text messages from the agent\n this.sdk.on('message', (message: { text: string; [key: string]: any }) => {\n const agentParticipant = Array.from(this.sdk.getRoom()?.remoteParticipants.values() ?? []).find((p) => p.identity.startsWith('agent'));\n this.transcriptManager.addMessage('assistant', message.text, agentParticipant?.identity);\n this.emit('message', message);\n this.emit('transcriptUpdate', this.transcriptManager.getLiveTranscripts());\n });\n }\n\n /**\n * Set up default RPC handlers for common agent interactions\n * This should be called after connection is established\n */\n private setupDefaultRpcHandlers(): void {\n // Register handler for receiving chat messages from agent\n this.registerRpcMethod('receiveChatMessage', async (data: any) => {\n const messageText = typeof data.payload === 'string' ? data.payload : data.payload?.text || '';\n \n if (messageText) {\n const agentParticipant = Array.from(this.sdk.getRoom()?.remoteParticipants.values() ?? []).find((p) =>\n p.identity.startsWith('agent')\n );\n \n this.transcriptManager.addMessage('assistant', messageText, agentParticipant?.identity);\n \n this.emit('message', { text: messageText });\n this.emit('transcriptUpdate', this.transcriptManager.getLiveTranscripts());\n }\n \n return 'Message received';\n });\n\n // Register handler for agent status updates\n this.registerRpcMethod('agentStatus', async (data: any) => {\n this.emit('status', data.payload);\n return 'Status received';\n });\n }\n\n /**\n * **Server-side only — requires an API key, do not call from the browser.**\n *\n * Puts a full-privilege `X-API-KEY` on the request, so this must run where the\n * key is safe. For the secure pattern, mint the room on your backend with\n * `createCall` (from `@trillet-ai/web-sdk/server`) and call {@link joinRoom} in\n * the browser instead. Kept for backward compatibility.\n */\n public async startCall(): Promise<void> {\n // Gate first: a rejection here must cost nothing — no room minted, no connection.\n await this.runBeforeCall();\n\n let data: TrilletRoomDetails;\n try {\n // Performs the authenticated POST /v1/api/web-call and returns room details\n // keyed off `connection`. Shared with the `/server` createCall export.\n data = await createCall({\n apiKey: this.config.apiKey!,\n agentId: this.config.agentId,\n mode: this.config.mode,\n variables: this.config.variables,\n callbackUrl: this.config.callbackUrl,\n apiBaseUrl: this.config.apiBaseUrl,\n });\n } catch (error) {\n console.error('Trillet SDK Error:', error);\n this.emit('error', error instanceof Error ? error : new Error(String(error)));\n throw error;\n }\n\n // connectToRoom owns its own error emission + rethrow. Called instead of the\n // public joinRoom so onBeforeCall is not run a second time.\n await this.connectToRoom(data);\n }\n\n public async startPublicCall(): Promise<void> {\n // Gate first: a rejection here must cost nothing — no room minted, no connection.\n await this.runBeforeCall();\n\n let data: TrilletRoomDetails;\n try {\n // Generate browser fingerprint before making the call.\n // Non-fatal: if it fails (Safari iOS quirks with crypto.subtle / canvas.toDataURL\n // in private mode or restricted contexts), fall back to null so the fetch still\n // happens. Backend's per-user limit tracking degrades gracefully.\n let browserFingerprint: string | null = null;\n try {\n browserFingerprint = await BrowserFingerprint.generate();\n } catch (fpError) {\n console.warn('Trillet SDK: fingerprint generation failed, proceeding without it', fpError);\n }\n\n // 2. Initialize public call\n const response = await fetch(apiUrl('/v1/api/web-call/public', this.config.apiBaseUrl), {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n 'x-workspace-id': this.config.workspaceId!,\n },\n body: JSON.stringify({\n call_agent_id: this.config.agentId,\n mode: this.config.mode,\n ...(this.config.mode === 'multimodal'\n ? { initial_modality: this.config.startWithVoice ? 'voice' : 'text' }\n : {}),\n dynamic_variables: this.config.variables || {},\n callback_url: this.config.callbackUrl,\n browser_fingerprint: browserFingerprint,\n demo_hash: this.config.demoHash, // Send demo hash if provided\n }),\n });\n\n if (!response.ok) {\n let errorMessage;\n try {\n const errorData = await response.json();\n errorMessage = errorData.message || errorData.error || 'Unknown error';\n } catch {\n errorMessage = await response.text();\n }\n throw new Error(`API Error: ${errorMessage}`);\n }\n\n data = await response.json();\n } catch (error) {\n console.error('Trillet SDK Error (public call):', error);\n this.emit('error', error instanceof Error ? error : new Error(String(error)));\n throw error;\n }\n\n // Key off the `connection` object (consistent across both endpoints) rather\n // than the inconsistent top-level token/roomName fields. connectToRoom owns its\n // own error emission + rethrow, and skips the already-run onBeforeCall gate.\n await this.connectToRoom(data);\n }\n\n /**\n * Connect to a pre-minted Trillet room. The secure browser entry point: takes\n * the room details returned by `createCall` (server-side) and joins LiveKit\n * directly — makes NO Trillet API call, so no API key, workspaceId or agentId\n * ever reaches the browser.\n *\n * @param roomDetails - the backend response, e.g. `{ connection: { url, token }, ... }`\n */\n public async joinRoom(roomDetails: TrilletRoomDetails): Promise<void> {\n await this.runBeforeCall();\n await this.connectToRoom(roomDetails);\n }\n\n /**\n * Run the caller's pre-call gate, if any.\n *\n * Invoked by each public call-start path exactly once. `startCall` and\n * `startPublicCall` therefore delegate to {@link connectToRoom} rather than to the\n * public {@link joinRoom} — routing them through `joinRoom` would fire a customer's\n * hook a second time per call, re-running their challenge or verification request.\n */\n private async runBeforeCall(): Promise<void> {\n if (!this.config.onBeforeCall) return;\n\n try {\n await this.config.onBeforeCall();\n } catch (error) {\n console.error('Trillet SDK Error (onBeforeCall):', error);\n this.emit('error', error instanceof Error ? error : new Error(String(error)));\n throw error;\n }\n }\n\n /** Join LiveKit. Assumes the pre-call gate has already run. */\n private async connectToRoom(roomDetails: TrilletRoomDetails): Promise<void> {\n try {\n const connection = roomDetails?.connection;\n if (!connection?.token) {\n throw new Error('Invalid room details: missing connection token');\n }\n\n // Prefer the server-provided WebSocket URL; fall back to the cluster default\n // only when it is missing.\n const wsUrl = connection.url || FALLBACK_WS_URL;\n\n await this.sdk.initializeCall({\n token: connection.token,\n wsUrl,\n mode: this.config.mode,\n startWithVoice: this.config.startWithVoice,\n audioSettings: {\n sampleRate: 48000,\n },\n features: {\n enableRawAudio: this.config.mode !== 'text',\n // Krisp AI noise cancellation on the local mic for voice calls — cleaner\n // input to STT in noisy environments. Emits `krispStatus` (TRI-629).\n enableKrispNoiseFilter: this.config.mode !== 'text',\n },\n });\n this.voiceEnabled =\n this.config.mode === 'voice' || (this.config.mode === 'multimodal' && Boolean(this.config.startWithVoice));\n\n // Audio playback for anything that can speak. Must run inside the visitor's\n // click (browsers block autoplay), which is why multimodal starts it up front.\n if (this.config.mode !== 'text') {\n await this.sdk.enableAudioPlayback();\n }\n\n // Set up default RPC handlers for text communication\n this.setupDefaultRpcHandlers();\n\n // Emit connection details, guarding fields that may be undefined.\n this.emit('connected', {\n callId: roomDetails.call_id,\n roomName: roomDetails.room_name,\n display: roomDetails.display,\n });\n // After 'connected', so a listener holding a message is already live.\n this.watchGreeting();\n } catch (error) {\n console.error('Trillet SDK Error (joinRoom):', error);\n this.emit('error', error instanceof Error ? error : new Error(String(error)));\n throw error;\n }\n }\n\n public endCall(): void {\n this.sdk.endCall();\n }\n\n public toggleMicrophone(enabled: boolean): void {\n this.sdk.toggleMicrophone(enabled);\n this.updateMuted(!enabled);\n }\n\n private muted = false;\n\n /** True while the visitor's microphone is muted on a live voice call. */\n public get isMuted(): boolean {\n return this.muted;\n }\n\n /**\n * Mute or unmute the visitor's microphone and wait for LiveKit to apply it.\n * Emits `muteChanged` (boolean). A no-op when no call is connected.\n */\n public async setMuted(muted: boolean): Promise<void> {\n if (!this.sdk.isConnected) return;\n await this.sdk.setMicrophone(!muted);\n this.updateMuted(muted);\n }\n\n private updateMuted(muted: boolean): void {\n if (this.muted === muted) return;\n this.muted = muted;\n this.emit('muteChanged', muted);\n }\n\n public get isAssistantSpeaking(): boolean {\n return this.sdk.isAssistantSpeaking;\n }\n\n /** The settled record: finals only. */\n public getTranscripts(): Transcript[] {\n return this.transcriptManager.getTranscripts();\n }\n\n /** Finals plus speech still in progress, the same list `transcriptUpdate` carries. */\n public getLiveTranscripts(): Transcript[] {\n return this.transcriptManager.getLiveTranscripts();\n }\n\n public getCurrentTranscript(): { [key: string]: string } {\n return this.transcriptManager.getCurrentTranscript();\n }\n\n /**\n * Register an RPC method handler for receiving calls from the agent\n * @param method - The RPC method name to handle\n * @param handler - The function to handle the RPC call\n */\n public registerRpcMethod(method: string, handler: (data: any) => Promise<any> | any): void {\n const room = this.sdk.getRoom();\n if (!room) {\n console.warn('Cannot register RPC method: not connected to room');\n return;\n }\n\n room.localParticipant.registerRpcMethod(method, async (data: any) => {\n try {\n const result = await handler(data);\n return result;\n } catch (error) {\n console.error(`RPC method ${method} error:`, error);\n throw error;\n }\n });\n }\n\n /**\n * Send an RPC call to the agent\n * @param method - The RPC method name\n * @param payload - The data to send\n * @param responseTimeout - Timeout in milliseconds (default: 30000)\n */\n public async sendRpcMessage(method: string, payload: any, responseTimeout: number = 30000): Promise<any> {\n const room = this.sdk.getRoom();\n if (!room || !this.sdk.isConnected) {\n throw new Error('Not connected. Cannot send RPC message.');\n }\n\n const agentParticipant = Array.from(room.remoteParticipants.values()).find((p) =>\n p.identity.startsWith('agent')\n );\n\n if (!agentParticipant) {\n throw new Error('No agent found to send RPC message to.');\n }\n\n try {\n const response = await room.localParticipant.performRpc({\n destinationIdentity: agentParticipant.identity,\n method,\n payload,\n responseTimeout,\n });\n return response;\n } catch (error) {\n console.error(`RPC call to method ${method} failed:`, error);\n throw error;\n }\n }\n\n private voiceEnabled = false;\n // Typed messages the agent will echo back as transcription; see the transcript handler.\n private recentTyped: { text: string; at: number }[] = [];\n\n /** Multimodal: whether the microphone/voice side is currently on. */\n public get isVoiceEnabled(): boolean {\n return this.voiceEnabled;\n }\n\n /**\n * Multimodal only: switch the SAME conversation between typing and talking. Turns\n * the mic on/off and tells the agent, which turns its speech on/off and keeps the\n * whole conversation in context. Emits `modalityChanged` with 'voice' | 'text'.\n */\n public async setVoiceEnabled(enabled: boolean): Promise<void> {\n if (this.config.mode !== 'multimodal') {\n console.warn('setVoiceEnabled is only available in multimodal mode.');\n return;\n }\n const room = this.sdk.getRoom();\n if (!room || !this.sdk.isConnected) throw new Error('Not connected.');\n if (enabled === this.voiceEnabled) return;\n\n // Mic first: if permission is refused, the agent never switches and the\n // conversation stays in text.\n await this.sdk.setMicrophone(enabled);\n if (enabled) await this.sdk.enableAudioPlayback();\n try {\n // The agent can still be joining (a switch tapped in the first seconds).\n await this.waitForAgent(15000);\n await this.sendRpcMessage('trillet.set_modality', JSON.stringify({ mode: enabled ? 'voice' : 'text' }), 8000);\n } catch (error) {\n await this.sdk.setMicrophone(!enabled).catch(() => undefined);\n throw error;\n }\n this.voiceEnabled = enabled;\n this.emit('modalityChanged', enabled ? 'voice' : 'text');\n }\n\n /**\n * Emit `greetingSkipped` once the agent says it will not greet (participant attribute\n * `trillet.greeting=none`, TRI-2230), so a message held for the greeting can go now.\n */\n private watchGreeting(): void {\n const room = this.sdk.getRoom();\n if (!room) return;\n const check = (): void => {\n if (!agentSkipsGreeting(room.remoteParticipants.values())) return;\n room.off(RoomEvent.ParticipantConnected, check);\n room.off(RoomEvent.ParticipantAttributesChanged, check);\n this.emit('greetingSkipped');\n };\n room.on(RoomEvent.ParticipantConnected, check);\n room.on(RoomEvent.ParticipantAttributesChanged, check);\n check();\n }\n\n /**\n * Resolve once the agent's session is ready to receive (its `lk.agent.state` has\n * moved past \"initializing\"), or reject after `timeoutMs`. Joining the room is not\n * enough: a text message sent before the session listens is silently dropped.\n */\n private waitForAgent(timeoutMs: number): Promise<void> {\n const room = this.sdk.getRoom();\n const ready = () =>\n Array.from(room?.remoteParticipants.values() ?? []).some((p) => {\n if (!p.identity.startsWith('agent')) return false;\n const state = p.attributes?.['lk.agent.state'];\n // Older agents never set the attribute: being present is the best signal.\n return !state || state !== 'initializing';\n });\n if (!room || ready()) return Promise.resolve();\n return new Promise((resolve, reject) => {\n const done = (ok: boolean) => {\n clearTimeout(timer);\n room.off(RoomEvent.ParticipantConnected, check);\n room.off(RoomEvent.ParticipantAttributesChanged, check);\n if (ok) resolve();\n else reject(new Error('The agent is not ready yet. Please try again.'));\n };\n const check = () => {\n if (ready()) done(true);\n };\n const timer = setTimeout(() => done(ready()), timeoutMs);\n room.on(RoomEvent.ParticipantConnected, check);\n room.on(RoomEvent.ParticipantAttributesChanged, check);\n });\n }\n\n public async sendTextMessage(text: string): Promise<void> {\n if (this.config.mode === 'voice') {\n console.warn('Cannot send text message in voice mode.');\n return;\n }\n\n const room = this.sdk.getRoom();\n if (!room || !this.sdk.isConnected) {\n this.emit('error', new Error('Not connected. Cannot send message.'));\n return;\n }\n\n // Text streams only reach participants already in the room, so a message sent\n // before the agent joins would be lost.\n try {\n await this.waitForAgent(30000);\n } catch (error) {\n this.emit('error', error instanceof Error ? error : new Error(String(error)));\n return;\n }\n\n // Add user message to transcripts immediately\n this.transcriptManager.addMessage('user', text, room.localParticipant.identity);\n this.recentTyped.push({ text: text.trim(), at: Date.now() });\n this.emit('transcriptUpdate', this.transcriptManager.getLiveTranscripts());\n\n // Send the text message using LiveKit's sendText API with topic 'lk.chat'.\n try {\n await room.localParticipant.sendText(text, { topic: 'lk.chat' });\n console.log('Text message sent to agent:', text);\n } catch (error) {\n console.error('Failed to send text message:', error);\n this.emit('error', new Error(`Failed to send message: ${error instanceof Error ? error.message : String(error)}`));\n }\n }\n\n /**\n * Get the browser fingerprint for this session\n * Useful for demo pages to send fingerprint when checking limits\n */\n public async getBrowserFingerprint(): Promise<string> {\n return await BrowserFingerprint.generate();\n }\n}\n","import { EventEmitter } from 'eventemitter3';\nimport { RemoteParticipant, RemoteTrack, RemoteAudioTrack, RemoteTrackPublication, Room, RoomEvent, Track, createAudioAnalyser, Participant, LocalAudioTrack } from 'livekit-client';\nimport type { KrispNoiseFilterProcessor } from '@livekit/krisp-noise-filter';\n\nconst decoder = new TextDecoder();\n\nexport interface TrilletCallConfig {\n token: string;\n wsUrl: string; // LiveKit WebSocket URL\n audioSettings?: {\n sampleRate?: number;\n inputDeviceId?: string; // Device ID for audio input\n outputDeviceId?: string; // Device ID for audio output\n };\n mode?: 'voice' | 'text' | 'multimodal';\n /** Multimodal sessions: turn the microphone on at connect (visitor chose Call). */\n startWithVoice?: boolean;\n features?: {\n enableRawAudio?: boolean; // Enable raw audio sampling for visualizations\n enableKrispNoiseFilter?: boolean; // Enable Krisp AI noise cancellation for local microphone\n };\n}\n\n// Internal SDK class\nexport class TrilletWebSDK extends EventEmitter {\n private room: Room | undefined;\n public isConnected: boolean = false;\n\n // Audio state tracking\n public isAssistantSpeaking: boolean = false;\n\n // Audio analysis tools\n public audioAnalyzer?: {\n calculateVolume: () => number;\n analyser: AnalyserNode;\n cleanup: () => Promise<void>;\n };\n\n // Krisp noise filter processor\n private krispProcessor?: KrispNoiseFilterProcessor;\n\n private audioFrameCapture: number | undefined;\n\n constructor() {\n super();\n }\n\n public async initializeCall(config: TrilletCallConfig): Promise<void> {\n try {\n this.room = new Room({\n audioCaptureDefaults: {\n autoGainControl: true,\n echoCancellation: true,\n noiseSuppression: true,\n channelCount: 1,\n deviceId: config.audioSettings?.inputDeviceId,\n sampleRate: config.audioSettings?.sampleRate,\n },\n audioOutput: {\n deviceId: config.audioSettings?.outputDeviceId,\n },\n });\n\n this.setupEventHandlers(config);\n\n this.room.prepareConnection(config.wsUrl, config.token);\n await this.room.connect(config.wsUrl, config.token);\n console.log('Connected to Trillet room:', this.room.name);\n\n this.krispWanted = Boolean(config.features?.enableKrispNoiseFilter);\n const micAtStart = config.mode === 'voice' || (config.mode === 'multimodal' && config.startWithVoice);\n if (micAtStart) {\n await this.setMicrophone(true);\n }\n this.isConnected = true;\n this.emit('connected');\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Failed to initialize call';\n this.emit('error', errorMessage);\n console.error('Call initialization failed:', error);\n this.endCall();\n throw error; // Re-throw to let TrilletAgent handle it\n }\n }\n\n public async enableAudioPlayback(): Promise<void> {\n await this.room?.startAudio();\n }\n\n /**\n * Tear the call down. Safe to call at any point, including while the call is\n * still coming up, and safe to call twice.\n *\n * This used to open with `if (!this.isConnected) return`, which made it do\n * nothing in exactly the window where it mattered most. `isConnected` is only\n * set at the very end of initializeCall, after `await setMicrophone(true)`\n * has waited on mic permission, the track publish and Krisp — seconds,\n * sometimes. The room is live well before that: connect() has resolved, the\n * agent is hearing audio, transcripts are streaming and the call is\n * recording. Callers offer an End Call button from the moment the agent\n * speaks, so pressing it there returned early and left the room up: mic still\n * published, recording still running, over a UI that said the call had ended\n * (TRI-1666).\n *\n * Re-entrancy is what that guard was really buying, since `room.disconnect()`\n * fires RoomEvent.Disconnected which calls straight back in here. That is now\n * an explicit flag rather than a side effect of the connection state.\n */\n public endCall(): void {\n if (this.ending) return;\n this.ending = true;\n\n const wasConnected = this.isConnected;\n const room = this.room;\n this.isConnected = false;\n this.room = undefined;\n\n // Only announce a drop to listeners that saw the call come up. Ending during\n // connect is something the caller already knows about, and firing here would\n // surprise UI that never showed a live call.\n if (wasConnected) this.emit('disconnected');\n room?.disconnect();\n\n this.isAssistantSpeaking = false;\n\n if (this.audioAnalyzer) {\n this.audioAnalyzer.cleanup();\n this.audioAnalyzer = undefined;\n }\n\n if (this.audioFrameCapture) {\n cancelAnimationFrame(this.audioFrameCapture);\n this.audioFrameCapture = undefined;\n }\n\n // Cleanup Krisp processor\n if (this.krispProcessor) {\n this.krispProcessor = undefined;\n }\n\n this.ending = false;\n }\n\n /** Guards endCall against the re-entry its own room.disconnect() causes. */\n private ending = false;\n\n private krispWanted = false;\n\n /**\n * Turn the microphone on or off and wait for it. Used for a multimodal session's\n * switch to and from voice; Krisp is attached the first time the mic comes on.\n */\n public async setMicrophone(enabled: boolean): Promise<void> {\n if (!this.room) return;\n await this.room.localParticipant.setMicrophoneEnabled(enabled);\n if (enabled && this.krispWanted && !this.krispProcessor) {\n await this.setupKrispNoiseFilter();\n }\n }\n\n public toggleMicrophone(enabled: boolean): void {\n if (this.isConnected && this.room) {\n this.room.localParticipant.setMicrophoneEnabled(enabled);\n }\n }\n\n private async setupKrispNoiseFilter(): Promise<void> {\n if (!this.room) return;\n\n try {\n // Dynamically import Krisp noise filter\n const { KrispNoiseFilter, isKrispNoiseFilterSupported } = await import('@livekit/krisp-noise-filter');\n\n // Check browser compatibility\n if (!isKrispNoiseFilterSupported()) {\n console.warn('Krisp noise filter is not supported on this browser');\n this.emit('krispStatus', { enabled: false, supported: false });\n return;\n }\n\n // Get the local microphone track\n const microphoneTrack = this.room.localParticipant.getTrackPublication(Track.Source.Microphone)?.track;\n\n if (microphoneTrack && microphoneTrack instanceof LocalAudioTrack) {\n // Initialize the Krisp processor\n this.krispProcessor = KrispNoiseFilter();\n await microphoneTrack.setProcessor(this.krispProcessor);\n\n // Enable the noise filter\n await this.krispProcessor.setEnabled(true);\n console.log('Krisp noise filter enabled successfully');\n this.emit('krispStatus', { enabled: true, supported: true });\n } else {\n console.warn('Could not find local microphone track to apply Krisp filter');\n this.emit('krispStatus', { enabled: false, supported: true });\n }\n } catch (error) {\n console.error('Failed to setup Krisp noise filter:', error);\n this.emit('krispStatus', { enabled: false, supported: false });\n }\n }\n\n private captureAudio(): void {\n if (!this.isConnected || !this.audioAnalyzer) return;\n\n const bufferSize = this.audioAnalyzer.analyser.fftSize;\n const audioData = new Float32Array(bufferSize);\n this.audioAnalyzer.analyser.getFloatTimeDomainData(audioData);\n this.emit('audioData', audioData);\n\n this.audioFrameCapture = requestAnimationFrame(() => this.captureAudio());\n }\n\n private setupEventHandlers(config: TrilletCallConfig): void {\n let wasAgentSpeaking = false;\n if (!this.room) return;\n\n // Room events\n this.room.on(RoomEvent.ParticipantDisconnected, (participant: RemoteParticipant) => {\n if (participant?.identity === 'assistant') {\n this.endCall();\n }\n });\n\n // Unconditional: a drop before `isConnected` flips still needs tearing down,\n // and endCall() is now re-entrancy-safe on its own (TRI-1666).\n this.room.on(RoomEvent.Disconnected, () => {\n this.endCall();\n });\n\n // Chunks are read as they arrive so text replies render progressively (partials).\n // Finality is `lk.transcription_final` read after close: agent segments carry it in\n // the trailer (merged into info), while each visitor interim is its own `false` stream.\n this.room.registerTextStreamHandler('lk.transcription', async (reader, info) => {\n if (!info) return;\n const participant = this.room?.getParticipantByIdentity(info.identity);\n if (!participant) return;\n\n let text = '';\n // Default false, not true: a stream that throws mid-read skips the read below,\n // and finalising it would push an interim as its own message — the very bug\n // this handler exists to stop. An agent segment lost that way is recovered by\n // the next one, and the duplicate guard in TranscriptManager covers a repeat.\n let isFinal = false;\n try {\n for await (const chunk of reader) {\n text += chunk;\n if (text.trim()) this.emit('transcript', { text, isFinal: false }, participant);\n }\n isFinal = reader.info?.attributes?.['lk.transcription_final'] === 'true';\n } catch (error) {\n console.warn('Trillet SDK: transcription stream ended early', error);\n }\n this.emit('transcript', { text, isFinal }, participant);\n });\n\n // Audio events\n this.room.on(RoomEvent.TrackSubscribed, (track: RemoteTrack, publication: RemoteTrackPublication) => {\n if (track.kind === Track.Kind.Audio) {\n if (publication.trackName === 'assistant_audio' && track instanceof RemoteAudioTrack && config.features?.enableRawAudio) {\n const analyzer = createAudioAnalyser(track);\n this.audioAnalyzer = {\n calculateVolume: analyzer.calculateVolume,\n analyser: analyzer.analyser,\n cleanup: analyzer.cleanup,\n };\n this.audioFrameCapture = requestAnimationFrame(() => this.captureAudio());\n }\n track.attach();\n }\n });\n\n // Data events\n this.room.on(RoomEvent.DataReceived, (payload: Uint8Array, participant?: RemoteParticipant) => {\n if (!participant?.identity.startsWith('agent')) return;\n\n try {\n const data = JSON.parse(decoder.decode(payload));\n this.handleDataEvent(data, participant);\n } catch (error) {\n console.error('Failed to process received data:', error);\n }\n });\n\n this.room.on(RoomEvent.ActiveSpeakersChanged, (speakers: Participant[]) => {\n const isAgentSpeaking = speakers.some((p) => p.identity.startsWith('agent'));\n\n if (isAgentSpeaking && !wasAgentSpeaking) {\n this.emit('assistantStartedSpeaking');\n } else if (!isAgentSpeaking && wasAgentSpeaking) {\n this.emit('assistantStoppedSpeaking');\n }\n\n wasAgentSpeaking = isAgentSpeaking;\n });\n\n // Handle RPC events if available\n // Note: LiveKit may not have specific RPC events, but we can monitor participant events\n this.room.on(RoomEvent.ParticipantConnected, (participant: RemoteParticipant) => {\n console.log('Participant connected:', participant.identity);\n if (participant.identity.startsWith('agent')) {\n console.log('Agent connected, RPC communication available');\n }\n });\n }\n\n private handleDataEvent(event: any, participant: RemoteParticipant): void {\n switch (event.type) {\n case 'status':\n this.emit('status', event);\n break;\n case 'metadata':\n this.emit('metadata', event);\n break;\n case 'transcript':\n // this is for agent-generated transcripts, which we are overriding with lk.transcription\n // this.emit('transcript', event.data, participant);\n break;\n case 'llm_call':\n this.emit('toolStarted', { name: event.name, args: event.arguments });\n break;\n case 'llm_call_response':\n this.emit('toolCompleted', {\n name: event.details.api_name,\n result: event.details.api_response,\n isError: event.details.status >= 400,\n });\n break;\n case 'error':\n this.emit('toolCompleted', {\n name: event.name,\n result: event.details,\n isError: true,\n });\n break;\n case 'assistant_speaking_started':\n this.isAssistantSpeaking = true;\n this.emit('assistantStartedSpeaking');\n break;\n case 'assistant_speaking_ended':\n this.isAssistantSpeaking = false;\n this.emit('assistantStoppedSpeaking');\n break;\n case 'agent_message':\n this.emit('message', event);\n break;\n }\n }\n\n public getRoom(): Room | undefined {\n return this.room;\n }\n} ","export interface ToolUsed {\n name: string;\n args?: any;\n status?: 'pending' | 'success' | 'error';\n}\n\nexport interface Transcript {\n role: 'user' | 'assistant';\n text: string;\n isFinal: boolean;\n timestamp: Date;\n participantId?: string;\n toolUsed?: ToolUsed;\n}\n\n/** Speech still arriving from one participant: no message exists for it yet. */\ninterface ActivePartial {\n text: string;\n isAgent: boolean;\n timestamp: Date;\n}\n\nexport class TranscriptManager {\n private transcripts: Transcript[] = [];\n private currentTranscript: { [key: string]: ActivePartial } = {};\n\n /** The settled record: finals only, and what call history and host pages are given. */\n public getTranscripts(): Transcript[] {\n return this.transcripts;\n }\n\n /** The text-only shape this has always returned. Renderers want getLiveTranscripts(). */\n public getCurrentTranscript(): { [key: string]: string } {\n const out: { [key: string]: string } = {};\n for (const participantId of Object.keys(this.currentTranscript)) {\n out[participantId] = this.currentTranscript[participantId].text;\n }\n return out;\n }\n\n /**\n * What a renderer should draw: the finals, then whatever is still being said, as a\n * non-final entry per speaker (TRI-1748).\n *\n * `transcriptUpdate` fires on every interim, but it used to carry getTranscripts(),\n * which holds finals only. So the event said \"something changed\" while its payload\n * had not, and each renderer had to reach into getCurrentTranscript() itself. The\n * widget did that for the agent alone and the demo page not at all, which is why a\n * visitor's own speech streamed nowhere. Carrying the partials here is what makes a\n * renderer stream by default rather than by remembering a side channel.\n */\n public getLiveTranscripts(): Transcript[] {\n const live: Transcript[] = [...this.transcripts];\n for (const participantId of Object.keys(this.currentTranscript)) {\n const partial = this.currentTranscript[participantId];\n const text = partial.text.trim();\n // Whitespace between words is not a message; drawing it flashes an empty bubble.\n if (!text) continue;\n live.push({\n role: partial.isAgent ? 'assistant' : 'user',\n text,\n isFinal: false,\n timestamp: partial.timestamp,\n participantId,\n });\n }\n return live;\n }\n\n public addToolStarted(toolCall: { name: string; args: any }): void {\n this.transcripts.push({\n role: 'assistant',\n text: `Using tool: ${toolCall.name}`,\n isFinal: true,\n timestamp: new Date(),\n toolUsed: { ...toolCall, status: 'pending' },\n });\n }\n\n public addToolCompleted(toolResult: { name: string; result: any; isError: boolean }): void {\n const toolTranscriptIndex = this.transcripts.map((t) => t.toolUsed?.name === toolResult.name && t.toolUsed?.status === 'pending').lastIndexOf(true);\n if (toolTranscriptIndex > -1) {\n const toolTranscript = this.transcripts[toolTranscriptIndex];\n if (toolTranscript && toolTranscript.toolUsed) {\n toolTranscript.toolUsed.status = toolResult.isError ? 'error' : 'success';\n }\n }\n }\n\n public handleTranscript(participantId: string, isAgent: boolean, transcriptData: { text: string; isFinal: boolean }): boolean {\n if (transcriptData.isFinal) {\n const hadPartial = participantId in this.currentTranscript;\n delete this.currentTranscript[participantId];\n\n const text = transcriptData.text.trim();\n // An empty final still clears a visible partial, so report that as a change.\n if (!text) return hadPartial;\n\n // Check for duplicates\n const lastMessage = this.transcripts[this.transcripts.length - 1];\n if (lastMessage && lastMessage.text === text && lastMessage.participantId === participantId && Date.now() - lastMessage.timestamp.getTime() < 1000) {\n return hadPartial;\n }\n\n this.transcripts.push({\n role: isAgent ? 'assistant' : 'user',\n text,\n isFinal: true,\n timestamp: new Date(),\n participantId,\n });\n } else {\n // Keep the first timestamp while a partial grows, so it does not jump about\n // if a renderer ever orders by time.\n const existing = this.currentTranscript[participantId];\n this.currentTranscript[participantId] = {\n text: transcriptData.text,\n isAgent,\n timestamp: existing ? existing.timestamp : new Date(),\n };\n }\n return true;\n }\n\n public addMessage(role: 'user' | 'assistant', text: string, participantId?: string) {\n this.transcripts.push({\n role,\n text,\n isFinal: true,\n timestamp: new Date(),\n participantId,\n });\n }\n} ","/**\r\n * Browser Fingerprinting Utility\r\n * Generates a deterministic fingerprint based on stable browser/hardware characteristics.\r\n * Used for demo link usage limit tracking.\r\n *\r\n * Strategy:\r\n * 1. localStorage persistence — generate once, reuse across tabs/sessions forever\r\n * 2. Stable hardware-only seed — if storage is cleared, the same hardware signals\r\n * produce the same hash, so the fingerprint stays consistent\r\n * 3. Server-side IP fallback — handled by the backend when no fingerprint is sent\r\n */\r\n\r\nconst STORAGE_KEY = 'trillet_dfp';\r\n\r\nexport class BrowserFingerprint {\r\n private static cachedFingerprint: string | null = null;\r\n\r\n /**\r\n * Generate (or retrieve) a deterministic browser fingerprint.\r\n * Cached in memory → localStorage → derived from stable hardware signals.\r\n */\r\n public static async generate(): Promise<string> {\r\n // 1. In-memory cache (fastest)\r\n if (this.cachedFingerprint) {\r\n return this.cachedFingerprint;\r\n }\r\n\r\n // 2. Persisted in localStorage (survives tab close / browser restart)\r\n const stored = this.getStored();\r\n if (stored) {\r\n this.cachedFingerprint = stored;\r\n return stored;\r\n }\r\n\r\n // 3. Derive from stable hardware signals and persist\r\n const signals = this.getStableSignals();\r\n const fingerprint = await this.hashComponents(signals);\r\n\r\n this.persist(fingerprint);\r\n this.cachedFingerprint = fingerprint;\r\n\r\n return fingerprint;\r\n }\r\n\r\n /**\r\n * Collect only hardware / environment signals that do NOT change between\r\n * tabs, sessions, or browser restarts on the same device.\r\n *\r\n * Deliberately excluded (volatile / anti-fingerprint randomised):\r\n * - canvas.toDataURL() — randomised per origin in many browsers\r\n * - font detection — noisy across rendering states\r\n * - screen.availWidth/Height — changes with taskbar / dock resize\r\n * - navigator.doNotTrack — user can toggle\r\n * - timezoneOffset — changes with DST\r\n * - navigator.userAgent — changes on browser update\r\n */\r\n private static getStableSignals(): Record<string, unknown> {\r\n return {\r\n // Hardware — fixed for a given device\r\n screen: {\r\n width: window.screen.width,\r\n height: window.screen.height,\r\n colorDepth: window.screen.colorDepth,\r\n pixelRatio: window.devicePixelRatio,\r\n },\r\n hardwareConcurrency: navigator.hardwareConcurrency,\r\n deviceMemory: (navigator as any).deviceMemory,\r\n platform: navigator.platform,\r\n maxTouchPoints: navigator.maxTouchPoints,\r\n\r\n // WebGL vendor/renderer — GPU-based, stable\r\n webgl: this.getWebGLFingerprint(),\r\n\r\n // Locale — stable unless user changes OS language or moves timezone\r\n timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,\r\n language: navigator.language,\r\n };\r\n }\r\n\r\n /**\r\n * WebGL vendor + renderer string (GPU identifier, very stable)\r\n */\r\n private static getWebGLFingerprint(): string {\r\n try {\r\n const canvas = document.createElement('canvas');\r\n const gl = canvas.getContext('webgl') || canvas.getContext('experimental-webgl');\r\n\r\n if (!gl) return 'no-webgl';\r\n\r\n const glContext = gl as WebGLRenderingContext;\r\n const debugInfo = glContext.getExtension('WEBGL_debug_renderer_info');\r\n\r\n const vendor = debugInfo\r\n ? glContext.getParameter(debugInfo.UNMASKED_VENDOR_WEBGL)\r\n : glContext.getParameter(glContext.VENDOR);\r\n const renderer = debugInfo\r\n ? glContext.getParameter(debugInfo.UNMASKED_RENDERER_WEBGL)\r\n : glContext.getParameter(glContext.RENDERER);\r\n\r\n return `${vendor}~${renderer}`;\r\n } catch {\r\n return 'webgl-error';\r\n }\r\n }\r\n\r\n /**\r\n * SHA-256 hash of the signals object → hex string\r\n */\r\n private static async hashComponents(components: Record<string, unknown>): Promise<string> {\r\n const data = new TextEncoder().encode(JSON.stringify(components));\r\n const hashBuffer = await crypto.subtle.digest('SHA-256', data);\r\n return Array.from(new Uint8Array(hashBuffer))\r\n .map((b) => b.toString(16).padStart(2, '0'))\r\n .join('');\r\n }\r\n\r\n // ── localStorage helpers ───────────────────────────────────────────\r\n\r\n private static getStored(): string | null {\r\n try {\r\n return localStorage.getItem(STORAGE_KEY);\r\n } catch {\r\n return null;\r\n }\r\n }\r\n\r\n private static persist(fingerprint: string): void {\r\n try {\r\n localStorage.setItem(STORAGE_KEY, fingerprint);\r\n } catch {\r\n // Storage full or disabled — fingerprint still works in-memory\r\n }\r\n }\r\n\r\n /**\r\n * Clear both in-memory and persisted fingerprint (useful for testing)\r\n */\r\n public static clearCache(): void {\r\n this.cachedFingerprint = null;\r\n try {\r\n localStorage.removeItem(STORAGE_KEY);\r\n } catch {\r\n // Ignore\r\n }\r\n }\r\n}\r\n","/**\n * The participant attribute the agent sets when it will not greet (TRI-2230).\n * Written by trillet-agent (src/agent/greeting_signal.py) at the point its greeting\n * would have been spoken, on flows that wait for the visitor to speak first.\n */\nexport const GREETING_ATTRIBUTE = 'trillet.greeting';\nexport const NO_GREETING = 'none';\n\ntype ParticipantLike = { identity: string; attributes?: Record<string, string> };\n\n/** True when the agent in the room has said it will not greet. */\nexport function agentSkipsGreeting(participants: Iterable<ParticipantLike>): boolean {\n for (const p of participants) {\n if (p.identity.startsWith('agent') && p.attributes?.[GREETING_ATTRIBUTE] === NO_GREETING) return true;\n }\n return false;\n}\n"],"mappings":";;;;;;AAAA,SAAS,gBAAAA,qBAAoB;AAC7B,SAAsB,aAAAC,kBAAiB;;;ACDvC,SAAS,oBAAoB;AAC7B,SAAyC,kBAA0C,MAAM,WAAW,OAAO,qBAAkC,uBAAuB;AAGpK,IAAM,UAAU,IAAI,YAAY;AAoBzB,IAAM,gBAAN,cAA4B,aAAa;AAAA,EAmB9C,cAAc;AACZ,UAAM;AAlBR,SAAO,cAAuB;AAG9B;AAAA,SAAO,sBAA+B;AAmHtC;AAAA,SAAQ,SAAS;AAEjB,SAAQ,cAAc;AAAA,EArGtB;AAAA,EAEA,MAAa,eAAe,QAA0C;AA/CxE;AAgDI,QAAI;AACF,WAAK,OAAO,IAAI,KAAK;AAAA,QACnB,sBAAsB;AAAA,UACpB,iBAAiB;AAAA,UACjB,kBAAkB;AAAA,UAClB,kBAAkB;AAAA,UAClB,cAAc;AAAA,UACd,WA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O;AACd,cAAQ,MAAM,gCAAgC,KAAK;AACnD,WAAK,KAAK,SAAS,IAAI,MAAM,2BAA2B,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC,EAAE,CAAC;AAAA,IACnH;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,MAAa,wBAAyC;AACpD,WAAO,MAAM,mBAAmB,SAAS;AAAA,EAC3C;AACF;","names":["EventEmitter","RoomEvent","decoder","EventEmitter","RoomEvent","_a"]}
package/dist/index.d.ts CHANGED
@@ -169,6 +169,11 @@ declare class TrilletAgent extends EventEmitter {
169
169
  * whole conversation in context. Emits `modalityChanged` with 'voice' | 'text'.
170
170
  */
171
171
  setVoiceEnabled(enabled: boolean): Promise<void>;
172
+ /**
173
+ * Emit `greetingSkipped` once the agent says it will not greet (participant attribute
174
+ * `trillet.greeting=none`, TRI-2230), so a message held for the greeting can go now.
175
+ */
176
+ private watchGreeting;
172
177
  /**
173
178
  * Resolve once the agent's session is ready to receive (its `lk.agent.state` has
174
179
  * moved past "initializing"), or reject after `timeoutMs`. Joining the room is not
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  BrowserFingerprint,
3
3
  TrilletAgent
4
- } from "./chunk-GUAIVASQ.js";
4
+ } from "./chunk-WSOSR3UF.js";
5
5
  import "./chunk-CVTVHUNZ.js";
6
6
  export {
7
7
  BrowserFingerprint,
@@ -333,7 +333,7 @@ declare class TrilletWidgetElement extends HTMLElement {
333
333
  private remote;
334
334
  private remoteDisplay;
335
335
  private remoteLoadedFor;
336
- private pendingMessage;
336
+ private held;
337
337
  getRoomDetails?: (context: {
338
338
  /** The side the conversation starts on. */
339
339
  mode: ActiveMode;
@@ -372,6 +372,8 @@ declare class TrilletWidgetElement extends HTMLElement {
372
372
  * first when needed; the message is delivered as soon as the session connects.
373
373
  */
374
374
  sendMessage(text: string): Promise<void>;
375
+ /** Send now, or behind a message still held for the agent's greeting (TRI-2230). */
376
+ private deliver;
375
377
  /**
376
378
  * Imperatively start a conversation. Primary headless API (convai-aligned).
377
379
  * @param modality - optional; only used in `mode="both"` to pick voice vs text.
@@ -404,15 +406,12 @@ declare class TrilletWidgetElement extends HTMLElement {
404
406
  * mic is refused, the conversation simply stays in text and says why.
405
407
  */
406
408
  private switchModality;
407
- private pendingTimer;
408
409
  /**
409
410
  * Listening <-> Speaking flips several times a second at turn edges. Patch the few
410
411
  * nodes that show it instead of re-rendering, which would rebuild (and flash) the UI.
411
412
  */
412
413
  private setSpeaking;
413
414
  private lastView;
414
- /** Send the message typed before the chat started (once). */
415
- private flushPending;
416
415
  private notice;
417
416
  private switchingSide;
418
417
  private callGeneration;
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  TrilletAgent
3
- } from "../chunk-GUAIVASQ.js";
3
+ } from "../chunk-WSOSR3UF.js";
4
4
  import {
5
5
  apiUrl
6
6
  } from "../chunk-CVTVHUNZ.js";
@@ -1209,6 +1209,86 @@ function renderMarkdown(source) {
1209
1209
  return fragment;
1210
1210
  }
1211
1211
 
1212
+ // src/widget/heldMessages.ts
1213
+ var HOLD_FALLBACK_MS = 25e3;
1214
+ var HeldMessages = class {
1215
+ constructor(send, fallbackMs = HOLD_FALLBACK_MS) {
1216
+ this.send = send;
1217
+ this.fallbackMs = fallbackMs;
1218
+ this.queue = [];
1219
+ this.sending = false;
1220
+ // Sends only work once the session is live. A greeting that lands earlier (audio
1221
+ // set-up can still be running after the room connects) is remembered until then.
1222
+ this.live = false;
1223
+ this.cued = false;
1224
+ this.timer = null;
1225
+ // Bumped by clear() so a send still in flight from a reset conversation stops there.
1226
+ this.generation = 0;
1227
+ }
1228
+ /** True while a message waits or is still going out. New text must queue behind it. */
1229
+ get holding() {
1230
+ return this.queue.length > 0 || this.sending;
1231
+ }
1232
+ hold(text) {
1233
+ this.queue.push(text);
1234
+ }
1235
+ /** The session is live: send if the agent already cued it, else start the fallback. */
1236
+ connected() {
1237
+ this.live = true;
1238
+ if (!this.queue.length) return;
1239
+ if (this.cued) {
1240
+ void this.release();
1241
+ return;
1242
+ }
1243
+ this.clearTimer();
1244
+ this.timer = setTimeout(() => void this.release(), this.fallbackMs);
1245
+ }
1246
+ /** The agent's greeting releases the queue. A tool call is not a greeting. */
1247
+ transcripts(list) {
1248
+ if (!this.queue.length) return;
1249
+ if (list.some((t) => t.isFinal && t.role === "assistant" && !t.toolUsed)) this.cue();
1250
+ }
1251
+ /** The agent said it will not greet. */
1252
+ greetingSkipped() {
1253
+ if (this.queue.length) this.cue();
1254
+ }
1255
+ /** Send what is held, oldest first, one at a time; text held meanwhile follows. */
1256
+ async release() {
1257
+ this.clearTimer();
1258
+ if (this.sending) return;
1259
+ const generation = this.generation;
1260
+ this.sending = true;
1261
+ try {
1262
+ while (this.queue.length && generation === this.generation) {
1263
+ const next = this.queue.shift();
1264
+ try {
1265
+ await this.send(next);
1266
+ } catch (e) {
1267
+ }
1268
+ }
1269
+ } finally {
1270
+ if (generation === this.generation) this.sending = false;
1271
+ }
1272
+ }
1273
+ /** Forget everything held: the conversation ended or was reset. */
1274
+ clear() {
1275
+ this.generation += 1;
1276
+ this.clearTimer();
1277
+ this.queue = [];
1278
+ this.sending = false;
1279
+ this.live = false;
1280
+ this.cued = false;
1281
+ }
1282
+ cue() {
1283
+ if (this.live) void this.release();
1284
+ else this.cued = true;
1285
+ }
1286
+ clearTimer() {
1287
+ if (this.timer) clearTimeout(this.timer);
1288
+ this.timer = null;
1289
+ }
1290
+ };
1291
+
1212
1292
  // src/widget/TrilletWidgetElement.ts
1213
1293
  var TrilletWidgetElement = class extends HTMLElement {
1214
1294
  constructor() {
@@ -1234,8 +1314,12 @@ var TrilletWidgetElement = class extends HTMLElement {
1234
1314
  this.remote = null;
1235
1315
  this.remoteDisplay = null;
1236
1316
  this.remoteLoadedFor = null;
1237
- // A suggested prompt clicked before the chat finished connecting; sent on connect.
1238
- this.pendingMessage = null;
1317
+ // Text typed before the agent was ready for it: held for its greeting, then sent in
1318
+ // the order typed (TRI-2230). Sent only on the live agent of this conversation.
1319
+ this.held = new HeldMessages(async (text) => {
1320
+ const agent = this.agent;
1321
+ if (agent && this.state === "live") await agent.sendTextMessage(text);
1322
+ });
1239
1323
  // maxCallDuration countdown (UX only — see startConversation()).
1240
1324
  this.durationTimer = null;
1241
1325
  this.remainingSeconds = null;
@@ -1254,7 +1338,6 @@ var TrilletWidgetElement = class extends HTMLElement {
1254
1338
  this.recaptchaSolved = false;
1255
1339
  this.recaptchaSlot = null;
1256
1340
  this.recaptchaWidgetId = null;
1257
- this.pendingTimer = null;
1258
1341
  // Which top-level view is on screen; the entrance animation only plays on a change.
1259
1342
  this.lastView = null;
1260
1343
  // Inline notice in the chat (e.g. microphone refused). Cleared on the next switch.
@@ -1341,18 +1424,29 @@ var TrilletWidgetElement = class extends HTMLElement {
1341
1424
  * first when needed; the message is delivered as soon as the session connects.
1342
1425
  */
1343
1426
  async sendMessage(text) {
1344
- var _a;
1345
1427
  const message = text.trim();
1346
1428
  if (!message) return;
1347
1429
  if (this.state === "live" && (this.resolvedMode() === "text" || this.config.mode === "both")) {
1348
- await ((_a = this.agent) == null ? void 0 : _a.sendTextMessage(message));
1430
+ await this.deliver(message);
1349
1431
  return;
1350
1432
  }
1351
1433
  if (this.config.mode === "voice") return;
1352
- if (this.state === "idle" || this.state === "ended") this.transcripts = [];
1353
- this.pendingMessage = message;
1434
+ if (this.state === "idle" || this.state === "ended") {
1435
+ this.transcripts = [];
1436
+ this.held.clear();
1437
+ }
1438
+ this.held.hold(message);
1354
1439
  if (this.state !== "connecting") await this.startConversation("text");
1355
1440
  }
1441
+ /** Send now, or behind a message still held for the agent's greeting (TRI-2230). */
1442
+ async deliver(text) {
1443
+ var _a;
1444
+ if (this.held.holding) {
1445
+ this.held.hold(text);
1446
+ return;
1447
+ }
1448
+ await ((_a = this.agent) == null ? void 0 : _a.sendTextMessage(text));
1449
+ }
1356
1450
  // ---- Public element API ----------------------------------------------------
1357
1451
  /**
1358
1452
  * Imperatively start a conversation. Primary headless API (convai-aligned).
@@ -1387,9 +1481,7 @@ var TrilletWidgetElement = class extends HTMLElement {
1387
1481
  this.callGeneration += 1;
1388
1482
  this.clearDurationTimer();
1389
1483
  this.teardownAgent();
1390
- if (this.pendingTimer) clearTimeout(this.pendingTimer);
1391
- this.pendingTimer = null;
1392
- this.pendingMessage = null;
1484
+ this.held.clear();
1393
1485
  this.transcripts = [];
1394
1486
  this.notice = null;
1395
1487
  this.errorText = null;
@@ -1479,14 +1571,6 @@ var TrilletWidgetElement = class extends HTMLElement {
1479
1571
  const status = this.root.querySelector(".tw-header .tw-status");
1480
1572
  if (status) status.textContent = this.statusText();
1481
1573
  }
1482
- /** Send the message typed before the chat started (once). */
1483
- flushPending() {
1484
- if (this.pendingTimer) clearTimeout(this.pendingTimer);
1485
- this.pendingTimer = null;
1486
- const queued = this.pendingMessage;
1487
- this.pendingMessage = null;
1488
- if (queued && this.agent && this.state === "live") void this.agent.sendTextMessage(queued);
1489
- }
1490
1574
  // ---- Credential resolution + call lifecycle --------------------------------
1491
1575
  async beginCall(modality) {
1492
1576
  if (this.config.termsText && !this.termsAccepted()) {
@@ -1563,10 +1647,9 @@ var TrilletWidgetElement = class extends HTMLElement {
1563
1647
  this.setState("live");
1564
1648
  this.startDurationTimer(!wasSwitching);
1565
1649
  this.switching = false;
1566
- if (this.pendingMessage) {
1567
- this.pendingTimer = setTimeout(() => this.flushPending(), 25e3);
1568
- }
1650
+ this.held.connected();
1569
1651
  });
1652
+ agent.on("greetingSkipped", () => this.held.greetingSkipped());
1570
1653
  agent.on("disconnected", () => {
1571
1654
  this.endLocalCall();
1572
1655
  });
@@ -1584,9 +1667,7 @@ var TrilletWidgetElement = class extends HTMLElement {
1584
1667
  agent.on("assistantStoppedSpeaking", () => this.setSpeaking(false));
1585
1668
  agent.on("transcriptUpdate", (transcripts) => {
1586
1669
  this.transcripts = [...transcripts];
1587
- if (this.pendingMessage && transcripts.some((t) => t.isFinal && t.role === "assistant" && !t.toolUsed)) {
1588
- this.flushPending();
1589
- }
1670
+ this.held.transcripts(transcripts);
1590
1671
  this.dispatch(
1591
1672
  "transcript",
1592
1673
  this.transcripts.filter((t) => t.isFinal)
@@ -1605,9 +1686,7 @@ var TrilletWidgetElement = class extends HTMLElement {
1605
1686
  this.dispatch("conversationEnded", this.elapsedSeconds);
1606
1687
  this.setState("ended");
1607
1688
  this.agent = null;
1608
- this.pendingMessage = null;
1609
- if (this.pendingTimer) clearTimeout(this.pendingTimer);
1610
- this.pendingTimer = null;
1689
+ this.held.clear();
1611
1690
  if (this.config.mode === "both") this.activeMode = null;
1612
1691
  }
1613
1692
  handleError(error) {
@@ -1618,6 +1697,7 @@ var TrilletWidgetElement = class extends HTMLElement {
1618
1697
  this.switching = false;
1619
1698
  this.dispatch("error", err);
1620
1699
  this.agent = null;
1700
+ this.held.clear();
1621
1701
  if (this.config.mode === "both") this.activeMode = null;
1622
1702
  this.setState("idle");
1623
1703
  }
@@ -2548,13 +2628,12 @@ var TrilletWidgetElement = class extends HTMLElement {
2548
2628
  input.style.height = `${Math.min(input.scrollHeight, 112)}px`;
2549
2629
  };
2550
2630
  const send = () => {
2551
- var _a;
2552
2631
  const text = input.value.trim();
2553
2632
  if (!text || this.state !== "live") return;
2554
2633
  this.draft = "";
2555
2634
  input.value = "";
2556
2635
  syncState();
2557
- void ((_a = this.agent) == null ? void 0 : _a.sendTextMessage(text));
2636
+ void this.deliver(text);
2558
2637
  };
2559
2638
  input.addEventListener("input", () => {
2560
2639
  this.draft = input.value;
@@ -2622,7 +2701,7 @@ var TrilletWidgetElement = class extends HTMLElement {
2622
2701
  }
2623
2702
  /** Connecting, or the visitor spoke last and the agent hasn't started answering. */
2624
2703
  isAwaitingReply() {
2625
- if (this.state === "connecting" || this.pendingMessage) return true;
2704
+ if (this.state === "connecting" || this.held.holding) return true;
2626
2705
  if (this.state !== "live") return false;
2627
2706
  const last = [...this.transcripts].reverse().find((t) => !t.toolUsed && t.isFinal);
2628
2707
  return (last == null ? void 0 : last.role) === "user";