@webex/contact-center 3.12.0 → 3.13.0-next.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (337) hide show
  1. package/.sdd/manifest.json +887 -0
  2. package/AGENTS.md +94 -0
  3. package/ai-docs/ARCHITECTURE.md +168 -0
  4. package/ai-docs/CONTRACTS.md +64 -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 +52 -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 +388 -0
  17. package/ai-docs/features/consult-transfer-list-policy/spec/feature-spec.md +362 -0
  18. package/ai-docs/features/contact-owner-change-refactor.md +78 -0
  19. package/ai-docs/features/generated-spec-conformance-fidelity-remediation/spec/feature-spec.md +117 -0
  20. package/ai-docs/features/residual-warning-coverage-completion/spec/feature-spec.md +203 -0
  21. package/ai-docs/features/validator-code-fidelity-drift-fix/spec/feature-spec.md +315 -0
  22. package/ai-docs/patterns/event-driven-patterns.md +485 -0
  23. package/ai-docs/patterns/testing-patterns.md +480 -0
  24. package/ai-docs/patterns/typescript-patterns.md +365 -0
  25. package/ai-docs/templates/README.md +102 -0
  26. package/ai-docs/templates/documentation/create-agents-md.md +240 -0
  27. package/ai-docs/templates/documentation/create-architecture-md.md +295 -0
  28. package/ai-docs/templates/existing-service/bug-fix.md +254 -0
  29. package/ai-docs/templates/existing-service/feature-enhancement.md +450 -0
  30. package/ai-docs/templates/new-method/00-master.md +80 -0
  31. package/ai-docs/templates/new-method/01-requirements.md +232 -0
  32. package/ai-docs/templates/new-method/02-implementation.md +295 -0
  33. package/ai-docs/templates/new-method/03-tests.md +201 -0
  34. package/ai-docs/templates/new-method/04-validation.md +141 -0
  35. package/ai-docs/templates/new-service/00-master.md +109 -0
  36. package/ai-docs/templates/new-service/01-pre-questions.md +159 -0
  37. package/ai-docs/templates/new-service/02-code-generation.md +346 -0
  38. package/ai-docs/templates/new-service/03-integration.md +178 -0
  39. package/ai-docs/templates/new-service/04-test-generation.md +205 -0
  40. package/ai-docs/templates/new-service/05-validation.md +145 -0
  41. package/dist/cc.js +1102 -47
  42. package/dist/cc.js.map +1 -1
  43. package/dist/config.js +13 -0
  44. package/dist/config.js.map +1 -1
  45. package/dist/constants.js +46 -3
  46. package/dist/constants.js.map +1 -1
  47. package/dist/index.js +86 -17
  48. package/dist/index.js.map +1 -1
  49. package/dist/metrics/MetricsManager.js +16 -0
  50. package/dist/metrics/MetricsManager.js.map +1 -1
  51. package/dist/metrics/behavioral-events.js +211 -0
  52. package/dist/metrics/behavioral-events.js.map +1 -1
  53. package/dist/metrics/constants.js +58 -4
  54. package/dist/metrics/constants.js.map +1 -1
  55. package/dist/services/AddressBook.js +18 -15
  56. package/dist/services/AddressBook.js.map +1 -1
  57. package/dist/services/AnswerCallOnWebexService.js +202 -0
  58. package/dist/services/AnswerCallOnWebexService.js.map +1 -0
  59. package/dist/services/ApiAiAssistant.js +369 -14
  60. package/dist/services/ApiAiAssistant.js.map +1 -1
  61. package/dist/services/EntryPoint.js +46 -68
  62. package/dist/services/EntryPoint.js.map +1 -1
  63. package/dist/services/Queue.js +27 -22
  64. package/dist/services/Queue.js.map +1 -1
  65. package/dist/services/UserPreference.js +427 -0
  66. package/dist/services/UserPreference.js.map +1 -0
  67. package/dist/services/WebCallingService.js +287 -37
  68. package/dist/services/WebCallingService.js.map +1 -1
  69. package/dist/services/WebexCrossClientService.js +225 -0
  70. package/dist/services/WebexCrossClientService.js.map +1 -0
  71. package/dist/services/WxAppTelephonyMercurySync.js +111 -0
  72. package/dist/services/WxAppTelephonyMercurySync.js.map +1 -0
  73. package/dist/services/config/Util.js +48 -48
  74. package/dist/services/config/Util.js.map +1 -1
  75. package/dist/services/config/constants.js +57 -79
  76. package/dist/services/config/constants.js.map +1 -1
  77. package/dist/services/config/index.js +100 -226
  78. package/dist/services/config/index.js.map +1 -1
  79. package/dist/services/config/types.js +100 -40
  80. package/dist/services/config/types.js.map +1 -1
  81. package/dist/services/constants.js +19 -1
  82. package/dist/services/constants.js.map +1 -1
  83. package/dist/services/core/Err.js.map +1 -1
  84. package/dist/services/core/Utils.js +131 -32
  85. package/dist/services/core/Utils.js.map +1 -1
  86. package/dist/services/core/WebexRequest.js +6 -2
  87. package/dist/services/core/WebexRequest.js.map +1 -1
  88. package/dist/services/core/aqm-reqs.js +17 -11
  89. package/dist/services/core/aqm-reqs.js.map +1 -1
  90. package/dist/services/core/constants.js +9 -1
  91. package/dist/services/core/constants.js.map +1 -1
  92. package/dist/services/core/types.js.map +1 -1
  93. package/dist/services/core/websocket/WebSocketManager.js +26 -6
  94. package/dist/services/core/websocket/WebSocketManager.js.map +1 -1
  95. package/dist/services/core/websocket/connection-service.js +3 -1
  96. package/dist/services/core/websocket/connection-service.js.map +1 -1
  97. package/dist/services/core/websocket/types.js.map +1 -1
  98. package/dist/services/index.js +6 -0
  99. package/dist/services/index.js.map +1 -1
  100. package/dist/services/task/Task.js +955 -0
  101. package/dist/services/task/Task.js.map +1 -0
  102. package/dist/services/task/TaskFactory.js +50 -0
  103. package/dist/services/task/TaskFactory.js.map +1 -0
  104. package/dist/services/task/TaskManager.js +1275 -504
  105. package/dist/services/task/TaskManager.js.map +1 -1
  106. package/dist/services/task/TaskUtils.js +221 -27
  107. package/dist/services/task/TaskUtils.js.map +1 -1
  108. package/dist/services/task/WebexCallingUtils.js +70 -0
  109. package/dist/services/task/WebexCallingUtils.js.map +1 -0
  110. package/dist/services/task/constants.js +22 -2
  111. package/dist/services/task/constants.js.map +1 -1
  112. package/dist/services/task/contact.js +29 -0
  113. package/dist/services/task/contact.js.map +1 -1
  114. package/dist/services/task/dialer.js +78 -0
  115. package/dist/services/task/dialer.js.map +1 -1
  116. package/dist/services/task/digital/Digital.js +78 -0
  117. package/dist/services/task/digital/Digital.js.map +1 -0
  118. package/dist/services/task/state-machine/TaskStateMachine.js +982 -0
  119. package/dist/services/task/state-machine/TaskStateMachine.js.map +1 -0
  120. package/dist/services/task/state-machine/actions.js +572 -0
  121. package/dist/services/task/state-machine/actions.js.map +1 -0
  122. package/dist/services/task/state-machine/constants.js +161 -0
  123. package/dist/services/task/state-machine/constants.js.map +1 -0
  124. package/dist/services/task/state-machine/guards.js +379 -0
  125. package/dist/services/task/state-machine/guards.js.map +1 -0
  126. package/dist/services/task/state-machine/index.js +53 -0
  127. package/dist/services/task/state-machine/index.js.map +1 -0
  128. package/dist/services/task/state-machine/types.js +54 -0
  129. package/dist/services/task/state-machine/types.js.map +1 -0
  130. package/dist/services/task/state-machine/uiControlsComputer.js +703 -0
  131. package/dist/services/task/state-machine/uiControlsComputer.js.map +1 -0
  132. package/dist/services/task/taskDataNormalizer.js +99 -0
  133. package/dist/services/task/taskDataNormalizer.js.map +1 -0
  134. package/dist/services/task/types.js +259 -5
  135. package/dist/services/task/types.js.map +1 -1
  136. package/dist/services/task/voice/Voice.js +1504 -0
  137. package/dist/services/task/voice/Voice.js.map +1 -0
  138. package/dist/services/task/voice/WebRTC.js +152 -0
  139. package/dist/services/task/voice/WebRTC.js.map +1 -0
  140. package/dist/services/task/voice/wxAppOfferObservability.js +145 -0
  141. package/dist/services/task/voice/wxAppOfferObservability.js.map +1 -0
  142. package/dist/services/task/voice/wxAppVoiceMethods.js +395 -0
  143. package/dist/services/task/voice/wxAppVoiceMethods.js.map +1 -0
  144. package/dist/services/wxAppDiagnosticLogging.js +159 -0
  145. package/dist/services/wxAppDiagnosticLogging.js.map +1 -0
  146. package/dist/services/wxAppTelephonyUtils.js +19 -0
  147. package/dist/services/wxAppTelephonyUtils.js.map +1 -0
  148. package/dist/types/cc.d.ts +222 -10
  149. package/dist/types/config.d.ts +13 -0
  150. package/dist/types/constants.d.ts +40 -1
  151. package/dist/types/index.d.ts +58 -22
  152. package/dist/types/metrics/MetricsManager.d.ts +6 -0
  153. package/dist/types/metrics/constants.d.ts +52 -1
  154. package/dist/types/services/AddressBook.d.ts +2 -1
  155. package/dist/types/services/AnswerCallOnWebexService.d.ts +38 -0
  156. package/dist/types/services/ApiAiAssistant.d.ts +67 -5
  157. package/dist/types/services/EntryPoint.d.ts +7 -5
  158. package/dist/types/services/Queue.d.ts +5 -3
  159. package/dist/types/services/UserPreference.d.ts +118 -0
  160. package/dist/types/services/WebexCrossClientService.d.ts +32 -0
  161. package/dist/types/services/WxAppTelephonyMercurySync.d.ts +28 -0
  162. package/dist/types/services/config/Util.d.ts +4 -8
  163. package/dist/types/services/config/constants.d.ts +49 -76
  164. package/dist/types/services/config/index.d.ts +16 -64
  165. package/dist/types/services/config/types.d.ts +252 -114
  166. package/dist/types/services/constants.d.ts +16 -0
  167. package/dist/types/services/core/Err.d.ts +6 -0
  168. package/dist/types/services/core/Utils.d.ts +43 -13
  169. package/dist/types/services/core/WebexRequest.d.ts +1 -0
  170. package/dist/types/services/core/constants.d.ts +7 -0
  171. package/dist/types/services/core/types.d.ts +2 -0
  172. package/dist/types/services/core/websocket/WebSocketManager.d.ts +2 -0
  173. package/dist/types/services/core/websocket/types.d.ts +1 -1
  174. package/dist/types/services/index.d.ts +2 -0
  175. package/dist/types/services/task/Task.d.ts +186 -0
  176. package/dist/types/services/task/TaskFactory.d.ts +14 -0
  177. package/dist/types/services/task/TaskUtils.d.ts +54 -2
  178. package/dist/types/services/task/WebexCallingUtils.d.ts +11 -0
  179. package/dist/types/services/task/constants.d.ts +20 -0
  180. package/dist/types/services/task/contact.d.ts +4 -0
  181. package/dist/types/services/task/dialer.d.ts +30 -0
  182. package/dist/types/services/task/digital/Digital.d.ts +23 -0
  183. package/dist/types/services/task/state-machine/TaskStateMachine.d.ts +1442 -0
  184. package/dist/types/services/task/state-machine/actions.d.ts +10 -0
  185. package/dist/types/services/task/state-machine/constants.d.ts +107 -0
  186. package/dist/types/services/task/state-machine/guards.d.ts +103 -0
  187. package/dist/types/services/task/state-machine/index.d.ts +13 -0
  188. package/dist/types/services/task/state-machine/types.d.ts +277 -0
  189. package/dist/types/services/task/state-machine/uiControlsComputer.d.ts +9 -0
  190. package/dist/types/services/task/taskDataNormalizer.d.ts +10 -0
  191. package/dist/types/services/task/types.d.ts +790 -66
  192. package/dist/types/services/task/voice/Voice.d.ts +241 -0
  193. package/dist/types/services/task/voice/WebRTC.d.ts +54 -0
  194. package/dist/types/services/task/voice/wxAppOfferObservability.d.ts +39 -0
  195. package/dist/types/services/task/voice/wxAppVoiceMethods.d.ts +68 -0
  196. package/dist/types/services/wxAppDiagnosticLogging.d.ts +63 -0
  197. package/dist/types/services/wxAppTelephonyUtils.d.ts +5 -0
  198. package/dist/types/types.d.ts +258 -11
  199. package/dist/types/utils/PageCache.d.ts +20 -3
  200. package/dist/types/webex.d.ts +1 -0
  201. package/dist/types.js +204 -6
  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 +22 -2
  206. package/dist/webex.js.map +1 -1
  207. package/package.json +16 -12
  208. package/src/cc.ts +1439 -105
  209. package/src/config.ts +13 -0
  210. package/src/constants.ts +53 -1
  211. package/src/index.ts +72 -16
  212. package/src/metrics/MetricsManager.ts +16 -0
  213. package/src/metrics/ai-docs/AGENTS.md +350 -0
  214. package/src/metrics/ai-docs/ARCHITECTURE.md +338 -0
  215. package/src/metrics/ai-docs/metrics-spec.md +971 -0
  216. package/src/metrics/behavioral-events.ts +218 -0
  217. package/src/metrics/constants.ts +63 -4
  218. package/src/services/AddressBook.ts +17 -6
  219. package/src/services/AnswerCallOnWebexService.ts +239 -0
  220. package/src/services/ApiAiAssistant.ts +494 -15
  221. package/src/services/EntryPoint.ts +59 -60
  222. package/src/services/Queue.ts +29 -12
  223. package/src/services/UserPreference.ts +509 -0
  224. package/src/services/WebCallingService.ts +362 -40
  225. package/src/services/WebexCrossClientService.ts +298 -0
  226. package/src/services/WxAppTelephonyMercurySync.ts +142 -0
  227. package/src/services/agent/ai-docs/AGENTS.md +240 -0
  228. package/src/services/agent/ai-docs/ARCHITECTURE.md +304 -0
  229. package/src/services/agent/ai-docs/agent-spec.md +505 -0
  230. package/src/services/ai-docs/AGENTS.md +386 -0
  231. package/src/services/ai-docs/services-spec.md +512 -0
  232. package/src/services/config/Util.ts +54 -84
  233. package/src/services/config/ai-docs/AGENTS.md +250 -0
  234. package/src/services/config/ai-docs/ARCHITECTURE.md +413 -0
  235. package/src/services/config/ai-docs/config-spec.md +669 -0
  236. package/src/services/config/constants.ts +64 -86
  237. package/src/services/config/index.ts +116 -277
  238. package/src/services/config/types.ts +238 -125
  239. package/src/services/constants.ts +18 -0
  240. package/src/services/core/Err.ts +3 -0
  241. package/src/services/core/Utils.ts +151 -37
  242. package/src/services/core/WebexRequest.ts +3 -1
  243. package/src/services/core/ai-docs/AGENTS.md +381 -0
  244. package/src/services/core/ai-docs/ARCHITECTURE.md +698 -0
  245. package/src/services/core/ai-docs/core-spec.md +797 -0
  246. package/src/services/core/aqm-reqs.ts +18 -12
  247. package/src/services/core/constants.ts +8 -0
  248. package/src/services/core/types.ts +33 -1
  249. package/src/services/core/websocket/WebSocketManager.ts +37 -8
  250. package/src/services/core/websocket/connection-service.ts +5 -1
  251. package/src/services/core/websocket/types.ts +1 -1
  252. package/src/services/index.ts +4 -0
  253. package/src/services/task/Task.ts +1211 -0
  254. package/src/services/task/TaskFactory.ts +82 -0
  255. package/src/services/task/TaskManager.ts +1551 -584
  256. package/src/services/task/TaskUtils.ts +316 -25
  257. package/src/services/task/WebexCallingUtils.ts +136 -0
  258. package/src/services/task/ai-docs/AGENTS.md +457 -0
  259. package/src/services/task/ai-docs/ARCHITECTURE.md +595 -0
  260. package/src/services/task/ai-docs/task-spec.md +1501 -0
  261. package/src/services/task/constants.ts +21 -0
  262. package/src/services/task/contact.ts +30 -0
  263. package/src/services/task/dialer.ts +80 -0
  264. package/src/services/task/digital/Digital.ts +102 -0
  265. package/src/services/task/state-machine/TaskStateMachine.ts +1320 -0
  266. package/src/services/task/state-machine/actions.ts +741 -0
  267. package/src/services/task/state-machine/ai-docs/AGENTS.md +460 -0
  268. package/src/services/task/state-machine/ai-docs/ARCHITECTURE.md +1156 -0
  269. package/src/services/task/state-machine/ai-docs/task-state-machine-spec.md +2247 -0
  270. package/src/services/task/state-machine/constants.ts +172 -0
  271. package/src/services/task/state-machine/guards.ts +442 -0
  272. package/src/services/task/state-machine/index.ts +28 -0
  273. package/src/services/task/state-machine/types.ts +258 -0
  274. package/src/services/task/state-machine/uiControlsComputer.ts +1135 -0
  275. package/src/services/task/taskDataNormalizer.ts +137 -0
  276. package/src/services/task/types.ts +974 -70
  277. package/src/services/task/voice/Voice.ts +1878 -0
  278. package/src/services/task/voice/WebRTC.ts +194 -0
  279. package/src/services/task/voice/wxAppOfferObservability.ts +204 -0
  280. package/src/services/task/voice/wxAppVoiceMethods.ts +575 -0
  281. package/src/services/wxAppDiagnosticLogging.ts +286 -0
  282. package/src/services/wxAppTelephonyUtils.ts +14 -0
  283. package/src/types.ts +323 -13
  284. package/src/utils/AGENTS.md +289 -0
  285. package/src/utils/PageCache.ts +38 -5
  286. package/src/utils/ai-docs/utils-spec.md +391 -0
  287. package/src/webex.js +10 -0
  288. package/test/unit/fixtures/aiSummaryTestUtils.ts +40 -0
  289. package/test/unit/spec/cc.ts +4046 -181
  290. package/test/unit/spec/index.ts +891 -0
  291. package/test/unit/spec/logger-proxy.ts +70 -0
  292. package/test/unit/spec/metrics/MetricsManager.ts +25 -0
  293. package/test/unit/spec/metrics/behavioral-events.ts +60 -0
  294. package/test/unit/spec/services/AddressBook.ts +37 -6
  295. package/test/unit/spec/services/AnswerCallOnWebexService.ts +264 -0
  296. package/test/unit/spec/services/ApiAiAssistant.ts +442 -23
  297. package/test/unit/spec/services/EntryPoint.ts +87 -40
  298. package/test/unit/spec/services/Queue.ts +123 -12
  299. package/test/unit/spec/services/UserPreference.ts +401 -0
  300. package/test/unit/spec/services/WebCallingService.ts +484 -49
  301. package/test/unit/spec/services/WebexCrossClientService.ts +509 -0
  302. package/test/unit/spec/services/WxAppTelephonyMercurySync.ts +136 -0
  303. package/test/unit/spec/services/config/Util.ts +501 -0
  304. package/test/unit/spec/services/config/index.ts +318 -548
  305. package/test/unit/spec/services/core/Utils.ts +447 -8
  306. package/test/unit/spec/services/core/WebexRequest.ts +8 -7
  307. package/test/unit/spec/services/core/aqm-reqs.ts +142 -1
  308. package/test/unit/spec/services/core/websocket/WebSocketManager.ts +132 -56
  309. package/test/unit/spec/services/core/websocket/connection-service.ts +3 -1
  310. package/test/unit/spec/services/task/AutoWrapup.ts +63 -0
  311. package/test/unit/spec/services/task/Task.ts +2723 -0
  312. package/test/unit/spec/services/task/TaskFactory.ts +116 -0
  313. package/test/unit/spec/services/task/TaskManager.ts +4800 -1586
  314. package/test/unit/spec/services/task/TaskUtils.ts +307 -0
  315. package/test/unit/spec/services/task/WebexCallingUtils.ts +153 -0
  316. package/test/unit/spec/services/task/contact.ts +33 -0
  317. package/test/unit/spec/services/task/dialer.ts +190 -0
  318. package/test/unit/spec/services/task/digital/Digital.ts +105 -0
  319. package/test/unit/spec/services/task/state-machine/TaskStateMachine.ts +4060 -0
  320. package/test/unit/spec/services/task/state-machine/guards.ts +839 -0
  321. package/test/unit/spec/services/task/state-machine/types.ts +18 -0
  322. package/test/unit/spec/services/task/state-machine/uiControlsComputer.ts +3101 -0
  323. package/test/unit/spec/services/task/taskTestUtils.ts +87 -0
  324. package/test/unit/spec/services/task/voice/Voice.ts +2355 -0
  325. package/test/unit/spec/services/task/voice/WebRTC.ts +235 -0
  326. package/test/unit/spec/services/task/voice/wxAppOfferObservability.ts +361 -0
  327. package/test/unit/spec/services/task/voice/wxAppVoiceMethods.ts +719 -0
  328. package/test/unit/spec/services/wxAppDiagnosticLogging.ts +179 -0
  329. package/test/unit/spec/wellnessSampleUtils.ts +288 -0
  330. package/typedoc.md +1 -1
  331. package/umd/contact-center.min.js +2 -2
  332. package/umd/contact-center.min.js.map +1 -1
  333. package/dist/services/task/index.js +0 -1525
  334. package/dist/services/task/index.js.map +0 -1
  335. package/dist/types/services/task/index.d.ts +0 -650
  336. package/src/services/task/index.ts +0 -1801
  337. package/test/unit/spec/services/task/index.ts +0 -2184
package/src/cc.ts CHANGED
@@ -25,6 +25,12 @@ import {
25
25
  UploadLogsResponse,
26
26
  UpdateDeviceTypeResponse,
27
27
  GenericError,
28
+ ConfigFlags,
29
+ WellnessBreakEvent,
30
+ WellnessBreakNotificationAction,
31
+ WELLNESS_BREAK_NOTIFICATION_ACTIONS,
32
+ VoiceConnectionState,
33
+ VOICE_CONNECTION_ERROR,
28
34
  } from './types';
29
35
  import {
30
36
  READY,
@@ -37,24 +43,32 @@ import {
37
43
  UNKNOWN_ERROR,
38
44
  MERCURY_DISCONNECTED_SUCCESS,
39
45
  METHODS,
46
+ WELLNESS_BREAK_HANDLER,
47
+ DEFAULT_VOICE_CONNECTION_STATE,
40
48
  } from './constants';
41
49
  import {AGENT_STATE_AVAILABLE, AGENT_STATE_AVAILABLE_ID} from './services/config/constants';
42
- import {AGENT, WEB_RTC_PREFIX} from './services/constants';
50
+ import {AGENT, RTD_SUBSCRIBE_API, SUBSCRIBE_API, WEB_RTC_PREFIX} from './services/constants';
43
51
  import Services from './services';
44
52
  import WebexRequest from './services/core/WebexRequest';
45
53
  import LoggerProxy from './logger-proxy';
46
54
  import {StateChange, Logout, StateChangeSuccess, AGENT_EVENTS} from './services/agent/types';
47
- import {getErrorDetails, isValidDialNumber} from './services/core/Utils';
55
+ import {getErrorDetails, isRecord, isValidDialNumber} from './services/core/Utils';
48
56
  import {
49
57
  Profile,
50
58
  WelcomeEvent,
51
59
  CC_EVENTS,
60
+ VOICE_CONNECTION_EVENTS,
52
61
  OutdialAniEntriesResponse,
53
62
  OutdialAniParams,
63
+ Entity,
54
64
  } from './services/config/types';
55
65
  import {ConnectionLostDetails} from './services/core/websocket/types';
56
66
  import TaskManager from './services/task/TaskManager';
57
67
  import WebCallingService from './services/WebCallingService';
68
+ import AnswerCallOnWebexService from './services/AnswerCallOnWebexService';
69
+ import WebexCrossClientService from './services/WebexCrossClientService';
70
+ import WxAppTelephonyMercurySync from './services/WxAppTelephonyMercurySync';
71
+ import {logWxAppSessionReadiness} from './services/wxAppDiagnosticLogging';
58
72
  import {
59
73
  ITask,
60
74
  TASK_EVENTS,
@@ -69,6 +83,7 @@ import {EntryPoint} from './services/EntryPoint';
69
83
  import {AddressBook} from './services/AddressBook';
70
84
  import {Queue} from './services/Queue';
71
85
  import {ApiAIAssistant} from './services/ApiAiAssistant';
86
+ import {UserPreference} from './services/UserPreference';
72
87
  import type {
73
88
  EntryPointListResponse,
74
89
  EntryPointSearchParams,
@@ -76,6 +91,13 @@ import type {
76
91
  ContactServiceQueueSearchParams,
77
92
  } from './types';
78
93
 
94
+ /**
95
+ * Typed allow-list of server-controlled websocket event names this SDK re-emits verbatim.
96
+ * Guards against emitting an arbitrary/unknown `data.type` supplied by the websocket payload.
97
+ * @ignore
98
+ */
99
+ const CC_EVENT_ALLOW_LIST = new Set<string>(Object.values(CC_EVENTS));
100
+
79
101
  /**
80
102
  * The main Contact Center plugin class that enables integration with Webex Contact Center.
81
103
  *
@@ -159,7 +181,7 @@ import type {
159
181
  *
160
182
  * // Login with browser-based calling
161
183
  * await cc.stationLogin({
162
- * teamId: profile.teams[0].teamId,
184
+ * teamId: profile.teams[0].id,
163
185
  * loginOption: 'BROWSER'
164
186
  * });
165
187
  *
@@ -230,6 +252,34 @@ export default class ContactCenter extends WebexPlugin implements IContactCenter
230
252
  */
231
253
  private webCallingService: WebCallingService;
232
254
 
255
+ /**
256
+ * REST telephony for wxApp thick-client answer (WXCC-6026)
257
+ * @private
258
+ */
259
+ private answerCallOnWebexService: AnswerCallOnWebexService;
260
+
261
+ /**
262
+ * usersub cross-client state for Webex App toast suppression
263
+ * @private
264
+ */
265
+ private webexCrossClientService: WebexCrossClientService;
266
+
267
+ /**
268
+ * Mercury telephony mute sync for wxApp thick-client answer
269
+ * @private
270
+ */
271
+ private wxAppTelephonyMercurySync: WxAppTelephonyMercurySync;
272
+
273
+ /** True when wxApp mute sync opened Mercury (Extension/DN-only profiles). */
274
+ private wxAppMercuryConnectedByCc = false;
275
+
276
+ /** True when wxApp mute sync registered the Webex device. */
277
+ private wxAppDeviceRegisteredByCc = false;
278
+
279
+ private static readonly WXAPP_FALSE_PUBLISH_RETRY_DELAY_MS = 30_000;
280
+ private static readonly WXAPP_FALSE_PUBLISH_MAX_RETRIES = 3;
281
+ private wxAppFalsePublishRetryTimer?: ReturnType<typeof setTimeout>;
282
+
233
283
  /**
234
284
  * Core service managers for Contact Center operations
235
285
  * Includes agent, connection, and configuration services
@@ -262,6 +312,19 @@ export default class ContactCenter extends WebexPlugin implements IContactCenter
262
312
  */
263
313
  private metricsManager: MetricsManager;
264
314
 
315
+ /** Current login/relogin session used for agent-scoped wellness validation. */
316
+ private currentAgentSessionId?: string;
317
+
318
+ /** Registered-session cache for the system WellbeingBreak idle code. */
319
+ private wellbeingBreakIdleCode?: Entity;
320
+
321
+ /** Registration generation that owns the wellness idle-code cache and in-flight lookups. */
322
+ private wellnessRegistrationGeneration = 0;
323
+
324
+ private updateWellnessSession(agentSessionId?: string): void {
325
+ this.currentAgentSessionId = agentSessionId;
326
+ }
327
+
265
328
  /**
266
329
  * API instance for managing Webex Contact Center entry points
267
330
  * Provides functionality to fetch entry points with caching support
@@ -325,7 +388,38 @@ export default class ContactCenter extends WebexPlugin implements IContactCenter
325
388
  * });
326
389
  * ```
327
390
  */
328
- private queue: Queue;
391
+ public queue: Queue;
392
+
393
+ /**
394
+ * API instance for managing Webex Contact Center user preferences
395
+ * Provides functionality to get, create, update, and delete user preferences
396
+ * @type {UserPreference}
397
+ * @public
398
+ * @example
399
+ * ```typescript
400
+ * const cc = webex.cc;
401
+ * await cc.register();
402
+ * await cc.stationLogin({ teamId: 'team123', loginOption: 'BROWSER' });
403
+ *
404
+ * // Get user preferences for current user
405
+ * const preferences = await cc.userPreference.getUserPreference();
406
+ *
407
+ * // Create new user preferences
408
+ * const newPrefs = await cc.userPreference.createUserPreference({
409
+ * userId: 'user123',
410
+ * preferences: { e911Reminder: true }
411
+ * });
412
+ *
413
+ * // Update user preferences
414
+ * const updatedPrefs = await cc.userPreference.updateUserPreference('user123', {
415
+ * preferences: { e911Reminder: false }
416
+ * });
417
+ *
418
+ * // Delete user preferences
419
+ * await cc.userPreference.deleteUserPreference('user123');
420
+ * ```
421
+ */
422
+ public userPreference: UserPreference;
329
423
 
330
424
  /**
331
425
  * API instance for AI Assistant operations such as transcript controls.
@@ -357,6 +451,7 @@ export default class ContactCenter extends WebexPlugin implements IContactCenter
357
451
  this.$webex.once(READY, () => {
358
452
  // @ts-ignore
359
453
  this.$config = this.config;
454
+ this.validatePluginConfig();
360
455
 
361
456
  /**
362
457
  * This is used for handling the async requests by sending webex.request and wait for corresponding websocket event.
@@ -369,17 +464,29 @@ export default class ContactCenter extends WebexPlugin implements IContactCenter
369
464
  webex: this.$webex,
370
465
  connectionConfig: this.getConnectionConfig(),
371
466
  });
372
- this.services.webSocketManager.on('message', this.handleWebsocketMessage);
373
467
 
374
468
  this.webCallingService = new WebCallingService(this.$webex);
375
- this.apiAIAssistant = new ApiAIAssistant(this.$webex);
469
+ this.webCallingService.on(
470
+ VOICE_CONNECTION_EVENTS.STATE_CHANGE,
471
+ this.handleVoiceConnectionStateChange
472
+ );
473
+ this.answerCallOnWebexService = new AnswerCallOnWebexService(this.$webex);
474
+ this.webexCrossClientService = new WebexCrossClientService(this.$webex);
475
+ this.wxAppTelephonyMercurySync = new WxAppTelephonyMercurySync(this.$webex);
476
+ this.apiAIAssistant = new ApiAIAssistant(this.$webex, () => ({
477
+ isWellnessBreakEnabled: this.agentConfig?.isWellnessBreakEnabled === true,
478
+ agentId: this.agentConfig?.agentId,
479
+ agentSessionId: this.currentAgentSessionId,
480
+ }));
376
481
  this.metricsManager = MetricsManager.getInstance({webex: this.$webex});
377
482
  this.taskManager = TaskManager.getTaskManager(
378
483
  this.apiAIAssistant,
379
484
  this.services.contact,
380
485
  this.webCallingService,
381
- this.services.webSocketManager
486
+ this.services.webSocketManager,
487
+ this.services.rtdWebSocketManager
382
488
  );
489
+ this.taskManager.setAnswerCallOnWebexService(this.answerCallOnWebexService);
383
490
  this.incomingTaskListener();
384
491
 
385
492
  // Initialize API instances
@@ -387,6 +494,7 @@ export default class ContactCenter extends WebexPlugin implements IContactCenter
387
494
  this.entryPoint = new EntryPoint(this.$webex);
388
495
  this.addressBook = new AddressBook(this.$webex, () => this.agentConfig?.addressBookId);
389
496
  this.queue = new Queue(this.$webex);
497
+ this.userPreference = new UserPreference(this.$webex, () => this.agentConfig?.agentId);
390
498
  LoggerProxy.initialize(this.$webex.logger);
391
499
  });
392
500
  }
@@ -401,6 +509,12 @@ export default class ContactCenter extends WebexPlugin implements IContactCenter
401
509
  this.trigger(TASK_EVENTS.TASK_INCOMING, task);
402
510
  };
403
511
 
512
+ private handleVoiceConnectionStateChange = (state: VoiceConnectionState): void => {
513
+ // WebexPlugin exposes `trigger` at runtime, though it is missing from its TypeScript types.
514
+ // @ts-ignore
515
+ this.trigger(VOICE_CONNECTION_EVENTS.STATE_CHANGE, state);
516
+ };
517
+
404
518
  /**
405
519
  * Handles task hydration events for updating task data
406
520
  * @private
@@ -411,6 +525,16 @@ export default class ContactCenter extends WebexPlugin implements IContactCenter
411
525
  this.trigger(TASK_EVENTS.TASK_HYDRATE, task);
412
526
  };
413
527
 
528
+ /**
529
+ * Handles multi-login hydrate events for SDK instances without Mobius registration
530
+ * @private
531
+ * @param {ITask} task The task object associated with the multi-login hydrate
532
+ */
533
+ private handleTaskMultiLoginHydrate = (task: ITask) => {
534
+ // @ts-ignore
535
+ this.trigger(TASK_EVENTS.TASK_MULTI_LOGIN_HYDRATE, task);
536
+ };
537
+
414
538
  /**
415
539
  * Handles task merged events when tasks are combined eg: EPDN merge/transfer
416
540
  * @private
@@ -431,6 +555,129 @@ export default class ContactCenter extends WebexPlugin implements IContactCenter
431
555
  this.trigger(TASK_EVENTS.TASK_CAMPAIGN_PREVIEW_RESERVATION, task);
432
556
  };
433
557
 
558
+ private trackInvalidWellnessEvent(reason: string): void {
559
+ this.metricsManager.trackEvent(
560
+ METRIC_EVENT_NAMES.AI_ASSISTANT_WELLNESS_EVENT_INVALID,
561
+ {reason},
562
+ ['operational']
563
+ );
564
+ }
565
+
566
+ private normalizeWellnessBreakEvent(payload: Record<string, unknown>): WellnessBreakEvent | null {
567
+ if (this.agentConfig?.isWellnessBreakEnabled !== true) {
568
+ this.trackInvalidWellnessEvent('wellness_disabled');
569
+
570
+ return null;
571
+ }
572
+
573
+ const notificationData = isRecord(payload.data) ? payload.data : null;
574
+ const notificationDetails =
575
+ notificationData && isRecord(notificationData.notifDetails)
576
+ ? notificationData.notifDetails
577
+ : null;
578
+ const sessionData =
579
+ notificationData && isRecord(notificationData.data) ? notificationData.data : null;
580
+ const actionEvent = notificationDetails?.actionEvent;
581
+
582
+ if (
583
+ payload.type !== WELLNESS_BREAK_HANDLER ||
584
+ notificationData?.notifType !== WELLNESS_BREAK_HANDLER ||
585
+ typeof actionEvent !== 'string'
586
+ ) {
587
+ this.trackInvalidWellnessEvent('malformed_wellness_event');
588
+
589
+ return null;
590
+ }
591
+
592
+ if (
593
+ !Object.values(WELLNESS_BREAK_NOTIFICATION_ACTIONS).includes(
594
+ actionEvent as WellnessBreakNotificationAction
595
+ )
596
+ ) {
597
+ this.trackInvalidWellnessEvent('unknown_wellness_action');
598
+
599
+ return null;
600
+ }
601
+
602
+ const agentId = notificationData.agentId;
603
+ const eventOrgId = notificationData.orgId;
604
+ const sessionOrgId = sessionData?.orgId;
605
+ const envelopeOrgId = payload.orgId;
606
+ const agentSessionId = sessionData?.agentSessionId;
607
+ const currentOrgId = this.$webex.credentials.getOrgId();
608
+
609
+ if (
610
+ typeof agentId !== 'string' ||
611
+ typeof eventOrgId !== 'string' ||
612
+ typeof sessionOrgId !== 'string' ||
613
+ typeof envelopeOrgId !== 'string' ||
614
+ typeof agentSessionId !== 'string' ||
615
+ !agentId ||
616
+ !eventOrgId ||
617
+ !sessionOrgId ||
618
+ !envelopeOrgId ||
619
+ !agentSessionId
620
+ ) {
621
+ this.trackInvalidWellnessEvent('missing_wellness_identity');
622
+
623
+ return null;
624
+ }
625
+
626
+ if (
627
+ agentId !== this.agentConfig?.agentId ||
628
+ eventOrgId !== currentOrgId ||
629
+ sessionOrgId !== currentOrgId ||
630
+ envelopeOrgId !== currentOrgId
631
+ ) {
632
+ this.trackInvalidWellnessEvent('mismatched_wellness_identity');
633
+
634
+ return null;
635
+ }
636
+
637
+ const interactionValue = sessionData.interactionId ?? sessionData.InteractionId;
638
+ const actionText = notificationDetails.actionText;
639
+ const trackingId = payload.trackingId;
640
+
641
+ return {
642
+ agentId,
643
+ orgId: currentOrgId,
644
+ agentSessionId,
645
+ actionEvent: actionEvent as WellnessBreakNotificationAction,
646
+ ...(typeof actionText === 'string' ? {actionText} : {}),
647
+ ...(typeof interactionValue === 'string' ? {interactionId: interactionValue} : {}),
648
+ ...(typeof trackingId === 'string' ? {trackingId} : {}),
649
+ };
650
+ }
651
+
652
+ private handleWellnessBreakWebsocketPayload(payload: Record<string, unknown>): boolean {
653
+ if (payload.type !== WELLNESS_BREAK_HANDLER) {
654
+ return false;
655
+ }
656
+
657
+ const wellnessEvent = this.normalizeWellnessBreakEvent(payload);
658
+ if (wellnessEvent) {
659
+ // @ts-ignore - WebexPlugin emit is available at runtime but absent from its declaration.
660
+ this.emit(CC_EVENTS.WELLNESS_BREAK, wellnessEvent);
661
+ }
662
+
663
+ return true;
664
+ }
665
+
666
+ private handleRTDWebsocketMessage = (event: string) => {
667
+ let payload: unknown;
668
+ try {
669
+ payload = JSON.parse(event);
670
+ } catch {
671
+ // TaskManager retains its existing malformed RTD message handling.
672
+ }
673
+
674
+ if (isRecord(payload) && this.handleWellnessBreakWebsocketPayload(payload)) {
675
+ return;
676
+ }
677
+
678
+ this.taskManager.handleRealtimeWebsocketEvent(event);
679
+ };
680
+
434
681
  /**
435
682
  * Sets up event listeners for incoming tasks and task hydration
436
683
  * Subscribes to task events from the task manager
@@ -439,6 +686,7 @@ export default class ContactCenter extends WebexPlugin implements IContactCenter
439
686
  private incomingTaskListener() {
440
687
  this.taskManager.on(TASK_EVENTS.TASK_INCOMING, this.handleIncomingTask);
441
688
  this.taskManager.on(TASK_EVENTS.TASK_HYDRATE, this.handleTaskHydrate);
689
+ this.taskManager.on(TASK_EVENTS.TASK_MULTI_LOGIN_HYDRATE, this.handleTaskMultiLoginHydrate);
442
690
  this.taskManager.on(TASK_EVENTS.TASK_MERGED, this.handleTaskMerged);
443
691
  this.taskManager.on(
444
692
  TASK_EVENTS.TASK_CAMPAIGN_PREVIEW_RESERVATION,
@@ -474,16 +722,18 @@ export default class ContactCenter extends WebexPlugin implements IContactCenter
474
722
  *
475
723
  * console.log('Agent ID:', profile.agentId);
476
724
  * console.log('Default DN:', profile.defaultDn);
477
- * console.log('Teams:', profile.teams.map(t => t.teamId));
725
+ * console.log('Teams:', profile.teams.map(t => t.id));
478
726
  * console.log('WebRTC Enabled:', profile.webRtcEnabled);
479
727
  * console.log('Supported Login Options:', profile.loginVoiceOptions);
480
728
  *
481
729
  * // Now you can proceed with station login, state changes, etc.
482
- * await cc.stationLogin({ teamId: profile.teams[0].teamId, loginOption: 'BROWSER' });
730
+ * await cc.stationLogin({ teamId: profile.teams[0].id, loginOption: 'BROWSER' });
483
731
  * ```
484
732
  */
485
733
  public async register(): Promise<Profile> {
486
- LoggerProxy.info('Starting CC SDK registration', {
734
+ this.wellnessRegistrationGeneration += 1;
735
+ this.wellbeingBreakIdleCode = undefined;
736
+ LoggerProxy.log('Starting CC SDK registration', {
487
737
  module: CC_FILE,
488
738
  method: METHODS.REGISTER,
489
739
  });
@@ -493,6 +743,7 @@ export default class ContactCenter extends WebexPlugin implements IContactCenter
493
743
  METRIC_EVENT_NAMES.WEBSOCKET_REGISTER_FAILED,
494
744
  ]);
495
745
  this.setupEventListeners();
746
+ this.services.webSocketManager.on('message', this.handleWebsocketMessage);
496
747
 
497
748
  const resp = await this.connectWebsocket();
498
749
  // Ensure 'dn' is always populated from 'defaultDn'
@@ -511,7 +762,12 @@ export default class ContactCenter extends WebexPlugin implements IContactCenter
511
762
  method: METHODS.REGISTER,
512
763
  });
513
764
 
514
- return resp;
765
+ // Registration can silently restore a station session without emitting a
766
+ // relogin event. Project the active session for consumers that must
767
+ // recover session-scoped state after a page refresh.
768
+ return resp.isAgentLoggedIn && this.currentAgentSessionId
769
+ ? {...resp, agentSessionId: this.currentAgentSessionId}
770
+ : resp;
515
771
  } catch (error) {
516
772
  this.metricsManager.trackEvent(
517
773
  METRIC_EVENT_NAMES.WEBSOCKET_REGISTER_FAILED,
@@ -564,14 +820,19 @@ export default class ContactCenter extends WebexPlugin implements IContactCenter
564
820
 
565
821
  */
566
822
  public async deregister(): Promise<void> {
823
+ this.wellnessRegistrationGeneration += 1;
824
+ this.wellbeingBreakIdleCode = undefined;
825
+ this.updateWellnessSession();
567
826
  try {
568
827
  this.metricsManager.timeEvent([
569
828
  METRIC_EVENT_NAMES.WEBSOCKET_DEREGISTER_SUCCESS,
570
829
  METRIC_EVENT_NAMES.WEBSOCKET_DEREGISTER_FAIL,
571
830
  ]);
572
831
 
832
+ this.taskManager.clearAISummaryState();
573
833
  this.taskManager.off(TASK_EVENTS.TASK_INCOMING, this.handleIncomingTask);
574
834
  this.taskManager.off(TASK_EVENTS.TASK_HYDRATE, this.handleTaskHydrate);
835
+ this.taskManager.off(TASK_EVENTS.TASK_MULTI_LOGIN_HYDRATE, this.handleTaskMultiLoginHydrate);
575
836
  this.taskManager.off(
576
837
  TASK_EVENTS.TASK_CAMPAIGN_PREVIEW_RESERVATION,
577
838
  this.handleCampaignPreviewReservation
@@ -579,8 +840,13 @@ export default class ContactCenter extends WebexPlugin implements IContactCenter
579
840
  this.taskManager.unregisterIncomingCallEvent();
580
841
 
581
842
  this.services.webSocketManager.off('message', this.handleWebsocketMessage);
843
+ this.services.rtdWebSocketManager.off('message', this.handleRTDWebsocketMessage);
582
844
  this.services.connectionService.off('connectionLost', this.handleConnectionLost);
583
845
 
846
+ const {publishError: wxAppPublishError} = await this.teardownWxAppLocalState({
847
+ clearInitFlag: true,
848
+ });
849
+
584
850
  if (
585
851
  this.agentConfig.webRtcEnabled &&
586
852
  this.agentConfig.loginVoiceOptions.includes(LoginOption.BROWSER)
@@ -601,9 +867,22 @@ export default class ContactCenter extends WebexPlugin implements IContactCenter
601
867
  if (!this.services.webSocketManager.isSocketClosed) {
602
868
  this.services.webSocketManager.close(false, 'Unregistering the SDK');
603
869
  }
870
+ if (this.services.rtdWebSocketManager && !this.services.rtdWebSocketManager.isSocketClosed) {
871
+ this.services.rtdWebSocketManager.close(false, 'Unregistering the SDK');
872
+ }
873
+
874
+ if (this.services.rtdWebSocketManager && !this.services.rtdWebSocketManager.isSocketClosed) {
875
+ this.services.rtdWebSocketManager.close(false, 'Unregistering the RTD websocket');
876
+ }
604
877
 
605
878
  // Clear any cached agent configuration
879
+ this.wellbeingBreakIdleCode = undefined;
606
880
  this.agentConfig = null;
881
+ this.updateWellnessSession();
882
+
883
+ if (wxAppPublishError) {
884
+ throw wxAppPublishError;
885
+ }
607
886
 
608
887
  LoggerProxy.log('Deregistered successfully', {
609
888
  module: CC_FILE,
@@ -667,6 +946,9 @@ export default class ContactCenter extends WebexPlugin implements IContactCenter
667
946
  * ```
668
947
  */
669
948
  public async getBuddyAgents(data: BuddyAgents): Promise<BuddyAgentsResponse> {
949
+ const {action, state, mediaType = 'telephony'} = data;
950
+ const buddyAgentState = state ?? (action === 'Transfer' ? AGENT_STATE_AVAILABLE : undefined);
951
+
670
952
  LoggerProxy.info('Fetching buddy agents', {
671
953
  module: CC_FILE,
672
954
  method: METHODS.GET_BUDDY_AGENTS,
@@ -677,15 +959,19 @@ export default class ContactCenter extends WebexPlugin implements IContactCenter
677
959
  METRIC_EVENT_NAMES.FETCH_BUDDY_AGENTS_FAILED,
678
960
  ]);
679
961
  const resp = await this.services.agent.buddyAgents({
680
- data: {agentProfileId: this.agentConfig.agentProfileID, ...data},
962
+ data: {
963
+ agentProfileId: this.agentConfig.agentProfileID,
964
+ mediaType,
965
+ ...(buddyAgentState ? {state: buddyAgentState} : {}),
966
+ },
681
967
  });
682
968
 
683
969
  this.metricsManager.trackEvent(
684
970
  METRIC_EVENT_NAMES.FETCH_BUDDY_AGENTS_SUCCESS,
685
971
  {
686
972
  ...MetricsManager.getCommonTrackingFieldForAQMResponse(resp),
687
- mediaType: data.mediaType,
688
- buddyAgentState: data.state,
973
+ mediaType,
974
+ buddyAgentState,
689
975
  buddyAgentCount: resp.data.agentList.length,
690
976
  },
691
977
  ['operational']
@@ -705,8 +991,8 @@ export default class ContactCenter extends WebexPlugin implements IContactCenter
705
991
  METRIC_EVENT_NAMES.FETCH_BUDDY_AGENTS_FAILED,
706
992
  {
707
993
  ...MetricsManager.getCommonTrackingFieldForAQMResponseFailed(failureResp),
708
- mediaType: data.mediaType,
709
- buddyAgentState: data.state,
994
+ mediaType,
995
+ buddyAgentState,
710
996
  },
711
997
  ['operational']
712
998
  );
@@ -722,7 +1008,7 @@ export default class ContactCenter extends WebexPlugin implements IContactCenter
722
1008
  * @private
723
1009
  */
724
1010
  private async connectWebsocket() {
725
- LoggerProxy.info('Connecting to websocket', {
1011
+ LoggerProxy.log('Connecting to websocket', {
726
1012
  module: CC_FILE,
727
1013
  method: METHODS.CONNECT_WEBSOCKET,
728
1014
  });
@@ -730,6 +1016,7 @@ export default class ContactCenter extends WebexPlugin implements IContactCenter
730
1016
  try {
731
1017
  const data = (await this.services.webSocketManager.initWebSocket({
732
1018
  body: this.getConnectionConfig(),
1019
+ resource: SUBSCRIBE_API,
733
1020
  })) as WelcomeEvent;
734
1021
 
735
1022
  const agentId = data.agentId;
@@ -741,15 +1028,72 @@ export default class ContactCenter extends WebexPlugin implements IContactCenter
741
1028
  method: METHODS.CONNECT_WEBSOCKET,
742
1029
  });
743
1030
 
1031
+ const configFlags: ConfigFlags = {
1032
+ isEndTaskEnabled: this.agentConfig.isEndTaskEnabled,
1033
+ isEndConsultEnabled: this.agentConfig.isEndConsultEnabled,
1034
+ webRtcEnabled: this.agentConfig.webRtcEnabled,
1035
+ autoWrapup: this.agentConfig.wrapUpData?.wrapUpProps?.autoWrapup ?? false,
1036
+ aiFeature: this.agentConfig.aiFeature,
1037
+ consultTransfer: {
1038
+ allowConsultToQueue: this.agentConfig.allowConsultToQueue,
1039
+ accessQueue: this.agentConfig.accessQueue,
1040
+ accessEntryPoint: this.agentConfig.accessEntryPoint,
1041
+ accessBuddyTeam: this.agentConfig.accessBuddyTeam,
1042
+ },
1043
+ enableWxBetterTogether: this.isWxBetterTogetherEnabled(),
1044
+ getWxAppUsersubPublished: () => this.webexCrossClientService.isAnswerCallsStateActive(),
1045
+ };
1046
+ this.taskManager.setConfigFlags(configFlags);
744
1047
  // TODO: Make profile a singleton to make it available throughout app/sdk so we dont need to inject info everywhere
745
1048
  this.taskManager.setWrapupData(this.agentConfig.wrapUpData);
746
1049
  this.taskManager.setAgentId(this.agentConfig.agentId);
1050
+ this.taskManager.setAgentName(this.agentConfig.agentName);
747
1051
  this.taskManager.setWebRtcEnabled(this.agentConfig.webRtcEnabled);
748
1052
  this.apiAIAssistant.setAIFeatureFlags(this.agentConfig.aiFeature);
1053
+ this.wellbeingBreakIdleCode = undefined;
1054
+ this.updateWellnessSession();
749
1055
 
1056
+ /**
1057
+ * RTD websocket currently supports realtime transcripts and suggested responses.
1058
+ * Extend this condition when additional AI RTD features are introduced.
1059
+ * Wellness break notifications also arrive on this websocket.
1060
+ */
750
1061
  if (
751
- this.agentConfig.webRtcEnabled &&
752
- this.agentConfig.loginVoiceOptions.includes(LoginOption.BROWSER)
1062
+ this.agentConfig.aiFeature?.realtimeTranscripts?.enable ||
1063
+ this.agentConfig.aiFeature?.suggestedResponses?.enable ||
1064
+ this.agentConfig.aiFeature?.generatedSummaries?.wrapUpSummariesEnabled === true ||
1065
+ this.agentConfig.aiFeature?.generatedSummaries?.consultTransferSummariesEnabled === true ||
1066
+ this.agentConfig.isWellnessBreakEnabled
1067
+ ) {
1068
+ LoggerProxy.info('Connecting to RTD websocket', {
1069
+ module: CC_FILE,
1070
+ method: METHODS.CONNECT_WEBSOCKET,
1071
+ });
1072
+
1073
+ this.services.rtdWebSocketManager
1074
+ .initWebSocket({
1075
+ body: this.getConnectionConfig(),
1076
+ resource: RTD_SUBSCRIBE_API,
1077
+ })
1078
+ .then(() => {
1079
+ LoggerProxy.log('RTD websocket connected successfully', {
1080
+ module: CC_FILE,
1081
+ method: METHODS.CONNECT_WEBSOCKET,
1082
+ });
1083
+ this.services.rtdWebSocketManager.on('message', this.handleRTDWebsocketMessage);
1084
+ })
1085
+ .catch((error) => {
1086
+ LoggerProxy.error(`Error connecting to RTD websocket ${error}`, {
1087
+ module: CC_FILE,
1088
+ method: METHODS.CONNECT_WEBSOCKET,
1089
+ });
1090
+ });
1091
+ }
1092
+
1093
+ if (
1094
+ this.agentConfig.loginVoiceOptions.some((loginOption) =>
1095
+ this.isBrowserVoiceRequired(loginOption)
1096
+ )
753
1097
  ) {
754
1098
  try {
755
1099
  await this.$webex.internal.mercury.connect();
@@ -763,14 +1107,28 @@ export default class ContactCenter extends WebexPlugin implements IContactCenter
763
1107
  method: METHODS.CONNECT_WEBSOCKET,
764
1108
  });
765
1109
  }
1110
+ } else if (this.isWebRTCRegistrationDisabled()) {
1111
+ LoggerProxy.info(
1112
+ 'Skipping Mobius registration because disableWebRTCRegistration is enabled',
1113
+ {
1114
+ module: CC_FILE,
1115
+ method: METHODS.CONNECT_WEBSOCKET,
1116
+ }
1117
+ );
766
1118
  }
767
1119
 
768
1120
  if (this.$config && this.$config.allowAutomatedRelogin) {
769
1121
  await this.silentRelogin();
1122
+ } else {
1123
+ LoggerProxy.log('Skipping silent relogin: allowAutomatedRelogin is disabled', {
1124
+ module: CC_FILE,
1125
+ method: METHODS.CONNECT_WEBSOCKET,
1126
+ });
770
1127
  }
771
1128
 
772
1129
  return this.agentConfig;
773
1130
  } catch (error) {
1131
+ this.updateWellnessSession();
774
1132
  LoggerProxy.error(`Error during register: ${error}`, {
775
1133
  module: CC_FILE,
776
1134
  method: METHODS.CONNECT_WEBSOCKET,
@@ -809,36 +1167,48 @@ export default class ContactCenter extends WebexPlugin implements IContactCenter
809
1167
  * ```
810
1168
  */
811
1169
  public async stationLogin(data: AgentLogin): Promise<StationLoginResponse> {
812
- LoggerProxy.info('Starting agent station login', {
813
- module: CC_FILE,
814
- method: METHODS.STATION_LOGIN,
815
- });
1170
+ const loggerContext = {module: CC_FILE, method: METHODS.STATION_LOGIN};
1171
+
816
1172
  try {
1173
+ LoggerProxy.log(
1174
+ `Starting agent station login | loginOption: ${data?.loginOption} teamId: ${data?.teamId}`,
1175
+ loggerContext
1176
+ );
817
1177
  this.metricsManager.timeEvent([
818
1178
  METRIC_EVENT_NAMES.STATION_LOGIN_SUCCESS,
819
1179
  METRIC_EVENT_NAMES.STATION_LOGIN_FAILED,
820
1180
  ]);
821
1181
 
822
1182
  const dialPlanEntries = this.agentConfig?.dialPlan?.dialPlanEntity ?? [];
823
- if (
824
- data.loginOption === LoginOption.AGENT_DN &&
825
- !isValidDialNumber(data.dialNumber, dialPlanEntries)
826
- ) {
827
- const error = new Error('INVALID_DIAL_NUMBER');
828
- // @ts-ignore - adding custom key to the error object
829
- error.details = {data: {reason: 'INVALID_DIAL_NUMBER'}} as Failure;
1183
+ if (data.loginOption === LoginOption.AGENT_DN) {
1184
+ LoggerProxy.log(
1185
+ `Validating dial number | dialPlanEnabled: ${!!this.agentConfig
1186
+ ?.dialPlan} | dialPlanEntryCount: ${dialPlanEntries.length}`,
1187
+ loggerContext
1188
+ );
830
1189
 
831
- throw error;
1190
+ if (!isValidDialNumber(data.dialNumber, dialPlanEntries)) {
1191
+ LoggerProxy.log(
1192
+ `Dial number validation failed | dialNumber: ${data.dialNumber} | dialPlanEntryCount: ${dialPlanEntries.length}`,
1193
+ loggerContext
1194
+ );
1195
+ const error = new Error('INVALID_DIAL_NUMBER');
1196
+ // @ts-ignore - adding custom key to the error object
1197
+ error.details = {data: {reason: 'INVALID_DIAL_NUMBER'}} as Failure;
1198
+
1199
+ throw error;
1200
+ }
832
1201
  }
833
1202
 
1203
+ const deviceId = this.getDeviceId(data.loginOption, data.dialNumber);
834
1204
  const loginResponse = await this.services.agent.stationLogin({
835
1205
  data: {
836
- dialNumber:
837
- data.loginOption === LoginOption.BROWSER ? this.agentConfig.agentId : data.dialNumber,
1206
+ // BROWSER DN must be webrtc-{agentId} so VPOP/RTMS do not treat a bare UUID as PSTN.
1207
+ dialNumber: data.loginOption === LoginOption.BROWSER ? deviceId : data.dialNumber,
838
1208
  teamId: data.teamId,
839
1209
  deviceType: data.loginOption,
840
1210
  isExtension: data.loginOption === LoginOption.EXTENSION,
841
- deviceId: this.getDeviceId(data.loginOption, data.dialNumber),
1211
+ deviceId,
842
1212
  roles: [AGENT],
843
1213
  teamName: EMPTY_STRING,
844
1214
  siteId: EMPTY_STRING,
@@ -847,12 +1217,28 @@ export default class ContactCenter extends WebexPlugin implements IContactCenter
847
1217
  },
848
1218
  });
849
1219
 
850
- if (this.agentConfig.webRtcEnabled && data.loginOption === LoginOption.BROWSER) {
1220
+ this.webCallingService.setLoginOption(data.loginOption);
1221
+ this.webCallingService.setBrowserVoiceRequired(this.isBrowserVoiceRequired(data.loginOption));
1222
+
1223
+ if (this.isBrowserVoiceRequired(data.loginOption)) {
851
1224
  await this.webCallingService.registerWebCallingLine();
1225
+ } else if (
1226
+ this.agentConfig.webRtcEnabled &&
1227
+ data.loginOption === LoginOption.BROWSER &&
1228
+ this.isWebRTCRegistrationDisabled()
1229
+ ) {
1230
+ LoggerProxy.info(
1231
+ 'Skipping web calling line registration because disableWebRTCRegistration is enabled',
1232
+ {
1233
+ module: CC_FILE,
1234
+ method: METHODS.STATION_LOGIN,
1235
+ }
1236
+ );
852
1237
  }
853
1238
 
854
1239
  const resp = await loginResponse;
855
1240
  const {channelsMap, ...loginData} = resp.data;
1241
+ this.updateWellnessSession(resp.data.agentSessionId);
856
1242
  this.agentConfig.currentTeamId = resp.data.teamId;
857
1243
  const response = {
858
1244
  ...loginData,
@@ -865,7 +1251,16 @@ export default class ContactCenter extends WebexPlugin implements IContactCenter
865
1251
  notifsTrackingId: resp.trackingId,
866
1252
  };
867
1253
 
868
- this.webCallingService.setLoginOption(data.loginOption);
1254
+ if (this.agentConfig) {
1255
+ this.agentConfig.deviceType = data.loginOption;
1256
+ if (
1257
+ data.loginOption === LoginOption.AGENT_DN ||
1258
+ data.loginOption === LoginOption.EXTENSION
1259
+ ) {
1260
+ this.agentConfig.defaultDn = data.dialNumber;
1261
+ this.agentConfig.dn = data.dialNumber;
1262
+ }
1263
+ }
869
1264
  this.metricsManager.trackEvent(
870
1265
  METRIC_EVENT_NAMES.STATION_LOGIN_SUCCESS,
871
1266
  {
@@ -887,6 +1282,8 @@ export default class ContactCenter extends WebexPlugin implements IContactCenter
887
1282
  }
888
1283
  );
889
1284
 
1285
+ await this.ensureWxAppPostStationLogin();
1286
+
890
1287
  return response;
891
1288
  } catch (error) {
892
1289
  const failure = error.details as Failure;
@@ -952,9 +1349,12 @@ export default class ContactCenter extends WebexPlugin implements IContactCenter
952
1349
  );
953
1350
 
954
1351
  if (this.webCallingService) {
955
- this.webCallingService.deregisterWebCallingLine();
1352
+ await this.webCallingService.deregisterWebCallingLine();
956
1353
  }
957
1354
 
1355
+ await this.teardownWxAppLocalState();
1356
+ this.updateWellnessSession();
1357
+
958
1358
  LoggerProxy.log(`Agent station logout completed successfully`, {
959
1359
  module: CC_FILE,
960
1360
  method: METHODS.STATION_LOGOUT,
@@ -1046,6 +1446,20 @@ export default class ContactCenter extends WebexPlugin implements IContactCenter
1046
1446
  METRIC_EVENT_NAMES.AGENT_STATE_CHANGE_SUCCESS,
1047
1447
  METRIC_EVENT_NAMES.AGENT_STATE_CHANGE_FAILED,
1048
1448
  ]);
1449
+ if (
1450
+ data.state === AGENT_STATE_AVAILABLE &&
1451
+ this.webCallingService?.isBrowserVoiceRequired() &&
1452
+ !this.webCallingService.isVoiceReady()
1453
+ ) {
1454
+ const error = new Error(VOICE_CONNECTION_ERROR.NOT_READY) as GenericError;
1455
+ error.details = {
1456
+ type: 'SDK_VALIDATION_ERROR',
1457
+ orgId: this.$webex.credentials.getOrgId(),
1458
+ trackingId: EMPTY_STRING,
1459
+ data: {reason: VOICE_CONNECTION_ERROR.NOT_READY},
1460
+ };
1461
+ throw error;
1462
+ }
1049
1463
  const agentStatusResponse = await this.services.agent.stateChange({
1050
1464
  data: {...data, agentId: data.agentId || this.agentConfig.agentId},
1051
1465
  });
@@ -1055,7 +1469,7 @@ export default class ContactCenter extends WebexPlugin implements IContactCenter
1055
1469
  {
1056
1470
  ...MetricsManager.getCommonTrackingFieldForAQMResponse(agentStatusResponse),
1057
1471
  requestedState: data.state,
1058
- teamId: this.agentConfig?.teams[0]?.teamId ?? EMPTY_STRING,
1472
+ teamId: this.agentConfig?.teams[0]?.id ?? EMPTY_STRING,
1059
1473
  status: agentStatusResponse.data?.status,
1060
1474
  subStatus: agentStatusResponse.data?.subStatus,
1061
1475
  auxCodeId: data.auxCodeId,
@@ -1091,6 +1505,98 @@ export default class ContactCenter extends WebexPlugin implements IContactCenter
1091
1505
  }
1092
1506
  }
1093
1507
 
1508
+ /**
1509
+ * Returns the system-managed `WellbeingBreak` idle code for the current registration.
1510
+ * The value is fetched outside Desktop Profile filtering and cached until deregistration.
1511
+ * @returns The normalized system idle-code entity
1512
+ * @throws Structured Contact Center error when wellness is disabled or the code is unavailable
1513
+ * @example
1514
+ * const idleCode = await webex.cc.getWellbeingBreakIdleCode();
1515
+ * @public
1516
+ */
1517
+ public async getWellbeingBreakIdleCode(): Promise<Entity> {
1518
+ const method = METHODS.GET_WELLBEING_BREAK_IDLE_CODE;
1519
+ try {
1520
+ if (!this.agentConfig?.isWellnessBreakEnabled) {
1521
+ const validationError = new Error('WELLNESS_BREAK_NOT_ENABLED') as GenericError;
1522
+ validationError.details = {
1523
+ type: 'SDK_VALIDATION_ERROR',
1524
+ orgId: this.$webex.credentials.getOrgId(),
1525
+ trackingId: EMPTY_STRING,
1526
+ data: {reason: 'WELLNESS_BREAK_NOT_ENABLED'},
1527
+ };
1528
+ throw validationError;
1529
+ }
1530
+
1531
+ if (this.wellbeingBreakIdleCode) {
1532
+ return this.wellbeingBreakIdleCode;
1533
+ }
1534
+
1535
+ this.metricsManager.timeEvent([
1536
+ METRIC_EVENT_NAMES.WELLBEING_BREAK_IDLE_CODE_FETCH_SUCCESS,
1537
+ METRIC_EVENT_NAMES.WELLBEING_BREAK_IDLE_CODE_FETCH_FAILED,
1538
+ ]);
1539
+ const registrationGeneration = this.wellnessRegistrationGeneration;
1540
+ const orgId = this.$webex.credentials.getOrgId();
1541
+ const idleCode = await this.services.config.getWellbeingBreakIdleCode(orgId);
1542
+
1543
+ if (
1544
+ registrationGeneration !== this.wellnessRegistrationGeneration ||
1545
+ orgId !== this.$webex.credentials.getOrgId() ||
1546
+ !this.agentConfig?.isWellnessBreakEnabled
1547
+ ) {
1548
+ const staleRegistrationError = new Error(
1549
+ 'WELLNESS_BREAK_REGISTRATION_CHANGED'
1550
+ ) as GenericError;
1551
+ staleRegistrationError.details = {
1552
+ type: 'SDK_VALIDATION_ERROR',
1553
+ orgId,
1554
+ trackingId: EMPTY_STRING,
1555
+ data: {reason: 'WELLNESS_BREAK_REGISTRATION_CHANGED'},
1556
+ };
1557
+ throw staleRegistrationError;
1558
+ }
1559
+
1560
+ this.wellbeingBreakIdleCode = idleCode;
1561
+ this.metricsManager.trackEvent(
1562
+ METRIC_EVENT_NAMES.WELLBEING_BREAK_IDLE_CODE_FETCH_SUCCESS,
1563
+ {},
1564
+ ['operational']
1565
+ );
1566
+
1567
+ return idleCode;
1568
+ } catch (error) {
1569
+ this.metricsManager.trackEvent(
1570
+ METRIC_EVENT_NAMES.WELLBEING_BREAK_IDLE_CODE_FETCH_FAILED,
1571
+ {reason: error instanceof Error ? error.message : UNKNOWN_ERROR},
1572
+ ['operational']
1573
+ );
1574
+ const {error: detailedError} = getErrorDetails(error, method, CC_FILE);
1575
+ throw detailedError;
1576
+ }
1577
+ }
1578
+
1579
+ /**
1580
+ * Returns the current browser voice connection state.
1581
+ * Subscribe to `voice:connectionStateChange` to receive updates. The snapshot keeps line
1582
+ * registration separate from Mobius socket connectivity and does not represent the Contact
1583
+ * Center WebSocket connection.
1584
+ *
1585
+ * @returns {VoiceConnectionState} Current browser voice status and underlying connection states
1586
+ * @fires voice:connectionStateChange When browser voice availability changes
1587
+ * @public
1588
+ * @example
1589
+ * ```typescript
1590
+ * cc.on('voice:connectionStateChange', onVoiceStateChange);
1591
+ * const state = cc.getVoiceConnectionState();
1592
+ * ```
1593
+ */
1594
+ public getVoiceConnectionState(): VoiceConnectionState {
1595
+ const state = this.webCallingService?.getVoiceConnectionState();
1596
+
1597
+ return state ?? {...DEFAULT_VOICE_CONNECTION_STATE};
1598
+ }
1599
+
1094
1600
  /**
1095
1601
  * Processes incoming websocket messages and emits corresponding events
1096
1602
  * Handles various event types including agent state changes, login events,
@@ -1100,8 +1606,14 @@ export default class ContactCenter extends WebexPlugin implements IContactCenter
1100
1606
  */
1101
1607
  private handleWebsocketMessage = (event: string) => {
1102
1608
  const eventData = JSON.parse(event);
1103
- // Re-emit all the events related to agent except keep-alives
1104
- if (!eventData.keepalive && eventData.data && eventData.data.type) {
1609
+ // Re-emit all the events related to agent except keep-alives. Only event names present in
1610
+ // the typed CC_EVENTS allow-list are emitted; unknown/server-injected types are ignored.
1611
+ if (
1612
+ !eventData.keepalive &&
1613
+ eventData.data &&
1614
+ eventData.data.type &&
1615
+ CC_EVENT_ALLOW_LIST.has(eventData.data.type)
1616
+ ) {
1105
1617
  // @ts-ignore
1106
1618
  this.emit(eventData.data.type, eventData.data);
1107
1619
  }
@@ -1129,8 +1641,19 @@ export default class ContactCenter extends WebexPlugin implements IContactCenter
1129
1641
  ]);
1130
1642
  }
1131
1643
 
1644
+ if (this.handleWellnessBreakWebsocketPayload(eventData)) {
1645
+ return;
1646
+ }
1647
+
1132
1648
  switch (eventData.type) {
1133
1649
  case CC_EVENTS.AGENT_MULTI_LOGIN:
1650
+ if (
1651
+ eventData.data?.type === 'AgentMultiLoginCloseSession' &&
1652
+ (!eventData.data.agentSessionId ||
1653
+ eventData.data.agentSessionId === this.currentAgentSessionId)
1654
+ ) {
1655
+ this.updateWellnessSession();
1656
+ }
1134
1657
  // @ts-ignore
1135
1658
  this.emit(AGENT_EVENTS.AGENT_MULTI_LOGIN, eventData.data);
1136
1659
  break;
@@ -1149,6 +1672,13 @@ export default class ContactCenter extends WebexPlugin implements IContactCenter
1149
1672
  switch (eventData.data.type) {
1150
1673
  case CC_EVENTS.AGENT_STATION_LOGIN_SUCCESS: {
1151
1674
  const {channelsMap, ...loginData} = eventData.data;
1675
+ this.updateWellnessSession(loginData.agentSessionId);
1676
+ if (
1677
+ loginData.deviceType === LoginOption.EXTENSION ||
1678
+ loginData.deviceType === LoginOption.AGENT_DN
1679
+ ) {
1680
+ this.webCallingService.setBrowserVoiceRequired(false);
1681
+ }
1152
1682
  const stationLoginData = {
1153
1683
  ...loginData,
1154
1684
  mmProfile: {
@@ -1164,23 +1694,23 @@ export default class ContactCenter extends WebexPlugin implements IContactCenter
1164
1694
  this.emit(AGENT_EVENTS.AGENT_STATION_LOGIN_SUCCESS, stationLoginData);
1165
1695
  break;
1166
1696
  }
1167
- case CC_EVENTS.AGENT_RELOGIN_SUCCESS:
1168
- {
1169
- const {channelsMap, ...loginData} = eventData.data;
1170
- const stationReLoginData = {
1171
- ...loginData,
1172
- mmProfile: {
1173
- chat: channelsMap.chat?.length,
1174
- email: channelsMap.email?.length,
1175
- social: channelsMap.social?.length,
1176
- telephony: channelsMap.telephony?.length,
1177
- },
1178
- notifsTrackingId: eventData.trackingId,
1179
- };
1180
- // @ts-ignore
1181
- this.emit(AGENT_EVENTS.AGENT_RELOGIN_SUCCESS, stationReLoginData);
1182
- }
1697
+ case CC_EVENTS.AGENT_RELOGIN_SUCCESS: {
1698
+ const {channelsMap, ...loginData} = eventData.data;
1699
+ this.updateWellnessSession(loginData.agentSessionId);
1700
+ const stationReLoginData = {
1701
+ ...loginData,
1702
+ mmProfile: {
1703
+ chat: channelsMap.chat?.length,
1704
+ email: channelsMap.email?.length,
1705
+ social: channelsMap.social?.length,
1706
+ telephony: channelsMap.telephony?.length,
1707
+ },
1708
+ notifsTrackingId: eventData.trackingId,
1709
+ };
1710
+ // @ts-ignore
1711
+ this.emit(AGENT_EVENTS.AGENT_RELOGIN_SUCCESS, stationReLoginData);
1183
1712
  break;
1713
+ }
1184
1714
  case CC_EVENTS.AGENT_STATE_CHANGE_SUCCESS:
1185
1715
  // @ts-ignore
1186
1716
  this.emit(AGENT_EVENTS.AGENT_STATE_CHANGE_SUCCESS, eventData.data);
@@ -1194,6 +1724,12 @@ export default class ContactCenter extends WebexPlugin implements IContactCenter
1194
1724
  this.emit(AGENT_EVENTS.AGENT_STATION_LOGIN_FAILED, eventData.data);
1195
1725
  break;
1196
1726
  case CC_EVENTS.AGENT_LOGOUT_SUCCESS:
1727
+ if (
1728
+ !eventData.data.agentSessionId ||
1729
+ eventData.data.agentSessionId === this.currentAgentSessionId
1730
+ ) {
1731
+ this.updateWellnessSession();
1732
+ }
1197
1733
  // @ts-ignore
1198
1734
  this.emit(AGENT_EVENTS.AGENT_LOGOUT_SUCCESS, eventData.data);
1199
1735
  break;
@@ -1211,68 +1747,695 @@ export default class ContactCenter extends WebexPlugin implements IContactCenter
1211
1747
  };
1212
1748
 
1213
1749
  /**
1214
- * Initializes event listeners for the Contact Center service
1215
- * Sets up handlers for connection state changes and other core events
1750
+ * Checks whether Mobius/WebRTC registration should be skipped by config
1751
+ * @returns {boolean} True when browser WebRTC registration is disabled
1216
1752
  * @private
1217
1753
  */
1218
- private setupEventListeners() {
1219
- this.services.connectionService.on('connectionLost', this.handleConnectionLost.bind(this));
1754
+ private isWebRTCRegistrationDisabled(): boolean {
1755
+ return this.$config?.disableWebRTCRegistration === true;
1220
1756
  }
1221
1757
 
1222
1758
  /**
1223
- * Returns the connection configuration
1224
- * @returns {SubscribeRequest} Connection configuration
1759
+ * Determines whether this local login should register a browser voice line.
1760
+ * @param {LoginOption} loginOption Login device selected for this station login
1761
+ * @returns {boolean} True when browser WebRTC registration is enabled
1225
1762
  * @private
1226
1763
  */
1227
- private getConnectionConfig(): SubscribeRequest {
1228
- return {
1229
- force: this.$config?.force ?? true,
1230
- isKeepAliveEnabled: this.$config?.isKeepAliveEnabled ?? false,
1231
- clientType: this.$config?.clientType ?? 'WebexCCSDK',
1232
- allowMultiLogin: this.$config?.allowMultiLogin ?? true,
1233
- };
1764
+ private isBrowserVoiceRequired(loginOption: LoginOption): boolean {
1765
+ return (
1766
+ loginOption === LoginOption.BROWSER &&
1767
+ this.agentConfig?.webRtcEnabled === true &&
1768
+ !this.isWebRTCRegistrationDisabled()
1769
+ );
1234
1770
  }
1235
1771
 
1236
1772
  /**
1237
- * Handles connection lost events and reconnection attempts
1238
- * @param {ConnectionLostDetails} msg Connection lost details
1773
+ * Validates contact-center plugin configuration before service initialization
1239
1774
  * @private
1240
1775
  */
1241
- private async handleConnectionLost(msg: ConnectionLostDetails): Promise<void> {
1242
- if (msg.isConnectionLost) {
1243
- // TODO: Emit an event saying connection is lost
1244
- LoggerProxy.info('event=handleConnectionLost | Connection lost', {
1245
- module: CC_FILE,
1246
- method: METHODS.HANDLE_CONNECTION_LOST,
1247
- });
1248
- } else if (msg.isSocketReconnected) {
1249
- // TODO: Emit an event saying connection is re-estabilished
1250
- LoggerProxy.info(
1251
- 'event=handleConnectionReconnect | Connection reconnected attempting to request silent relogin',
1252
- {module: CC_FILE, method: METHODS.HANDLE_CONNECTION_LOST}
1776
+ private validatePluginConfig(): void {
1777
+ if (
1778
+ this.$config?.disableWebRTCRegistration === true &&
1779
+ this.$config?.allowMultiLogin === false
1780
+ ) {
1781
+ throw new Error(
1782
+ 'Invalid Contact Center configuration: disableWebRTCRegistration cannot be true when allowMultiLogin is false. Enable allowMultiLogin or allow WebRTC registration so an SDK instance can receive Mobius/WebRTC task events.'
1253
1783
  );
1254
- if (this.$config && this.$config.allowAutomatedRelogin) {
1255
- await this.silentRelogin();
1256
- }
1257
1784
  }
1258
1785
  }
1259
1786
 
1260
1787
  /**
1261
- * Handles silent relogin after registration completion
1788
+ * Whether wxApp thick-client answer is enabled for this SDK instance.
1789
+ * @public
1790
+ */
1791
+ public isWxBetterTogetherEnabled(): boolean {
1792
+ return this.$config?.enableWxBetterTogether === true;
1793
+ }
1794
+
1795
+ /**
1796
+ * Current station login option (Extension, Dial Number, or Browser/Desktop).
1797
+ * Prefer webCallingService — updated on every stationLogin before wxApp hooks run.
1262
1798
  * @private
1263
1799
  */
1264
- private async silentRelogin(): Promise<void> {
1265
- LoggerProxy.info('Starting silent relogin process', {
1266
- module: CC_FILE,
1267
- method: METHODS.SILENT_RELOGIN,
1268
- });
1800
+ private getCurrentStationLoginOption(): LoginOption | undefined {
1801
+ return this.webCallingService?.loginOption ?? this.agentConfig?.deviceType;
1802
+ }
1269
1803
 
1270
- try {
1271
- const reLoginResponse = await this.services.agent.reload();
1272
- const {
1273
- agentId,
1274
- lastStateChangeReason,
1275
- deviceType,
1804
+ /**
1805
+ * wxApp thick-client answer is supported for Extension and Dial Number station login only —
1806
+ * not Browser/Desktop (WebRTC) login.
1807
+ * @private
1808
+ */
1809
+ private assertWxAppStationLoginSupportedForEnable(): void {
1810
+ const loginOption = this.getCurrentStationLoginOption();
1811
+ if (loginOption !== LoginOption.EXTENSION && loginOption !== LoginOption.AGENT_DN) {
1812
+ throw new Error(
1813
+ 'setManageWebexCallingInWxcc requires EXTENSION or AGENT_DN station login. Complete station login before enabling.'
1814
+ );
1815
+ }
1816
+ }
1817
+
1818
+ /**
1819
+ * Clears runtime wxApp config after logout/deregister so stale flags do not apply on relogin.
1820
+ * @private
1821
+ */
1822
+ private resetEnableWxBetterTogetherConfig(): void {
1823
+ if (this.$config) {
1824
+ this.$config.enableWxBetterTogether = false;
1825
+ }
1826
+ this.taskManager.applyEnableWxBetterTogether(false);
1827
+ }
1828
+
1829
+ /**
1830
+ * Runtime enable/disable for wxApp Better Together (toast suppression + Mercury mute sync).
1831
+ *
1832
+ * **Phase 1 (WXCC-6026 / MMT): NOT part of the public host contract.**
1833
+ * Hosts must set `webexConfig.cc.enableWxBetterTogether` before `webex.init()` / `cc.register()`.
1834
+ * To change the flag after the SDK is initialized, re-init the SDK with the updated config.
1835
+ *
1836
+ * **Supported public read API:** {@link isWxBetterTogetherEnabled}.
1837
+ * **Supported telephony API:** unified `task.accept()`, `task.decline()`, `task.toggleMute()`,
1838
+ * `task.transmitDtmf()` — SDK routes wxApp calls internally when the init flag is active.
1839
+ *
1840
+ * **Production lifecycle does not call this method.** Station login, silent relogin, logout,
1841
+ * and deregister use {@link ensureWxAppPostStationLogin} and {@link teardownWxAppLocalState}
1842
+ * (usersub publish + Mercury subscribe/unsubscribe based on the init flag).
1843
+ *
1844
+ * This setter remains as a **private implementation** for Phase 2 runtime toggle and unit tests.
1845
+ * It updates `$config.enableWxBetterTogether`, TaskManager flags, cross-client usersub
1846
+ * (`answer-calls-on-wxcc`), and Mercury mute sync; rolls back config on publish/connect failure.
1847
+ *
1848
+ * @param enabled - `true` to enable wxApp answer + usersub suppression; `false` to disable and tear down.
1849
+ * @throws When enabling without login, on unsupported BROWSER station login, or when usersub/Mercury init fails.
1850
+ * @internal
1851
+ * @see enableWxBetterTogether (CCPluginConfig init flag)
1852
+ * @see ensureWxAppPostStationLogin
1853
+ * @see teardownWxAppLocalState
1854
+ */
1855
+ private async setManageWebexCallingInWxcc(enabled: boolean): Promise<void> {
1856
+ if (enabled && !this.$webex.internal.device?.userId) {
1857
+ throw new Error('Cannot publish answer-calls-on-wxcc: user is not logged in');
1858
+ }
1859
+
1860
+ if (enabled) {
1861
+ this.assertWxAppStationLoginSupportedForEnable();
1862
+ }
1863
+
1864
+ const previousEnabled = this.isWxBetterTogetherEnabled();
1865
+
1866
+ if (this.$config) {
1867
+ this.$config.enableWxBetterTogether = enabled;
1868
+ }
1869
+
1870
+ this.taskManager.applyEnableWxBetterTogether(enabled);
1871
+
1872
+ let publishedEnable = false;
1873
+
1874
+ try {
1875
+ if (enabled) {
1876
+ await this.ensureWxAppMercuryAndSubscribe();
1877
+ await this.publishAnswerOnWebexCrossClientState(true);
1878
+ publishedEnable = true;
1879
+ this.taskManager.syncWxAppMuteFromCallDetailsForAllTasks();
1880
+ this.taskManager.refreshWxAppOfferObservabilityForAllTasks();
1881
+ } else {
1882
+ await this.publishAnswerOnWebexCrossClientState(false);
1883
+ this.wxAppTelephonyMercurySync.unsubscribe();
1884
+ await this.releaseWxAppMercuryResources();
1885
+ }
1886
+ } catch (error) {
1887
+ if (publishedEnable) {
1888
+ await this.revertWxAppCrossClientPublish();
1889
+ } else if (enabled) {
1890
+ this.wxAppTelephonyMercurySync.unsubscribe();
1891
+ await this.releaseWxAppMercuryResources();
1892
+ }
1893
+
1894
+ if (this.$config) {
1895
+ this.$config.enableWxBetterTogether = previousEnabled;
1896
+ }
1897
+ this.taskManager.applyEnableWxBetterTogether(previousEnabled);
1898
+ throw error;
1899
+ }
1900
+ }
1901
+
1902
+ private getWxAppTelephonyTaskType(): 'Voice' | 'WebRTC' | 'unknown' {
1903
+ const loginOption = this.getCurrentStationLoginOption();
1904
+
1905
+ if (loginOption === LoginOption.BROWSER) {
1906
+ return 'WebRTC';
1907
+ }
1908
+
1909
+ if (loginOption === LoginOption.EXTENSION || loginOption === LoginOption.AGENT_DN) {
1910
+ return 'Voice';
1911
+ }
1912
+
1913
+ return 'unknown';
1914
+ }
1915
+
1916
+ private async ensureWxAppPostStationLogin(): Promise<void> {
1917
+ const loginOption = this.getCurrentStationLoginOption();
1918
+ const flagEnabled = this.isWxBetterTogetherEnabled();
1919
+ const telephonyTaskType = this.getWxAppTelephonyTaskType();
1920
+
1921
+ if (loginOption === LoginOption.BROWSER) {
1922
+ if (flagEnabled) {
1923
+ logWxAppSessionReadiness({
1924
+ enableWxBetterTogether: true,
1925
+ loginOption,
1926
+ wxAppHooksApplied: false,
1927
+ usersubPublished: false,
1928
+ mercurySubscribed: false,
1929
+ telephonyTaskType,
1930
+ skipReason: 'unsupported_browser_login',
1931
+ });
1932
+
1933
+ this.metricsManager.trackEvent(
1934
+ METRIC_EVENT_NAMES.WXAPP_SESSION_SKIPPED,
1935
+ {
1936
+ loginOption,
1937
+ enableWxBetterTogether: true,
1938
+ skipReason: 'unsupported_browser_login',
1939
+ },
1940
+ ['operational', 'behavioral']
1941
+ );
1942
+ }
1943
+
1944
+ return;
1945
+ }
1946
+
1947
+ let publishedEnable = false;
1948
+ let wxAppInitStage: 'mercury' | 'publish' = 'mercury';
1949
+
1950
+ try {
1951
+ if (flagEnabled) {
1952
+ this.metricsManager.timeEvent([
1953
+ METRIC_EVENT_NAMES.WXAPP_SESSION_INIT_SUCCESS,
1954
+ METRIC_EVENT_NAMES.WXAPP_SESSION_INIT_FAILED,
1955
+ ]);
1956
+
1957
+ await this.ensureWxAppMercuryAndSubscribe();
1958
+ wxAppInitStage = 'publish';
1959
+ await this.publishAnswerOnWebexCrossClientState(true);
1960
+ publishedEnable = true;
1961
+ this.taskManager.syncWxAppMuteFromCallDetailsForAllTasks();
1962
+ this.taskManager.refreshWxAppOfferObservabilityForAllTasks();
1963
+
1964
+ const mercurySubscribed = this.wxAppTelephonyMercurySync.isSubscribed();
1965
+ const usersubPublished = this.webexCrossClientService.isAnswerCallsStateActive();
1966
+
1967
+ logWxAppSessionReadiness({
1968
+ enableWxBetterTogether: true,
1969
+ loginOption,
1970
+ wxAppHooksApplied: true,
1971
+ usersubPublished,
1972
+ mercurySubscribed,
1973
+ telephonyTaskType,
1974
+ });
1975
+
1976
+ const sessionInitReady = mercurySubscribed && usersubPublished;
1977
+
1978
+ if (sessionInitReady) {
1979
+ this.metricsManager.trackEvent(
1980
+ METRIC_EVENT_NAMES.WXAPP_SESSION_INIT_SUCCESS,
1981
+ {
1982
+ loginOption,
1983
+ enableWxBetterTogether: true,
1984
+ usersubPublished,
1985
+ mercurySubscribed,
1986
+ telephonyTaskType,
1987
+ },
1988
+ ['operational', 'behavioral']
1989
+ );
1990
+ } else {
1991
+ this.metricsManager.trackEvent(
1992
+ METRIC_EVENT_NAMES.WXAPP_SESSION_INIT_FAILED,
1993
+ {
1994
+ loginOption,
1995
+ enableWxBetterTogether: true,
1996
+ usersubPublished,
1997
+ mercurySubscribed,
1998
+ telephonyTaskType,
1999
+ skipReason: !usersubPublished ? 'usersub_not_published' : 'mercury_not_subscribed',
2000
+ },
2001
+ ['operational', 'behavioral']
2002
+ );
2003
+ }
2004
+ } else {
2005
+ await this.ensureWxAppDeviceRegistered();
2006
+ await this.publishAnswerOnWebexCrossClientState(false, {force: true});
2007
+ this.webexCrossClientService.teardown();
2008
+ this.wxAppTelephonyMercurySync.unsubscribe();
2009
+ await this.releaseWxAppMercuryResources();
2010
+
2011
+ logWxAppSessionReadiness({
2012
+ enableWxBetterTogether: false,
2013
+ loginOption,
2014
+ wxAppHooksApplied: true,
2015
+ usersubPublished: false,
2016
+ mercurySubscribed: false,
2017
+ telephonyTaskType,
2018
+ skipReason: 'flag_disabled',
2019
+ });
2020
+
2021
+ this.metricsManager.trackEvent(
2022
+ METRIC_EVENT_NAMES.WXAPP_SESSION_SKIPPED,
2023
+ {loginOption, enableWxBetterTogether: false, skipReason: 'flag_disabled'},
2024
+ ['operational', 'behavioral']
2025
+ );
2026
+ }
2027
+ } catch (error) {
2028
+ LoggerProxy.error(`Failed to initialize wxApp post-station-login: ${error}`, {
2029
+ module: CC_FILE,
2030
+ method: METHODS.STATION_LOGIN,
2031
+ });
2032
+
2033
+ if (flagEnabled) {
2034
+ const sessionInitFailureReason =
2035
+ wxAppInitStage === 'mercury' ? 'mercury_subscribe_failed' : 'publish_failed';
2036
+
2037
+ this.metricsManager.trackEvent(
2038
+ METRIC_EVENT_NAMES.WXAPP_SESSION_INIT_FAILED,
2039
+ {
2040
+ loginOption,
2041
+ enableWxBetterTogether: true,
2042
+ usersubPublished: this.webexCrossClientService.isAnswerCallsStateActive(),
2043
+ mercurySubscribed: this.wxAppTelephonyMercurySync.isSubscribed(),
2044
+ telephonyTaskType,
2045
+ skipReason: sessionInitFailureReason,
2046
+ error: error instanceof Error ? error.toString() : String(error),
2047
+ },
2048
+ ['operational', 'behavioral']
2049
+ );
2050
+
2051
+ logWxAppSessionReadiness({
2052
+ enableWxBetterTogether: true,
2053
+ loginOption,
2054
+ wxAppHooksApplied: false,
2055
+ usersubPublished: this.webexCrossClientService.isAnswerCallsStateActive(),
2056
+ mercurySubscribed: this.wxAppTelephonyMercurySync.isSubscribed(),
2057
+ telephonyTaskType,
2058
+ skipReason: sessionInitFailureReason,
2059
+ });
2060
+
2061
+ if (publishedEnable) {
2062
+ await this.revertWxAppCrossClientPublish();
2063
+ } else {
2064
+ this.wxAppTelephonyMercurySync.unsubscribe();
2065
+ await this.releaseWxAppMercuryResources();
2066
+ }
2067
+ this.resetEnableWxBetterTogetherConfig();
2068
+ } else {
2069
+ this.scheduleForcedFalsePublishRetry();
2070
+ }
2071
+ }
2072
+ }
2073
+
2074
+ private clearWxAppFalsePublishRetryTimer(): void {
2075
+ if (this.wxAppFalsePublishRetryTimer) {
2076
+ clearTimeout(this.wxAppFalsePublishRetryTimer);
2077
+ this.wxAppFalsePublishRetryTimer = undefined;
2078
+ }
2079
+ }
2080
+
2081
+ private scheduleForcedFalsePublishRetry(retryAttempt = 0): void {
2082
+ this.scheduleFalsePublishRetry(retryAttempt, {requireDisabled: true});
2083
+ }
2084
+
2085
+ /**
2086
+ * Retries compensating false publish after rollback failure, regardless of enabled flag.
2087
+ * @private
2088
+ */
2089
+ private scheduleCompensatingFalsePublishRetry(retryAttempt = 0): void {
2090
+ this.scheduleFalsePublishRetry(retryAttempt);
2091
+ }
2092
+
2093
+ private scheduleFalsePublishRetry(
2094
+ retryAttempt = 0,
2095
+ options: {requireDisabled?: boolean} = {}
2096
+ ): void {
2097
+ if (retryAttempt >= ContactCenter.WXAPP_FALSE_PUBLISH_MAX_RETRIES) {
2098
+ return;
2099
+ }
2100
+
2101
+ if (options?.requireDisabled && this.isWxBetterTogetherEnabled()) {
2102
+ return;
2103
+ }
2104
+
2105
+ this.clearWxAppFalsePublishRetryTimer();
2106
+
2107
+ this.wxAppFalsePublishRetryTimer = setTimeout(async () => {
2108
+ this.wxAppFalsePublishRetryTimer = undefined;
2109
+
2110
+ if (options?.requireDisabled && this.isWxBetterTogetherEnabled()) {
2111
+ return;
2112
+ }
2113
+
2114
+ if (
2115
+ !options?.requireDisabled &&
2116
+ this.isWxBetterTogetherEnabled() &&
2117
+ this.webexCrossClientService.isAnswerCallsStateActive()
2118
+ ) {
2119
+ return;
2120
+ }
2121
+
2122
+ try {
2123
+ await this.ensureWxAppDeviceRegistered();
2124
+ await this.publishAnswerOnWebexCrossClientState(false, {force: true});
2125
+ this.webexCrossClientService.teardown();
2126
+ this.wxAppTelephonyMercurySync.unsubscribe();
2127
+ await this.releaseWxAppMercuryResources();
2128
+ } catch (retryError) {
2129
+ LoggerProxy.error(
2130
+ `Failed to retry forced answer-calls-on-wxcc false publish: ${retryError}`,
2131
+ {
2132
+ module: CC_FILE,
2133
+ method: METHODS.SET_MANAGE_WEBEX_CALLING_IN_WXCC,
2134
+ }
2135
+ );
2136
+ this.scheduleFalsePublishRetry(retryAttempt + 1, options);
2137
+ }
2138
+ }, ContactCenter.WXAPP_FALSE_PUBLISH_RETRY_DELAY_MS);
2139
+ }
2140
+
2141
+ /**
2142
+ * Best-effort rollback when usersub true was published but wxApp setup did not complete.
2143
+ * @private
2144
+ */
2145
+ private async revertWxAppCrossClientPublish(): Promise<void> {
2146
+ try {
2147
+ await this.publishAnswerOnWebexCrossClientState(false, {force: true});
2148
+ } catch (error) {
2149
+ LoggerProxy.error(
2150
+ `Failed to publish compensating answer-calls-on-wxcc false during wxApp rollback: ${error}`,
2151
+ {
2152
+ module: CC_FILE,
2153
+ method: METHODS.SET_MANAGE_WEBEX_CALLING_IN_WXCC,
2154
+ }
2155
+ );
2156
+ this.scheduleCompensatingFalsePublishRetry();
2157
+ }
2158
+
2159
+ this.webexCrossClientService.teardown();
2160
+ this.wxAppTelephonyMercurySync.unsubscribe();
2161
+ await this.releaseWxAppMercuryResources();
2162
+ }
2163
+
2164
+ private async ensureWxAppDeviceRegistered(): Promise<void> {
2165
+ const device = this.$webex.internal.device;
2166
+
2167
+ if (device && !device.registered && device.register) {
2168
+ await device.register();
2169
+ this.wxAppDeviceRegisteredByCc = true;
2170
+ LoggerProxy.log('WxApp: device registered for cross-client publish', {
2171
+ module: CC_FILE,
2172
+ method: METHODS.ENSURE_WXAPP_MERCURY_CONNECTED,
2173
+ });
2174
+ }
2175
+ }
2176
+
2177
+ private async ensureWxAppMercuryConnected(): Promise<void> {
2178
+ const mercury = this.$webex.internal.mercury;
2179
+
2180
+ await this.ensureWxAppDeviceRegistered();
2181
+
2182
+ if (mercury && !mercury.connected) {
2183
+ await mercury.connect();
2184
+ this.wxAppMercuryConnectedByCc = true;
2185
+ LoggerProxy.log('WxApp mute sync: mercury connected', {
2186
+ module: CC_FILE,
2187
+ method: METHODS.ENSURE_WXAPP_MERCURY_CONNECTED,
2188
+ });
2189
+ }
2190
+ }
2191
+
2192
+ /**
2193
+ * Disconnects Mercury and unregisters the device when wxApp mute sync opened them.
2194
+ * @private
2195
+ */
2196
+ private async releaseWxAppMercuryResources(): Promise<void> {
2197
+ const mercury = this.$webex.internal.mercury;
2198
+ const device = this.$webex.internal.device;
2199
+
2200
+ if (this.wxAppMercuryConnectedByCc && mercury?.connected) {
2201
+ try {
2202
+ await mercury.disconnect();
2203
+ this.wxAppMercuryConnectedByCc = false;
2204
+ LoggerProxy.log('WxApp mute sync: mercury disconnected', {
2205
+ module: CC_FILE,
2206
+ method: METHODS.ENSURE_WXAPP_MERCURY_CONNECTED,
2207
+ });
2208
+ } catch (error) {
2209
+ LoggerProxy.error(`Failed to disconnect wxApp Mercury: ${error}`, {
2210
+ module: CC_FILE,
2211
+ method: METHODS.ENSURE_WXAPP_MERCURY_CONNECTED,
2212
+ });
2213
+ }
2214
+ }
2215
+
2216
+ if (this.wxAppDeviceRegisteredByCc && device?.registered && device.unregister) {
2217
+ try {
2218
+ // @ts-ignore
2219
+ await device.unregister();
2220
+ this.wxAppDeviceRegisteredByCc = false;
2221
+ LoggerProxy.log('WxApp mute sync: device unregistered', {
2222
+ module: CC_FILE,
2223
+ method: METHODS.ENSURE_WXAPP_MERCURY_CONNECTED,
2224
+ });
2225
+ } catch (error) {
2226
+ LoggerProxy.error(`Failed to unregister wxApp device: ${error}`, {
2227
+ module: CC_FILE,
2228
+ method: METHODS.ENSURE_WXAPP_MERCURY_CONNECTED,
2229
+ });
2230
+ }
2231
+ } else if (this.wxAppDeviceRegisteredByCc) {
2232
+ this.wxAppDeviceRegisteredByCc = false;
2233
+ }
2234
+ }
2235
+
2236
+ /**
2237
+ * Clears wxApp runtime state and feature-owned resources. Publish failures are logged;
2238
+ * optional rethrow for deregister when callers need to surface usersub errors.
2239
+ * @private
2240
+ */
2241
+ private async teardownWxAppLocalState(options?: {
2242
+ rethrowPublishError?: boolean;
2243
+ clearInitFlag?: boolean;
2244
+ }): Promise<{publishError?: unknown}> {
2245
+ this.clearWxAppFalsePublishRetryTimer();
2246
+ let publishError: unknown;
2247
+
2248
+ try {
2249
+ const shouldForceFalsePublish =
2250
+ this.isWxBetterTogetherEnabled() || this.webexCrossClientService.isAnswerCallsStateActive();
2251
+
2252
+ await this.publishAnswerOnWebexCrossClientState(false, {
2253
+ force: shouldForceFalsePublish,
2254
+ });
2255
+ } catch (error) {
2256
+ publishError = error;
2257
+ LoggerProxy.error(
2258
+ `Failed to publish answer-calls-on-wxcc false during wxApp teardown: ${error}`,
2259
+ {
2260
+ module: CC_FILE,
2261
+ method: METHODS.SET_MANAGE_WEBEX_CALLING_IN_WXCC,
2262
+ }
2263
+ );
2264
+ }
2265
+
2266
+ this.webexCrossClientService.teardown();
2267
+ this.wxAppTelephonyMercurySync.unsubscribe();
2268
+ await this.releaseWxAppMercuryResources();
2269
+
2270
+ if (options?.clearInitFlag) {
2271
+ this.resetEnableWxBetterTogetherConfig();
2272
+ }
2273
+
2274
+ if (publishError) {
2275
+ this.scheduleCompensatingFalsePublishRetry();
2276
+ }
2277
+
2278
+ if (options?.rethrowPublishError && publishError) {
2279
+ throw publishError;
2280
+ }
2281
+
2282
+ return {publishError: publishError ?? undefined};
2283
+ }
2284
+
2285
+ private async ensureWxAppMercuryAndSubscribe(): Promise<void> {
2286
+ if (!this.isWxBetterTogetherEnabled()) {
2287
+ return;
2288
+ }
2289
+
2290
+ if (this.getCurrentStationLoginOption() === LoginOption.BROWSER) {
2291
+ return;
2292
+ }
2293
+
2294
+ const agentId = this.agentConfig?.agentId;
2295
+ if (!agentId) {
2296
+ LoggerProxy.error('Cannot subscribe wxApp mute sync: agentId unavailable', {
2297
+ module: CC_FILE,
2298
+ method: METHODS.SYNC_WXAPP_MUTE_FROM_MERCURY,
2299
+ });
2300
+
2301
+ this.metricsManager.trackEvent(
2302
+ METRIC_EVENT_NAMES.WXAPP_MERCURY_SUBSCRIBE_FAILED,
2303
+ {error: 'agentId unavailable', mercurySubscribed: false},
2304
+ ['operational', 'behavioral']
2305
+ );
2306
+
2307
+ return;
2308
+ }
2309
+
2310
+ try {
2311
+ await this.ensureWxAppMercuryConnected();
2312
+ this.wxAppTelephonyMercurySync.subscribe(agentId, (callId, muted) => {
2313
+ this.taskManager.applyWxAppMuteStateFromSync(callId, muted);
2314
+ });
2315
+ } catch (error) {
2316
+ LoggerProxy.error(`Failed to ensure wxApp Mercury mute sync: ${error}`, {
2317
+ module: CC_FILE,
2318
+ method: METHODS.SYNC_WXAPP_MUTE_FROM_MERCURY,
2319
+ });
2320
+ this.metricsManager.trackEvent(
2321
+ METRIC_EVENT_NAMES.WXAPP_MERCURY_SUBSCRIBE_FAILED,
2322
+ {
2323
+ error: error instanceof Error ? error.toString() : String(error),
2324
+ mercurySubscribed: false,
2325
+ },
2326
+ ['operational', 'behavioral']
2327
+ );
2328
+ this.wxAppTelephonyMercurySync.unsubscribe();
2329
+ await this.releaseWxAppMercuryResources();
2330
+ throw error;
2331
+ }
2332
+ }
2333
+
2334
+ private async publishAnswerOnWebexCrossClientState(
2335
+ enable: boolean,
2336
+ options?: {force?: boolean}
2337
+ ): Promise<void> {
2338
+ if (enable && !this.isWxBetterTogetherEnabled()) {
2339
+ return;
2340
+ }
2341
+
2342
+ if (!enable && !options?.force && !this.webexCrossClientService.isAnswerCallsStateActive()) {
2343
+ return;
2344
+ }
2345
+
2346
+ const userId = this.$webex.internal.device?.userId;
2347
+ if (!userId) {
2348
+ if (enable && this.isWxBetterTogetherEnabled()) {
2349
+ this.metricsManager.trackEvent(
2350
+ METRIC_EVENT_NAMES.WXAPP_USERSUB_PUBLISH_FAILED,
2351
+ {
2352
+ enableWxBetterTogether: true,
2353
+ usersubPublished: this.webexCrossClientService.isAnswerCallsStateActive(),
2354
+ skipReason: 'user_id_unavailable',
2355
+ error: 'User ID is unavailable for cross-client publish',
2356
+ },
2357
+ ['operational', 'behavioral']
2358
+ );
2359
+ }
2360
+
2361
+ return;
2362
+ }
2363
+
2364
+ await this.webexCrossClientService.setManageWebexCallingInWxcc(enable, {
2365
+ userId,
2366
+ trackPublishMetrics: true,
2367
+ });
2368
+
2369
+ if (enable) {
2370
+ this.clearWxAppFalsePublishRetryTimer();
2371
+ }
2372
+ }
2373
+
2374
+ /**
2375
+ * Initializes event listeners for the Contact Center service
2376
+ * Sets up handlers for connection state changes and other core events
2377
+ * @private
2378
+ */
2379
+ private setupEventListeners() {
2380
+ this.services.connectionService.on('connectionLost', this.handleConnectionLost.bind(this));
2381
+ }
2382
+
2383
+ /**
2384
+ * Returns the connection configuration
2385
+ * @returns {SubscribeRequest} Connection configuration
2386
+ * @private
2387
+ */
2388
+ private getConnectionConfig(): SubscribeRequest {
2389
+ return {
2390
+ force: this.$config?.force ?? true,
2391
+ isKeepAliveEnabled: this.$config?.isKeepAliveEnabled ?? false,
2392
+ clientType: this.$config?.clientType ?? 'WebexCCSDK',
2393
+ allowMultiLogin: this.$config?.allowMultiLogin ?? true,
2394
+ };
2395
+ }
2396
+
2397
+ /**
2398
+ * Handles connection lost events and reconnection attempts
2399
+ * @param {ConnectionLostDetails} msg Connection lost details
2400
+ * @private
2401
+ */
2402
+ private async handleConnectionLost(msg: ConnectionLostDetails): Promise<void> {
2403
+ if (msg.isConnectionLost) {
2404
+ // TODO: Emit an event saying connection is lost
2405
+ LoggerProxy.log('event=handleConnectionLost | Connection lost', {
2406
+ module: CC_FILE,
2407
+ method: METHODS.HANDLE_CONNECTION_LOST,
2408
+ });
2409
+ } else if (msg.isSocketReconnected) {
2410
+ // TODO: Emit an event saying connection is re-estabilished
2411
+ LoggerProxy.log(
2412
+ 'event=handleConnectionReconnect | Connection reconnected attempting to request silent relogin',
2413
+ {module: CC_FILE, method: METHODS.HANDLE_CONNECTION_LOST}
2414
+ );
2415
+ if (this.$config && this.$config.allowAutomatedRelogin) {
2416
+ await this.silentRelogin();
2417
+ }
2418
+ }
2419
+ }
2420
+
2421
+ /**
2422
+ * Handles silent relogin after registration completion
2423
+ * @private
2424
+ */
2425
+ private async silentRelogin(): Promise<void> {
2426
+ LoggerProxy.log('Starting silent relogin process', {
2427
+ module: CC_FILE,
2428
+ method: METHODS.SILENT_RELOGIN,
2429
+ });
2430
+
2431
+ try {
2432
+ const reLoginResponse = await this.services.agent.reload();
2433
+ this.updateWellnessSession(reLoginResponse.data.agentSessionId);
2434
+
2435
+ const {
2436
+ agentId,
2437
+ lastStateChangeReason,
2438
+ deviceType,
1276
2439
  dn,
1277
2440
  lastStateChangeTimestamp,
1278
2441
  lastIdleCodeChangeTimestamp,
@@ -1284,7 +2447,7 @@ export default class ContactCenter extends WebexPlugin implements IContactCenter
1284
2447
  await this.handleDeviceType(deviceType as LoginOption, dn);
1285
2448
 
1286
2449
  if (lastStateChangeReason === 'agent-wss-disconnect') {
1287
- LoggerProxy.info(
2450
+ LoggerProxy.log(
1288
2451
  'event=requestAutoStateChange | Requesting state change to available on socket reconnect',
1289
2452
  {module: CC_FILE, method: METHODS.SILENT_RELOGIN}
1290
2453
  );
@@ -1313,8 +2476,8 @@ export default class ContactCenter extends WebexPlugin implements IContactCenter
1313
2476
  }
1314
2477
  this.agentConfig.lastStateAuxCodeId = auxCodeId;
1315
2478
  this.agentConfig.isAgentLoggedIn = true;
1316
- // TODO: https://jira-eng-gpk2.cisco.com/jira/browse/SPARK-626777 Implement the de-register method and close the listener there
1317
- this.services.webSocketManager.on('message', this.handleWebsocketMessage);
2479
+
2480
+ await this.ensureWxAppPostStationLogin();
1318
2481
 
1319
2482
  LoggerProxy.log(
1320
2483
  `Silent relogin process completed successfully with login Option: ${reLoginResponse.data.deviceType} teamId: ${reLoginResponse.data.teamId}`,
@@ -1352,9 +2515,20 @@ export default class ContactCenter extends WebexPlugin implements IContactCenter
1352
2515
  */
1353
2516
  private async handleDeviceType(deviceType: LoginOption, dn: string): Promise<void> {
1354
2517
  this.webCallingService.setLoginOption(deviceType);
2518
+ this.webCallingService.setBrowserVoiceRequired(this.isBrowserVoiceRequired(deviceType));
1355
2519
  this.agentConfig.deviceType = deviceType;
1356
2520
  switch (deviceType) {
1357
2521
  case LoginOption.BROWSER:
2522
+ if (this.isWebRTCRegistrationDisabled()) {
2523
+ LoggerProxy.info(
2524
+ 'Skipping web calling line registration because disableWebRTCRegistration is enabled',
2525
+ {
2526
+ module: CC_FILE,
2527
+ method: METHODS.HANDLE_DEVICE_TYPE,
2528
+ }
2529
+ );
2530
+ break;
2531
+ }
1358
2532
  try {
1359
2533
  await this.webCallingService.registerWebCallingLine();
1360
2534
  } catch (error) {
@@ -1620,6 +2794,166 @@ export default class ContactCenter extends WebexPlugin implements IContactCenter
1620
2794
  }
1621
2795
  }
1622
2796
 
2797
+ /**
2798
+ * Skips a campaign preview contact, requesting the next contact from the campaign.
2799
+ *
2800
+ * When a campaign manager reserves a contact for an agent, the agent receives an
2801
+ * `AgentOfferCampaignReservation` event. Instead of accepting, the agent can skip the
2802
+ * preview contact to move to the next contact in the campaign.
2803
+ *
2804
+ * @param {PreviewContactPayload} payload - The preview contact payload containing interactionId and campaignId (campaign name, not UUID).
2805
+ * @returns {Promise<TaskResponse>} Promise resolving with agent contact on success.
2806
+ * @throws {Error} If the operation fails (network error, etc.)
2807
+ *
2808
+ * @example
2809
+ * ```typescript
2810
+ * webex.cc.on('task:campaignPreviewReservation', async (task) => {
2811
+ * const { interactionId } = task.data;
2812
+ * const campaignId = task.data.interaction.callProcessingDetails.campaignId;
2813
+ *
2814
+ * const result = await webex.cc.skipPreviewContact({ interactionId, campaignId });
2815
+ * });
2816
+ * ```
2817
+ */
2818
+ public async skipPreviewContact(payload: PreviewContactPayload): Promise<TaskResponse> {
2819
+ const task = this.taskManager.getTask(payload.interactionId);
2820
+ if (task?.data?.interaction?.callProcessingDetails?.campaignPreviewSkipDisabled === 'true') {
2821
+ LoggerProxy.warn('Skip action is disabled for this campaign preview contact', {
2822
+ module: CC_FILE,
2823
+ method: METHODS.SKIP_PREVIEW_CONTACT,
2824
+ interactionId: payload.interactionId,
2825
+ });
2826
+ throw new Error('Skip action is disabled for this campaign preview contact');
2827
+ }
2828
+
2829
+ LoggerProxy.info('Skipping campaign preview contact', {
2830
+ module: CC_FILE,
2831
+ method: METHODS.SKIP_PREVIEW_CONTACT,
2832
+ });
2833
+ try {
2834
+ this.metricsManager.timeEvent([
2835
+ METRIC_EVENT_NAMES.CAMPAIGN_PREVIEW_SKIP_SUCCESS,
2836
+ METRIC_EVENT_NAMES.CAMPAIGN_PREVIEW_SKIP_FAILED,
2837
+ ]);
2838
+
2839
+ const result = await this.services.dialer.skipPreviewContact({data: payload});
2840
+
2841
+ this.metricsManager.trackEvent(
2842
+ METRIC_EVENT_NAMES.CAMPAIGN_PREVIEW_SKIP_SUCCESS,
2843
+ {
2844
+ ...MetricsManager.getCommonTrackingFieldForAQMResponse(result),
2845
+ interactionId: payload.interactionId,
2846
+ campaignId: payload.campaignId,
2847
+ },
2848
+ ['behavioral', 'business', 'operational']
2849
+ );
2850
+
2851
+ LoggerProxy.log('Campaign preview contact skipped successfully', {
2852
+ module: CC_FILE,
2853
+ method: METHODS.SKIP_PREVIEW_CONTACT,
2854
+ trackingId: result.trackingId,
2855
+ interactionId: payload.interactionId,
2856
+ });
2857
+
2858
+ return result;
2859
+ } catch (error) {
2860
+ const failure = error.details as Failure;
2861
+ this.metricsManager.trackEvent(
2862
+ METRIC_EVENT_NAMES.CAMPAIGN_PREVIEW_SKIP_FAILED,
2863
+ {
2864
+ ...MetricsManager.getCommonTrackingFieldForAQMResponseFailed(failure),
2865
+ interactionId: payload.interactionId,
2866
+ campaignId: payload.campaignId,
2867
+ },
2868
+ ['behavioral', 'business', 'operational']
2869
+ );
2870
+ const {error: detailedError} = getErrorDetails(error, METHODS.SKIP_PREVIEW_CONTACT, CC_FILE);
2871
+ throw detailedError;
2872
+ }
2873
+ }
2874
+
2875
+ /**
2876
+ * Removes a campaign preview contact from the campaign list entirely.
2877
+ *
2878
+ * When a campaign manager reserves a contact for an agent, the agent receives an
2879
+ * `AgentOfferCampaignReservation` event. Instead of accepting or skipping, the agent can
2880
+ * remove the preview contact to permanently take it out of the campaign contact list.
2881
+ *
2882
+ * @param {PreviewContactPayload} payload - The preview contact payload containing interactionId and campaignId (campaign name, not UUID).
2883
+ * @returns {Promise<TaskResponse>} Promise resolving with agent contact on success.
2884
+ * @throws {Error} If the operation fails (network error, etc.)
2885
+ *
2886
+ * @example
2887
+ * ```typescript
2888
+ * webex.cc.on('task:campaignPreviewReservation', async (task) => {
2889
+ * const { interactionId } = task.data;
2890
+ * const campaignId = task.data.interaction.callProcessingDetails.campaignId;
2891
+ *
2892
+ * const result = await webex.cc.removePreviewContact({ interactionId, campaignId });
2893
+ * });
2894
+ * ```
2895
+ */
2896
+ public async removePreviewContact(payload: PreviewContactPayload): Promise<TaskResponse> {
2897
+ const task = this.taskManager.getTask(payload.interactionId);
2898
+ if (task?.data?.interaction?.callProcessingDetails?.campaignPreviewRemoveDisabled === 'true') {
2899
+ LoggerProxy.warn('Remove action is disabled for this campaign preview contact', {
2900
+ module: CC_FILE,
2901
+ method: METHODS.REMOVE_PREVIEW_CONTACT,
2902
+ interactionId: payload.interactionId,
2903
+ });
2904
+ throw new Error('Remove action is disabled for this campaign preview contact');
2905
+ }
2906
+
2907
+ LoggerProxy.info('Removing campaign preview contact', {
2908
+ module: CC_FILE,
2909
+ method: METHODS.REMOVE_PREVIEW_CONTACT,
2910
+ });
2911
+ try {
2912
+ this.metricsManager.timeEvent([
2913
+ METRIC_EVENT_NAMES.CAMPAIGN_PREVIEW_REMOVE_SUCCESS,
2914
+ METRIC_EVENT_NAMES.CAMPAIGN_PREVIEW_REMOVE_FAILED,
2915
+ ]);
2916
+
2917
+ const result = await this.services.dialer.removePreviewContact({data: payload});
2918
+
2919
+ this.metricsManager.trackEvent(
2920
+ METRIC_EVENT_NAMES.CAMPAIGN_PREVIEW_REMOVE_SUCCESS,
2921
+ {
2922
+ ...MetricsManager.getCommonTrackingFieldForAQMResponse(result),
2923
+ interactionId: payload.interactionId,
2924
+ campaignId: payload.campaignId,
2925
+ },
2926
+ ['behavioral', 'business', 'operational']
2927
+ );
2928
+
2929
+ LoggerProxy.log('Campaign preview contact removed successfully', {
2930
+ module: CC_FILE,
2931
+ method: METHODS.REMOVE_PREVIEW_CONTACT,
2932
+ trackingId: result.trackingId,
2933
+ interactionId: payload.interactionId,
2934
+ });
2935
+
2936
+ return result;
2937
+ } catch (error) {
2938
+ const failure = error.details as Failure;
2939
+ this.metricsManager.trackEvent(
2940
+ METRIC_EVENT_NAMES.CAMPAIGN_PREVIEW_REMOVE_FAILED,
2941
+ {
2942
+ ...MetricsManager.getCommonTrackingFieldForAQMResponseFailed(failure),
2943
+ interactionId: payload.interactionId,
2944
+ campaignId: payload.campaignId,
2945
+ },
2946
+ ['behavioral', 'business', 'operational']
2947
+ );
2948
+ const {error: detailedError} = getErrorDetails(
2949
+ error,
2950
+ METHODS.REMOVE_PREVIEW_CONTACT,
2951
+ CC_FILE
2952
+ );
2953
+ throw detailedError;
2954
+ }
2955
+ }
2956
+
1623
2957
  /**
1624
2958
  * Fetches outdial ANI (Automatic Number Identification) entries for an outdial ANI ID.
1625
2959
  *
@@ -1864,8 +3198,8 @@ export default class ContactCenter extends WebexPlugin implements IContactCenter
1864
3198
  }
1865
3199
 
1866
3200
  /**
1867
- * Returns paginated entry points for the organization.
1868
- * Thin wrapper around internal EntryPoint instance.
3201
+ * Returns paginated entry points using the EntryPoint service defaults.
3202
+ * Existing request parameters can override those defaults.
1869
3203
  * @public
1870
3204
  */
1871
3205
  public async getEntryPoints(
@@ -1875,8 +3209,8 @@ export default class ContactCenter extends WebexPlugin implements IContactCenter
1875
3209
  }
1876
3210
 
1877
3211
  /**
1878
- * Returns paginated contact service queues for the organization.
1879
- * Thin wrapper around internal Queue instance.
3212
+ * Returns paginated contact service queues using the Queue service defaults.
3213
+ * Existing request parameters can override those defaults.
1880
3214
  * @public
1881
3215
  */
1882
3216
  public async getQueues(