@wix/legends-platform-sdk 1.29.0 → 1.30.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/dist/cjs/conversation/types.js.map +1 -1
- package/dist/cjs/hooks/useConversation/livekit/useConversation.js +30 -16
- package/dist/cjs/hooks/useConversation/livekit/useConversation.js.map +1 -1
- package/dist/cjs/hooks/useConversation/livekit/utils/dataChannel.js +4 -0
- package/dist/cjs/hooks/useConversation/livekit/utils/dataChannel.js.map +1 -1
- package/dist/cjs/hooks/useConversationEvents/types.js.map +1 -1
- package/dist/cjs/hooks/useCreateConversation/createConversationFailureStatus.js +20 -0
- package/dist/cjs/hooks/useCreateConversation/createConversationFailureStatus.js.map +1 -0
- package/dist/cjs/hooks/useCreateConversation/useCreateConversation.js +7 -6
- package/dist/cjs/hooks/useCreateConversation/useCreateConversation.js.map +1 -1
- package/dist/cjs/services/FetchPersonaChatService.js +8 -1
- package/dist/cjs/services/FetchPersonaChatService.js.map +1 -1
- package/dist/esm/conversation/types.js.map +1 -1
- package/dist/esm/hooks/useConversation/livekit/useConversation.js +31 -17
- package/dist/esm/hooks/useConversation/livekit/useConversation.js.map +1 -1
- package/dist/esm/hooks/useConversation/livekit/utils/dataChannel.js +3 -0
- package/dist/esm/hooks/useConversation/livekit/utils/dataChannel.js.map +1 -1
- package/dist/esm/hooks/useConversationEvents/types.js.map +1 -1
- package/dist/esm/hooks/useCreateConversation/createConversationFailureStatus.js +16 -0
- package/dist/esm/hooks/useCreateConversation/createConversationFailureStatus.js.map +1 -0
- package/dist/esm/hooks/useCreateConversation/useCreateConversation.js +7 -6
- package/dist/esm/hooks/useCreateConversation/useCreateConversation.js.map +1 -1
- package/dist/esm/services/FetchPersonaChatService.js +8 -1
- package/dist/esm/services/FetchPersonaChatService.js.map +1 -1
- package/dist/types/conversation/types.d.ts +1 -1
- package/dist/types/conversation/types.d.ts.map +1 -1
- package/dist/types/hooks/useConversation/livekit/useConversation.d.ts.map +1 -1
- package/dist/types/hooks/useConversation/livekit/utils/dataChannel.d.ts +1 -0
- package/dist/types/hooks/useConversation/livekit/utils/dataChannel.d.ts.map +1 -1
- package/dist/types/hooks/useConversationEvents/types.d.ts +5 -0
- package/dist/types/hooks/useConversationEvents/types.d.ts.map +1 -1
- package/dist/types/hooks/useCreateConversation/createConversationFailureStatus.d.ts +5 -0
- package/dist/types/hooks/useCreateConversation/createConversationFailureStatus.d.ts.map +1 -0
- package/dist/types/hooks/useCreateConversation/useCreateConversation.d.ts.map +1 -1
- package/dist/types/services/FetchPersonaChatService.d.ts.map +1 -1
- package/package.json +6 -6
package/README.md
CHANGED
|
@@ -105,7 +105,7 @@ const { status, join, leave } = useConversation({
|
|
|
105
105
|
|
|
106
106
|
| Return | Type | Description |
|
|
107
107
|
|--------|------|-------------|
|
|
108
|
-
| `status` | `'pending' \| 'created' \| 'destroying' \| 'destroyed' \| 'exceeded' \| 'inactivity-timeout' \| 'credit-exhausted' \| 'conversation-limit-reached' \| 'voice-not-found' \| 'initialization-error' \| 'error'` | Current conversation state |
|
|
108
|
+
| `status` | `'pending' \| 'created' \| 'destroying' \| 'destroyed' \| 'exceeded' \| 'inactivity-timeout' \| 'credit-exhausted' \| 'conversation-limit-reached' \| 'plan-minutes-exhausted' \| 'voice-not-found' \| 'initialization-error' \| 'error'` | Current conversation state |
|
|
109
109
|
| `join()` | `() => void` | Start the conversation |
|
|
110
110
|
| `leave()` | `(destroy?: boolean) => Promise<void>` | End the conversation |
|
|
111
111
|
|
|
@@ -157,7 +157,7 @@ const result = await send({ message: 'Hello' });
|
|
|
157
157
|
```tsx
|
|
158
158
|
const status = useConversationStatus();
|
|
159
159
|
// 'pending' | 'created' | 'destroying' | 'destroyed' | 'exceeded'
|
|
160
|
-
// | 'inactivity-timeout' | 'credit-exhausted' | 'conversation-limit-reached' | 'voice-not-found' | 'initialization-error' | 'error'
|
|
160
|
+
// | 'inactivity-timeout' | 'credit-exhausted' | 'conversation-limit-reached' | 'plan-minutes-exhausted' | 'voice-not-found' | 'initialization-error' | 'error'
|
|
161
161
|
```
|
|
162
162
|
|
|
163
163
|
#### `useConversationTimer()`
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"names":[],"sources":["../../../src/conversation/types.ts"],"sourcesContent":["export type ConversationType = 'video' | 'audio';\n\nexport type ConversationParticipantRole = 'user' | 'agent';\n\nexport type ConversationVendor =\n | 'LIVEKIT'\n | 'DAILY'\n | 'HUME'\n | 'ELEVEN_LABS'\n | 'UNKNOWN_VENDOR';\n\nexport type AgentConnectionState =\n | 'joined' // agent is connected to the conversation\n | 'joining' // agent is connecting to the conversation\n | 'left' // agent left the conversation\n | 'idle'; // agent is not connected to the conversation\n\nexport type UserConnectionState =\n | 'joined' // user is connected to the conversation\n | 'joining' // user is connecting to the conversation\n | 'idle' // user is not connected to the conversation\n | 'leaving' // user is leaving the conversation\n | 'join-error'; // failed to join the conversation\n\nexport type ActivityState = 'idle' | 'speaking' | 'listening';\n\nexport type ConversationStatus =\n // Initial state\n | 'pending' // conversation is not created yet\n // States\n | 'created' // conversation was created\n | 'destroying' // destroying the conversation\n | 'destroyed' // conversation was destroyed\n | 'exceeded' // conversation limit is exceeded\n | 'inactivity-timeout' // conversation ended due to inactivity\n | 'credit-exhausted' // the server ended the conversation because the Legend owner ran out of credit\n | 'conversation-limit-reached' // the server ended the conversation because the caller reached the Legend's daily conversation limit\n // Errors\n | 'voice-not-found' // failed to find a voice\n | 'initialization-error' // failed to create conversation\n | 'error'; // unknown error\n\nexport type Conversation = {\n id: string;\n url: string;\n limit?: number;\n type: ConversationType;\n};\n\nexport type ConversationTranscription = {\n message: string;\n source: ConversationParticipantRole;\n id: string;\n};\n\nexport type ConversationDevice = {\n enabled: boolean;\n deviceId: string;\n};\n\nexport type ConversationAudio = {\n // Range between `0.0` and `1.0`.\n volume: number;\n muted: boolean;\n};\n"],"mappings":"","ignoreList":[]}
|
|
1
|
+
{"version":3,"names":[],"sources":["../../../src/conversation/types.ts"],"sourcesContent":["export type ConversationType = 'video' | 'audio';\n\nexport type ConversationParticipantRole = 'user' | 'agent';\n\nexport type ConversationVendor =\n | 'LIVEKIT'\n | 'DAILY'\n | 'HUME'\n | 'ELEVEN_LABS'\n | 'UNKNOWN_VENDOR';\n\nexport type AgentConnectionState =\n | 'joined' // agent is connected to the conversation\n | 'joining' // agent is connecting to the conversation\n | 'left' // agent left the conversation\n | 'idle'; // agent is not connected to the conversation\n\nexport type UserConnectionState =\n | 'joined' // user is connected to the conversation\n | 'joining' // user is connecting to the conversation\n | 'idle' // user is not connected to the conversation\n | 'leaving' // user is leaving the conversation\n | 'join-error'; // failed to join the conversation\n\nexport type ActivityState = 'idle' | 'speaking' | 'listening';\n\nexport type ConversationStatus =\n // Initial state\n | 'pending' // conversation is not created yet\n // States\n | 'created' // conversation was created\n | 'destroying' // destroying the conversation\n | 'destroyed' // conversation was destroyed\n | 'exceeded' // conversation limit is exceeded\n | 'inactivity-timeout' // conversation ended due to inactivity\n | 'credit-exhausted' // the server ended the conversation because the Legend owner ran out of credit\n | 'conversation-limit-reached' // the server ended the conversation because the caller reached the Legend's daily conversation limit\n | 'plan-minutes-exhausted' // the server ended the conversation because the member used up their plan's minutes\n // Errors\n | 'voice-not-found' // failed to find a voice\n | 'initialization-error' // failed to create conversation\n | 'error'; // unknown error\n\nexport type Conversation = {\n id: string;\n url: string;\n limit?: number;\n type: ConversationType;\n};\n\nexport type ConversationTranscription = {\n message: string;\n source: ConversationParticipantRole;\n id: string;\n};\n\nexport type ConversationDevice = {\n enabled: boolean;\n deviceId: string;\n};\n\nexport type ConversationAudio = {\n // Range between `0.0` and `1.0`.\n volume: number;\n muted: boolean;\n};\n"],"mappings":"","ignoreList":[]}
|
|
@@ -77,6 +77,7 @@ function useConversation({
|
|
|
77
77
|
const inactivityTimeoutRef = (0, _react.useRef)(false);
|
|
78
78
|
const creditExhaustedRef = (0, _react.useRef)(false);
|
|
79
79
|
const conversationLimitReachedRef = (0, _react.useRef)(false);
|
|
80
|
+
const planMinutesExhaustedRef = (0, _react.useRef)(false);
|
|
80
81
|
const acousticPhaseRef = (0, _react.useRef)('idle');
|
|
81
82
|
const acousticT0Ref = (0, _react.useRef)(null);
|
|
82
83
|
const latestTurnMetadataRef = (0, _react.useRef)({});
|
|
@@ -362,6 +363,14 @@ function useConversation({
|
|
|
362
363
|
});
|
|
363
364
|
return;
|
|
364
365
|
}
|
|
366
|
+
if ((0, _utils.checkIsPlanMinutesExhaustedMessage)(decoded, topic)) {
|
|
367
|
+
var _conversationRef$curr8;
|
|
368
|
+
planMinutesExhaustedRef.current = true;
|
|
369
|
+
emitEvent('planMinutesExhausted', {
|
|
370
|
+
conversationId: (_conversationRef$curr8 = conversationRef.current) == null ? void 0 : _conversationRef$curr8.id
|
|
371
|
+
});
|
|
372
|
+
return;
|
|
373
|
+
}
|
|
365
374
|
for (const {
|
|
366
375
|
guard,
|
|
367
376
|
handle
|
|
@@ -375,12 +384,12 @@ function useConversation({
|
|
|
375
384
|
}
|
|
376
385
|
}
|
|
377
386
|
function handleConnectedEvent() {
|
|
378
|
-
var _conversationRef$
|
|
387
|
+
var _conversationRef$curr9;
|
|
379
388
|
isConnectedRef.current = true;
|
|
380
389
|
setUserConnectionState('joined');
|
|
381
390
|
setAgentConnectionState('joining');
|
|
382
391
|
emitEvent('callStarted', {
|
|
383
|
-
conversationId: (_conversationRef$
|
|
392
|
+
conversationId: (_conversationRef$curr9 = conversationRef.current) == null ? void 0 : _conversationRef$curr9.id
|
|
384
393
|
});
|
|
385
394
|
}
|
|
386
395
|
async function handleEncryptionErrorEvent(error) {
|
|
@@ -413,6 +422,11 @@ function useConversation({
|
|
|
413
422
|
setConversationStatus('conversation-limit-reached');
|
|
414
423
|
return;
|
|
415
424
|
}
|
|
425
|
+
if (planMinutesExhaustedRef.current) {
|
|
426
|
+
planMinutesExhaustedRef.current = false;
|
|
427
|
+
setConversationStatus('plan-minutes-exhausted');
|
|
428
|
+
return;
|
|
429
|
+
}
|
|
416
430
|
switch (reason) {
|
|
417
431
|
case _livekitClient.DisconnectReason.CLIENT_INITIATED:
|
|
418
432
|
break;
|
|
@@ -431,18 +445,18 @@ function useConversation({
|
|
|
431
445
|
}
|
|
432
446
|
}
|
|
433
447
|
function handleAgentJoin(participant) {
|
|
434
|
-
var _conversationRef$
|
|
448
|
+
var _conversationRef$curr0;
|
|
435
449
|
setAgentConnectionState('joined');
|
|
436
450
|
emitEvent('agentJoined', {
|
|
437
|
-
conversationId: (_conversationRef$
|
|
451
|
+
conversationId: (_conversationRef$curr0 = conversationRef.current) == null ? void 0 : _conversationRef$curr0.id,
|
|
438
452
|
participant
|
|
439
453
|
});
|
|
440
454
|
}
|
|
441
455
|
function handleParticipantDisconnectedEvent(participant) {
|
|
442
|
-
var _conversationRef$
|
|
456
|
+
var _conversationRef$curr1;
|
|
443
457
|
setAgentConnectionState('left');
|
|
444
458
|
emitEvent('agentLeft', {
|
|
445
|
-
conversationId: (_conversationRef$
|
|
459
|
+
conversationId: (_conversationRef$curr1 = conversationRef.current) == null ? void 0 : _conversationRef$curr1.id,
|
|
446
460
|
participant
|
|
447
461
|
});
|
|
448
462
|
}
|
|
@@ -451,13 +465,13 @@ function useConversation({
|
|
|
451
465
|
return;
|
|
452
466
|
}
|
|
453
467
|
try {
|
|
454
|
-
var _conversationRef$
|
|
468
|
+
var _conversationRef$curr10;
|
|
455
469
|
setUserConnectionState('leaving');
|
|
456
470
|
await (room == null ? void 0 : room.disconnect(true));
|
|
457
471
|
setConversationStatus('destroyed');
|
|
458
472
|
setJoinedAt(undefined);
|
|
459
473
|
emitEvent('callEnded', {
|
|
460
|
-
conversationId: (_conversationRef$
|
|
474
|
+
conversationId: (_conversationRef$curr10 = conversationRef.current) == null ? void 0 : _conversationRef$curr10.id
|
|
461
475
|
});
|
|
462
476
|
} catch (error) {
|
|
463
477
|
console.error('Failed to leave', error);
|
|
@@ -465,22 +479,22 @@ function useConversation({
|
|
|
465
479
|
}
|
|
466
480
|
}
|
|
467
481
|
async function handleExpire() {
|
|
468
|
-
var _conversationRef$
|
|
482
|
+
var _conversationRef$curr11, _conversationRef$curr12;
|
|
469
483
|
// The duration timer keeps running after the call ends.
|
|
470
|
-
if (conversationStatus === 'credit-exhausted' || conversationStatus === 'conversation-limit-reached') {
|
|
484
|
+
if (conversationStatus === 'credit-exhausted' || conversationStatus === 'conversation-limit-reached' || conversationStatus === 'plan-minutes-exhausted') {
|
|
471
485
|
return;
|
|
472
486
|
}
|
|
473
487
|
emitEvent('timeExceeded', {
|
|
474
|
-
conversationId: (_conversationRef$
|
|
475
|
-
limit: (_conversationRef$
|
|
488
|
+
conversationId: (_conversationRef$curr11 = conversationRef.current) == null ? void 0 : _conversationRef$curr11.id,
|
|
489
|
+
limit: (_conversationRef$curr12 = conversationRef.current) == null ? void 0 : _conversationRef$curr12.limit
|
|
476
490
|
});
|
|
477
491
|
await leave();
|
|
478
492
|
setConversationStatus('exceeded');
|
|
479
493
|
}
|
|
480
494
|
async function interrupt() {
|
|
481
|
-
var _conversationRef$
|
|
495
|
+
var _conversationRef$curr13;
|
|
482
496
|
emitEvent('interrupt', {
|
|
483
|
-
conversationId: (_conversationRef$
|
|
497
|
+
conversationId: (_conversationRef$curr13 = conversationRef.current) == null ? void 0 : _conversationRef$curr13.id
|
|
484
498
|
});
|
|
485
499
|
await (0, _utils.publishConversationDataMessage)(room, {}, 'interrupt');
|
|
486
500
|
}
|
|
@@ -490,7 +504,7 @@ function useConversation({
|
|
|
490
504
|
}, 'inactivity_dismiss');
|
|
491
505
|
}
|
|
492
506
|
async function send(message, attachments = []) {
|
|
493
|
-
var _conversationRef$
|
|
507
|
+
var _conversationRef$curr14;
|
|
494
508
|
await (room == null ? void 0 : room.localParticipant.sendText(message, {
|
|
495
509
|
topic: 'lk.chat',
|
|
496
510
|
attributes: {
|
|
@@ -498,7 +512,7 @@ function useConversation({
|
|
|
498
512
|
}
|
|
499
513
|
}));
|
|
500
514
|
emitEvent('userSendMessage', {
|
|
501
|
-
conversationId: (_conversationRef$
|
|
515
|
+
conversationId: (_conversationRef$curr14 = conversationRef.current) == null ? void 0 : _conversationRef$curr14.id,
|
|
502
516
|
message
|
|
503
517
|
});
|
|
504
518
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"names":["_react","require","_livekitClient","_invariant","_interopRequireDefault","_reactTimerHook","_reactUse","_componentsReact","_jotai","_conversation","_sdkConsumer","_useCreateConversation","_useSpeechActivityDetector","_useParticipantTrack","_useEmitConversationEvent","_useToolCallingRuntime","_serialize","_utils","_constants","useConversation","autoJoin","type","config","startWithMicrophone","startWithCamera","firstConversation","lastConversationTopic","_conversation$data2","setLogLevel","LogLevel","silent","conversation","useCreateConversation","room","useEnsureRoom","speaker","useAtomValue","state","microphone","setMicrophone","useAtom","camera","setCamera","tools","toolsRegistry","useSdkConsumer","toolRuntime","useToolCallingRuntime","toolsRegistryRef","useLatest","conversationRef","data","toolRuntimeRef","conversationStatus","setConversationStatus","userConnectionState","setUserConnectionState","joinedAt","setJoinedAt","setActiveMediaDevice","setMicrophoneDeviceId","useMediaDeviceSelect","kind","setSpeakerDeviceId","setCameraDeviceId","requestPermissions","enabled","setTranscriptions","useSetAtom","transcriptions","agentConnectionState","setAgentConnectionState","setAgentActivityState","agentActivityState","setUserActivityState","userActivityState","emitEvent","useEmitConversationEvent","inactivityTimeoutRef","useRef","creditExhaustedRef","conversationLimitReachedRef","acousticPhaseRef","acousticT0Ref","latestTurnMetadataRef","isConnectedRef","userCumulativeTrackStatsRef","undefined","agentCumulativeTrackStatsRef","userMicPublication","useParticipantTrack","source","Source","Microphone","agentMicPublication","timer","useTimer","autoStart","onExpire","handleExpire","expiryTimestamp","Date","useEffect","registerRoomEvents","unregisterRoomEvents","useUpdateEffect","deviceId","localParticipant","setMicrophoneEnabled","setCameraEnabled","resolution","width","height","join","_conversation$data","limit","restart","getTime","_conversation$data3","invariant","url","URL","accessToken","searchParams","get","connect","remoteParticipant","findJoinedAgentParticipant","handleAgentJoin","enableMediaDevices","error","console","handleTranscriptionReceivedEvent","segments","participant","map","s","id","message","text","ParticipantKind","AGENT","old","mergeTranscriptions","handleTurnDetectionEvent","_conversationRef$curr","conversationId","current","participantKind","eventState","turnDetectionStrategy","sequence","speechId","handleAcousticUserOnset","handleAcousticUserOffset","timestampMs","ACOUSTIC_USER_HANGOVER_MS","handleAcousticAgentOnset","_conversationRef$curr2","latencyMs","emitConversationTurnLatency","clientAcousticLatencyMs","_conversationRef$curr3","userReport","agentReport","Promise","all","getTrackStats","userStats","parseTrackStats","agentStats","cumulativeTrackStats","rttMs","roundTripTimeMs","jitterBufferDelayMs","userPacketsLost","packetsLost","agentPacketsLost","handleAcousticAgentOffset","useSpeechActivityDetector","onSpeechStart","onSpeechEnd","thresholdRms","ACOUSTIC_USER_THRESHOLD_RMS","hangoverMs","ACOUSTIC_AGENT_HANGOVER_MS","handleInactivityWarningEvent","_conversationRef$curr4","gracePeriodSec","grace_period_sec","handleInactivityTimeoutEvent","_data","_conversationRef$curr5","handleGetToolsRpc","JSON","stringify","buildToolDefinitions","handleExecuteToolRpc","call","parseFunctionCallPayload","payload","functionCallId","result","executeToolCalls","extractToolErrorMessage","dataChannelHandlers","guard","checkIsTurnDetectionData","handle","checkIsInactivityWarningData","checkIsInactivityTimeoutData","handleDataReceivedEvent","_participant","_kind","topic","decoded","decodeDataPayload","checkIsCreditExhaustedMessage","_conversationRef$curr6","checkIsConversationLimitReachedMessage","_conversationRef$curr7","resolve","catch","handleConnectedEvent","_conversationRef$curr8","handleEncryptionErrorEvent","handleDisconnectedEvent","reason","DisconnectReason","CLIENT_INITIATED","ROOM_CLOSED","handleParticipantConnectedEvent","shouldHandleParticipantConnected","_conversationRef$curr9","handleParticipantDisconnectedEvent","_conversationRef$curr0","leave","_conversationRef$curr1","disconnect","_conversationRef$curr10","_conversationRef$curr11","interrupt","_conversationRef$curr12","publishConversationDataMessage","dismissInactivity","send","attachments","_conversationRef$curr13","sendText","attributes","safeStringify","on","unregisterRpcMethod","GET_TOOLS_RPC_METHOD","EXECUTE_TOOL_RPC_METHOD","registerRpcMethod","off","status"],"sources":["../../../../../src/hooks/useConversation/livekit/useConversation.ts"],"sourcesContent":["import { useEffect, useRef } from 'react';\nimport {\n DisconnectReason,\n Participant,\n setLogLevel,\n ParticipantKind,\n RemoteParticipant,\n TranscriptionSegment,\n LogLevel,\n type RpcInvocationData,\n} from 'livekit-client';\nimport invariant from 'invariant';\nimport { useTimer } from 'react-timer-hook';\nimport { useLatest, useUpdateEffect } from 'react-use';\nimport { useEnsureRoom, useMediaDeviceSelect } from '@livekit/components-react';\nimport { useAtom, useAtomValue, useSetAtom } from 'jotai';\nimport {\n Conversation,\n state,\n type ConversationTranscription,\n} from '../../../conversation';\nimport type {\n UseConversationResult,\n UseConversationOptions,\n Attachment,\n} from '../types';\nimport type { FunctionCallResult } from '../../../types/service';\nimport { useSdkConsumer } from '../../../sdk-consumer';\nimport type {\n InactivityWarningData,\n InactivityTimeoutData,\n TurnDetectionData,\n} from './types';\nimport { useCreateConversation } from '../../useCreateConversation';\nimport { useSpeechActivityDetector } from '../../useSpeechActivityDetector';\nimport {\n useParticipantTrack,\n Source,\n getTrackStats,\n parseTrackStats,\n type CumulativeTrackStats,\n} from '../../useParticipantTrack';\n\nimport { useEmitConversationEvent } from '../../useConversationEvents/useEmitConversationEvent';\nimport { useToolCallingRuntime } from '../../useTools/runtime/useToolCallingRuntime';\nimport { extractToolErrorMessage } from '../../useTools/utils/serialize';\nimport {\n checkIsTurnDetectionData,\n checkIsInactivityWarningData,\n checkIsInactivityTimeoutData,\n checkIsCreditExhaustedMessage,\n checkIsConversationLimitReachedMessage,\n buildToolDefinitions,\n decodeDataPayload,\n findJoinedAgentParticipant,\n mergeTranscriptions,\n parseFunctionCallPayload,\n publishConversationDataMessage,\n safeStringify,\n shouldHandleParticipantConnected,\n} from './utils';\nimport {\n ACOUSTIC_AGENT_HANGOVER_MS,\n ACOUSTIC_USER_HANGOVER_MS,\n ACOUSTIC_USER_THRESHOLD_RMS,\n EXECUTE_TOOL_RPC_METHOD,\n GET_TOOLS_RPC_METHOD,\n} from './constants';\n\nexport function useConversation({\n autoJoin = true,\n type,\n config,\n startWithMicrophone = false,\n startWithCamera = false,\n firstConversation,\n lastConversationTopic,\n}: UseConversationOptions): UseConversationResult {\n setLogLevel(LogLevel.silent);\n\n const conversation = useCreateConversation({\n type,\n config,\n firstConversation,\n lastConversationTopic,\n });\n const room = useEnsureRoom();\n const speaker = useAtomValue(state.speaker);\n const [microphone, setMicrophone] = useAtom(state.microphone);\n const [camera, setCamera] = useAtom(state.camera);\n const { tools: toolsRegistry = {} } = useSdkConsumer();\n const toolRuntime = useToolCallingRuntime();\n const toolsRegistryRef = useLatest(toolsRegistry);\n\n // for use in register/unregister room events\n const conversationRef = useLatest<Conversation | undefined>(\n conversation.data,\n );\n const toolRuntimeRef = useLatest(toolRuntime);\n\n const [conversationStatus, setConversationStatus] = useAtom(\n state.conversationStatus,\n );\n\n const [userConnectionState, setUserConnectionState] = useAtom(\n state.userConnectionState,\n );\n\n const [joinedAt, setJoinedAt] = useAtom(state.joinedAt);\n\n const { setActiveMediaDevice: setMicrophoneDeviceId } = useMediaDeviceSelect({\n kind: 'audioinput',\n });\n const { setActiveMediaDevice: setSpeakerDeviceId } = useMediaDeviceSelect({\n kind: 'audiooutput',\n });\n const { setActiveMediaDevice: setCameraDeviceId } = useMediaDeviceSelect({\n kind: 'videoinput',\n requestPermissions: camera.enabled,\n });\n\n const setTranscriptions = useSetAtom(state.transcriptions);\n const [agentConnectionState, setAgentConnectionState] = useAtom(\n state.agentConnectionState,\n );\n const setAgentActivityState = useSetAtom(state.agentActivityState);\n const setUserActivityState = useSetAtom(state.userActivityState);\n const emitEvent = useEmitConversationEvent();\n\n const inactivityTimeoutRef = useRef(false);\n const creditExhaustedRef = useRef(false);\n const conversationLimitReachedRef = useRef(false);\n const acousticPhaseRef = useRef<'idle' | 'waitingForAgent' | 'busy'>('idle');\n const acousticT0Ref = useRef<number | null>(null);\n const latestTurnMetadataRef = useRef<{\n turnDetectionStrategy?: string;\n sequence?: number;\n speechId?: string;\n }>({});\n const isConnectedRef = useRef(false);\n const userCumulativeTrackStatsRef = useRef<CumulativeTrackStats | undefined>(\n undefined,\n );\n const agentCumulativeTrackStatsRef = useRef<CumulativeTrackStats | undefined>(\n undefined,\n );\n\n const userMicPublication = useParticipantTrack({\n type: 'user',\n source: Source.Microphone,\n });\n const agentMicPublication = useParticipantTrack({\n type: 'agent',\n source: Source.Microphone,\n });\n\n const timer = useTimer({\n autoStart: false,\n onExpire: handleExpire,\n expiryTimestamp: new Date(),\n });\n\n useEffect(() => {\n if (!room) {\n return;\n }\n registerRoomEvents();\n\n return () => {\n unregisterRoomEvents();\n };\n }, [room]);\n\n useUpdateEffect(() => {\n setMicrophoneDeviceId(microphone.deviceId);\n }, [microphone.deviceId]);\n\n useUpdateEffect(() => {\n setSpeakerDeviceId(speaker.deviceId);\n }, [speaker.deviceId]);\n\n useUpdateEffect(() => {\n setCameraDeviceId(camera.deviceId);\n }, [camera.deviceId]);\n\n useUpdateEffect(() => {\n if (agentConnectionState !== 'joined') {\n return;\n }\n room.localParticipant.setMicrophoneEnabled(microphone.enabled);\n }, [microphone.enabled, agentConnectionState]);\n\n useUpdateEffect(() => {\n if (agentConnectionState !== 'joined') {\n return;\n }\n room.localParticipant.setCameraEnabled(camera.enabled, {\n resolution: { width: 1920, height: 1080 },\n });\n }, [camera.enabled, agentConnectionState]);\n\n useEffect(() => {\n if (!autoJoin) {\n return;\n }\n\n if (conversationStatus === 'created') {\n void join();\n }\n }, [conversationStatus, autoJoin]);\n\n useEffect(() => {\n if (!joinedAt || conversation.data?.limit === undefined) {\n return;\n }\n\n timer.restart(new Date(joinedAt.getTime() + conversation.data!.limit!));\n }, [joinedAt, conversation.data?.limit]);\n\n async function join() {\n invariant(userConnectionState === 'idle', 'Already joined');\n invariant(conversation.data, 'Conversation is not ready');\n const url = new URL(conversation?.data?.url || '');\n const accessToken = url.searchParams.get('token');\n try {\n setUserConnectionState('joining');\n await room?.connect(conversation.data.url, accessToken!, {});\n\n // sometimes the agent is already joined before the user joins the conversation\n const remoteParticipant = findJoinedAgentParticipant(room, type);\n if (remoteParticipant && agentConnectionState !== 'joined') {\n handleAgentJoin(remoteParticipant);\n }\n\n enableMediaDevices();\n } catch (error) {\n console.error('Failed to join', error);\n setUserConnectionState('join-error');\n }\n }\n\n function enableMediaDevices() {\n if (startWithMicrophone) {\n setMicrophone({ ...microphone, enabled: true });\n }\n if (startWithCamera && type === 'video') {\n setCamera({ ...camera, enabled: true });\n }\n }\n\n function handleTranscriptionReceivedEvent(\n segments: TranscriptionSegment[],\n participant?: Participant,\n ) {\n const transcriptions: ConversationTranscription[] = segments.map((s) => ({\n id: s.id,\n message: s.text,\n source: participant?.kind === ParticipantKind.AGENT ? 'agent' : 'user',\n }));\n\n setTranscriptions((old) => mergeTranscriptions(transcriptions, old));\n }\n\n function handleTurnDetectionEvent(data: TurnDetectionData) {\n const conversationId = conversationRef.current?.id;\n const { participantKind, state: eventState } = data;\n switch (participantKind) {\n case 'STANDARD':\n if (eventState === 'listening') {\n latestTurnMetadataRef.current = {\n turnDetectionStrategy: data.turnDetectionStrategy,\n sequence: data.sequence,\n speechId: data.speechId,\n };\n }\n emitEvent(\n eventState === 'speaking' ? 'userSpeakStart' : 'userSpeakStop',\n { conversationId: conversationId! },\n );\n setUserActivityState(eventState);\n break;\n case 'AGENT':\n if (data.speechId) {\n latestTurnMetadataRef.current = {\n ...latestTurnMetadataRef.current,\n speechId: data.speechId,\n };\n }\n emitEvent(\n eventState === 'speaking' ? 'agentSpeakStart' : 'agentSpeakStop',\n { conversationId: conversationId! },\n );\n setAgentActivityState(eventState);\n break;\n }\n }\n\n function handleAcousticUserOnset() {\n if (!isConnectedRef.current) {\n return;\n }\n if (acousticPhaseRef.current === 'waitingForAgent') {\n acousticPhaseRef.current = 'idle';\n acousticT0Ref.current = null;\n }\n }\n\n function handleAcousticUserOffset(timestampMs: number) {\n if (!isConnectedRef.current || acousticPhaseRef.current !== 'idle') {\n return;\n }\n acousticT0Ref.current = timestampMs - ACOUSTIC_USER_HANGOVER_MS;\n acousticPhaseRef.current = 'waitingForAgent';\n }\n\n function handleAcousticAgentOnset(timestampMs: number) {\n if (\n !isConnectedRef.current ||\n acousticPhaseRef.current !== 'waitingForAgent' ||\n acousticT0Ref.current == null\n ) {\n return;\n }\n\n const latencyMs = timestampMs - acousticT0Ref.current;\n acousticT0Ref.current = null;\n acousticPhaseRef.current = 'busy';\n\n if (latencyMs < 0 || latencyMs > 15000) {\n return;\n }\n\n emitEvent('responseLatency', {\n conversationId: conversationRef.current?.id!,\n latencyMs,\n turnDetectionStrategy:\n latestTurnMetadataRef.current.turnDetectionStrategy!,\n sequence: latestTurnMetadataRef.current.sequence,\n speechId: latestTurnMetadataRef.current.speechId,\n });\n\n void emitConversationTurnLatency(latencyMs);\n }\n\n async function emitConversationTurnLatency(clientAcousticLatencyMs: number) {\n const [userReport, agentReport] = await Promise.all([\n getTrackStats(userMicPublication),\n getTrackStats(agentMicPublication),\n ]);\n const userStats = parseTrackStats(\n userReport,\n userCumulativeTrackStatsRef.current,\n );\n const agentStats = parseTrackStats(\n agentReport,\n agentCumulativeTrackStatsRef.current,\n );\n userCumulativeTrackStatsRef.current = userStats.cumulativeTrackStats;\n agentCumulativeTrackStatsRef.current = agentStats.cumulativeTrackStats;\n\n emitEvent('conversationTurnLatency', {\n conversationId: conversationRef.current?.id!,\n speechId: latestTurnMetadataRef.current.speechId,\n sequence: latestTurnMetadataRef.current.sequence,\n clientAcousticLatencyMs,\n rttMs: userStats.roundTripTimeMs,\n jitterBufferDelayMs: agentStats.jitterBufferDelayMs,\n userPacketsLost: userStats.packetsLost,\n agentPacketsLost: agentStats.packetsLost,\n });\n }\n\n function handleAcousticAgentOffset() {\n acousticPhaseRef.current = 'idle';\n }\n\n useSpeechActivityDetector({\n source: 'user',\n onSpeechStart: handleAcousticUserOnset,\n onSpeechEnd: handleAcousticUserOffset,\n thresholdRms: ACOUSTIC_USER_THRESHOLD_RMS,\n hangoverMs: ACOUSTIC_USER_HANGOVER_MS,\n });\n useSpeechActivityDetector({\n source: 'agent',\n onSpeechStart: handleAcousticAgentOnset,\n onSpeechEnd: handleAcousticAgentOffset,\n hangoverMs: ACOUSTIC_AGENT_HANGOVER_MS,\n });\n\n function handleInactivityWarningEvent(data: InactivityWarningData) {\n emitEvent('inactivityWarning', {\n conversationId: conversationRef.current?.id!,\n gracePeriodSec: data.grace_period_sec,\n });\n }\n\n function handleInactivityTimeoutEvent(_data: InactivityTimeoutData) {\n inactivityTimeoutRef.current = true;\n emitEvent('inactivityTimeout', {\n conversationId: conversationRef.current?.id!,\n });\n }\n\n async function handleGetToolsRpc() {\n return JSON.stringify(buildToolDefinitions(toolsRegistryRef.current));\n }\n\n async function handleExecuteToolRpc(data: RpcInvocationData) {\n const call = parseFunctionCallPayload(data.payload);\n if (!call) {\n return JSON.stringify({\n functionCallId: '',\n result: '',\n error: 'Malformed function call payload.',\n } satisfies FunctionCallResult);\n }\n try {\n const [result] = await toolRuntimeRef.current.executeToolCalls([call]);\n return JSON.stringify(result);\n } catch (error) {\n return JSON.stringify({\n functionCallId: call.functionCallId,\n result: '',\n error: extractToolErrorMessage(error),\n } satisfies FunctionCallResult);\n }\n }\n\n const dataChannelHandlers: {\n guard: (data: unknown) => boolean;\n handle: (data: unknown) => void | Promise<void>;\n }[] = [\n {\n guard: checkIsTurnDetectionData,\n handle: handleTurnDetectionEvent as (data: unknown) => void,\n },\n {\n guard: checkIsInactivityWarningData,\n handle: handleInactivityWarningEvent as (data: unknown) => void,\n },\n {\n guard: checkIsInactivityTimeoutData,\n handle: handleInactivityTimeoutEvent as (data: unknown) => void,\n },\n ];\n\n function handleDataReceivedEvent(\n payload: Uint8Array,\n _participant?: RemoteParticipant,\n _kind?: unknown,\n topic?: string,\n ) {\n const decoded = decodeDataPayload(payload);\n if (decoded === null) {\n return;\n }\n if (checkIsCreditExhaustedMessage(decoded, topic)) {\n creditExhaustedRef.current = true;\n emitEvent('creditExhausted', {\n conversationId: conversationRef.current?.id!,\n });\n return;\n }\n if (checkIsConversationLimitReachedMessage(decoded, topic)) {\n conversationLimitReachedRef.current = true;\n emitEvent('conversationLimitReached', {\n conversationId: conversationRef.current?.id!,\n });\n return;\n }\n for (const { guard, handle } of dataChannelHandlers) {\n if (guard(decoded)) {\n void Promise.resolve(handle(decoded)).catch((error) => {\n console.error('Failed to handle data channel payload', error);\n });\n return;\n }\n }\n }\n\n function handleConnectedEvent() {\n isConnectedRef.current = true;\n setUserConnectionState('joined');\n setAgentConnectionState('joining');\n emitEvent('callStarted', {\n conversationId: conversationRef.current?.id!,\n });\n }\n\n async function handleEncryptionErrorEvent(error: Error) {\n console.error('Encryption error', error);\n setConversationStatus('error');\n }\n\n function handleDisconnectedEvent(reason?: DisconnectReason) {\n isConnectedRef.current = false;\n acousticPhaseRef.current = 'idle';\n acousticT0Ref.current = null;\n latestTurnMetadataRef.current = {};\n userCumulativeTrackStatsRef.current = undefined;\n agentCumulativeTrackStatsRef.current = undefined;\n setAgentActivityState('idle');\n setAgentConnectionState('idle');\n setUserActivityState('idle');\n setUserConnectionState('idle');\n\n if (inactivityTimeoutRef.current) {\n inactivityTimeoutRef.current = false;\n setConversationStatus('inactivity-timeout');\n return;\n }\n\n if (creditExhaustedRef.current) {\n creditExhaustedRef.current = false;\n setConversationStatus('credit-exhausted');\n return;\n }\n\n if (conversationLimitReachedRef.current) {\n conversationLimitReachedRef.current = false;\n setConversationStatus('conversation-limit-reached');\n return;\n }\n\n switch (reason) {\n case DisconnectReason.CLIENT_INITIATED:\n break;\n case DisconnectReason.ROOM_CLOSED:\n setConversationStatus('destroyed');\n break;\n default:\n console.error('Conversation disconnected with reason', reason);\n setConversationStatus('error');\n break;\n }\n }\n\n function handleParticipantConnectedEvent(participant: RemoteParticipant) {\n if (shouldHandleParticipantConnected(participant, type)) {\n handleAgentJoin(participant);\n }\n }\n\n function handleAgentJoin(participant: RemoteParticipant) {\n setAgentConnectionState('joined');\n emitEvent('agentJoined', {\n conversationId: conversationRef.current?.id!,\n participant,\n });\n }\n\n function handleParticipantDisconnectedEvent(participant: RemoteParticipant) {\n setAgentConnectionState('left');\n emitEvent('agentLeft', {\n conversationId: conversationRef.current?.id!,\n participant,\n });\n }\n\n async function leave() {\n if (userConnectionState !== 'joined' && userConnectionState !== 'joining') {\n return;\n }\n\n try {\n setUserConnectionState('leaving');\n await room?.disconnect(true);\n setConversationStatus('destroyed');\n setJoinedAt(undefined);\n emitEvent('callEnded', {\n conversationId: conversationRef.current?.id!,\n });\n } catch (error) {\n console.error('Failed to leave', error);\n setConversationStatus('error');\n }\n }\n\n async function handleExpire() {\n // The duration timer keeps running after the call ends.\n if (\n conversationStatus === 'credit-exhausted' ||\n conversationStatus === 'conversation-limit-reached'\n ) {\n return;\n }\n emitEvent('timeExceeded', {\n conversationId: conversationRef.current?.id!,\n limit: conversationRef.current?.limit!,\n });\n await leave();\n setConversationStatus('exceeded');\n }\n\n async function interrupt() {\n emitEvent('interrupt', {\n conversationId: conversationRef.current?.id!,\n });\n\n await publishConversationDataMessage(room, {}, 'interrupt');\n }\n\n async function dismissInactivity() {\n await publishConversationDataMessage(\n room,\n { type: 'inactivity_dismiss' },\n 'inactivity_dismiss',\n );\n }\n\n async function send(message: string, attachments: Attachment[] = []) {\n await room?.localParticipant.sendText(message, {\n topic: 'lk.chat',\n attributes: {\n attachments: safeStringify(attachments),\n },\n });\n emitEvent('userSendMessage', {\n conversationId: conversationRef.current?.id!,\n message,\n });\n }\n\n function registerRoomEvents() {\n room\n .on('connected', handleConnectedEvent)\n .on('encryptionError', handleEncryptionErrorEvent)\n .on('disconnected', handleDisconnectedEvent)\n .on('transcriptionReceived', handleTranscriptionReceivedEvent)\n .on('participantConnected', handleParticipantConnectedEvent)\n .on('participantDisconnected', handleParticipantDisconnectedEvent)\n .on('dataReceived', handleDataReceivedEvent);\n room.unregisterRpcMethod(GET_TOOLS_RPC_METHOD);\n room.unregisterRpcMethod(EXECUTE_TOOL_RPC_METHOD);\n room.registerRpcMethod(GET_TOOLS_RPC_METHOD, handleGetToolsRpc);\n room.registerRpcMethod(EXECUTE_TOOL_RPC_METHOD, handleExecuteToolRpc);\n }\n\n function unregisterRoomEvents() {\n room.unregisterRpcMethod(GET_TOOLS_RPC_METHOD);\n room.unregisterRpcMethod(EXECUTE_TOOL_RPC_METHOD);\n room.off('connected', handleConnectedEvent);\n room.off('encryptionError', handleEncryptionErrorEvent);\n room.off('disconnected', handleDisconnectedEvent);\n room.off('transcriptionReceived', handleTranscriptionReceivedEvent);\n room.off('participantConnected', handleParticipantConnectedEvent);\n room.off('participantDisconnected', handleParticipantDisconnectedEvent);\n room.off('dataReceived', handleDataReceivedEvent);\n }\n\n return {\n status: conversationStatus,\n conversation: conversation.data,\n join,\n send,\n interrupt,\n dismissInactivity,\n leave,\n };\n}\n"],"mappings":";;;;;AAAA,IAAAA,MAAA,GAAAC,OAAA;AACA,IAAAC,cAAA,GAAAD,OAAA;AAUA,IAAAE,UAAA,GAAAC,sBAAA,CAAAH,OAAA;AACA,IAAAI,eAAA,GAAAJ,OAAA;AACA,IAAAK,SAAA,GAAAL,OAAA;AACA,IAAAM,gBAAA,GAAAN,OAAA;AACA,IAAAO,MAAA,GAAAP,OAAA;AACA,IAAAQ,aAAA,GAAAR,OAAA;AAWA,IAAAS,YAAA,GAAAT,OAAA;AAMA,IAAAU,sBAAA,GAAAV,OAAA;AACA,IAAAW,0BAAA,GAAAX,OAAA;AACA,IAAAY,oBAAA,GAAAZ,OAAA;AAQA,IAAAa,yBAAA,GAAAb,OAAA;AACA,IAAAc,sBAAA,GAAAd,OAAA;AACA,IAAAe,UAAA,GAAAf,OAAA;AACA,IAAAgB,MAAA,GAAAhB,OAAA;AAeA,IAAAiB,UAAA,GAAAjB,OAAA;AAQO,SAASkB,eAAeA,CAAC;EAC9BC,QAAQ,GAAG,IAAI;E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+B,CAAC,CAC3DoB,EAAE,CAAC,yBAAyB,EAAEjB,kCAAkC,CAAC,CACjEiB,EAAE,CAAC,cAAc,EAAExC,uBAAuB,CAAC;IAC9ClL,IAAI,CAAC2N,mBAAmB,CAACC,+BAAoB,CAAC;IAC9C5N,IAAI,CAAC2N,mBAAmB,CAACE,kCAAuB,CAAC;IACjD7N,IAAI,CAAC8N,iBAAiB,CAACF,+BAAoB,EAAE5D,iBAAiB,CAAC;IAC/DhK,IAAI,CAAC8N,iBAAiB,CAACD,kCAAuB,EAAEzD,oBAAoB,CAAC;EACvE;EAEA,SAAS7F,oBAAoBA,CAAA,EAAG;IAC9BvE,IAAI,CAAC2N,mBAAmB,CAACC,+BAAoB,CAAC;IAC9C5N,IAAI,CAAC2N,mBAAmB,CAACE,kCAAuB,CAAC;IACjD7N,IAAI,CAAC+N,GAAG,CAAC,WAAW,EAAEjC,oBAAoB,CAAC;IAC3C9L,IAAI,CAAC+N,GAAG,CAAC,iBAAiB,EAAE/B,0BAA0B,CAAC;IACvDhM,IAAI,CAAC+N,GAAG,CAAC,cAAc,EAAE9B,uBAAuB,CAAC;IACjDjM,IAAI,CAAC+N,GAAG,CAAC,uBAAuB,EAAE5H,gCAAgC,CAAC;IACnEnG,IAAI,CAAC+N,GAAG,CAAC,sBAAsB,EAAEzB,+BAA+B,CAAC;IACjEtM,IAAI,CAAC+N,GAAG,CAAC,yBAAyB,EAAEtB,kCAAkC,CAAC;IACvEzM,IAAI,CAAC+N,GAAG,CAAC,cAAc,EAAE7C,uBAAuB,CAAC;EACnD;EAEA,OAAO;IACL8C,MAAM,EAAE5M,kBAAkB;IAC1BtB,YAAY,EAAEA,YAAY,CAACoB,IAAI;IAC/B8D,IAAI;IACJoI,IAAI;IACJJ,SAAS;IACTG,iBAAiB;IACjBR;EACF,CAAC;AACH","ignoreList":[]}
|
|
1
|
+
{"version":3,"names":["_react","require","_livekitClient","_invariant","_interopRequireDefault","_reactTimerHook","_reactUse","_componentsReact","_jotai","_conversation","_sdkConsumer","_useCreateConversation","_useSpeechActivityDetector","_useParticipantTrack","_useEmitConversationEvent","_useToolCallingRuntime","_serialize","_utils","_constants","useConversation","autoJoin","type","config","startWithMicrophone","startWithCamera","firstConversation","lastConversationTopic","_conversation$data2","setLogLevel","LogLevel","silent","conversation","useCreateConversation","room","useEnsureRoom","speaker","useAtomValue","state","microphone","setMicrophone","useAtom","camera","setCamera","tools","toolsRegistry","useSdkConsumer","toolRuntime","useToolCallingRuntime","toolsRegistryRef","useLatest","conversationRef","data","toolRuntimeRef","conversationStatus","setConversationStatus","userConnectionState","setUserConnectionState","joinedAt","setJoinedAt","setActiveMediaDevice","setMicrophoneDeviceId","useMediaDeviceSelect","kind","setSpeakerDeviceId","setCameraDeviceId","requestPermissions","enabled","setTranscriptions","useSetAtom","transcriptions","agentConnectionState","setAgentConnectionState","setAgentActivityState","agentActivityState","setUserActivityState","userActivityState","emitEvent","useEmitConversationEvent","inactivityTimeoutRef","useRef","creditExhaustedRef","conversationLimitReachedRef","planMinutesExhaustedRef","acousticPhaseRef","acousticT0Ref","latestTurnMetadataRef","isConnectedRef","userCumulativeTrackStatsRef","undefined","agentCumulativeTrackStatsRef","userMicPublication","useParticipantTrack","source","Source","Microphone","agentMicPublication","timer","useTimer","autoStart","onExpire","handleExpire","expiryTimestamp","Date","useEffect","registerRoomEvents","unregisterRoomEvents","useUpdateEffect","deviceId","localParticipant","setMicrophoneEnabled","setCameraEnabled","resolution","width","height","join","_conversation$data","limit","restart","getTime","_conversation$data3","invariant","url","URL","accessToken","searchParams","get","connect","remoteParticipant","findJoinedAgentParticipant","handleAgentJoin","enableMediaDevices","error","console","handleTranscriptionReceivedEvent","segments","participant","map","s","id","message","text","ParticipantKind","AGENT","old","mergeTranscriptions","handleTurnDetectionEvent","_conversationRef$curr","conversationId","current","participantKind","eventState","turnDetectionStrategy","sequence","speechId","handleAcousticUserOnset","handleAcousticUserOffset","timestampMs","ACOUSTIC_USER_HANGOVER_MS","handleAcousticAgentOnset","_conversationRef$curr2","latencyMs","emitConversationTurnLatency","clientAcousticLatencyMs","_conversationRef$curr3","userReport","agentReport","Promise","all","getTrackStats","userStats","parseTrackStats","agentStats","cumulativeTrackStats","rttMs","roundTripTimeMs","jitterBufferDelayMs","userPacketsLost","packetsLost","agentPacketsLost","handleAcousticAgentOffset","useSpeechActivityDetector","onSpeechStart","onSpeechEnd","thresholdRms","ACOUSTIC_USER_THRESHOLD_RMS","hangoverMs","ACOUSTIC_AGENT_HANGOVER_MS","handleInactivityWarningEvent","_conversationRef$curr4","gracePeriodSec","grace_period_sec","handleInactivityTimeoutEvent","_data","_conversationRef$curr5","handleGetToolsRpc","JSON","stringify","buildToolDefinitions","handleExecuteToolRpc","call","parseFunctionCallPayload","payload","functionCallId","result","executeToolCalls","extractToolErrorMessage","dataChannelHandlers","guard","checkIsTurnDetectionData","handle","checkIsInactivityWarningData","checkIsInactivityTimeoutData","handleDataReceivedEvent","_participant","_kind","topic","decoded","decodeDataPayload","checkIsCreditExhaustedMessage","_conversationRef$curr6","checkIsConversationLimitReachedMessage","_conversationRef$curr7","checkIsPlanMinutesExhaustedMessage","_conversationRef$curr8","resolve","catch","handleConnectedEvent","_conversationRef$curr9","handleEncryptionErrorEvent","handleDisconnectedEvent","reason","DisconnectReason","CLIENT_INITIATED","ROOM_CLOSED","handleParticipantConnectedEvent","shouldHandleParticipantConnected","_conversationRef$curr0","handleParticipantDisconnectedEvent","_conversationRef$curr1","leave","_conversationRef$curr10","disconnect","_conversationRef$curr11","_conversationRef$curr12","interrupt","_conversationRef$curr13","publishConversationDataMessage","dismissInactivity","send","attachments","_conversationRef$curr14","sendText","attributes","safeStringify","on","unregisterRpcMethod","GET_TOOLS_RPC_METHOD","EXECUTE_TOOL_RPC_METHOD","registerRpcMethod","off","status"],"sources":["../../../../../src/hooks/useConversation/livekit/useConversation.ts"],"sourcesContent":["import { useEffect, useRef } from 'react';\nimport {\n DisconnectReason,\n Participant,\n setLogLevel,\n ParticipantKind,\n RemoteParticipant,\n TranscriptionSegment,\n LogLevel,\n type RpcInvocationData,\n} from 'livekit-client';\nimport invariant from 'invariant';\nimport { useTimer } from 'react-timer-hook';\nimport { useLatest, useUpdateEffect } from 'react-use';\nimport { useEnsureRoom, useMediaDeviceSelect } from '@livekit/components-react';\nimport { useAtom, useAtomValue, useSetAtom } from 'jotai';\nimport {\n Conversation,\n state,\n type ConversationTranscription,\n} from '../../../conversation';\nimport type {\n UseConversationResult,\n UseConversationOptions,\n Attachment,\n} from '../types';\nimport type { FunctionCallResult } from '../../../types/service';\nimport { useSdkConsumer } from '../../../sdk-consumer';\nimport type {\n InactivityWarningData,\n InactivityTimeoutData,\n TurnDetectionData,\n} from './types';\nimport { useCreateConversation } from '../../useCreateConversation';\nimport { useSpeechActivityDetector } from '../../useSpeechActivityDetector';\nimport {\n useParticipantTrack,\n Source,\n getTrackStats,\n parseTrackStats,\n type CumulativeTrackStats,\n} from '../../useParticipantTrack';\n\nimport { useEmitConversationEvent } from '../../useConversationEvents/useEmitConversationEvent';\nimport { useToolCallingRuntime } from '../../useTools/runtime/useToolCallingRuntime';\nimport { extractToolErrorMessage } from '../../useTools/utils/serialize';\nimport {\n checkIsTurnDetectionData,\n checkIsInactivityWarningData,\n checkIsInactivityTimeoutData,\n checkIsCreditExhaustedMessage,\n checkIsConversationLimitReachedMessage,\n checkIsPlanMinutesExhaustedMessage,\n buildToolDefinitions,\n decodeDataPayload,\n findJoinedAgentParticipant,\n mergeTranscriptions,\n parseFunctionCallPayload,\n publishConversationDataMessage,\n safeStringify,\n shouldHandleParticipantConnected,\n} from './utils';\nimport {\n ACOUSTIC_AGENT_HANGOVER_MS,\n ACOUSTIC_USER_HANGOVER_MS,\n ACOUSTIC_USER_THRESHOLD_RMS,\n EXECUTE_TOOL_RPC_METHOD,\n GET_TOOLS_RPC_METHOD,\n} from './constants';\n\nexport function useConversation({\n autoJoin = true,\n type,\n config,\n startWithMicrophone = false,\n startWithCamera = false,\n firstConversation,\n lastConversationTopic,\n}: UseConversationOptions): UseConversationResult {\n setLogLevel(LogLevel.silent);\n\n const conversation = useCreateConversation({\n type,\n config,\n firstConversation,\n lastConversationTopic,\n });\n const room = useEnsureRoom();\n const speaker = useAtomValue(state.speaker);\n const [microphone, setMicrophone] = useAtom(state.microphone);\n const [camera, setCamera] = useAtom(state.camera);\n const { tools: toolsRegistry = {} } = useSdkConsumer();\n const toolRuntime = useToolCallingRuntime();\n const toolsRegistryRef = useLatest(toolsRegistry);\n\n // for use in register/unregister room events\n const conversationRef = useLatest<Conversation | undefined>(\n conversation.data,\n );\n const toolRuntimeRef = useLatest(toolRuntime);\n\n const [conversationStatus, setConversationStatus] = useAtom(\n state.conversationStatus,\n );\n\n const [userConnectionState, setUserConnectionState] = useAtom(\n state.userConnectionState,\n );\n\n const [joinedAt, setJoinedAt] = useAtom(state.joinedAt);\n\n const { setActiveMediaDevice: setMicrophoneDeviceId } = useMediaDeviceSelect({\n kind: 'audioinput',\n });\n const { setActiveMediaDevice: setSpeakerDeviceId } = useMediaDeviceSelect({\n kind: 'audiooutput',\n });\n const { setActiveMediaDevice: setCameraDeviceId } = useMediaDeviceSelect({\n kind: 'videoinput',\n requestPermissions: camera.enabled,\n });\n\n const setTranscriptions = useSetAtom(state.transcriptions);\n const [agentConnectionState, setAgentConnectionState] = useAtom(\n state.agentConnectionState,\n );\n const setAgentActivityState = useSetAtom(state.agentActivityState);\n const setUserActivityState = useSetAtom(state.userActivityState);\n const emitEvent = useEmitConversationEvent();\n\n const inactivityTimeoutRef = useRef(false);\n const creditExhaustedRef = useRef(false);\n const conversationLimitReachedRef = useRef(false);\n const planMinutesExhaustedRef = useRef(false);\n const acousticPhaseRef = useRef<'idle' | 'waitingForAgent' | 'busy'>('idle');\n const acousticT0Ref = useRef<number | null>(null);\n const latestTurnMetadataRef = useRef<{\n turnDetectionStrategy?: string;\n sequence?: number;\n speechId?: string;\n }>({});\n const isConnectedRef = useRef(false);\n const userCumulativeTrackStatsRef = useRef<CumulativeTrackStats | undefined>(\n undefined,\n );\n const agentCumulativeTrackStatsRef = useRef<CumulativeTrackStats | undefined>(\n undefined,\n );\n\n const userMicPublication = useParticipantTrack({\n type: 'user',\n source: Source.Microphone,\n });\n const agentMicPublication = useParticipantTrack({\n type: 'agent',\n source: Source.Microphone,\n });\n\n const timer = useTimer({\n autoStart: false,\n onExpire: handleExpire,\n expiryTimestamp: new Date(),\n });\n\n useEffect(() => {\n if (!room) {\n return;\n }\n registerRoomEvents();\n\n return () => {\n unregisterRoomEvents();\n };\n }, [room]);\n\n useUpdateEffect(() => {\n setMicrophoneDeviceId(microphone.deviceId);\n }, [microphone.deviceId]);\n\n useUpdateEffect(() => {\n setSpeakerDeviceId(speaker.deviceId);\n }, [speaker.deviceId]);\n\n useUpdateEffect(() => {\n setCameraDeviceId(camera.deviceId);\n }, [camera.deviceId]);\n\n useUpdateEffect(() => {\n if (agentConnectionState !== 'joined') {\n return;\n }\n room.localParticipant.setMicrophoneEnabled(microphone.enabled);\n }, [microphone.enabled, agentConnectionState]);\n\n useUpdateEffect(() => {\n if (agentConnectionState !== 'joined') {\n return;\n }\n room.localParticipant.setCameraEnabled(camera.enabled, {\n resolution: { width: 1920, height: 1080 },\n });\n }, [camera.enabled, agentConnectionState]);\n\n useEffect(() => {\n if (!autoJoin) {\n return;\n }\n\n if (conversationStatus === 'created') {\n void join();\n }\n }, [conversationStatus, autoJoin]);\n\n useEffect(() => {\n if (!joinedAt || conversation.data?.limit === undefined) {\n return;\n }\n\n timer.restart(new Date(joinedAt.getTime() + conversation.data!.limit!));\n }, [joinedAt, conversation.data?.limit]);\n\n async function join() {\n invariant(userConnectionState === 'idle', 'Already joined');\n invariant(conversation.data, 'Conversation is not ready');\n const url = new URL(conversation?.data?.url || '');\n const accessToken = url.searchParams.get('token');\n try {\n setUserConnectionState('joining');\n await room?.connect(conversation.data.url, accessToken!, {});\n\n // sometimes the agent is already joined before the user joins the conversation\n const remoteParticipant = findJoinedAgentParticipant(room, type);\n if (remoteParticipant && agentConnectionState !== 'joined') {\n handleAgentJoin(remoteParticipant);\n }\n\n enableMediaDevices();\n } catch (error) {\n console.error('Failed to join', error);\n setUserConnectionState('join-error');\n }\n }\n\n function enableMediaDevices() {\n if (startWithMicrophone) {\n setMicrophone({ ...microphone, enabled: true });\n }\n if (startWithCamera && type === 'video') {\n setCamera({ ...camera, enabled: true });\n }\n }\n\n function handleTranscriptionReceivedEvent(\n segments: TranscriptionSegment[],\n participant?: Participant,\n ) {\n const transcriptions: ConversationTranscription[] = segments.map((s) => ({\n id: s.id,\n message: s.text,\n source: participant?.kind === ParticipantKind.AGENT ? 'agent' : 'user',\n }));\n\n setTranscriptions((old) => mergeTranscriptions(transcriptions, old));\n }\n\n function handleTurnDetectionEvent(data: TurnDetectionData) {\n const conversationId = conversationRef.current?.id;\n const { participantKind, state: eventState } = data;\n switch (participantKind) {\n case 'STANDARD':\n if (eventState === 'listening') {\n latestTurnMetadataRef.current = {\n turnDetectionStrategy: data.turnDetectionStrategy,\n sequence: data.sequence,\n speechId: data.speechId,\n };\n }\n emitEvent(\n eventState === 'speaking' ? 'userSpeakStart' : 'userSpeakStop',\n { conversationId: conversationId! },\n );\n setUserActivityState(eventState);\n break;\n case 'AGENT':\n if (data.speechId) {\n latestTurnMetadataRef.current = {\n ...latestTurnMetadataRef.current,\n speechId: data.speechId,\n };\n }\n emitEvent(\n eventState === 'speaking' ? 'agentSpeakStart' : 'agentSpeakStop',\n { conversationId: conversationId! },\n );\n setAgentActivityState(eventState);\n break;\n }\n }\n\n function handleAcousticUserOnset() {\n if (!isConnectedRef.current) {\n return;\n }\n if (acousticPhaseRef.current === 'waitingForAgent') {\n acousticPhaseRef.current = 'idle';\n acousticT0Ref.current = null;\n }\n }\n\n function handleAcousticUserOffset(timestampMs: number) {\n if (!isConnectedRef.current || acousticPhaseRef.current !== 'idle') {\n return;\n }\n acousticT0Ref.current = timestampMs - ACOUSTIC_USER_HANGOVER_MS;\n acousticPhaseRef.current = 'waitingForAgent';\n }\n\n function handleAcousticAgentOnset(timestampMs: number) {\n if (\n !isConnectedRef.current ||\n acousticPhaseRef.current !== 'waitingForAgent' ||\n acousticT0Ref.current == null\n ) {\n return;\n }\n\n const latencyMs = timestampMs - acousticT0Ref.current;\n acousticT0Ref.current = null;\n acousticPhaseRef.current = 'busy';\n\n if (latencyMs < 0 || latencyMs > 15000) {\n return;\n }\n\n emitEvent('responseLatency', {\n conversationId: conversationRef.current?.id!,\n latencyMs,\n turnDetectionStrategy:\n latestTurnMetadataRef.current.turnDetectionStrategy!,\n sequence: latestTurnMetadataRef.current.sequence,\n speechId: latestTurnMetadataRef.current.speechId,\n });\n\n void emitConversationTurnLatency(latencyMs);\n }\n\n async function emitConversationTurnLatency(clientAcousticLatencyMs: number) {\n const [userReport, agentReport] = await Promise.all([\n getTrackStats(userMicPublication),\n getTrackStats(agentMicPublication),\n ]);\n const userStats = parseTrackStats(\n userReport,\n userCumulativeTrackStatsRef.current,\n );\n const agentStats = parseTrackStats(\n agentReport,\n agentCumulativeTrackStatsRef.current,\n );\n userCumulativeTrackStatsRef.current = userStats.cumulativeTrackStats;\n agentCumulativeTrackStatsRef.current = agentStats.cumulativeTrackStats;\n\n emitEvent('conversationTurnLatency', {\n conversationId: conversationRef.current?.id!,\n speechId: latestTurnMetadataRef.current.speechId,\n sequence: latestTurnMetadataRef.current.sequence,\n clientAcousticLatencyMs,\n rttMs: userStats.roundTripTimeMs,\n jitterBufferDelayMs: agentStats.jitterBufferDelayMs,\n userPacketsLost: userStats.packetsLost,\n agentPacketsLost: agentStats.packetsLost,\n });\n }\n\n function handleAcousticAgentOffset() {\n acousticPhaseRef.current = 'idle';\n }\n\n useSpeechActivityDetector({\n source: 'user',\n onSpeechStart: handleAcousticUserOnset,\n onSpeechEnd: handleAcousticUserOffset,\n thresholdRms: ACOUSTIC_USER_THRESHOLD_RMS,\n hangoverMs: ACOUSTIC_USER_HANGOVER_MS,\n });\n useSpeechActivityDetector({\n source: 'agent',\n onSpeechStart: handleAcousticAgentOnset,\n onSpeechEnd: handleAcousticAgentOffset,\n hangoverMs: ACOUSTIC_AGENT_HANGOVER_MS,\n });\n\n function handleInactivityWarningEvent(data: InactivityWarningData) {\n emitEvent('inactivityWarning', {\n conversationId: conversationRef.current?.id!,\n gracePeriodSec: data.grace_period_sec,\n });\n }\n\n function handleInactivityTimeoutEvent(_data: InactivityTimeoutData) {\n inactivityTimeoutRef.current = true;\n emitEvent('inactivityTimeout', {\n conversationId: conversationRef.current?.id!,\n });\n }\n\n async function handleGetToolsRpc() {\n return JSON.stringify(buildToolDefinitions(toolsRegistryRef.current));\n }\n\n async function handleExecuteToolRpc(data: RpcInvocationData) {\n const call = parseFunctionCallPayload(data.payload);\n if (!call) {\n return JSON.stringify({\n functionCallId: '',\n result: '',\n error: 'Malformed function call payload.',\n } satisfies FunctionCallResult);\n }\n try {\n const [result] = await toolRuntimeRef.current.executeToolCalls([call]);\n return JSON.stringify(result);\n } catch (error) {\n return JSON.stringify({\n functionCallId: call.functionCallId,\n result: '',\n error: extractToolErrorMessage(error),\n } satisfies FunctionCallResult);\n }\n }\n\n const dataChannelHandlers: {\n guard: (data: unknown) => boolean;\n handle: (data: unknown) => void | Promise<void>;\n }[] = [\n {\n guard: checkIsTurnDetectionData,\n handle: handleTurnDetectionEvent as (data: unknown) => void,\n },\n {\n guard: checkIsInactivityWarningData,\n handle: handleInactivityWarningEvent as (data: unknown) => void,\n },\n {\n guard: checkIsInactivityTimeoutData,\n handle: handleInactivityTimeoutEvent as (data: unknown) => void,\n },\n ];\n\n function handleDataReceivedEvent(\n payload: Uint8Array,\n _participant?: RemoteParticipant,\n _kind?: unknown,\n topic?: string,\n ) {\n const decoded = decodeDataPayload(payload);\n if (decoded === null) {\n return;\n }\n if (checkIsCreditExhaustedMessage(decoded, topic)) {\n creditExhaustedRef.current = true;\n emitEvent('creditExhausted', {\n conversationId: conversationRef.current?.id!,\n });\n return;\n }\n if (checkIsConversationLimitReachedMessage(decoded, topic)) {\n conversationLimitReachedRef.current = true;\n emitEvent('conversationLimitReached', {\n conversationId: conversationRef.current?.id!,\n });\n return;\n }\n if (checkIsPlanMinutesExhaustedMessage(decoded, topic)) {\n planMinutesExhaustedRef.current = true;\n emitEvent('planMinutesExhausted', {\n conversationId: conversationRef.current?.id!,\n });\n return;\n }\n for (const { guard, handle } of dataChannelHandlers) {\n if (guard(decoded)) {\n void Promise.resolve(handle(decoded)).catch((error) => {\n console.error('Failed to handle data channel payload', error);\n });\n return;\n }\n }\n }\n\n function handleConnectedEvent() {\n isConnectedRef.current = true;\n setUserConnectionState('joined');\n setAgentConnectionState('joining');\n emitEvent('callStarted', {\n conversationId: conversationRef.current?.id!,\n });\n }\n\n async function handleEncryptionErrorEvent(error: Error) {\n console.error('Encryption error', error);\n setConversationStatus('error');\n }\n\n function handleDisconnectedEvent(reason?: DisconnectReason) {\n isConnectedRef.current = false;\n acousticPhaseRef.current = 'idle';\n acousticT0Ref.current = null;\n latestTurnMetadataRef.current = {};\n userCumulativeTrackStatsRef.current = undefined;\n agentCumulativeTrackStatsRef.current = undefined;\n setAgentActivityState('idle');\n setAgentConnectionState('idle');\n setUserActivityState('idle');\n setUserConnectionState('idle');\n\n if (inactivityTimeoutRef.current) {\n inactivityTimeoutRef.current = false;\n setConversationStatus('inactivity-timeout');\n return;\n }\n\n if (creditExhaustedRef.current) {\n creditExhaustedRef.current = false;\n setConversationStatus('credit-exhausted');\n return;\n }\n\n if (conversationLimitReachedRef.current) {\n conversationLimitReachedRef.current = false;\n setConversationStatus('conversation-limit-reached');\n return;\n }\n\n if (planMinutesExhaustedRef.current) {\n planMinutesExhaustedRef.current = false;\n setConversationStatus('plan-minutes-exhausted');\n return;\n }\n\n switch (reason) {\n case DisconnectReason.CLIENT_INITIATED:\n break;\n case DisconnectReason.ROOM_CLOSED:\n setConversationStatus('destroyed');\n break;\n default:\n console.error('Conversation disconnected with reason', reason);\n setConversationStatus('error');\n break;\n }\n }\n\n function handleParticipantConnectedEvent(participant: RemoteParticipant) {\n if (shouldHandleParticipantConnected(participant, type)) {\n handleAgentJoin(participant);\n }\n }\n\n function handleAgentJoin(participant: RemoteParticipant) {\n setAgentConnectionState('joined');\n emitEvent('agentJoined', {\n conversationId: conversationRef.current?.id!,\n participant,\n });\n }\n\n function handleParticipantDisconnectedEvent(participant: RemoteParticipant) {\n setAgentConnectionState('left');\n emitEvent('agentLeft', {\n conversationId: conversationRef.current?.id!,\n participant,\n });\n }\n\n async function leave() {\n if (userConnectionState !== 'joined' && userConnectionState !== 'joining') {\n return;\n }\n\n try {\n setUserConnectionState('leaving');\n await room?.disconnect(true);\n setConversationStatus('destroyed');\n setJoinedAt(undefined);\n emitEvent('callEnded', {\n conversationId: conversationRef.current?.id!,\n });\n } catch (error) {\n console.error('Failed to leave', error);\n setConversationStatus('error');\n }\n }\n\n async function handleExpire() {\n // The duration timer keeps running after the call ends.\n if (\n conversationStatus === 'credit-exhausted' ||\n conversationStatus === 'conversation-limit-reached' ||\n conversationStatus === 'plan-minutes-exhausted'\n ) {\n return;\n }\n emitEvent('timeExceeded', {\n conversationId: conversationRef.current?.id!,\n limit: conversationRef.current?.limit!,\n });\n await leave();\n setConversationStatus('exceeded');\n }\n\n async function interrupt() {\n emitEvent('interrupt', {\n conversationId: conversationRef.current?.id!,\n });\n\n await publishConversationDataMessage(room, {}, 'interrupt');\n }\n\n async function dismissInactivity() {\n await publishConversationDataMessage(\n room,\n { type: 'inactivity_dismiss' },\n 'inactivity_dismiss',\n );\n }\n\n async function send(message: string, attachments: Attachment[] = []) {\n await room?.localParticipant.sendText(message, {\n topic: 'lk.chat',\n attributes: {\n attachments: safeStringify(attachments),\n },\n });\n emitEvent('userSendMessage', {\n conversationId: conversationRef.current?.id!,\n message,\n });\n }\n\n function registerRoomEvents() {\n room\n .on('connected', handleConnectedEvent)\n .on('encryptionError', handleEncryptionErrorEvent)\n .on('disconnected', handleDisconnectedEvent)\n .on('transcriptionReceived', handleTranscriptionReceivedEvent)\n .on('participantConnected', handleParticipantConnectedEvent)\n .on('participantDisconnected', handleParticipantDisconnectedEvent)\n .on('dataReceived', handleDataReceivedEvent);\n room.unregisterRpcMethod(GET_TOOLS_RPC_METHOD);\n room.unregisterRpcMethod(EXECUTE_TOOL_RPC_METHOD);\n room.registerRpcMethod(GET_TOOLS_RPC_METHOD, handleGetToolsRpc);\n room.registerRpcMethod(EXECUTE_TOOL_RPC_METHOD, handleExecuteToolRpc);\n }\n\n function unregisterRoomEvents() {\n room.unregisterRpcMethod(GET_TOOLS_RPC_METHOD);\n room.unregisterRpcMethod(EXECUTE_TOOL_RPC_METHOD);\n room.off('connected', handleConnectedEvent);\n room.off('encryptionError', handleEncryptionErrorEvent);\n room.off('disconnected', handleDisconnectedEvent);\n room.off('transcriptionReceived', handleTranscriptionReceivedEvent);\n room.off('participantConnected', handleParticipantConnectedEvent);\n room.off('participantDisconnected', handleParticipantDisconnectedEvent);\n room.off('dataReceived', handleDataReceivedEvent);\n }\n\n return {\n status: conversationStatus,\n conversation: conversation.data,\n join,\n send,\n interrupt,\n dismissInactivity,\n leave,\n };\n}\n"],"mappings":";;;;;AAAA,IAAAA,MAAA,GAAAC,OAAA;AACA,IAAAC,cAAA,GAAAD,OAAA;AAUA,IAAAE,UAAA,GAAAC,sBAAA,CAAAH,OAAA;AACA,IAAAI,eAAA,GAAAJ,OAAA;AACA,IAAAK,SAAA,GAAAL,OAAA;AACA,IAAAM,gBAAA,GAAAN,OAAA;AACA,IAAAO,MAAA,GAAAP,OAAA;AACA,IAAAQ,aAAA,GAAAR,OAAA;AAWA,IAAAS,YAAA,GAAAT,OAAA;AAMA,IAAAU,sBAAA,GAAAV,OAAA;AACA,IAAAW,0BAAA,GAAAX,OAAA;AACA,IAAAY,oBAAA,GAAAZ,OAAA;AAQA,IAAAa,yBAAA,GAAAb,OAAA;AACA,IAAAc,sBAAA,GAAAd,OAAA;AACA,IAAAe,UAAA,GAAAf,OAAA;AACA,IAAAgB,MAAA,GAAAhB,OAAA;AAgBA,IAAA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AACkO,GAAG,CAAC,cAAc,EAAE9B,uBAAuB,CAAC;IACjDpM,IAAI,CAACkO,GAAG,CAAC,uBAAuB,EAAE9H,gCAAgC,CAAC;IACnEpG,IAAI,CAACkO,GAAG,CAAC,sBAAsB,EAAEzB,+BAA+B,CAAC;IACjEzM,IAAI,CAACkO,GAAG,CAAC,yBAAyB,EAAEtB,kCAAkC,CAAC;IACvE5M,IAAI,CAACkO,GAAG,CAAC,cAAc,EAAE/C,uBAAuB,CAAC;EACnD;EAEA,OAAO;IACLgD,MAAM,EAAE/M,kBAAkB;IAC1BtB,YAAY,EAAEA,YAAY,CAACoB,IAAI;IAC/B+D,IAAI;IACJsI,IAAI;IACJJ,SAAS;IACTG,iBAAiB;IACjBR;EACF,CAAC;AACH","ignoreList":[]}
|
|
@@ -5,6 +5,7 @@ exports.checkIsConversationLimitReachedMessage = checkIsConversationLimitReached
|
|
|
5
5
|
exports.checkIsCreditExhaustedMessage = checkIsCreditExhaustedMessage;
|
|
6
6
|
exports.checkIsInactivityTimeoutData = checkIsInactivityTimeoutData;
|
|
7
7
|
exports.checkIsInactivityWarningData = checkIsInactivityWarningData;
|
|
8
|
+
exports.checkIsPlanMinutesExhaustedMessage = checkIsPlanMinutesExhaustedMessage;
|
|
8
9
|
exports.checkIsTurnDetectionData = checkIsTurnDetectionData;
|
|
9
10
|
exports.decodeDataPayload = decodeDataPayload;
|
|
10
11
|
function decodeDataPayload(data) {
|
|
@@ -33,4 +34,7 @@ function checkIsCreditExhaustedMessage(data, topic) {
|
|
|
33
34
|
function checkIsConversationLimitReachedMessage(data, topic) {
|
|
34
35
|
return checkIsBillingEndedMessage(data, topic, 'limit_reached');
|
|
35
36
|
}
|
|
37
|
+
function checkIsPlanMinutesExhaustedMessage(data, topic) {
|
|
38
|
+
return checkIsBillingEndedMessage(data, topic, 'plan_minutes_exhausted');
|
|
39
|
+
}
|
|
36
40
|
//# sourceMappingURL=dataChannel.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"names":["decodeDataPayload","data","JSON","parse","TextDecoder","decode","error","console","checkIsTurnDetectionData","checkIsInactivityWarningData","type","grace_period_sec","checkIsInactivityTimeoutData","checkIsBillingEndedMessage","topic","reason","checkIsCreditExhaustedMessage","checkIsConversationLimitReachedMessage"],"sources":["../../../../../../src/hooks/useConversation/livekit/utils/dataChannel.ts"],"sourcesContent":["import type {\n InactivityWarningData,\n InactivityTimeoutData,\n TurnDetectionData,\n} from '../types';\n\nexport function decodeDataPayload(data: Uint8Array): unknown {\n try {\n return JSON.parse(new TextDecoder().decode(data));\n } catch (error) {\n console.error('Failed to decode data received payload', error);\n return null;\n }\n}\n\nexport function checkIsTurnDetectionData(\n data: unknown,\n): data is TurnDetectionData {\n return (\n typeof data === 'object' &&\n data !== null &&\n 'participantKind' in data &&\n 'state' in data\n );\n}\n\nexport function checkIsInactivityWarningData(\n data: unknown,\n): data is InactivityWarningData {\n return (\n typeof data === 'object' &&\n data !== null &&\n 'type' in data &&\n (data as Record<string, unknown>).type === 'inactivity_warning' &&\n 'grace_period_sec' in data &&\n typeof (data as Record<string, unknown>).grace_period_sec === 'number'\n );\n}\n\nexport function checkIsInactivityTimeoutData(\n data: unknown,\n): data is InactivityTimeoutData {\n return (\n typeof data === 'object' &&\n data !== null &&\n 'type' in data &&\n (data as Record<string, unknown>).type === 'inactivity_timeout'\n );\n}\n\nfunction checkIsBillingEndedMessage(\n data: unknown,\n topic: string | undefined,\n reason: string,\n): boolean {\n return (\n topic === 'billing' &&\n typeof data === 'object' &&\n data !== null &&\n (data as Record<string, unknown>).type === 'ended' &&\n (data as Record<string, unknown>).reason === reason\n );\n}\n\nexport function checkIsCreditExhaustedMessage(\n data: unknown,\n topic: string | undefined,\n): boolean {\n return checkIsBillingEndedMessage(data, topic, 'insufficient_credit');\n}\n\nexport function checkIsConversationLimitReachedMessage(\n data: unknown,\n topic: string | undefined,\n): boolean {\n return checkIsBillingEndedMessage(data, topic, 'limit_reached');\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"names":["decodeDataPayload","data","JSON","parse","TextDecoder","decode","error","console","checkIsTurnDetectionData","checkIsInactivityWarningData","type","grace_period_sec","checkIsInactivityTimeoutData","checkIsBillingEndedMessage","topic","reason","checkIsCreditExhaustedMessage","checkIsConversationLimitReachedMessage","checkIsPlanMinutesExhaustedMessage"],"sources":["../../../../../../src/hooks/useConversation/livekit/utils/dataChannel.ts"],"sourcesContent":["import type {\n InactivityWarningData,\n InactivityTimeoutData,\n TurnDetectionData,\n} from '../types';\n\nexport function decodeDataPayload(data: Uint8Array): unknown {\n try {\n return JSON.parse(new TextDecoder().decode(data));\n } catch (error) {\n console.error('Failed to decode data received payload', error);\n return null;\n }\n}\n\nexport function checkIsTurnDetectionData(\n data: unknown,\n): data is TurnDetectionData {\n return (\n typeof data === 'object' &&\n data !== null &&\n 'participantKind' in data &&\n 'state' in data\n );\n}\n\nexport function checkIsInactivityWarningData(\n data: unknown,\n): data is InactivityWarningData {\n return (\n typeof data === 'object' &&\n data !== null &&\n 'type' in data &&\n (data as Record<string, unknown>).type === 'inactivity_warning' &&\n 'grace_period_sec' in data &&\n typeof (data as Record<string, unknown>).grace_period_sec === 'number'\n );\n}\n\nexport function checkIsInactivityTimeoutData(\n data: unknown,\n): data is InactivityTimeoutData {\n return (\n typeof data === 'object' &&\n data !== null &&\n 'type' in data &&\n (data as Record<string, unknown>).type === 'inactivity_timeout'\n );\n}\n\nfunction checkIsBillingEndedMessage(\n data: unknown,\n topic: string | undefined,\n reason: string,\n): boolean {\n return (\n topic === 'billing' &&\n typeof data === 'object' &&\n data !== null &&\n (data as Record<string, unknown>).type === 'ended' &&\n (data as Record<string, unknown>).reason === reason\n );\n}\n\nexport function checkIsCreditExhaustedMessage(\n data: unknown,\n topic: string | undefined,\n): boolean {\n return checkIsBillingEndedMessage(data, topic, 'insufficient_credit');\n}\n\nexport function checkIsConversationLimitReachedMessage(\n data: unknown,\n topic: string | undefined,\n): boolean {\n return checkIsBillingEndedMessage(data, topic, 'limit_reached');\n}\n\nexport function checkIsPlanMinutesExhaustedMessage(\n data: unknown,\n topic: string | undefined,\n): boolean {\n return checkIsBillingEndedMessage(data, topic, 'plan_minutes_exhausted');\n}\n"],"mappings":";;;;;;;;;;AAMO,SAASA,iBAAiBA,CAACC,IAAgB,EAAW;EAC3D,IAAI;IACF,OAAOC,IAAI,CAACC,KAAK,CAAC,IAAIC,WAAW,CAAC,CAAC,CAACC,MAAM,CAACJ,IAAI,CAAC,CAAC;EACnD,CAAC,CAAC,OAAOK,KAAK,EAAE;IACdC,OAAO,CAACD,KAAK,CAAC,wCAAwC,EAAEA,KAAK,CAAC;IAC9D,OAAO,IAAI;EACb;AACF;AAEO,SAASE,wBAAwBA,CACtCP,IAAa,EACc;EAC3B,OACE,OAAOA,IAAI,KAAK,QAAQ,IACxBA,IAAI,KAAK,IAAI,IACb,iBAAiB,IAAIA,IAAI,IACzB,OAAO,IAAIA,IAAI;AAEnB;AAEO,SAASQ,4BAA4BA,CAC1CR,IAAa,EACkB;EAC/B,OACE,OAAOA,IAAI,KAAK,QAAQ,IACxBA,IAAI,KAAK,IAAI,IACb,MAAM,IAAIA,IAAI,IACbA,IAAI,CAA6BS,IAAI,KAAK,oBAAoB,IAC/D,kBAAkB,IAAIT,IAAI,IAC1B,OAAQA,IAAI,CAA6BU,gBAAgB,KAAK,QAAQ;AAE1E;AAEO,SAASC,4BAA4BA,CAC1CX,IAAa,EACkB;EAC/B,OACE,OAAOA,IAAI,KAAK,QAAQ,IACxBA,IAAI,KAAK,IAAI,IACb,MAAM,IAAIA,IAAI,IACbA,IAAI,CAA6BS,IAAI,KAAK,oBAAoB;AAEnE;AAEA,SAASG,0BAA0BA,CACjCZ,IAAa,EACba,KAAyB,EACzBC,MAAc,EACL;EACT,OACED,KAAK,KAAK,SAAS,IACnB,OAAOb,IAAI,KAAK,QAAQ,IACxBA,IAAI,KAAK,IAAI,IACZA,IAAI,CAA6BS,IAAI,KAAK,OAAO,IACjDT,IAAI,CAA6Bc,MAAM,KAAKA,MAAM;AAEvD;AAEO,SAASC,6BAA6BA,CAC3Cf,IAAa,EACba,KAAyB,EAChB;EACT,OAAOD,0BAA0B,CAACZ,IAAI,EAAEa,KAAK,EAAE,qBAAqB,CAAC;AACvE;AAEO,SAASG,sCAAsCA,CACpDhB,IAAa,EACba,KAAyB,EAChB;EACT,OAAOD,0BAA0B,CAACZ,IAAI,EAAEa,KAAK,EAAE,eAAe,CAAC;AACjE;AAEO,SAASI,kCAAkCA,CAChDjB,IAAa,EACba,KAAyB,EAChB;EACT,OAAOD,0BAA0B,CAACZ,IAAI,EAAEa,KAAK,EAAE,wBAAwB,CAAC;AAC1E","ignoreList":[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"names":[],"sources":["../../../../src/hooks/useConversationEvents/types.tsx"],"sourcesContent":["import React from 'react';\nimport type { RemoteParticipant } from 'livekit-client';\n\nexport type UserSpeakStartPayload = {\n conversationId: string;\n};\n\nexport type TimeExceededPayload = {\n conversationId: string;\n limit: number;\n};\n\nexport type UserSpeakStopPayload = {\n conversationId: string;\n};\n\nexport type AgentSpeakStartPayload = {\n conversationId: string;\n};\n\nexport type AgentSpeakStopPayload = {\n conversationId: string;\n};\n\nexport type ResponseLatencyPayload = {\n conversationId: string;\n latencyMs: number;\n turnDetectionStrategy: string;\n sequence?: number;\n speechId?: string;\n};\n\nexport type ConversationTurnLatencyPayload = {\n conversationId: string;\n speechId?: string;\n sequence?: number;\n clientAcousticLatencyMs: number;\n rttMs?: number;\n jitterBufferDelayMs?: number;\n userPacketsLost?: number;\n agentPacketsLost?: number;\n};\n\nexport type InterruptPayload = {\n conversationId: string;\n};\n\nexport type CallStartedPayload = {\n conversationId: string;\n};\n\nexport type CallEndedPayload = {\n conversationId: string;\n};\n\nexport type UserSendMessagePayload = {\n conversationId: string;\n message: string;\n};\n\nexport type AgentJoinedPayload = {\n conversationId: string;\n participant: RemoteParticipant;\n};\n\nexport type AgentLeftPayload = {\n conversationId: string;\n participant?: RemoteParticipant;\n};\n\nexport type AgentVideoLoadedPayload = {\n videoRef: React.RefObject<HTMLVideoElement>;\n};\n\nexport type InactivityWarningPayload = {\n conversationId: string;\n gracePeriodSec: number;\n};\n\nexport type InactivityTimeoutPayload = {\n conversationId: string;\n};\n\nexport type CreditExhaustedPayload = {\n conversationId: string;\n};\n\nexport type ConversationLimitReachedPayload = {\n conversationId: string;\n};\n\nexport type ConversationEventMap = {\n userSpeakStart: UserSpeakStartPayload;\n userSpeakStop: UserSpeakStopPayload;\n agentSpeakStart: AgentSpeakStartPayload;\n agentSpeakStop: AgentSpeakStopPayload;\n responseLatency: ResponseLatencyPayload;\n conversationTurnLatency: ConversationTurnLatencyPayload;\n interrupt: InterruptPayload;\n callStarted: CallStartedPayload;\n callEnded: CallEndedPayload;\n userSendMessage: UserSendMessagePayload;\n agentJoined: AgentJoinedPayload;\n agentLeft: AgentLeftPayload;\n timeExceeded: TimeExceededPayload;\n agentVideoLoaded: AgentVideoLoadedPayload;\n inactivityWarning: InactivityWarningPayload;\n inactivityTimeout: InactivityTimeoutPayload;\n creditExhausted: CreditExhaustedPayload;\n conversationLimitReached: ConversationLimitReachedPayload;\n};\n\nexport type ConversationEvent = keyof ConversationEventMap;\n\nexport type EventPayload<T extends ConversationEvent> = ConversationEventMap[T];\n"],"mappings":"","ignoreList":[]}
|
|
1
|
+
{"version":3,"names":[],"sources":["../../../../src/hooks/useConversationEvents/types.tsx"],"sourcesContent":["import React from 'react';\nimport type { RemoteParticipant } from 'livekit-client';\n\nexport type UserSpeakStartPayload = {\n conversationId: string;\n};\n\nexport type TimeExceededPayload = {\n conversationId: string;\n limit: number;\n};\n\nexport type UserSpeakStopPayload = {\n conversationId: string;\n};\n\nexport type AgentSpeakStartPayload = {\n conversationId: string;\n};\n\nexport type AgentSpeakStopPayload = {\n conversationId: string;\n};\n\nexport type ResponseLatencyPayload = {\n conversationId: string;\n latencyMs: number;\n turnDetectionStrategy: string;\n sequence?: number;\n speechId?: string;\n};\n\nexport type ConversationTurnLatencyPayload = {\n conversationId: string;\n speechId?: string;\n sequence?: number;\n clientAcousticLatencyMs: number;\n rttMs?: number;\n jitterBufferDelayMs?: number;\n userPacketsLost?: number;\n agentPacketsLost?: number;\n};\n\nexport type InterruptPayload = {\n conversationId: string;\n};\n\nexport type CallStartedPayload = {\n conversationId: string;\n};\n\nexport type CallEndedPayload = {\n conversationId: string;\n};\n\nexport type UserSendMessagePayload = {\n conversationId: string;\n message: string;\n};\n\nexport type AgentJoinedPayload = {\n conversationId: string;\n participant: RemoteParticipant;\n};\n\nexport type AgentLeftPayload = {\n conversationId: string;\n participant?: RemoteParticipant;\n};\n\nexport type AgentVideoLoadedPayload = {\n videoRef: React.RefObject<HTMLVideoElement>;\n};\n\nexport type InactivityWarningPayload = {\n conversationId: string;\n gracePeriodSec: number;\n};\n\nexport type InactivityTimeoutPayload = {\n conversationId: string;\n};\n\nexport type CreditExhaustedPayload = {\n conversationId: string;\n};\n\nexport type ConversationLimitReachedPayload = {\n conversationId: string;\n};\n\nexport type PlanMinutesExhaustedPayload = {\n /** Absent when the server refused to start the conversation. */\n conversationId?: string;\n};\n\nexport type ConversationEventMap = {\n userSpeakStart: UserSpeakStartPayload;\n userSpeakStop: UserSpeakStopPayload;\n agentSpeakStart: AgentSpeakStartPayload;\n agentSpeakStop: AgentSpeakStopPayload;\n responseLatency: ResponseLatencyPayload;\n conversationTurnLatency: ConversationTurnLatencyPayload;\n interrupt: InterruptPayload;\n callStarted: CallStartedPayload;\n callEnded: CallEndedPayload;\n userSendMessage: UserSendMessagePayload;\n agentJoined: AgentJoinedPayload;\n agentLeft: AgentLeftPayload;\n timeExceeded: TimeExceededPayload;\n agentVideoLoaded: AgentVideoLoadedPayload;\n inactivityWarning: InactivityWarningPayload;\n inactivityTimeout: InactivityTimeoutPayload;\n creditExhausted: CreditExhaustedPayload;\n conversationLimitReached: ConversationLimitReachedPayload;\n planMinutesExhausted: PlanMinutesExhaustedPayload;\n};\n\nexport type ConversationEvent = keyof ConversationEventMap;\n\nexport type EventPayload<T extends ConversationEvent> = ConversationEventMap[T];\n"],"mappings":"","ignoreList":[]}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
exports.__esModule = true;
|
|
4
|
+
exports.createConversationFailureStatus = createConversationFailureStatus;
|
|
5
|
+
const PLAN_MINUTES_EXHAUSTED = 'PLAN_MINUTES_EXHAUSTED';
|
|
6
|
+
function createConversationFailureStatus(error) {
|
|
7
|
+
var _err$response, _err$response2, _body$details, _err$message;
|
|
8
|
+
const err = error ?? {};
|
|
9
|
+
// @wix/http-client puts the status and body on `response`; the SDK's HttpError puts them on the error.
|
|
10
|
+
const status = err.status ?? ((_err$response = err.response) == null ? void 0 : _err$response.status);
|
|
11
|
+
const body = ((_err$response2 = err.response) == null ? void 0 : _err$response2.data) ?? err.data;
|
|
12
|
+
if ((body == null || (_body$details = body.details) == null || (_body$details = _body$details.applicationError) == null ? void 0 : _body$details.code) === PLAN_MINUTES_EXHAUSTED) {
|
|
13
|
+
return 'plan-minutes-exhausted';
|
|
14
|
+
}
|
|
15
|
+
if (status === 404 && (_err$message = err.message) != null && _err$message.includes('not found')) {
|
|
16
|
+
return 'voice-not-found';
|
|
17
|
+
}
|
|
18
|
+
return 'initialization-error';
|
|
19
|
+
}
|
|
20
|
+
//# sourceMappingURL=createConversationFailureStatus.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"names":["PLAN_MINUTES_EXHAUSTED","createConversationFailureStatus","error","_err$response","_err$response2","_body$details","_err$message","err","status","response","body","data","details","applicationError","code","message","includes"],"sources":["../../../../src/hooks/useCreateConversation/createConversationFailureStatus.ts"],"sourcesContent":["import type { ConversationStatus } from '../../conversation';\n\ntype CreateConversationFailureStatus = Extract<\n ConversationStatus,\n 'plan-minutes-exhausted' | 'voice-not-found' | 'initialization-error'\n>;\n\ntype ErrorBody = {\n details?: { applicationError?: { code?: string } };\n};\n\ntype CreateConversationError = {\n status?: number;\n message?: string;\n data?: ErrorBody;\n response?: { status?: number; data?: ErrorBody };\n};\n\nconst PLAN_MINUTES_EXHAUSTED = 'PLAN_MINUTES_EXHAUSTED';\n\nexport function createConversationFailureStatus(\n error: unknown,\n): CreateConversationFailureStatus {\n const err = (error ?? {}) as CreateConversationError;\n // @wix/http-client puts the status and body on `response`; the SDK's HttpError puts them on the error.\n const status = err.status ?? err.response?.status;\n const body = err.response?.data ?? err.data;\n\n if (body?.details?.applicationError?.code === PLAN_MINUTES_EXHAUSTED) {\n return 'plan-minutes-exhausted';\n }\n if (status === 404 && err.message?.includes('not found')) {\n return 'voice-not-found';\n }\n return 'initialization-error';\n}\n"],"mappings":";;;;AAkBA,MAAMA,sBAAsB,GAAG,wBAAwB;AAEhD,SAASC,+BAA+BA,CAC7CC,KAAc,EACmB;EAAA,IAAAC,aAAA,EAAAC,cAAA,EAAAC,aAAA,EAAAC,YAAA;EACjC,MAAMC,GAAG,GAAIL,KAAK,IAAI,CAAC,CAA6B;EACpD;EACA,MAAMM,MAAM,GAAGD,GAAG,CAACC,MAAM,MAAAL,aAAA,GAAII,GAAG,CAACE,QAAQ,qBAAZN,aAAA,CAAcK,MAAM;EACjD,MAAME,IAAI,GAAG,EAAAN,cAAA,GAAAG,GAAG,CAACE,QAAQ,qBAAZL,cAAA,CAAcO,IAAI,KAAIJ,GAAG,CAACI,IAAI;EAE3C,IAAI,CAAAD,IAAI,aAAAL,aAAA,GAAJK,IAAI,CAAEE,OAAO,cAAAP,aAAA,GAAbA,aAAA,CAAeQ,gBAAgB,qBAA/BR,aAAA,CAAiCS,IAAI,MAAKd,sBAAsB,EAAE;IACpE,OAAO,wBAAwB;EACjC;EACA,IAAIQ,MAAM,KAAK,GAAG,KAAAF,YAAA,GAAIC,GAAG,CAACQ,OAAO,aAAXT,YAAA,CAAaU,QAAQ,CAAC,WAAW,CAAC,EAAE;IACxD,OAAO,iBAAiB;EAC1B;EACA,OAAO,sBAAsB;AAC/B","ignoreList":[]}
|
|
@@ -9,6 +9,8 @@ var _jotai = require("jotai");
|
|
|
9
9
|
var _reactUse = require("react-use");
|
|
10
10
|
var _conversation = require("../../conversation");
|
|
11
11
|
var _sdkConsumer = require("../../sdk-consumer");
|
|
12
|
+
var _useEmitConversationEvent = require("../useConversationEvents/useEmitConversationEvent");
|
|
13
|
+
var _createConversationFailureStatus = require("./createConversationFailureStatus");
|
|
12
14
|
var _helpers = require("./helpers");
|
|
13
15
|
function useCreateConversation(options) {
|
|
14
16
|
const {
|
|
@@ -24,15 +26,14 @@ function useCreateConversation(options) {
|
|
|
24
26
|
} = (0, _sdkConsumer.useSdkConsumer)();
|
|
25
27
|
const setConversationStatus = (0, _jotai.useSetAtom)(_conversation.state.conversationStatus);
|
|
26
28
|
const [conversation, setConversation] = (0, _jotai.useAtom)(_conversation.state.conversation);
|
|
29
|
+
const emitEvent = (0, _useEmitConversationEvent.useEmitConversationEvent)();
|
|
27
30
|
(0, _react.useEffect)(() => {
|
|
28
31
|
void create().then(() => setConversationStatus('created')).catch(error => {
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
setConversationStatus('voice-not-found');
|
|
33
|
-
} else {
|
|
34
|
-
setConversationStatus('initialization-error');
|
|
32
|
+
const status = (0, _createConversationFailureStatus.createConversationFailureStatus)(error);
|
|
33
|
+
if (status === 'plan-minutes-exhausted') {
|
|
34
|
+
emitEvent('planMinutesExhausted', {});
|
|
35
35
|
}
|
|
36
|
+
setConversationStatus(status);
|
|
36
37
|
});
|
|
37
38
|
}, [type, chatId]);
|
|
38
39
|
(0, _reactUse.useUnmount)(() => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"names":["_invariant","_interopRequireDefault","require","_react","_jotai","_reactUse","_conversation","_sdkConsumer","_helpers","useCreateConversation","options","type","config","chatConfig","firstConversation","lastConversationTopic","chatId","namespace","personaChatService","useSdkConsumer","setConversationStatus","useSetAtom","state","conversationStatus","conversation","setConversation","useAtom","
|
|
1
|
+
{"version":3,"names":["_invariant","_interopRequireDefault","require","_react","_jotai","_reactUse","_conversation","_sdkConsumer","_useEmitConversationEvent","_createConversationFailureStatus","_helpers","useCreateConversation","options","type","config","chatConfig","firstConversation","lastConversationTopic","chatId","namespace","personaChatService","useSdkConsumer","setConversationStatus","useSetAtom","state","conversationStatus","conversation","setConversation","useAtom","emitEvent","useEmitConversationEvent","useEffect","create","then","catch","error","status","createConversationFailureStatus","useUnmount","destroy","limit","data","invariant","result","createInteractiveConversation","url","id","createVoiceConversation","Error","endInteractiveConversation","conversationId","undefined"],"sources":["../../../../src/hooks/useCreateConversation/useCreateConversation.ts"],"sourcesContent":["import invariant from 'invariant';\nimport { useEffect } from 'react';\nimport { useAtom, useSetAtom } from 'jotai';\nimport { useUnmount } from 'react-use';\n\nimport {\n state,\n type ConversationType,\n type Conversation,\n} from '../../conversation';\nimport { useSdkConsumer } from '../../sdk-consumer';\nimport { useEmitConversationEvent } from '../useConversationEvents/useEmitConversationEvent';\nimport { createConversationFailureStatus } from './createConversationFailureStatus';\nimport { limit } from './helpers';\n\nexport type UseCreateConversationOptions = {\n type: ConversationType;\n config?: object;\n /** Whether this is the visitor's first-ever conversation with the persona (drives the opening message). */\n firstConversation?: boolean;\n /** Title of the visitor's last meaningful conversation, for a returning-visitor greeting. */\n lastConversationTopic?: string;\n};\n\nexport type UseCreateConversationResult = {\n data?: Conversation;\n destroy(): Promise<void>;\n};\n\nexport function useCreateConversation(\n options: UseCreateConversationOptions,\n): UseCreateConversationResult {\n const {\n type,\n config: chatConfig,\n firstConversation,\n lastConversationTopic,\n } = options;\n\n const { chatId, namespace, personaChatService } = useSdkConsumer();\n\n const setConversationStatus = useSetAtom(state.conversationStatus);\n const [conversation, setConversation] = useAtom(state.conversation);\n const emitEvent = useEmitConversationEvent();\n\n useEffect(() => {\n void create()\n .then(() => setConversationStatus('created'))\n .catch((error: unknown) => {\n const status = createConversationFailureStatus(error);\n if (status === 'plan-minutes-exhausted') {\n emitEvent('planMinutesExhausted', {});\n }\n setConversationStatus(status);\n });\n }, [type, chatId]);\n\n useUnmount(() => {\n if (!conversation) {\n return;\n }\n void destroy();\n });\n\n useEffect(() => {\n if (!conversation) {\n return;\n }\n if (conversation.limit === 0) {\n setConversationStatus('exceeded');\n }\n }, [conversation]);\n\n return { data: conversation, destroy };\n\n async function create() {\n invariant(\n personaChatService,\n 'personaChatService is required. Pass it as a prop to LegendsPlatform.',\n );\n\n switch (type) {\n case 'video': {\n const result = await personaChatService.createInteractiveConversation({\n chatId,\n namespace,\n chatConfig,\n firstConversation,\n lastConversationTopic,\n });\n setConversation({\n type: 'video',\n url: result.url,\n id: result.id,\n limit: limit(result.limit),\n });\n break;\n }\n case 'audio': {\n const result = await personaChatService.createVoiceConversation({\n chatId,\n namespace,\n chatConfig,\n firstConversation,\n lastConversationTopic,\n });\n setConversation({\n type: 'audio',\n url: result.url,\n id: result.id,\n limit: limit(result.limit),\n });\n break;\n }\n default:\n throw new Error(`Unsupported conversation type: ${type}`);\n }\n }\n\n async function destroy() {\n invariant(conversation, 'Conversation is not ready');\n invariant(personaChatService, 'personaChatService is required.');\n\n setConversationStatus('destroying');\n\n if (conversation.type === 'video') {\n await personaChatService\n .endInteractiveConversation({\n chatId,\n conversationId: conversation.id,\n namespace,\n })\n .catch(() => {});\n }\n\n setConversationStatus('destroyed');\n setConversation(undefined);\n }\n}\n"],"mappings":";;;;;AAAA,IAAAA,UAAA,GAAAC,sBAAA,CAAAC,OAAA;AACA,IAAAC,MAAA,GAAAD,OAAA;AACA,IAAAE,MAAA,GAAAF,OAAA;AACA,IAAAG,SAAA,GAAAH,OAAA;AAEA,IAAAI,aAAA,GAAAJ,OAAA;AAKA,IAAAK,YAAA,GAAAL,OAAA;AACA,IAAAM,yBAAA,GAAAN,OAAA;AACA,IAAAO,gCAAA,GAAAP,OAAA;AACA,IAAAQ,QAAA,GAAAR,OAAA;AAgBO,SAASS,qBAAqBA,CACnCC,OAAqC,EACR;E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;QAC/B3B;MACF,CAAC,CAAC,CACDe,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC;IACpB;IAEAZ,qBAAqB,CAAC,WAAW,CAAC;IAClCK,eAAe,CAACwB,SAAS,CAAC;EAC5B;AACF","ignoreList":[]}
|
|
@@ -39,7 +39,7 @@ class FetchPersonaChatService {
|
|
|
39
39
|
});
|
|
40
40
|
if (!response.ok) {
|
|
41
41
|
const text = await response.text().catch(() => '');
|
|
42
|
-
throw new _http.HttpError(response.status, `Request failed: ${response.status} ${text}
|
|
42
|
+
throw new _http.HttpError(response.status, `Request failed: ${response.status} ${text}`, parseJson(text));
|
|
43
43
|
}
|
|
44
44
|
return response.json();
|
|
45
45
|
}
|
|
@@ -146,4 +146,11 @@ class FetchPersonaChatService {
|
|
|
146
146
|
}
|
|
147
147
|
}
|
|
148
148
|
exports.FetchPersonaChatService = FetchPersonaChatService;
|
|
149
|
+
function parseJson(text) {
|
|
150
|
+
try {
|
|
151
|
+
return JSON.parse(text);
|
|
152
|
+
} catch {
|
|
153
|
+
return undefined;
|
|
154
|
+
}
|
|
155
|
+
}
|
|
149
156
|
//# sourceMappingURL=FetchPersonaChatService.js.map
|