@webex/contact-center 3.12.0-next.12 → 3.12.0-next.121

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.
Files changed (307) hide show
  1. package/.sdd/manifest.json +884 -0
  2. package/AGENTS.md +94 -0
  3. package/ai-docs/ARCHITECTURE.md +168 -0
  4. package/ai-docs/CONTRACTS.md +51 -0
  5. package/ai-docs/GETTING_STARTED.md +168 -0
  6. package/ai-docs/GLOSSARY.md +43 -0
  7. package/ai-docs/README.md +138 -0
  8. package/ai-docs/REVIEW_CHECKLIST.md +41 -0
  9. package/ai-docs/RULES.md +444 -0
  10. package/ai-docs/SECURITY.md +52 -0
  11. package/ai-docs/SERVICE_STATE.md +48 -0
  12. package/ai-docs/SPEC_INDEX.md +65 -0
  13. package/ai-docs/adr/0001-spec-source-policy.md +55 -0
  14. package/ai-docs/adr/README.md +8 -0
  15. package/ai-docs/adr/_adr-template.md +31 -0
  16. package/ai-docs/contact-center-spec.md +359 -0
  17. package/ai-docs/features/consult-transfer-list-policy/spec/feature-spec.md +362 -0
  18. package/ai-docs/features/generated-spec-conformance-fidelity-remediation/spec/feature-spec.md +117 -0
  19. package/ai-docs/features/residual-warning-coverage-completion/spec/feature-spec.md +203 -0
  20. package/ai-docs/features/validator-code-fidelity-drift-fix/spec/feature-spec.md +315 -0
  21. package/ai-docs/patterns/event-driven-patterns.md +485 -0
  22. package/ai-docs/patterns/testing-patterns.md +480 -0
  23. package/ai-docs/patterns/typescript-patterns.md +365 -0
  24. package/ai-docs/templates/README.md +102 -0
  25. package/ai-docs/templates/documentation/create-agents-md.md +240 -0
  26. package/ai-docs/templates/documentation/create-architecture-md.md +295 -0
  27. package/ai-docs/templates/existing-service/bug-fix.md +254 -0
  28. package/ai-docs/templates/existing-service/feature-enhancement.md +450 -0
  29. package/ai-docs/templates/new-method/00-master.md +80 -0
  30. package/ai-docs/templates/new-method/01-requirements.md +232 -0
  31. package/ai-docs/templates/new-method/02-implementation.md +295 -0
  32. package/ai-docs/templates/new-method/03-tests.md +201 -0
  33. package/ai-docs/templates/new-method/04-validation.md +141 -0
  34. package/ai-docs/templates/new-service/00-master.md +109 -0
  35. package/ai-docs/templates/new-service/01-pre-questions.md +159 -0
  36. package/ai-docs/templates/new-service/02-code-generation.md +346 -0
  37. package/ai-docs/templates/new-service/03-integration.md +178 -0
  38. package/ai-docs/templates/new-service/04-test-generation.md +205 -0
  39. package/ai-docs/templates/new-service/05-validation.md +145 -0
  40. package/dist/cc.js +808 -40
  41. package/dist/cc.js.map +1 -1
  42. package/dist/config.js +13 -0
  43. package/dist/config.js.map +1 -1
  44. package/dist/constants.js +27 -3
  45. package/dist/constants.js.map +1 -1
  46. package/dist/index.js +20 -5
  47. package/dist/index.js.map +1 -1
  48. package/dist/metrics/MetricsManager.js +16 -0
  49. package/dist/metrics/MetricsManager.js.map +1 -1
  50. package/dist/metrics/behavioral-events.js +205 -0
  51. package/dist/metrics/behavioral-events.js.map +1 -1
  52. package/dist/metrics/constants.js +43 -4
  53. package/dist/metrics/constants.js.map +1 -1
  54. package/dist/services/AddressBook.js +18 -15
  55. package/dist/services/AddressBook.js.map +1 -1
  56. package/dist/services/AnswerCallOnWebexService.js +202 -0
  57. package/dist/services/AnswerCallOnWebexService.js.map +1 -0
  58. package/dist/services/ApiAiAssistant.js +153 -8
  59. package/dist/services/ApiAiAssistant.js.map +1 -1
  60. package/dist/services/EntryPoint.js +46 -68
  61. package/dist/services/EntryPoint.js.map +1 -1
  62. package/dist/services/Queue.js +27 -22
  63. package/dist/services/Queue.js.map +1 -1
  64. package/dist/services/UserPreference.js +427 -0
  65. package/dist/services/UserPreference.js.map +1 -0
  66. package/dist/services/WebexCrossClientService.js +222 -0
  67. package/dist/services/WebexCrossClientService.js.map +1 -0
  68. package/dist/services/WxAppTelephonyMercurySync.js +108 -0
  69. package/dist/services/WxAppTelephonyMercurySync.js.map +1 -0
  70. package/dist/services/config/Util.js +6 -3
  71. package/dist/services/config/Util.js.map +1 -1
  72. package/dist/services/config/constants.js +33 -8
  73. package/dist/services/config/constants.js.map +1 -1
  74. package/dist/services/config/types.js +53 -9
  75. package/dist/services/config/types.js.map +1 -1
  76. package/dist/services/core/Err.js.map +1 -1
  77. package/dist/services/core/Utils.js +107 -32
  78. package/dist/services/core/Utils.js.map +1 -1
  79. package/dist/services/core/WebexRequest.js +6 -2
  80. package/dist/services/core/WebexRequest.js.map +1 -1
  81. package/dist/services/core/aqm-reqs.js +28 -14
  82. package/dist/services/core/aqm-reqs.js.map +1 -1
  83. package/dist/services/core/types.js.map +1 -1
  84. package/dist/services/core/websocket/WebSocketManager.js +2 -1
  85. package/dist/services/core/websocket/WebSocketManager.js.map +1 -1
  86. package/dist/services/core/websocket/types.js.map +1 -1
  87. package/dist/services/index.js +1 -1
  88. package/dist/services/index.js.map +1 -1
  89. package/dist/services/task/Task.js +754 -0
  90. package/dist/services/task/Task.js.map +1 -0
  91. package/dist/services/task/TaskFactory.js +49 -0
  92. package/dist/services/task/TaskFactory.js.map +1 -0
  93. package/dist/services/task/TaskManager.js +1053 -520
  94. package/dist/services/task/TaskManager.js.map +1 -1
  95. package/dist/services/task/TaskUtils.js +211 -27
  96. package/dist/services/task/TaskUtils.js.map +1 -1
  97. package/dist/services/task/WebexCallingUtils.js +70 -0
  98. package/dist/services/task/WebexCallingUtils.js.map +1 -0
  99. package/dist/services/task/constants.js +12 -2
  100. package/dist/services/task/constants.js.map +1 -1
  101. package/dist/services/task/contact.js +29 -0
  102. package/dist/services/task/contact.js.map +1 -1
  103. package/dist/services/task/dialer.js +78 -0
  104. package/dist/services/task/dialer.js.map +1 -1
  105. package/dist/services/task/digital/Digital.js +78 -0
  106. package/dist/services/task/digital/Digital.js.map +1 -0
  107. package/dist/services/task/state-machine/TaskStateMachine.js +954 -0
  108. package/dist/services/task/state-machine/TaskStateMachine.js.map +1 -0
  109. package/dist/services/task/state-machine/actions.js +572 -0
  110. package/dist/services/task/state-machine/actions.js.map +1 -0
  111. package/dist/services/task/state-machine/constants.js +161 -0
  112. package/dist/services/task/state-machine/constants.js.map +1 -0
  113. package/dist/services/task/state-machine/guards.js +379 -0
  114. package/dist/services/task/state-machine/guards.js.map +1 -0
  115. package/dist/services/task/state-machine/index.js +53 -0
  116. package/dist/services/task/state-machine/index.js.map +1 -0
  117. package/dist/services/task/state-machine/types.js +54 -0
  118. package/dist/services/task/state-machine/types.js.map +1 -0
  119. package/dist/services/task/state-machine/uiControlsComputer.js +703 -0
  120. package/dist/services/task/state-machine/uiControlsComputer.js.map +1 -0
  121. package/dist/services/task/taskDataNormalizer.js +99 -0
  122. package/dist/services/task/taskDataNormalizer.js.map +1 -0
  123. package/dist/services/task/types.js +228 -5
  124. package/dist/services/task/types.js.map +1 -1
  125. package/dist/services/task/voice/Voice.js +1447 -0
  126. package/dist/services/task/voice/Voice.js.map +1 -0
  127. package/dist/services/task/voice/WebRTC.js +152 -0
  128. package/dist/services/task/voice/WebRTC.js.map +1 -0
  129. package/dist/services/task/voice/wxAppVoiceMethods.js +354 -0
  130. package/dist/services/task/voice/wxAppVoiceMethods.js.map +1 -0
  131. package/dist/services/wxAppDiagnosticLogging.js +122 -0
  132. package/dist/services/wxAppDiagnosticLogging.js.map +1 -0
  133. package/dist/services/wxAppTelephonyUtils.js +19 -0
  134. package/dist/services/wxAppTelephonyUtils.js.map +1 -0
  135. package/dist/types/cc.d.ts +172 -5
  136. package/dist/types/config.d.ts +13 -0
  137. package/dist/types/constants.d.ts +25 -1
  138. package/dist/types/index.d.ts +24 -7
  139. package/dist/types/metrics/MetricsManager.d.ts +6 -0
  140. package/dist/types/metrics/constants.d.ts +38 -1
  141. package/dist/types/services/AddressBook.d.ts +2 -1
  142. package/dist/types/services/AnswerCallOnWebexService.d.ts +38 -0
  143. package/dist/types/services/ApiAiAssistant.d.ts +22 -4
  144. package/dist/types/services/EntryPoint.d.ts +7 -5
  145. package/dist/types/services/Queue.d.ts +5 -3
  146. package/dist/types/services/UserPreference.d.ts +118 -0
  147. package/dist/types/services/WebexCrossClientService.d.ts +32 -0
  148. package/dist/types/services/WxAppTelephonyMercurySync.d.ts +28 -0
  149. package/dist/types/services/config/constants.d.ts +29 -5
  150. package/dist/types/services/config/types.d.ts +184 -10
  151. package/dist/types/services/core/Err.d.ts +6 -0
  152. package/dist/types/services/core/Utils.d.ts +33 -13
  153. package/dist/types/services/core/WebexRequest.d.ts +1 -0
  154. package/dist/types/services/core/types.d.ts +2 -0
  155. package/dist/types/services/core/websocket/WebSocketManager.d.ts +1 -0
  156. package/dist/types/services/core/websocket/types.d.ts +1 -1
  157. package/dist/types/services/index.d.ts +1 -1
  158. package/dist/types/services/task/Task.d.ts +175 -0
  159. package/dist/types/services/task/TaskFactory.d.ts +13 -0
  160. package/dist/types/services/task/TaskUtils.d.ts +48 -2
  161. package/dist/types/services/task/WebexCallingUtils.d.ts +11 -0
  162. package/dist/types/services/task/constants.d.ts +10 -0
  163. package/dist/types/services/task/contact.d.ts +4 -0
  164. package/dist/types/services/task/dialer.d.ts +30 -0
  165. package/dist/types/services/task/digital/Digital.d.ts +22 -0
  166. package/dist/types/services/task/state-machine/TaskStateMachine.d.ts +1356 -0
  167. package/dist/types/services/task/state-machine/actions.d.ts +10 -0
  168. package/dist/types/services/task/state-machine/constants.d.ts +107 -0
  169. package/dist/types/services/task/state-machine/guards.d.ts +103 -0
  170. package/dist/types/services/task/state-machine/index.d.ts +13 -0
  171. package/dist/types/services/task/state-machine/types.d.ts +277 -0
  172. package/dist/types/services/task/state-machine/uiControlsComputer.d.ts +9 -0
  173. package/dist/types/services/task/taskDataNormalizer.d.ts +10 -0
  174. package/dist/types/services/task/types.d.ts +680 -66
  175. package/dist/types/services/task/voice/Voice.d.ts +227 -0
  176. package/dist/types/services/task/voice/WebRTC.d.ts +53 -0
  177. package/dist/types/services/task/voice/wxAppVoiceMethods.d.ts +55 -0
  178. package/dist/types/services/wxAppDiagnosticLogging.d.ts +51 -0
  179. package/dist/types/services/wxAppTelephonyUtils.d.ts +5 -0
  180. package/dist/types/types.d.ts +149 -8
  181. package/dist/types/utils/PageCache.d.ts +20 -3
  182. package/dist/types/webex.d.ts +1 -0
  183. package/dist/types.js +125 -4
  184. package/dist/types.js.map +1 -1
  185. package/dist/utils/PageCache.js +19 -5
  186. package/dist/utils/PageCache.js.map +1 -1
  187. package/dist/webex.js +14 -2
  188. package/dist/webex.js.map +1 -1
  189. package/package.json +16 -12
  190. package/src/cc.ts +986 -42
  191. package/src/config.ts +13 -0
  192. package/src/constants.ts +25 -1
  193. package/src/index.ts +25 -5
  194. package/src/metrics/MetricsManager.ts +16 -0
  195. package/src/metrics/ai-docs/AGENTS.md +350 -0
  196. package/src/metrics/ai-docs/ARCHITECTURE.md +338 -0
  197. package/src/metrics/ai-docs/metrics-spec.md +922 -0
  198. package/src/metrics/behavioral-events.ts +212 -0
  199. package/src/metrics/constants.ts +47 -4
  200. package/src/services/AddressBook.ts +17 -6
  201. package/src/services/AnswerCallOnWebexService.ts +239 -0
  202. package/src/services/ApiAiAssistant.ts +203 -8
  203. package/src/services/EntryPoint.ts +59 -60
  204. package/src/services/Queue.ts +29 -12
  205. package/src/services/UserPreference.ts +509 -0
  206. package/src/services/WebexCrossClientService.ts +293 -0
  207. package/src/services/WxAppTelephonyMercurySync.ts +142 -0
  208. package/src/services/agent/ai-docs/AGENTS.md +240 -0
  209. package/src/services/agent/ai-docs/ARCHITECTURE.md +304 -0
  210. package/src/services/agent/ai-docs/agent-spec.md +505 -0
  211. package/src/services/ai-docs/AGENTS.md +386 -0
  212. package/src/services/ai-docs/services-spec.md +497 -0
  213. package/src/services/config/Util.ts +6 -3
  214. package/src/services/config/ai-docs/AGENTS.md +255 -0
  215. package/src/services/config/ai-docs/ARCHITECTURE.md +426 -0
  216. package/src/services/config/ai-docs/config-spec.md +675 -0
  217. package/src/services/config/constants.ts +35 -7
  218. package/src/services/config/types.ts +186 -11
  219. package/src/services/core/Err.ts +3 -0
  220. package/src/services/core/Utils.ts +123 -37
  221. package/src/services/core/WebexRequest.ts +3 -1
  222. package/src/services/core/ai-docs/AGENTS.md +381 -0
  223. package/src/services/core/ai-docs/ARCHITECTURE.md +698 -0
  224. package/src/services/core/ai-docs/core-spec.md +787 -0
  225. package/src/services/core/aqm-reqs.ts +30 -15
  226. package/src/services/core/types.ts +2 -0
  227. package/src/services/core/websocket/WebSocketManager.ts +2 -0
  228. package/src/services/core/websocket/types.ts +1 -1
  229. package/src/services/index.ts +1 -1
  230. package/src/services/task/Task.ts +908 -0
  231. package/src/services/task/TaskFactory.ts +60 -0
  232. package/src/services/task/TaskManager.ts +1239 -608
  233. package/src/services/task/TaskUtils.ts +303 -25
  234. package/src/services/task/WebexCallingUtils.ts +136 -0
  235. package/src/services/task/ai-docs/AGENTS.md +457 -0
  236. package/src/services/task/ai-docs/ARCHITECTURE.md +595 -0
  237. package/src/services/task/ai-docs/task-spec.md +1470 -0
  238. package/src/services/task/constants.ts +10 -0
  239. package/src/services/task/contact.ts +30 -0
  240. package/src/services/task/dialer.ts +80 -0
  241. package/src/services/task/digital/Digital.ts +97 -0
  242. package/src/services/task/state-machine/TaskStateMachine.ts +1293 -0
  243. package/src/services/task/state-machine/actions.ts +741 -0
  244. package/src/services/task/state-machine/ai-docs/AGENTS.md +460 -0
  245. package/src/services/task/state-machine/ai-docs/ARCHITECTURE.md +1145 -0
  246. package/src/services/task/state-machine/ai-docs/task-state-machine-spec.md +2207 -0
  247. package/src/services/task/state-machine/constants.ts +172 -0
  248. package/src/services/task/state-machine/guards.ts +442 -0
  249. package/src/services/task/state-machine/index.ts +28 -0
  250. package/src/services/task/state-machine/types.ts +258 -0
  251. package/src/services/task/state-machine/uiControlsComputer.ts +1135 -0
  252. package/src/services/task/taskDataNormalizer.ts +137 -0
  253. package/src/services/task/types.ts +819 -70
  254. package/src/services/task/voice/Voice.ts +1809 -0
  255. package/src/services/task/voice/WebRTC.ts +191 -0
  256. package/src/services/task/voice/wxAppVoiceMethods.ts +516 -0
  257. package/src/services/wxAppDiagnosticLogging.ts +174 -0
  258. package/src/services/wxAppTelephonyUtils.ts +14 -0
  259. package/src/types.ts +199 -11
  260. package/src/utils/AGENTS.md +289 -0
  261. package/src/utils/PageCache.ts +38 -5
  262. package/src/utils/ai-docs/utils-spec.md +391 -0
  263. package/src/webex.js +2 -0
  264. package/test/unit/spec/cc.ts +1947 -124
  265. package/test/unit/spec/logger-proxy.ts +70 -0
  266. package/test/unit/spec/metrics/MetricsManager.ts +25 -0
  267. package/test/unit/spec/metrics/behavioral-events.ts +60 -0
  268. package/test/unit/spec/services/AddressBook.ts +37 -6
  269. package/test/unit/spec/services/AnswerCallOnWebexService.ts +264 -0
  270. package/test/unit/spec/services/ApiAiAssistant.ts +178 -20
  271. package/test/unit/spec/services/EntryPoint.ts +87 -40
  272. package/test/unit/spec/services/Queue.ts +123 -12
  273. package/test/unit/spec/services/UserPreference.ts +401 -0
  274. package/test/unit/spec/services/WebCallingService.ts +7 -1
  275. package/test/unit/spec/services/WebexCrossClientService.ts +467 -0
  276. package/test/unit/spec/services/WxAppTelephonyMercurySync.ts +136 -0
  277. package/test/unit/spec/services/config/Util.ts +85 -0
  278. package/test/unit/spec/services/config/index.ts +30 -30
  279. package/test/unit/spec/services/core/Utils.ts +425 -8
  280. package/test/unit/spec/services/core/WebexRequest.ts +3 -1
  281. package/test/unit/spec/services/core/aqm-reqs.ts +113 -1
  282. package/test/unit/spec/services/core/websocket/WebSocketManager.ts +66 -40
  283. package/test/unit/spec/services/task/AutoWrapup.ts +63 -0
  284. package/test/unit/spec/services/task/Task.ts +677 -0
  285. package/test/unit/spec/services/task/TaskFactory.ts +99 -0
  286. package/test/unit/spec/services/task/TaskManager.ts +1972 -1549
  287. package/test/unit/spec/services/task/TaskUtils.ts +235 -0
  288. package/test/unit/spec/services/task/WebexCallingUtils.ts +153 -0
  289. package/test/unit/spec/services/task/contact.ts +33 -0
  290. package/test/unit/spec/services/task/dialer.ts +190 -0
  291. package/test/unit/spec/services/task/digital/Digital.ts +105 -0
  292. package/test/unit/spec/services/task/state-machine/TaskStateMachine.ts +3459 -0
  293. package/test/unit/spec/services/task/state-machine/guards.ts +839 -0
  294. package/test/unit/spec/services/task/state-machine/types.ts +18 -0
  295. package/test/unit/spec/services/task/state-machine/uiControlsComputer.ts +3101 -0
  296. package/test/unit/spec/services/task/taskTestUtils.ts +87 -0
  297. package/test/unit/spec/services/task/voice/Voice.ts +1903 -0
  298. package/test/unit/spec/services/task/voice/WebRTC.ts +235 -0
  299. package/test/unit/spec/services/task/voice/wxAppVoiceMethods.ts +603 -0
  300. package/test/unit/spec/services/wxAppDiagnosticLogging.ts +143 -0
  301. package/umd/contact-center.min.js +2 -2
  302. package/umd/contact-center.min.js.map +1 -1
  303. package/dist/services/task/index.js +0 -1525
  304. package/dist/services/task/index.js.map +0 -1
  305. package/dist/types/services/task/index.d.ts +0 -650
  306. package/src/services/task/index.ts +0 -1801
  307. package/test/unit/spec/services/task/index.ts +0 -2184
@@ -0,0 +1,1809 @@
1
+ import {CC_FILE, METHODS} from '../../../constants';
2
+ import {
3
+ buildConsultConferenceParamData,
4
+ calculateDestAgentId,
5
+ calculateDestType,
6
+ getErrorDetails,
7
+ } from '../../core/Utils';
8
+ import routingContact from '../contact';
9
+ import {
10
+ ConsultPayload,
11
+ ConsultEndPayload,
12
+ ResumeRecordingPayload,
13
+ TaskData,
14
+ TaskResponse,
15
+ DropConferenceParticipantPayload,
16
+ IVoice,
17
+ VoiceUIControlOptions,
18
+ TaskToggleMuteOptions,
19
+ TaskTransmitDtmfOptions,
20
+ TransferPayLoad,
21
+ ConsultTransferPayLoad,
22
+ consultConferencePayloadData,
23
+ CONSULT_TRANSFER_DESTINATION_TYPE,
24
+ TASK_EVENTS,
25
+ VOICE_VARIANT,
26
+ } from '../types';
27
+ import Task from '../Task';
28
+ import LoggerProxy from '../../../logger-proxy';
29
+ import MetricsManager from '../../../metrics/MetricsManager';
30
+ import {METRIC_EVENT_NAMES} from '../../../metrics/constants';
31
+ import {TaskState, TaskEvent, TaskActionArgs} from '../state-machine';
32
+ import {WrapupData} from '../../config/types';
33
+ import {getConsultMediaResourceId, getIsConferenceInProgress} from '../TaskUtils';
34
+ import AnswerCallOnWebexService from '../../AnswerCallOnWebexService';
35
+ import {isWxAppCallNotFoundError} from '../../wxAppTelephonyUtils';
36
+ import {
37
+ getCallingDeviceDetails,
38
+ getWebexCallingCallId,
39
+ resolveWxAppLineOwnerId,
40
+ isWebexAppCallingOffer as wxIsWebexAppCallingOffer,
41
+ isWebexAppInboundCallingOffer as wxIsWebexAppInboundCallingOffer,
42
+ mapWxAppVoiceError,
43
+ runWxAppAccept,
44
+ runWxAppOutdialDecline,
45
+ runWxAppReject,
46
+ runWxAppToggleMute,
47
+ runWxAppTransmitDtmf,
48
+ WxAppVoiceDependencies,
49
+ WxAppVoiceLifecycle,
50
+ } from './wxAppVoiceMethods';
51
+ import {
52
+ deriveWxAppAcceptReason,
53
+ logWxAppMercuryMuteSync,
54
+ logWxAppOfferDecision,
55
+ callIdSuffix,
56
+ WxAppAcceptReason,
57
+ } from '../../wxAppDiagnosticLogging';
58
+
59
+ export default class Voice extends Task implements IVoice {
60
+ private static readonly WXAPP_MUTE_SYNC_RETRY_DELAY_MS = 50;
61
+ private static readonly WXAPP_MUTE_SYNC_MAX_RETRIES = 3;
62
+
63
+ private answerCallOnWebexService?: AnswerCallOnWebexService;
64
+ private enableWxBetterTogether = false;
65
+ private wxAppMuted = false;
66
+ private wxAppAnswerPending = false;
67
+ private wxAppAcceptInFlight = false;
68
+ private wxAppMuteSyncInFlight?: Promise<boolean | undefined>;
69
+ private wxAppMuteToggleTail: Promise<void> = Promise.resolve();
70
+ private wxAppDtmfTail: Promise<void> = Promise.resolve();
71
+ private lastLoggedWxAppAcceptReason?: WxAppAcceptReason;
72
+
73
+ constructor(
74
+ contact: ReturnType<typeof routingContact>,
75
+ data: TaskData,
76
+ callOptions?: VoiceUIControlOptions,
77
+ wrapupData?: WrapupData,
78
+ agentId?: string
79
+ ) {
80
+ const resolvedOptions = {
81
+ isEndTaskEnabled: callOptions?.isEndTaskEnabled ?? true,
82
+ isEndConsultEnabled: callOptions?.isEndConsultEnabled ?? true,
83
+ voiceVariant: callOptions?.voiceVariant ?? VOICE_VARIANT.PSTN,
84
+ isRecordingEnabled: callOptions?.isRecordingEnabled ?? true,
85
+ enableWxBetterTogether: callOptions?.enableWxBetterTogether ?? false,
86
+ };
87
+
88
+ super(
89
+ contact,
90
+ data,
91
+ {
92
+ ...resolvedOptions,
93
+ consultTransferConfig: callOptions?.consultTransferConfig,
94
+ },
95
+ wrapupData,
96
+ agentId
97
+ );
98
+
99
+ this.enableWxBetterTogether = resolvedOptions.enableWxBetterTogether;
100
+ this.answerCallOnWebexService = callOptions?.answerCallOnWebexService;
101
+ }
102
+
103
+ private getWxAppVoiceDependencies(): WxAppVoiceDependencies {
104
+ return {
105
+ enableWxBetterTogether: this.enableWxBetterTogether,
106
+ answerCallOnWebexService: this.answerCallOnWebexService,
107
+ agentId: this.agentId,
108
+ metricsManager: this.metricsManager,
109
+ getTaskData: () => this.data,
110
+ getTaskState: () => this.stateMachineService?.getSnapshot?.()?.value as TaskState | undefined,
111
+ getWxAppMuted: () => this.wxAppMuted,
112
+ setWxAppMuted: (muted: boolean) => {
113
+ this.wxAppMuted = muted;
114
+ },
115
+ };
116
+ }
117
+
118
+ /** @deprecated Use {@link Voice.getWxAppVoiceDependencies} */
119
+ private getWxAppVoiceDeps(): WxAppVoiceDependencies {
120
+ return this.getWxAppVoiceDependencies();
121
+ }
122
+
123
+ public isWebexAppCallingOffer(): boolean {
124
+ return wxIsWebexAppCallingOffer(this.getWxAppVoiceDeps());
125
+ }
126
+
127
+ public isWebexAppInboundCallingOffer(): boolean {
128
+ return wxIsWebexAppInboundCallingOffer(this.getWxAppVoiceDeps());
129
+ }
130
+
131
+ private setWxAppAnswerPending(pending: boolean): void {
132
+ this.wxAppAnswerPending = pending;
133
+ this.uiControlConfig = {...this.uiControlConfig, wxAppAnswerPending: pending};
134
+ this.updateUiControls(true);
135
+ }
136
+
137
+ private setWxAppAcceptInFlight(inFlight: boolean): void {
138
+ this.wxAppAcceptInFlight = inFlight;
139
+ this.uiControlConfig = {...this.uiControlConfig, wxAppAcceptInFlight: inFlight};
140
+ this.updateUiControls(true);
141
+ }
142
+
143
+ public setEnableWxBetterTogether(enabled: boolean): void {
144
+ this.enableWxBetterTogether = enabled;
145
+ this.uiControlConfig = {...this.uiControlConfig, enableWxBetterTogether: enabled};
146
+ this.updateUiControls(true);
147
+ }
148
+
149
+ protected updateUiControls(forceEmit = false): void {
150
+ super.updateUiControls(forceEmit);
151
+ this.logWxAppOfferDecisionIfNeeded();
152
+ }
153
+
154
+ private logWxAppOfferDecisionIfNeeded(): void {
155
+ if (!this.enableWxBetterTogether) {
156
+ return;
157
+ }
158
+
159
+ const state = this.stateMachineService?.getSnapshot?.()?.value as TaskState | undefined;
160
+ if (state !== TaskState.OFFERED) {
161
+ return;
162
+ }
163
+
164
+ const accept = this.currentUiControls?.main?.accept;
165
+ if (!accept?.isVisible) {
166
+ return;
167
+ }
168
+
169
+ const deps = this.getWxAppVoiceDependencies();
170
+ const isOutdial = this.data?.interaction?.outboundType === 'OUTDIAL';
171
+ const isWxAppInboundOffer = this.isWebexAppInboundCallingOffer();
172
+ const isWxAppOutdialOffer = this.isWebexAppCallingOffer() && isOutdial;
173
+ const deviceDetails = getCallingDeviceDetails(deps);
174
+ const acceptReason = deriveWxAppAcceptReason({
175
+ isWxAppInboundOffer,
176
+ isWxAppOutdialOffer,
177
+ isWebrtc: this.uiControlConfig.voiceVariant === VOICE_VARIANT.WEBRTC,
178
+ isOutdial,
179
+ wxAppAcceptInFlight: this.wxAppAcceptInFlight,
180
+ wxAppAnswerPending: this.wxAppAnswerPending,
181
+ enableWxBetterTogether: this.enableWxBetterTogether,
182
+ hasDeviceCallId: Boolean(deviceDetails?.deviceCallId),
183
+ });
184
+
185
+ if (acceptReason === this.lastLoggedWxAppAcceptReason) {
186
+ return;
187
+ }
188
+
189
+ this.lastLoggedWxAppAcceptReason = acceptReason;
190
+
191
+ logWxAppOfferDecision({
192
+ interactionId: this.data.interactionId,
193
+ acceptVisible: accept.isVisible,
194
+ acceptEnabled: accept.isEnabled,
195
+ acceptReason,
196
+ wxAppParticipantDeviceType: deviceDetails?.deviceType,
197
+ hasDeviceCallId: Boolean(deviceDetails?.deviceCallId),
198
+ });
199
+ }
200
+
201
+ public applyWxAppMuteStateFromSync(incomingCallId: string, muted: boolean): void {
202
+ if (!this.enableWxBetterTogether) {
203
+ return;
204
+ }
205
+
206
+ const activeCallId = this.getWebexCallingCallId();
207
+ const incomingSuffix = callIdSuffix(incomingCallId);
208
+ const activeSuffix = callIdSuffix(activeCallId);
209
+
210
+ if (!activeCallId || !incomingCallId.endsWith(activeCallId)) {
211
+ logWxAppMercuryMuteSync({
212
+ phase: 'dropped',
213
+ muted,
214
+ callIdSuffix: incomingSuffix,
215
+ interactionId: this.data.interactionId,
216
+ dropReason: !activeCallId ? 'no_active_wxApp_call' : 'call_id_mismatch',
217
+ });
218
+
219
+ return;
220
+ }
221
+
222
+ if (this.wxAppMuted === muted) {
223
+ logWxAppMercuryMuteSync({
224
+ phase: 'dropped',
225
+ muted,
226
+ callIdSuffix: incomingSuffix,
227
+ interactionId: this.data.interactionId,
228
+ dropReason: 'mute_state_unchanged',
229
+ });
230
+
231
+ return;
232
+ }
233
+
234
+ this.wxAppMuted = muted;
235
+ logWxAppMercuryMuteSync({
236
+ phase: 'applied',
237
+ muted,
238
+ callIdSuffix: activeSuffix,
239
+ interactionId: this.data.interactionId,
240
+ });
241
+ this.emit(TASK_EVENTS.TASK_WXAPP_MUTE_STATE_UPDATED, {muted});
242
+ }
243
+
244
+ public getWxAppMuted(): boolean {
245
+ return this.wxAppMuted;
246
+ }
247
+
248
+ private static delay(ms: number): Promise<void> {
249
+ return new Promise((resolve) => {
250
+ setTimeout(resolve, ms);
251
+ });
252
+ }
253
+
254
+ private canRetryWxAppMuteSync(): boolean {
255
+ if (!this.enableWxBetterTogether) {
256
+ return false;
257
+ }
258
+
259
+ return (
260
+ Boolean(getCallingDeviceDetails(this.getWxAppVoiceDeps())?.deviceCallId) &&
261
+ !this.getWebexCallingCallId()
262
+ );
263
+ }
264
+
265
+ private shouldSkipWxAppMuteSync(): boolean {
266
+ if (this.data?.interaction?.isTerminated) {
267
+ return true;
268
+ }
269
+
270
+ return this.isWebexAppCallingOffer() && !this.uiControlConfig?.wxAppAnswerPending;
271
+ }
272
+
273
+ private applyWxAppMuteFromBackfill(callId: string, muted: boolean): void {
274
+ if (!this.enableWxBetterTogether || this.wxAppMuted === muted) {
275
+ return;
276
+ }
277
+
278
+ const activeCallId = this.getWebexCallingCallId();
279
+ if (activeCallId && !callId.endsWith(activeCallId) && !activeCallId.endsWith(callId)) {
280
+ return;
281
+ }
282
+
283
+ this.wxAppMuted = muted;
284
+ this.emit(TASK_EVENTS.TASK_WXAPP_MUTE_STATE_UPDATED, {muted});
285
+ }
286
+
287
+ public async syncWxAppMuteFromCallDetails(retryAttempt = 0): Promise<boolean | undefined> {
288
+ if (!this.enableWxBetterTogether || !this.answerCallOnWebexService) {
289
+ return undefined;
290
+ }
291
+
292
+ if (retryAttempt === 0 && this.shouldSkipWxAppMuteSync()) {
293
+ return undefined;
294
+ }
295
+
296
+ if (retryAttempt === 0 && this.wxAppMuteSyncInFlight) {
297
+ return this.wxAppMuteSyncInFlight;
298
+ }
299
+
300
+ const syncPromise = this.performWxAppMuteSync(retryAttempt);
301
+
302
+ if (retryAttempt === 0) {
303
+ this.wxAppMuteSyncInFlight = syncPromise;
304
+ syncPromise
305
+ .finally(() => {
306
+ if (this.wxAppMuteSyncInFlight === syncPromise) {
307
+ this.wxAppMuteSyncInFlight = undefined;
308
+ }
309
+ })
310
+ .catch(() => undefined);
311
+
312
+ return syncPromise;
313
+ }
314
+
315
+ return syncPromise;
316
+ }
317
+
318
+ private async performWxAppMuteSync(retryAttempt: number): Promise<boolean | undefined> {
319
+ if (this.shouldSkipWxAppMuteSync()) {
320
+ return undefined;
321
+ }
322
+
323
+ let callId = this.getWebexCallingCallId();
324
+ if (!callId) {
325
+ if (retryAttempt < Voice.WXAPP_MUTE_SYNC_MAX_RETRIES && this.canRetryWxAppMuteSync()) {
326
+ await Voice.delay(Voice.WXAPP_MUTE_SYNC_RETRY_DELAY_MS);
327
+
328
+ return this.performWxAppMuteSync(retryAttempt + 1);
329
+ }
330
+
331
+ callId = getCallingDeviceDetails(this.getWxAppVoiceDeps())?.deviceCallId ?? null;
332
+ if (!callId) {
333
+ return undefined;
334
+ }
335
+ }
336
+
337
+ try {
338
+ const lineOwnerId = resolveWxAppLineOwnerId(this.getWxAppVoiceDeps());
339
+ const details = await this.answerCallOnWebexService.getCallDetails({callId, lineOwnerId});
340
+ if (details.muted !== undefined) {
341
+ this.applyWxAppMuteStateFromSync(callId, details.muted);
342
+ if (this.wxAppMuted !== details.muted) {
343
+ this.applyWxAppMuteFromBackfill(callId, details.muted);
344
+ }
345
+
346
+ return details.muted;
347
+ }
348
+
349
+ return this.wxAppMuted;
350
+ } catch (error) {
351
+ if (!isWxAppCallNotFoundError(error)) {
352
+ LoggerProxy.error(`Failed to sync wxApp mute from call details: ${error}`, {
353
+ module: CC_FILE,
354
+ method: METHODS.GET_CALL_DETAILS_ON_WEBEX,
355
+ interactionId: this.data?.interactionId,
356
+ });
357
+ }
358
+
359
+ return undefined;
360
+ }
361
+ }
362
+
363
+ protected onTaskAssigned(): void {
364
+ this.setWxAppAnswerPending(false);
365
+ queueMicrotask(() => {
366
+ this.syncWxAppMuteFromCallDetails().catch(() => undefined);
367
+ });
368
+ }
369
+
370
+ protected onTaskHydrated(): void {
371
+ const state = this.stateMachineService?.getSnapshot?.()?.value as TaskState | undefined;
372
+ const answerStillPending =
373
+ state === TaskState.OFFERED &&
374
+ (this.uiControlConfig?.wxAppAcceptInFlight || this.uiControlConfig?.wxAppAnswerPending);
375
+
376
+ if (!answerStillPending) {
377
+ this.setWxAppAnswerPending(false);
378
+ }
379
+
380
+ this.syncWxAppMuteFromCallDetails().catch(() => undefined);
381
+ }
382
+
383
+ public getCallingDeviceDetails() {
384
+ return getCallingDeviceDetails(this.getWxAppVoiceDeps());
385
+ }
386
+
387
+ public getWebexCallingCallId(): string | null {
388
+ return getWebexCallingCallId(this.getWxAppVoiceDeps());
389
+ }
390
+
391
+ private createWxAppLifecycle(): WxAppVoiceLifecycle {
392
+ return {
393
+ setWxAppAcceptInFlight: (inFlight) => this.setWxAppAcceptInFlight(inFlight),
394
+ setWxAppAnswerPending: (pending) => this.setWxAppAnswerPending(pending),
395
+ resetWxAppMuted: () => {
396
+ this.wxAppMuted = false;
397
+ },
398
+ syncWxAppMuteFromCallDetails: () => this.syncWxAppMuteFromCallDetails(),
399
+ mapWxAppVoiceError: (error, method) => mapWxAppVoiceError(error, method, CC_FILE),
400
+ };
401
+ }
402
+
403
+ private getStateMachineSnapshot() {
404
+ return this.stateMachineService?.getSnapshot?.();
405
+ }
406
+
407
+ /**
408
+ * Accepts the task. Routes to wxApp telephony answer when `enableWxBetterTogether` and wxApp offer.
409
+ */
410
+ public async accept(): Promise<TaskResponse> {
411
+ if (this.enableWxBetterTogether && this.isWebexAppCallingOffer()) {
412
+ await runWxAppAccept(this.getWxAppVoiceDependencies(), this.createWxAppLifecycle());
413
+
414
+ return Promise.resolve();
415
+ }
416
+
417
+ return super.unsupportedMethodError(METHODS.ACCEPT);
418
+ }
419
+
420
+ /**
421
+ * Declines the task. Routes wxApp inbound to telephony reject; wxApp outdial offer to cancelTask.
422
+ */
423
+ public async decline(): Promise<TaskResponse> {
424
+ if (this.enableWxBetterTogether && this.isWebexAppInboundCallingOffer()) {
425
+ await runWxAppReject(this.getWxAppVoiceDependencies(), this.createWxAppLifecycle());
426
+
427
+ return Promise.resolve();
428
+ }
429
+
430
+ const isOutdial = this.data?.interaction?.outboundType === 'OUTDIAL';
431
+ if (!this.enableWxBetterTogether || !isOutdial || !this.isWebexAppCallingOffer()) {
432
+ return super.unsupportedMethodError(METHODS.REJECT);
433
+ }
434
+
435
+ const interactionId = this.data.interactionId;
436
+ LoggerProxy.log(`Declining wxApp outdial task for taskId:${interactionId}`, {
437
+ module: CC_FILE,
438
+ method: METHODS.REJECT,
439
+ interactionId,
440
+ });
441
+
442
+ try {
443
+ this.metricsManager.timeEvent([
444
+ METRIC_EVENT_NAMES.TASK_DECLINE_SUCCESS,
445
+ METRIC_EVENT_NAMES.TASK_DECLINE_FAILED,
446
+ ]);
447
+
448
+ this.setWxAppAnswerPending(false);
449
+ const response = await runWxAppOutdialDecline(this.getWxAppVoiceDependencies(), () =>
450
+ this.contact.cancelTask({interactionId})
451
+ );
452
+
453
+ this.metricsManager.trackEvent(
454
+ METRIC_EVENT_NAMES.TASK_DECLINE_SUCCESS,
455
+ {
456
+ taskId: interactionId,
457
+ ...MetricsManager.getCommonTrackingFieldForAQMResponse(response),
458
+ },
459
+ ['operational', 'behavioral']
460
+ );
461
+
462
+ return response;
463
+ } catch (error) {
464
+ this.metricsManager.trackEvent(
465
+ METRIC_EVENT_NAMES.TASK_DECLINE_FAILED,
466
+ {
467
+ taskId: interactionId,
468
+ error: error.toString(),
469
+ ...MetricsManager.getCommonTrackingFieldForAQMResponseFailed(
470
+ (error as any).details || {}
471
+ ),
472
+ },
473
+ ['operational', 'behavioral']
474
+ );
475
+ const {error: detailedError} = getErrorDetails(error, METHODS.REJECT, CC_FILE);
476
+ throw detailedError;
477
+ }
478
+ }
479
+
480
+ /**
481
+ * Toggles mute for wxApp engaged telephony when `enableWxBetterTogether` is active.
482
+ */
483
+ public async toggleMute(options?: TaskToggleMuteOptions): Promise<void> {
484
+ if (this.enableWxBetterTogether && this.getWebexCallingCallId()) {
485
+ const togglePromise = this.wxAppMuteToggleTail
486
+ .catch(() => undefined)
487
+ .then(() =>
488
+ runWxAppToggleMute(this.getWxAppVoiceDependencies(), this.createWxAppLifecycle(), options)
489
+ );
490
+
491
+ this.wxAppMuteToggleTail = togglePromise.catch(() => undefined);
492
+ await togglePromise;
493
+
494
+ return;
495
+ }
496
+
497
+ super.unsupportedMethodError(METHODS.TOGGLE_MUTE);
498
+ }
499
+
500
+ /**
501
+ * Sends in-call DTMF for wxApp engaged telephony when `enableWxBetterTogether` is active.
502
+ */
503
+ public async transmitDtmf(options: TaskTransmitDtmfOptions): Promise<void> {
504
+ if (this.enableWxBetterTogether && this.getWebexCallingCallId()) {
505
+ const dtmfPromise = this.wxAppDtmfTail
506
+ .catch(() => undefined)
507
+ .then(() =>
508
+ runWxAppTransmitDtmf(
509
+ this.getWxAppVoiceDependencies(),
510
+ this.createWxAppLifecycle(),
511
+ options
512
+ )
513
+ );
514
+
515
+ this.wxAppDtmfTail = dtmfPromise.catch(() => undefined);
516
+ await dtmfPromise;
517
+
518
+ return;
519
+ }
520
+
521
+ super.unsupportedMethodError(METHODS.TRANSMIT_DTMF);
522
+ }
523
+
524
+ /**
525
+ * This is used to hold the task.
526
+ * @returns Promise<TaskResponse>
527
+ * @throws Error
528
+ * @example
529
+ * ```typescript
530
+ * task.hold().then(()=>{}).catch(()=>{})
531
+ * ```
532
+ * */
533
+ public async hold(): Promise<TaskResponse> {
534
+ return this.holdResume();
535
+ }
536
+
537
+ /**
538
+ * This is used to resume the task.
539
+ * @returns Promise<TaskResponse>
540
+ * @throws Error
541
+ * @example
542
+ * ```typescript
543
+ * task.resume().then(()=>{}).catch(()=>{})
544
+ * ```
545
+ * */
546
+ public async resume(): Promise<TaskResponse> {
547
+ return this.holdResume();
548
+ }
549
+
550
+ /**
551
+ * This is used to hold or resume the task.
552
+ * @param isHeld: boolean - true to hold the task, false to resume it
553
+ * @returns Promise<TaskResponse>
554
+ * @throws Error
555
+ * @example
556
+ * ```typescript
557
+ * task.holdResume(isHeld: true).then(()=>{}).catch(()=>{})
558
+ * ```
559
+ * */
560
+ public async holdResume(): Promise<TaskResponse> {
561
+ /*
562
+ Determine if the task is being held or resumed based on the media resource state
563
+ If the media resource is not found, default to resuming the task
564
+ */
565
+ const snapshot = this.getStateMachineSnapshot();
566
+ const snapshotState = snapshot?.value as TaskState | undefined;
567
+ const mainInteractionId = this.data.interaction?.mainInteractionId || this.data.interactionId;
568
+ const mainMediaResource =
569
+ this.data.interaction?.media?.[mainInteractionId]?.mediaResourceId ||
570
+ this.data.mediaResourceId;
571
+ const mediaHoldState =
572
+ this.data.interaction?.media?.[mainInteractionId]?.isHold ??
573
+ this.data.interaction.media?.[mainMediaResource]?.isHold;
574
+ let shouldHold = !(mediaHoldState ?? false);
575
+ if (snapshotState === TaskState.HELD || snapshotState === TaskState.RESUME_INITIATING) {
576
+ shouldHold = false;
577
+ } else if (snapshotState === TaskState.CONNECTED && mediaHoldState !== true) {
578
+ // CONNECTED with isHold:true can happen after consult RONA/decline when event ordering
579
+ // leaves the machine in CONNECTED while main media is still on hold — resume on first click.
580
+ shouldHold = true;
581
+ }
582
+
583
+ // Validate operation is allowed in current state
584
+ const state = snapshot;
585
+ if (state) {
586
+ const currentState = state.value as TaskState;
587
+ if (shouldHold) {
588
+ if (!state.matches(TaskState.CONNECTED)) {
589
+ const error = new Error(`Cannot hold call in current state: ${currentState}`);
590
+ LoggerProxy.error('Hold operation not allowed', {
591
+ module: CC_FILE,
592
+ method: METHODS.HOLD_RESUME,
593
+ interactionId: this.data.interactionId,
594
+ });
595
+ throw error;
596
+ }
597
+ } else if (
598
+ !state.matches(TaskState.HELD) &&
599
+ !(state.matches(TaskState.CONFERENCING) && mediaHoldState === true) &&
600
+ !(state.matches(TaskState.CONNECTED) && mediaHoldState === true)
601
+ ) {
602
+ const error = new Error(`Cannot resume call in current state: ${currentState}`);
603
+ LoggerProxy.error('Resume operation not allowed', {
604
+ module: CC_FILE,
605
+ method: METHODS.HOLD_RESUME,
606
+ interactionId: this.data.interactionId,
607
+ });
608
+ throw error;
609
+ }
610
+ }
611
+
612
+ // Send initiating event to transition to intermediate state
613
+ if (this.stateMachineService) {
614
+ const initiatingEvent = shouldHold ? TaskEvent.HOLD_INITIATED : TaskEvent.UNHOLD_INITIATED;
615
+ this.stateMachineService.send({
616
+ type: initiatingEvent,
617
+ mediaResourceId: mainMediaResource,
618
+ });
619
+ }
620
+
621
+ LoggerProxy.info(`${shouldHold ? 'Holding' : 'Resuming'} task`, {
622
+ module: CC_FILE,
623
+ method: METHODS.HOLD_RESUME,
624
+ interactionId: this.data.interactionId,
625
+ });
626
+ const [successEvt, failedEvt] = shouldHold
627
+ ? [METRIC_EVENT_NAMES.TASK_HOLD_SUCCESS, METRIC_EVENT_NAMES.TASK_HOLD_FAILED]
628
+ : [METRIC_EVENT_NAMES.TASK_RESUME_SUCCESS, METRIC_EVENT_NAMES.TASK_RESUME_FAILED];
629
+
630
+ this.metricsManager.timeEvent([successEvt, failedEvt]);
631
+
632
+ try {
633
+ let response: TaskResponse;
634
+ if (shouldHold) {
635
+ response = await this.contact.hold({
636
+ interactionId: this.data.interactionId,
637
+ data: {mediaResourceId: mainMediaResource},
638
+ });
639
+
640
+ // Send success event to complete the transition
641
+ if (this.stateMachineService) {
642
+ this.stateMachineService.send({
643
+ type: TaskEvent.HOLD_SUCCESS,
644
+ mediaResourceId: mainMediaResource,
645
+ });
646
+ }
647
+
648
+ this.metricsManager.trackEvent(
649
+ successEvt,
650
+ {
651
+ taskId: this.data.interactionId,
652
+ mediaResourceId: mainMediaResource,
653
+ ...MetricsManager.getCommonTrackingFieldForAQMResponse(response),
654
+ },
655
+ ['operational', 'behavioral']
656
+ );
657
+ LoggerProxy.log(`Task placed on hold successfully`, {
658
+ module: CC_FILE,
659
+ method: METHODS.HOLD_RESUME,
660
+ trackingId: response.trackingId,
661
+ interactionId: this.data.interactionId,
662
+ });
663
+ } else {
664
+ response = await this.contact.unHold({
665
+ interactionId: this.data.interactionId,
666
+ data: {mediaResourceId: mainMediaResource},
667
+ });
668
+
669
+ // Send success event to complete the transition
670
+ if (this.stateMachineService) {
671
+ this.stateMachineService.send({
672
+ type: TaskEvent.UNHOLD_SUCCESS,
673
+ mediaResourceId: mainMediaResource,
674
+ });
675
+ }
676
+
677
+ this.metricsManager.trackEvent(
678
+ successEvt,
679
+ {
680
+ taskId: this.data.interactionId,
681
+ mainInteractionId,
682
+ mediaResourceId: mainMediaResource,
683
+ ...MetricsManager.getCommonTrackingFieldForAQMResponse(response),
684
+ },
685
+ ['operational', 'behavioral']
686
+ );
687
+ LoggerProxy.log(`Task resumed successfully`, {
688
+ module: CC_FILE,
689
+ method: METHODS.HOLD_RESUME,
690
+ trackingId: response.trackingId,
691
+ interactionId: this.data.interactionId,
692
+ });
693
+ }
694
+
695
+ return response;
696
+ } catch (error) {
697
+ const failureEvent = shouldHold ? TaskEvent.HOLD_FAILED : TaskEvent.UNHOLD_FAILED;
698
+ this.stateMachineService.send({
699
+ type: failureEvent,
700
+ reason: error.toString(),
701
+ mediaResourceId: this.data.mediaResourceId,
702
+ });
703
+
704
+ const {error: detailedError} = getErrorDetails(error, 'holdResume', CC_FILE);
705
+ this.metricsManager.trackEvent(
706
+ failedEvt,
707
+ shouldHold
708
+ ? {
709
+ taskId: this.data.interactionId,
710
+ mediaResourceId: this.data.mediaResourceId,
711
+ error: error.toString(),
712
+ ...MetricsManager.getCommonTrackingFieldForAQMResponseFailed(error.details || {}),
713
+ }
714
+ : {
715
+ taskId: this.data.interactionId,
716
+ error: error.toString(),
717
+ ...MetricsManager.getCommonTrackingFieldForAQMResponseFailed(error.details || {}),
718
+ },
719
+ ['operational', 'behavioral']
720
+ );
721
+ throw detailedError;
722
+ }
723
+ }
724
+
725
+ /**
726
+ * This is used to pause the call recording
727
+ * @returns Promise<TaskResponse>
728
+ * @throws Error
729
+ * @example
730
+ * ```typescript
731
+ * task.pauseRecording().then(()=>{}).catch(()=>{});
732
+ * ```
733
+ */
734
+ public async pauseRecording(): Promise<TaskResponse> {
735
+ // Validate recording is active
736
+ const state = this.getStateMachineSnapshot();
737
+ if (state) {
738
+ const {recordingControlsAvailable, recordingInProgress} = state.context as {
739
+ recordingControlsAvailable?: boolean;
740
+ recordingInProgress?: boolean;
741
+ };
742
+ const recordingActive = Boolean(recordingControlsAvailable && recordingInProgress);
743
+ if (!recordingActive) {
744
+ const error = new Error('Recording is not active or already paused');
745
+ LoggerProxy.error('Pause recording operation not allowed', {
746
+ module: CC_FILE,
747
+ method: 'pauseRecording',
748
+ interactionId: this.data.interactionId,
749
+ });
750
+ throw error;
751
+ }
752
+ }
753
+
754
+ try {
755
+ LoggerProxy.info(`Pausing recording`, {
756
+ module: CC_FILE,
757
+ method: 'pauseRecording',
758
+ interactionId: this.data.interactionId,
759
+ });
760
+ this.metricsManager.timeEvent([
761
+ METRIC_EVENT_NAMES.TASK_PAUSE_RECORDING_SUCCESS,
762
+ METRIC_EVENT_NAMES.TASK_PAUSE_RECORDING_FAILED,
763
+ ]);
764
+ const result = await this.contact.pauseRecording({interactionId: this.data.interactionId});
765
+ this.metricsManager.trackEvent(
766
+ METRIC_EVENT_NAMES.TASK_PAUSE_RECORDING_SUCCESS,
767
+ {
768
+ taskId: this.data.interactionId,
769
+ ...MetricsManager.getCommonTrackingFieldForAQMResponse(result),
770
+ },
771
+ ['operational', 'behavioral', 'business']
772
+ );
773
+ LoggerProxy.log(`Recording paused successfully`, {
774
+ module: CC_FILE,
775
+ method: 'pauseRecording',
776
+ trackingId: result.trackingId,
777
+ interactionId: this.data.interactionId,
778
+ });
779
+
780
+ return result;
781
+ } catch (error) {
782
+ const {error: detailedError} = getErrorDetails(error, 'pauseRecording', CC_FILE);
783
+ this.metricsManager.trackEvent(
784
+ METRIC_EVENT_NAMES.TASK_PAUSE_RECORDING_FAILED,
785
+ {
786
+ taskId: this.data.interactionId,
787
+ error: error.toString(),
788
+ ...MetricsManager.getCommonTrackingFieldForAQMResponseFailed(error.details || {}),
789
+ },
790
+ ['operational', 'behavioral', 'business']
791
+ );
792
+ throw detailedError;
793
+ }
794
+ }
795
+
796
+ /**
797
+ * This is used to pause the call recording
798
+ * @param resumeRecordingPayload
799
+ * @returns Promise<TaskResponse>
800
+ * @throws Error
801
+ * @example
802
+ * ```typescript
803
+ * task.resumeRecording(resumeRecordingPayload).then(()=>{}).catch(()=>{});
804
+ * ```
805
+ */
806
+ public async resumeRecording(
807
+ resumeRecordingPayload?: ResumeRecordingPayload
808
+ ): Promise<TaskResponse> {
809
+ // Validate recording is paused
810
+ const state = this.getStateMachineSnapshot();
811
+ if (state) {
812
+ const {recordingControlsAvailable, recordingInProgress} = state.context as {
813
+ recordingControlsAvailable?: boolean;
814
+ recordingInProgress?: boolean;
815
+ };
816
+ const recordingPaused = Boolean(recordingControlsAvailable && !recordingInProgress);
817
+ if (!recordingPaused) {
818
+ const error = new Error('Recording is not paused');
819
+ LoggerProxy.error('Resume recording operation not allowed', {
820
+ module: CC_FILE,
821
+ method: 'resumeRecording',
822
+ interactionId: this.data.interactionId,
823
+ });
824
+ throw error;
825
+ }
826
+ }
827
+
828
+ try {
829
+ LoggerProxy.info(`Resuming recording`, {
830
+ module: CC_FILE,
831
+ method: 'resumeRecording',
832
+ interactionId: this.data.interactionId,
833
+ });
834
+ this.metricsManager.timeEvent([
835
+ METRIC_EVENT_NAMES.TASK_RESUME_RECORDING_SUCCESS,
836
+ METRIC_EVENT_NAMES.TASK_RESUME_RECORDING_FAILED,
837
+ ]);
838
+ resumeRecordingPayload ??= {autoResumed: false};
839
+
840
+ const result = await this.contact.resumeRecording({
841
+ interactionId: this.data.interactionId,
842
+ data: resumeRecordingPayload,
843
+ });
844
+ this.metricsManager.trackEvent(
845
+ METRIC_EVENT_NAMES.TASK_RESUME_RECORDING_SUCCESS,
846
+ {
847
+ taskId: this.data.interactionId,
848
+ ...MetricsManager.getCommonTrackingFieldForAQMResponse(result),
849
+ },
850
+ ['operational', 'behavioral', 'business']
851
+ );
852
+ LoggerProxy.log(`Recording resumed successfully`, {
853
+ module: CC_FILE,
854
+ method: 'resumeRecording',
855
+ trackingId: result.trackingId,
856
+ interactionId: this.data.interactionId,
857
+ });
858
+
859
+ return result;
860
+ } catch (error) {
861
+ const {error: detailedError} = getErrorDetails(error, 'resumeRecording', CC_FILE);
862
+ this.metricsManager.trackEvent(
863
+ METRIC_EVENT_NAMES.TASK_RESUME_RECORDING_FAILED,
864
+ {
865
+ taskId: this.data.interactionId,
866
+ error: error.toString(),
867
+ ...MetricsManager.getCommonTrackingFieldForAQMResponseFailed(error.details || {}),
868
+ },
869
+ ['operational', 'behavioral', 'business']
870
+ );
871
+ throw detailedError;
872
+ }
873
+ }
874
+
875
+ /**
876
+ * This is used to consult the task
877
+ * @param consultPayload
878
+ * @returns Promise<TaskResponse>
879
+ * @throws Error
880
+ * @example
881
+ * ```typescript
882
+ * const consultPayload = {
883
+ * destination: 'myBuddyAgentId',
884
+ * destinationType: DESTINATION_TYPE.AGENT,
885
+ * }
886
+ * task.consult(consultPayload).then(()=>{}).catch(()=>{});
887
+ * ```
888
+ * */
889
+ public async consult(consultPayload?: ConsultPayload): Promise<TaskResponse> {
890
+ // Validate consult is allowed
891
+ const state = this.getStateMachineSnapshot();
892
+ const canConsult =
893
+ state &&
894
+ (state.matches(TaskState.CONNECTED) ||
895
+ state.matches(TaskState.HELD) ||
896
+ state.matches(TaskState.CONFERENCING));
897
+
898
+ if (!canConsult) {
899
+ const currentState = state?.value as TaskState;
900
+ const error = new Error(`Cannot initiate consult in ${currentState} state`);
901
+ LoggerProxy.error('Consult operation not allowed', {
902
+ module: CC_FILE,
903
+ method: 'consult',
904
+ interactionId: this.data.interactionId,
905
+ });
906
+ throw error;
907
+ }
908
+
909
+ // Send initiating event to transition to CONSULT_INITIATING state
910
+ if (this.stateMachineService) {
911
+ this.stateMachineService.send({
912
+ type: TaskEvent.CONSULT,
913
+ destination: consultPayload.to,
914
+ destinationType: consultPayload.destinationType,
915
+ });
916
+ }
917
+
918
+ const requestInteractionId =
919
+ this.data.interaction?.mainInteractionId || this.data.interactionId;
920
+
921
+ try {
922
+ LoggerProxy.info(`Starting consult`, {
923
+ module: CC_FILE,
924
+ method: 'consult',
925
+ interactionId: requestInteractionId,
926
+ });
927
+ this.metricsManager.timeEvent([
928
+ METRIC_EVENT_NAMES.TASK_CONSULT_START_SUCCESS,
929
+ METRIC_EVENT_NAMES.TASK_CONSULT_START_FAILED,
930
+ ]);
931
+ const result = await this.contact.consult({
932
+ interactionId: requestInteractionId,
933
+ data: consultPayload,
934
+ });
935
+
936
+ // Send success event to transition to CONSULTING state
937
+ if (this.stateMachineService) {
938
+ this.stateMachineService.send({
939
+ type: TaskEvent.CONSULT_SUCCESS,
940
+ taskData: result.data,
941
+ });
942
+ }
943
+
944
+ this.metricsManager.trackEvent(
945
+ METRIC_EVENT_NAMES.TASK_CONSULT_START_SUCCESS,
946
+ {
947
+ taskId: this.data.interactionId,
948
+ requestInteractionId,
949
+ destination: consultPayload.to,
950
+ destinationType: consultPayload.destinationType,
951
+ ...MetricsManager.getCommonTrackingFieldForAQMResponse(result),
952
+ },
953
+ ['operational', 'behavioral', 'business']
954
+ );
955
+ LoggerProxy.log(`Consult successfully initiated to ${consultPayload.to}`, {
956
+ module: CC_FILE,
957
+ method: 'consult',
958
+ trackingId: result.trackingId,
959
+ interactionId: requestInteractionId,
960
+ });
961
+
962
+ return result;
963
+ } catch (error) {
964
+ this.stateMachineService.send({
965
+ type: TaskEvent.CONSULT_FAILED,
966
+ reason: error.toString(),
967
+ });
968
+
969
+ const {error: detailedError} = getErrorDetails(error, 'consult', CC_FILE);
970
+ this.metricsManager.trackEvent(
971
+ METRIC_EVENT_NAMES.TASK_CONSULT_START_FAILED,
972
+ {
973
+ taskId: this.data.interactionId,
974
+ requestInteractionId,
975
+ destination: consultPayload.to,
976
+ destinationType: consultPayload.destinationType,
977
+ error: error.toString(),
978
+ ...MetricsManager.getCommonTrackingFieldForAQMResponseFailed(error.details || {}),
979
+ },
980
+ ['operational', 'behavioral', 'business']
981
+ );
982
+ throw detailedError;
983
+ }
984
+ }
985
+
986
+ /**
987
+ * This is used to end the consult session on the task.
988
+ * @param consultEndPayload - Payload indicating consult end flags and identifiers
989
+ * @returns Promise<TaskResponse>
990
+ * @throws Error
991
+ * @example
992
+ * ```typescript
993
+ * task.endConsult({
994
+ * isConsult: true,
995
+ * queueId: 'myQueueId',
996
+ * taskId: 'taskId',
997
+ * });
998
+ * ```
999
+ */
1000
+ public async endConsult(consultEndPayload?: ConsultEndPayload): Promise<TaskResponse> {
1001
+ const requestInteractionId =
1002
+ this.data.interaction?.mainInteractionId || this.data.interactionId;
1003
+
1004
+ try {
1005
+ LoggerProxy.info(`Ending consult`, {
1006
+ module: CC_FILE,
1007
+ method: 'endConsult',
1008
+ interactionId: requestInteractionId,
1009
+ });
1010
+ this.metricsManager.timeEvent([
1011
+ METRIC_EVENT_NAMES.TASK_CONSULT_END_SUCCESS,
1012
+ METRIC_EVENT_NAMES.TASK_CONSULT_END_FAILED,
1013
+ ]);
1014
+ const result = await this.contact.consultEnd({
1015
+ interactionId: requestInteractionId,
1016
+ data: consultEndPayload,
1017
+ });
1018
+ this.metricsManager.trackEvent(
1019
+ METRIC_EVENT_NAMES.TASK_CONSULT_END_SUCCESS,
1020
+ {
1021
+ taskId: this.data.interactionId,
1022
+ requestInteractionId,
1023
+ ...MetricsManager.getCommonTrackingFieldForAQMResponse(result),
1024
+ },
1025
+ ['operational', 'behavioral', 'business']
1026
+ );
1027
+ LoggerProxy.log(`Consult ended successfully`, {
1028
+ module: CC_FILE,
1029
+ method: 'endConsult',
1030
+ trackingId: result.trackingId,
1031
+ interactionId: this.data.interactionId,
1032
+ });
1033
+
1034
+ return result;
1035
+ } catch (error) {
1036
+ const {error: detailedError} = getErrorDetails(error, 'endConsult', CC_FILE);
1037
+ this.metricsManager.trackEvent(
1038
+ METRIC_EVENT_NAMES.TASK_CONSULT_END_FAILED,
1039
+ {
1040
+ taskId: this.data.interactionId,
1041
+ requestInteractionId,
1042
+ error: error.toString(),
1043
+ ...MetricsManager.getCommonTrackingFieldForAQMResponseFailed(error.details || {}),
1044
+ },
1045
+ ['operational', 'behavioral', 'business']
1046
+ );
1047
+ throw detailedError;
1048
+ }
1049
+ }
1050
+
1051
+ /**
1052
+ * This is used to transfer the task.
1053
+ * @param payload - Transfer payload
1054
+ * @returns Promise<TaskResponse>
1055
+ * @throws Error
1056
+ * @example
1057
+ * ```typescript
1058
+ * task.transfer({
1059
+ * to: 'destinationId',
1060
+ * destinationType: DESTINATION_TYPE.AGENT,
1061
+ * consult: true, // Optional, if true will perform a consult transfer else blind transfer
1062
+ * });
1063
+ * ```
1064
+ */
1065
+ public async transfer(payload: TransferPayLoad): Promise<TaskResponse> {
1066
+ try {
1067
+ LoggerProxy.info(`Transferring task to ${payload.to}`, {
1068
+ module: CC_FILE,
1069
+ method: METHODS.TRANSFER_CALL,
1070
+ interactionId: this.data.interactionId,
1071
+ });
1072
+ this.metricsManager.timeEvent([
1073
+ METRIC_EVENT_NAMES.TASK_TRANSFER_SUCCESS,
1074
+ METRIC_EVENT_NAMES.TASK_TRANSFER_FAILED,
1075
+ ]);
1076
+
1077
+ // consult transfer path
1078
+ if (this.data.interaction.state === 'consulting') {
1079
+ const normalizedDestinationType =
1080
+ payload.destinationType === 'Agent' || payload.destinationType === 'Queue'
1081
+ ? (payload.destinationType.toLowerCase() as ConsultTransferPayLoad['destinationType'])
1082
+ : payload.destinationType;
1083
+ let consultPayload: ConsultTransferPayLoad = {
1084
+ to: payload.to,
1085
+ destinationType: normalizedDestinationType,
1086
+ };
1087
+
1088
+ if (normalizedDestinationType === CONSULT_TRANSFER_DESTINATION_TYPE.QUEUE) {
1089
+ const consultContext = this.getStateMachineSnapshot()?.context;
1090
+ const destAgent = consultContext?.consultDestinationAgentId || this.data.destAgentId;
1091
+ if (!destAgent) {
1092
+ throw new Error('No agent has accepted this queue consult yet');
1093
+ }
1094
+ consultPayload = {
1095
+ to: destAgent,
1096
+ destinationType: CONSULT_TRANSFER_DESTINATION_TYPE.AGENT,
1097
+ };
1098
+ }
1099
+
1100
+ const result = await this.contact.consultTransfer({
1101
+ interactionId: this.data.interactionId,
1102
+ data: consultPayload,
1103
+ });
1104
+ this.metricsManager.trackEvent(
1105
+ METRIC_EVENT_NAMES.TASK_TRANSFER_SUCCESS,
1106
+ {
1107
+ taskId: this.data.interactionId,
1108
+ destination: consultPayload.to,
1109
+ destinationType: consultPayload.destinationType,
1110
+ isConsultTransfer: true,
1111
+ ...MetricsManager.getCommonTrackingFieldForAQMResponse(result),
1112
+ },
1113
+ ['operational', 'behavioral', 'business']
1114
+ );
1115
+ LoggerProxy.log(`Consult transfer completed successfully to ${consultPayload.to}`, {
1116
+ module: CC_FILE,
1117
+ method: METHODS.TRANSFER_CALL,
1118
+ trackingId: result.trackingId,
1119
+ interactionId: this.data.interactionId,
1120
+ });
1121
+
1122
+ return result;
1123
+ }
1124
+
1125
+ // standard blind transfer
1126
+ return await super.transfer({
1127
+ to: payload.to,
1128
+ destinationType: payload.destinationType,
1129
+ });
1130
+ } catch (err) {
1131
+ const {error: detailedError} = getErrorDetails(err, METHODS.TRANSFER_CALL, CC_FILE);
1132
+ this.metricsManager.trackEvent(
1133
+ METRIC_EVENT_NAMES.TASK_TRANSFER_FAILED,
1134
+ {
1135
+ taskId: this.data.interactionId,
1136
+ destination: payload.to,
1137
+ destinationType: payload.destinationType,
1138
+ isConsultTransfer: this.data.interaction.state === 'consulting',
1139
+ error: err.toString(),
1140
+ ...MetricsManager.getCommonTrackingFieldForAQMResponseFailed(err.details || {}),
1141
+ },
1142
+ ['operational', 'behavioral', 'business']
1143
+ );
1144
+ throw detailedError;
1145
+ }
1146
+ }
1147
+
1148
+ /**
1149
+ * Start a consult conference, merging main and consult calls.
1150
+ */
1151
+ public async consultConference(): Promise<TaskResponse> {
1152
+ const derivedDestAgentId =
1153
+ this.data.interaction && this.data.agentId
1154
+ ? calculateDestAgentId(this.data.interaction, this.data.agentId)
1155
+ : '';
1156
+ const derivedDestType =
1157
+ this.data.interaction && this.data.agentId
1158
+ ? calculateDestType(this.data.interaction, this.data.agentId)
1159
+ : '';
1160
+
1161
+ // derivedDestType is most reliable as it inspects live interaction participants
1162
+ const resolvedDestinationType =
1163
+ derivedDestType ||
1164
+ this.getStateMachineSnapshot()?.context?.consultDestinationType ||
1165
+ this.data.destinationType ||
1166
+ 'agent';
1167
+
1168
+ const consultationData: consultConferencePayloadData = {
1169
+ agentId: this.data.agentId,
1170
+ destinationType: resolvedDestinationType,
1171
+ // derivedDestAgentId is most reliable as it resolves epId for EP_DN
1172
+ // and agent ID for regular agents from live interaction data
1173
+ destAgentId:
1174
+ derivedDestAgentId ||
1175
+ this.getStateMachineSnapshot()?.context?.consultDestinationAgentId ||
1176
+ this.data.destAgentId,
1177
+ };
1178
+
1179
+ // Send state machine event to transition to CONF_INITIATING
1180
+ if (this.stateMachineService) {
1181
+ this.stateMachineService.send({
1182
+ type: TaskEvent.MERGE_TO_CONFERENCE,
1183
+ });
1184
+ }
1185
+
1186
+ try {
1187
+ if (!consultationData.destAgentId) {
1188
+ throw new Error('Unable to determine consult destination for conference');
1189
+ }
1190
+
1191
+ LoggerProxy.info(`Initiating consult conference to ${consultationData.destAgentId}`, {
1192
+ module: CC_FILE,
1193
+ method: METHODS.CONSULT_CONFERENCE,
1194
+ interactionId: this.data.interactionId,
1195
+ });
1196
+
1197
+ const paramsDataForConferenceV2 = buildConsultConferenceParamData(
1198
+ consultationData,
1199
+ this.data.interactionId
1200
+ );
1201
+
1202
+ const response = await this.contact.consultConference({
1203
+ interactionId: paramsDataForConferenceV2.interactionId,
1204
+ data: paramsDataForConferenceV2.data,
1205
+ });
1206
+
1207
+ // Send success event to transition to CONFERENCING
1208
+ if (this.stateMachineService) {
1209
+ this.stateMachineService.send({
1210
+ type: TaskEvent.CONFERENCE_START,
1211
+ });
1212
+ }
1213
+
1214
+ this.metricsManager.trackEvent(
1215
+ METRIC_EVENT_NAMES.TASK_CONFERENCE_START_SUCCESS,
1216
+ {
1217
+ taskId: this.data.interactionId,
1218
+ destination: paramsDataForConferenceV2.data.to,
1219
+ destinationType: paramsDataForConferenceV2.data.destinationType,
1220
+ agentId: paramsDataForConferenceV2.data.agentId,
1221
+ ...MetricsManager.getCommonTrackingFieldForAQMResponse(response),
1222
+ },
1223
+ ['operational', 'behavioral', 'business']
1224
+ );
1225
+
1226
+ LoggerProxy.log(`Consult conference started successfully`, {
1227
+ module: CC_FILE,
1228
+ method: METHODS.CONSULT_CONFERENCE,
1229
+ interactionId: this.data.interactionId,
1230
+ });
1231
+
1232
+ return response;
1233
+ } catch (error) {
1234
+ // Send failure event to revert state
1235
+ if (this.stateMachineService) {
1236
+ this.stateMachineService.send({
1237
+ type: TaskEvent.CONFERENCE_FAILED,
1238
+ reason: error.toString(),
1239
+ });
1240
+ }
1241
+
1242
+ const {error: detailedError} = getErrorDetails(error, METHODS.CONSULT_CONFERENCE, CC_FILE);
1243
+
1244
+ const failedParamsData = buildConsultConferenceParamData(
1245
+ consultationData,
1246
+ this.data.interactionId
1247
+ );
1248
+
1249
+ this.metricsManager.trackEvent(
1250
+ METRIC_EVENT_NAMES.TASK_CONFERENCE_START_FAILED,
1251
+ {
1252
+ taskId: this.data.interactionId,
1253
+ destination: failedParamsData.data.to,
1254
+ destinationType: failedParamsData.data.destinationType,
1255
+ agentId: failedParamsData.data.agentId,
1256
+ error: error.toString(),
1257
+ ...MetricsManager.getCommonTrackingFieldForAQMResponseFailed(error.details || {}),
1258
+ },
1259
+ ['operational', 'behavioral', 'business']
1260
+ );
1261
+
1262
+ LoggerProxy.error(`Failed to start consult conference`, {
1263
+ module: CC_FILE,
1264
+ method: METHODS.CONSULT_CONFERENCE,
1265
+ interactionId: this.data.interactionId,
1266
+ });
1267
+
1268
+ throw detailedError;
1269
+ }
1270
+ }
1271
+
1272
+ /**
1273
+ * Removes another participant from an active conference.
1274
+ * Completion is correlated with ParticipantLeftConference by the AQM request layer.
1275
+ * @param payload - Participant identifier to remove
1276
+ * @returns Promise<TaskResponse>
1277
+ */
1278
+ public async dropConferenceParticipant(
1279
+ payload: DropConferenceParticipantPayload
1280
+ ): Promise<TaskResponse> {
1281
+ // The TypeScript contract requires payload, but the published SDK is also callable from
1282
+ // untyped JavaScript. Keep an explicit runtime boundary check before direct property access.
1283
+ if (!payload) {
1284
+ throw new Error('participantId must be a non-empty string');
1285
+ }
1286
+
1287
+ const {participantId} = payload;
1288
+
1289
+ if (typeof participantId !== 'string' || participantId.trim().length === 0) {
1290
+ throw new Error('participantId must be a non-empty string');
1291
+ }
1292
+
1293
+ const requestInteractionId =
1294
+ this.data.interaction?.mainInteractionId || this.data.interactionId;
1295
+ // taskId identifies the SDK task instance, which can remain child-interaction keyed after
1296
+ // consult/EP-DN flows. requestInteractionId identifies the main interaction sent to AQM.
1297
+
1298
+ LoggerProxy.info('Dropping conference participant', {
1299
+ module: CC_FILE,
1300
+ method: METHODS.DROP_CONFERENCE_PARTICIPANT,
1301
+ interactionId: requestInteractionId,
1302
+ });
1303
+
1304
+ try {
1305
+ this.metricsManager.timeEvent([
1306
+ METRIC_EVENT_NAMES.TASK_CONFERENCE_PARTICIPANT_DROP_SUCCESS,
1307
+ METRIC_EVENT_NAMES.TASK_CONFERENCE_PARTICIPANT_DROP_FAILED,
1308
+ ]);
1309
+
1310
+ const response = await this.contact.dropConferenceParticipant({
1311
+ interactionId: requestInteractionId,
1312
+ participantId,
1313
+ });
1314
+
1315
+ this.metricsManager.trackEvent(
1316
+ METRIC_EVENT_NAMES.TASK_CONFERENCE_PARTICIPANT_DROP_SUCCESS,
1317
+ {
1318
+ taskId: this.data.interactionId,
1319
+ requestInteractionId,
1320
+ ...MetricsManager.getCommonTrackingFieldForAQMResponse(response),
1321
+ agentId: this.agentId,
1322
+ },
1323
+ ['operational', 'behavioral', 'business']
1324
+ );
1325
+
1326
+ LoggerProxy.log('Successfully dropped conference participant', {
1327
+ module: CC_FILE,
1328
+ method: METHODS.DROP_CONFERENCE_PARTICIPANT,
1329
+ trackingId: response?.trackingId,
1330
+ interactionId: requestInteractionId,
1331
+ });
1332
+
1333
+ return response;
1334
+ } catch (error) {
1335
+ const failureTrackingFields = MetricsManager.getCommonTrackingFieldForAQMResponseFailed(
1336
+ error?.details || {}
1337
+ );
1338
+
1339
+ this.metricsManager.trackEvent(
1340
+ METRIC_EVENT_NAMES.TASK_CONFERENCE_PARTICIPANT_DROP_FAILED,
1341
+ {
1342
+ taskId: this.data.interactionId,
1343
+ requestInteractionId,
1344
+ agentId: this.agentId,
1345
+ trackingId: failureTrackingFields.trackingId,
1346
+ notifTrackingId: failureTrackingFields.notifTrackingId,
1347
+ orgId: failureTrackingFields.orgId,
1348
+ failureType: failureTrackingFields.failureType,
1349
+ reasonCode: failureTrackingFields.reasonCode,
1350
+ },
1351
+ ['operational', 'behavioral', 'business']
1352
+ );
1353
+
1354
+ LoggerProxy.error('Failed to drop conference participant', {
1355
+ module: CC_FILE,
1356
+ method: METHODS.DROP_CONFERENCE_PARTICIPANT,
1357
+ trackingId: failureTrackingFields.trackingId,
1358
+ interactionId: requestInteractionId,
1359
+ });
1360
+
1361
+ throw error;
1362
+ }
1363
+ }
1364
+
1365
+ /**
1366
+ * Exit from a conference call.
1367
+ * Per conference-spec.md:
1368
+ * - Primary agent exits to wrapup
1369
+ * - Non-primary agent exits to available/connected
1370
+ * - Other participants continue the call
1371
+ *
1372
+ * @returns Promise<TaskResponse>
1373
+ * @throws Error if not in conference or exit fails
1374
+ * @example
1375
+ * ```typescript
1376
+ * task.exitConference().then(() => {}).catch(() => {});
1377
+ * ```
1378
+ */
1379
+ public async exitConference(): Promise<TaskResponse> {
1380
+ // Validate we're in conference state OR conference is in progress per task data
1381
+ // This handles cases where:
1382
+ // 1. State machine is in CONFERENCING state
1383
+ // 2. State machine is in CONNECTED but conference is active (e.g., ownership transferred)
1384
+ const state = this.getStateMachineSnapshot();
1385
+ const isConferencingState = state?.matches(TaskState.CONFERENCING);
1386
+
1387
+ const isConferenceInProgressFromData = this.data ? getIsConferenceInProgress(this.data) : false;
1388
+
1389
+ if (!state || (!isConferencingState && !isConferenceInProgressFromData)) {
1390
+ const currentState = state?.value as TaskState;
1391
+ const error = new Error(`Cannot exit conference in ${currentState} state`);
1392
+ LoggerProxy.error('Exit conference operation not allowed', {
1393
+ module: CC_FILE,
1394
+ method: 'exitConference',
1395
+ interactionId: this.data.interactionId,
1396
+ });
1397
+ throw error;
1398
+ }
1399
+
1400
+ // Send state machine event
1401
+ if (this.stateMachineService) {
1402
+ this.stateMachineService.send({
1403
+ type: TaskEvent.EXIT_CONFERENCE,
1404
+ agentId: this.data.agentId,
1405
+ });
1406
+ }
1407
+
1408
+ const requestInteractionId =
1409
+ this.data.interaction?.mainInteractionId || this.data.interactionId;
1410
+
1411
+ try {
1412
+ LoggerProxy.info(`Exiting conference`, {
1413
+ module: CC_FILE,
1414
+ method: 'exitConference',
1415
+ interactionId: requestInteractionId,
1416
+ });
1417
+
1418
+ this.metricsManager.timeEvent([
1419
+ METRIC_EVENT_NAMES.TASK_CONFERENCE_EXIT_SUCCESS,
1420
+ METRIC_EVENT_NAMES.TASK_CONFERENCE_EXIT_FAILED,
1421
+ ]);
1422
+
1423
+ const response = await this.contact.exitConference({
1424
+ interactionId: requestInteractionId,
1425
+ });
1426
+
1427
+ // Send success event to transition state
1428
+ if (this.stateMachineService) {
1429
+ this.stateMachineService.send({
1430
+ type: TaskEvent.EXIT_CONFERENCE_SUCCESS,
1431
+ taskData: response.data,
1432
+ });
1433
+ }
1434
+
1435
+ this.metricsManager.trackEvent(
1436
+ METRIC_EVENT_NAMES.TASK_CONFERENCE_EXIT_SUCCESS,
1437
+ {
1438
+ taskId: this.data.interactionId,
1439
+ requestInteractionId,
1440
+ agentId: this.data.agentId,
1441
+ ...MetricsManager.getCommonTrackingFieldForAQMResponse(response),
1442
+ },
1443
+ ['operational', 'behavioral', 'business']
1444
+ );
1445
+
1446
+ LoggerProxy.log(`Successfully exited conference`, {
1447
+ module: CC_FILE,
1448
+ method: 'exitConference',
1449
+ trackingId: response.trackingId,
1450
+ interactionId: requestInteractionId,
1451
+ });
1452
+
1453
+ return response;
1454
+ } catch (error) {
1455
+ // Send failure event
1456
+ if (this.stateMachineService) {
1457
+ this.stateMachineService.send({
1458
+ type: TaskEvent.EXIT_CONFERENCE_FAILED,
1459
+ reason: error.toString(),
1460
+ });
1461
+ }
1462
+
1463
+ const {error: detailedError} = getErrorDetails(error, 'exitConference', CC_FILE);
1464
+ this.metricsManager.trackEvent(
1465
+ METRIC_EVENT_NAMES.TASK_CONFERENCE_EXIT_FAILED,
1466
+ {
1467
+ taskId: this.data.interactionId,
1468
+ requestInteractionId,
1469
+ agentId: this.data.agentId,
1470
+ error: error.toString(),
1471
+ ...MetricsManager.getCommonTrackingFieldForAQMResponseFailed(error.details || {}),
1472
+ },
1473
+ ['operational', 'behavioral', 'business']
1474
+ );
1475
+
1476
+ LoggerProxy.error(`Failed to exit conference`, {
1477
+ module: CC_FILE,
1478
+ method: 'exitConference',
1479
+ interactionId: requestInteractionId,
1480
+ });
1481
+
1482
+ throw detailedError;
1483
+ }
1484
+ }
1485
+
1486
+ /**
1487
+ * Transfer the conference to another participant.
1488
+ * Per conference-spec.md: Only primary agent can transfer conference.
1489
+ * After transfer, the transferring agent exits to wrapup.
1490
+ *
1491
+ * @returns Promise<TaskResponse>
1492
+ * @throws Error if not in conference or transfer fails
1493
+ * @example
1494
+ * ```typescript
1495
+ * task.transferConference().then(() => {}).catch(() => {});
1496
+ * ```
1497
+ */
1498
+ public async transferConference(): Promise<TaskResponse> {
1499
+ // Validate we're in conference or consulting state
1500
+ // CONSULTING is allowed because agent can transfer conference while consulting
1501
+ // (transfers ownership to the consulted agent)
1502
+ const state = this.getStateMachineSnapshot();
1503
+ const isValidState =
1504
+ state && (state.matches(TaskState.CONFERENCING) || state.matches(TaskState.CONSULTING));
1505
+ if (!isValidState) {
1506
+ const currentState = state?.value as TaskState;
1507
+ const error = new Error(`Cannot transfer conference in ${currentState} state`);
1508
+ LoggerProxy.error('Transfer conference operation not allowed', {
1509
+ module: CC_FILE,
1510
+ method: 'transferConference',
1511
+ interactionId: this.data.interactionId,
1512
+ });
1513
+ throw error;
1514
+ }
1515
+
1516
+ // Send state machine event
1517
+ if (this.stateMachineService) {
1518
+ this.stateMachineService.send({
1519
+ type: TaskEvent.TRANSFER_CONFERENCE,
1520
+ agentId: this.data.agentId,
1521
+ });
1522
+ }
1523
+
1524
+ const requestInteractionId =
1525
+ this.data.interaction?.mainInteractionId || this.data.interactionId;
1526
+
1527
+ try {
1528
+ LoggerProxy.info(`Transferring conference`, {
1529
+ module: CC_FILE,
1530
+ method: 'transferConference',
1531
+ interactionId: requestInteractionId,
1532
+ });
1533
+
1534
+ this.metricsManager.timeEvent([
1535
+ METRIC_EVENT_NAMES.TASK_CONFERENCE_TRANSFER_SUCCESS,
1536
+ METRIC_EVENT_NAMES.TASK_CONFERENCE_TRANSFER_FAILED,
1537
+ ]);
1538
+
1539
+ const response = await this.contact.conferenceTransfer({
1540
+ interactionId: requestInteractionId,
1541
+ });
1542
+
1543
+ // Send success event to transition state
1544
+ if (this.stateMachineService) {
1545
+ this.stateMachineService.send({
1546
+ type: TaskEvent.TRANSFER_CONFERENCE_SUCCESS,
1547
+ taskData: response.data,
1548
+ });
1549
+ }
1550
+
1551
+ this.metricsManager.trackEvent(
1552
+ METRIC_EVENT_NAMES.TASK_CONFERENCE_TRANSFER_SUCCESS,
1553
+ {
1554
+ taskId: this.data.interactionId,
1555
+ requestInteractionId,
1556
+ agentId: this.data.agentId,
1557
+ ...MetricsManager.getCommonTrackingFieldForAQMResponse(response),
1558
+ },
1559
+ ['operational', 'behavioral', 'business']
1560
+ );
1561
+
1562
+ LoggerProxy.log(`Successfully transferred conference`, {
1563
+ module: CC_FILE,
1564
+ method: 'transferConference',
1565
+ trackingId: response.trackingId,
1566
+ interactionId: requestInteractionId,
1567
+ });
1568
+
1569
+ return response;
1570
+ } catch (error) {
1571
+ // Send failure event
1572
+ if (this.stateMachineService) {
1573
+ this.stateMachineService.send({
1574
+ type: TaskEvent.TRANSFER_CONFERENCE_FAILED,
1575
+ reason: error.toString(),
1576
+ });
1577
+ }
1578
+
1579
+ const {error: detailedError} = getErrorDetails(error, 'transferConference', CC_FILE);
1580
+ this.metricsManager.trackEvent(
1581
+ METRIC_EVENT_NAMES.TASK_CONFERENCE_TRANSFER_FAILED,
1582
+ {
1583
+ taskId: this.data.interactionId,
1584
+ requestInteractionId,
1585
+ agentId: this.data.agentId,
1586
+ error: error.toString(),
1587
+ ...MetricsManager.getCommonTrackingFieldForAQMResponseFailed(error.details || {}),
1588
+ },
1589
+ ['operational', 'behavioral', 'business']
1590
+ );
1591
+
1592
+ LoggerProxy.error(`Failed to transfer conference`, {
1593
+ module: CC_FILE,
1594
+ method: 'transferConference',
1595
+ interactionId: requestInteractionId,
1596
+ });
1597
+
1598
+ throw detailedError;
1599
+ }
1600
+ }
1601
+
1602
+ /**
1603
+ * Toggle between consult call and main call during consulting.
1604
+ * If on consult leg (consultCallHeld = false), switches to main call by holding consult.
1605
+ * If on main call (consultCallHeld = true), switches to consult by resuming consult.
1606
+ *
1607
+ * @returns Promise<TaskResponse>
1608
+ * @throws Error if not in CONSULTING state or no consult media resource
1609
+ * @example
1610
+ * ```typescript
1611
+ * await task.switchCall();
1612
+ * ```
1613
+ */
1614
+ public async switchCall(): Promise<TaskResponse> {
1615
+ // Validate we're in CONSULTING state
1616
+ const state = this.getStateMachineSnapshot();
1617
+ if (!state?.matches(TaskState.CONSULTING)) {
1618
+ const currentState = state?.value as TaskState;
1619
+ const error = new Error(`Cannot switch call in ${currentState} state`);
1620
+ LoggerProxy.error('Switch call operation not allowed', {
1621
+ module: CC_FILE,
1622
+ method: 'switchCall',
1623
+ interactionId: this.data.interactionId,
1624
+ });
1625
+ throw error;
1626
+ }
1627
+
1628
+ // Validate we have a consult media resource
1629
+ const consultMediaResourceId = getConsultMediaResourceId(
1630
+ this.data.interaction,
1631
+ this.data.consultMediaResourceId,
1632
+ this.data.agentId
1633
+ );
1634
+ if (!consultMediaResourceId) {
1635
+ const error = new Error('No consult media resource available');
1636
+ LoggerProxy.error('Switch call failed - no consult media resource', {
1637
+ module: CC_FILE,
1638
+ method: 'switchCall',
1639
+ interactionId: this.data.interactionId,
1640
+ });
1641
+ throw error;
1642
+ }
1643
+
1644
+ const context = state.context;
1645
+ const isOnConsultLeg = !context.consultCallHeld;
1646
+
1647
+ // Determine direction and send appropriate state machine event
1648
+ const targetEvent = isOnConsultLeg
1649
+ ? TaskEvent.SWITCH_TO_MAIN_CALL
1650
+ : TaskEvent.SWITCH_TO_CONSULT;
1651
+ const revertEvent = isOnConsultLeg
1652
+ ? TaskEvent.SWITCH_TO_CONSULT
1653
+ : TaskEvent.SWITCH_TO_MAIN_CALL;
1654
+
1655
+ if (this.stateMachineService) {
1656
+ this.stateMachineService.send({type: targetEvent});
1657
+ }
1658
+
1659
+ this.metricsManager.timeEvent([
1660
+ METRIC_EVENT_NAMES.TASK_SWITCH_CALL_SUCCESS,
1661
+ METRIC_EVENT_NAMES.TASK_SWITCH_CALL_FAILED,
1662
+ ]);
1663
+
1664
+ try {
1665
+ if (isOnConsultLeg) {
1666
+ const response = await this.contact.unHold({
1667
+ interactionId: this.data.interactionId,
1668
+ data: {mediaResourceId: this.data.mediaResourceId},
1669
+ });
1670
+
1671
+ this.metricsManager.trackEvent(
1672
+ METRIC_EVENT_NAMES.TASK_SWITCH_CALL_SUCCESS,
1673
+ {
1674
+ taskId: this.data.interactionId,
1675
+ direction: 'toMainCall',
1676
+ mediaResourceId: consultMediaResourceId,
1677
+ ...MetricsManager.getCommonTrackingFieldForAQMResponse(response),
1678
+ },
1679
+ ['operational', 'behavioral']
1680
+ );
1681
+
1682
+ LoggerProxy.log(`Switched to main call successfully`, {
1683
+ module: CC_FILE,
1684
+ method: 'switchCall',
1685
+ trackingId: response.trackingId,
1686
+ interactionId: this.data.interactionId,
1687
+ });
1688
+
1689
+ return response;
1690
+ }
1691
+
1692
+ const response = await this.contact.hold({
1693
+ interactionId: this.data.interactionId,
1694
+ data: {mediaResourceId: this.data.mediaResourceId},
1695
+ });
1696
+
1697
+ this.metricsManager.trackEvent(
1698
+ METRIC_EVENT_NAMES.TASK_SWITCH_CALL_SUCCESS,
1699
+ {
1700
+ taskId: this.data.interactionId,
1701
+ direction: 'toConsultCall',
1702
+ mediaResourceId: consultMediaResourceId,
1703
+ ...MetricsManager.getCommonTrackingFieldForAQMResponse(response),
1704
+ },
1705
+ ['operational', 'behavioral']
1706
+ );
1707
+
1708
+ LoggerProxy.log(`Switched to consult call successfully`, {
1709
+ module: CC_FILE,
1710
+ method: 'switchCall',
1711
+ trackingId: response.trackingId,
1712
+ interactionId: this.data.interactionId,
1713
+ });
1714
+
1715
+ return response;
1716
+ } catch (error) {
1717
+ if (this.stateMachineService) {
1718
+ this.stateMachineService.send({type: revertEvent});
1719
+ }
1720
+
1721
+ this.metricsManager.trackEvent(
1722
+ METRIC_EVENT_NAMES.TASK_SWITCH_CALL_FAILED,
1723
+ {
1724
+ taskId: this.data.interactionId,
1725
+ direction: isOnConsultLeg ? 'toMainCall' : 'toConsultCall',
1726
+ mediaResourceId: consultMediaResourceId,
1727
+ error: error.toString(),
1728
+ ...MetricsManager.getCommonTrackingFieldForAQMResponseFailed(error.details || {}),
1729
+ },
1730
+ ['operational', 'behavioral']
1731
+ );
1732
+
1733
+ const {error: detailedError} = getErrorDetails(error, 'switchCall', CC_FILE);
1734
+ LoggerProxy.error(`Failed to switch call`, {
1735
+ module: CC_FILE,
1736
+ method: 'switchCall',
1737
+ interactionId: this.data.interactionId,
1738
+ });
1739
+ throw detailedError;
1740
+ }
1741
+ }
1742
+
1743
+ protected override getChannelSpecificActionOverrides() {
1744
+ const baseOverrides = super.getChannelSpecificActionOverrides();
1745
+
1746
+ return {
1747
+ ...baseOverrides,
1748
+ emitTaskHold: this.createEmitSelfAction(TASK_EVENTS.TASK_HOLD, {updateTaskData: true}),
1749
+ emitTaskResume: this.createEmitSelfAction(TASK_EVENTS.TASK_RESUME, {updateTaskData: true}),
1750
+ emitTaskRecordingStarted: this.createEmitSelfAction(TASK_EVENTS.TASK_RECORDING_STARTED, {
1751
+ updateTaskData: true,
1752
+ }),
1753
+ emitTaskRecordingPaused: this.createEmitSelfAction(TASK_EVENTS.TASK_RECORDING_PAUSED, {
1754
+ updateTaskData: true,
1755
+ }),
1756
+ emitTaskRecordingPauseFailed: this.createEmitSelfAction(
1757
+ TASK_EVENTS.TASK_RECORDING_PAUSE_FAILED,
1758
+ {updateTaskData: true}
1759
+ ),
1760
+ emitTaskRecordingResumed: this.createEmitSelfAction(TASK_EVENTS.TASK_RECORDING_RESUMED, {
1761
+ updateTaskData: true,
1762
+ }),
1763
+ emitTaskRecordingResumeFailed: this.createEmitSelfAction(
1764
+ TASK_EVENTS.TASK_RECORDING_RESUME_FAILED,
1765
+ {updateTaskData: true}
1766
+ ),
1767
+ // Conference event emitters
1768
+ emitTaskParticipantJoined: this.createEmitSelfAction(TASK_EVENTS.TASK_PARTICIPANT_JOINED, {
1769
+ updateTaskData: true,
1770
+ }),
1771
+ emitTaskParticipantLeft: this.createEmitSelfAction(TASK_EVENTS.TASK_PARTICIPANT_LEFT, {
1772
+ updateTaskData: true,
1773
+ }),
1774
+ emitTaskConferenceStarted: this.createEmitSelfAction(TASK_EVENTS.TASK_CONFERENCE_STARTED, {
1775
+ updateTaskData: true,
1776
+ }),
1777
+ emitTaskConferenceEnded: this.createEmitSelfAction(TASK_EVENTS.TASK_CONFERENCE_ENDED, {
1778
+ updateTaskData: true,
1779
+ }),
1780
+ emitTaskConferenceFailed: this.createEmitSelfAction(TASK_EVENTS.TASK_CONFERENCE_FAILED, {
1781
+ updateTaskData: true,
1782
+ }),
1783
+ emitTaskExitConference: this.createEmitSelfAction(TASK_EVENTS.TASK_EXIT_CONFERENCE, {
1784
+ updateTaskData: false,
1785
+ }),
1786
+ emitTaskTransferConference: this.createEmitSelfAction(TASK_EVENTS.TASK_TRANSFER_CONFERENCE, {
1787
+ updateTaskData: false,
1788
+ }),
1789
+ emitTaskSwitchCall: this.createEmitSelfAction(TASK_EVENTS.TASK_SWITCH_CALL, {
1790
+ updateTaskData: false,
1791
+ }),
1792
+ emitTaskTransferConferenceFailed: this.createEmitSelfAction(
1793
+ TASK_EVENTS.TASK_CONFERENCE_TRANSFER_FAILED,
1794
+ {updateTaskData: true}
1795
+ ),
1796
+ emitTaskOutdialFailed: ({event}: TaskActionArgs) => {
1797
+ const taskData = (event as {taskData?: TaskData})?.taskData;
1798
+ if (taskData) {
1799
+ this.updateTaskData(taskData);
1800
+ }
1801
+ if (taskData?.suppressOutdialFailedPopup) {
1802
+ return;
1803
+ }
1804
+ const reason = (event as {reason?: string})?.reason || 'Outdial failed';
1805
+ this.emit(TASK_EVENTS.TASK_OUTDIAL_FAILED, reason);
1806
+ },
1807
+ };
1808
+ }
1809
+ }