@webex/contact-center 3.11.0 → 3.12.0-auth-prejoin-fetch.1

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