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

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 (297) hide show
  1. package/.repo-context.json +704 -0
  2. package/.sdd/manifest.json +1613 -0
  3. package/AGENTS.md +969 -0
  4. package/dist/cc.js +1102 -47
  5. package/dist/cc.js.map +1 -1
  6. package/dist/config.js +13 -0
  7. package/dist/config.js.map +1 -1
  8. package/dist/constants.js +46 -3
  9. package/dist/constants.js.map +1 -1
  10. package/dist/index.js +86 -17
  11. package/dist/index.js.map +1 -1
  12. package/dist/metrics/MetricsManager.js +16 -0
  13. package/dist/metrics/MetricsManager.js.map +1 -1
  14. package/dist/metrics/behavioral-events.js +211 -0
  15. package/dist/metrics/behavioral-events.js.map +1 -1
  16. package/dist/metrics/constants.js +58 -4
  17. package/dist/metrics/constants.js.map +1 -1
  18. package/dist/services/AddressBook.js +18 -15
  19. package/dist/services/AddressBook.js.map +1 -1
  20. package/dist/services/AnswerCallOnWebexService.js +202 -0
  21. package/dist/services/AnswerCallOnWebexService.js.map +1 -0
  22. package/dist/services/ApiAiAssistant.js +369 -14
  23. package/dist/services/ApiAiAssistant.js.map +1 -1
  24. package/dist/services/EntryPoint.js +46 -68
  25. package/dist/services/EntryPoint.js.map +1 -1
  26. package/dist/services/Queue.js +27 -22
  27. package/dist/services/Queue.js.map +1 -1
  28. package/dist/services/UserPreference.js +427 -0
  29. package/dist/services/UserPreference.js.map +1 -0
  30. package/dist/services/WebCallingService.js +287 -37
  31. package/dist/services/WebCallingService.js.map +1 -1
  32. package/dist/services/WebexCrossClientService.js +225 -0
  33. package/dist/services/WebexCrossClientService.js.map +1 -0
  34. package/dist/services/WxAppTelephonyMercurySync.js +111 -0
  35. package/dist/services/WxAppTelephonyMercurySync.js.map +1 -0
  36. package/dist/services/config/Util.js +48 -48
  37. package/dist/services/config/Util.js.map +1 -1
  38. package/dist/services/config/constants.js +57 -79
  39. package/dist/services/config/constants.js.map +1 -1
  40. package/dist/services/config/index.js +100 -226
  41. package/dist/services/config/index.js.map +1 -1
  42. package/dist/services/config/types.js +100 -40
  43. package/dist/services/config/types.js.map +1 -1
  44. package/dist/services/constants.js +19 -1
  45. package/dist/services/constants.js.map +1 -1
  46. package/dist/services/core/Err.js.map +1 -1
  47. package/dist/services/core/Utils.js +131 -32
  48. package/dist/services/core/Utils.js.map +1 -1
  49. package/dist/services/core/WebexRequest.js +6 -2
  50. package/dist/services/core/WebexRequest.js.map +1 -1
  51. package/dist/services/core/aqm-reqs.js +17 -11
  52. package/dist/services/core/aqm-reqs.js.map +1 -1
  53. package/dist/services/core/constants.js +9 -1
  54. package/dist/services/core/constants.js.map +1 -1
  55. package/dist/services/core/types.js.map +1 -1
  56. package/dist/services/core/websocket/WebSocketManager.js +26 -6
  57. package/dist/services/core/websocket/WebSocketManager.js.map +1 -1
  58. package/dist/services/core/websocket/connection-service.js +3 -1
  59. package/dist/services/core/websocket/connection-service.js.map +1 -1
  60. package/dist/services/core/websocket/types.js.map +1 -1
  61. package/dist/services/index.js +6 -0
  62. package/dist/services/index.js.map +1 -1
  63. package/dist/services/task/Task.js +955 -0
  64. package/dist/services/task/Task.js.map +1 -0
  65. package/dist/services/task/TaskFactory.js +50 -0
  66. package/dist/services/task/TaskFactory.js.map +1 -0
  67. package/dist/services/task/TaskManager.js +1275 -504
  68. package/dist/services/task/TaskManager.js.map +1 -1
  69. package/dist/services/task/TaskUtils.js +221 -27
  70. package/dist/services/task/TaskUtils.js.map +1 -1
  71. package/dist/services/task/WebexCallingUtils.js +70 -0
  72. package/dist/services/task/WebexCallingUtils.js.map +1 -0
  73. package/dist/services/task/constants.js +22 -2
  74. package/dist/services/task/constants.js.map +1 -1
  75. package/dist/services/task/contact.js +29 -0
  76. package/dist/services/task/contact.js.map +1 -1
  77. package/dist/services/task/dialer.js +78 -0
  78. package/dist/services/task/dialer.js.map +1 -1
  79. package/dist/services/task/digital/Digital.js +78 -0
  80. package/dist/services/task/digital/Digital.js.map +1 -0
  81. package/dist/services/task/state-machine/TaskStateMachine.js +982 -0
  82. package/dist/services/task/state-machine/TaskStateMachine.js.map +1 -0
  83. package/dist/services/task/state-machine/actions.js +572 -0
  84. package/dist/services/task/state-machine/actions.js.map +1 -0
  85. package/dist/services/task/state-machine/constants.js +161 -0
  86. package/dist/services/task/state-machine/constants.js.map +1 -0
  87. package/dist/services/task/state-machine/guards.js +379 -0
  88. package/dist/services/task/state-machine/guards.js.map +1 -0
  89. package/dist/services/task/state-machine/index.js +53 -0
  90. package/dist/services/task/state-machine/index.js.map +1 -0
  91. package/dist/services/task/state-machine/types.js +54 -0
  92. package/dist/services/task/state-machine/types.js.map +1 -0
  93. package/dist/services/task/state-machine/uiControlsComputer.js +703 -0
  94. package/dist/services/task/state-machine/uiControlsComputer.js.map +1 -0
  95. package/dist/services/task/taskDataNormalizer.js +99 -0
  96. package/dist/services/task/taskDataNormalizer.js.map +1 -0
  97. package/dist/services/task/types.js +259 -5
  98. package/dist/services/task/types.js.map +1 -1
  99. package/dist/services/task/voice/Voice.js +1504 -0
  100. package/dist/services/task/voice/Voice.js.map +1 -0
  101. package/dist/services/task/voice/WebRTC.js +152 -0
  102. package/dist/services/task/voice/WebRTC.js.map +1 -0
  103. package/dist/services/task/voice/wxAppOfferObservability.js +145 -0
  104. package/dist/services/task/voice/wxAppOfferObservability.js.map +1 -0
  105. package/dist/services/task/voice/wxAppVoiceMethods.js +395 -0
  106. package/dist/services/task/voice/wxAppVoiceMethods.js.map +1 -0
  107. package/dist/services/wxAppDiagnosticLogging.js +159 -0
  108. package/dist/services/wxAppDiagnosticLogging.js.map +1 -0
  109. package/dist/services/wxAppTelephonyUtils.js +19 -0
  110. package/dist/services/wxAppTelephonyUtils.js.map +1 -0
  111. package/dist/types/cc.d.ts +222 -10
  112. package/dist/types/config.d.ts +13 -0
  113. package/dist/types/constants.d.ts +40 -1
  114. package/dist/types/index.d.ts +58 -22
  115. package/dist/types/metrics/MetricsManager.d.ts +6 -0
  116. package/dist/types/metrics/constants.d.ts +52 -1
  117. package/dist/types/services/AddressBook.d.ts +2 -1
  118. package/dist/types/services/AnswerCallOnWebexService.d.ts +38 -0
  119. package/dist/types/services/ApiAiAssistant.d.ts +67 -5
  120. package/dist/types/services/EntryPoint.d.ts +7 -5
  121. package/dist/types/services/Queue.d.ts +5 -3
  122. package/dist/types/services/UserPreference.d.ts +118 -0
  123. package/dist/types/services/WebexCrossClientService.d.ts +32 -0
  124. package/dist/types/services/WxAppTelephonyMercurySync.d.ts +28 -0
  125. package/dist/types/services/config/Util.d.ts +4 -8
  126. package/dist/types/services/config/constants.d.ts +49 -76
  127. package/dist/types/services/config/index.d.ts +16 -64
  128. package/dist/types/services/config/types.d.ts +252 -114
  129. package/dist/types/services/constants.d.ts +16 -0
  130. package/dist/types/services/core/Err.d.ts +6 -0
  131. package/dist/types/services/core/Utils.d.ts +43 -13
  132. package/dist/types/services/core/WebexRequest.d.ts +1 -0
  133. package/dist/types/services/core/constants.d.ts +7 -0
  134. package/dist/types/services/core/types.d.ts +2 -0
  135. package/dist/types/services/core/websocket/WebSocketManager.d.ts +2 -0
  136. package/dist/types/services/core/websocket/types.d.ts +1 -1
  137. package/dist/types/services/index.d.ts +2 -0
  138. package/dist/types/services/task/Task.d.ts +186 -0
  139. package/dist/types/services/task/TaskFactory.d.ts +14 -0
  140. package/dist/types/services/task/TaskUtils.d.ts +54 -2
  141. package/dist/types/services/task/WebexCallingUtils.d.ts +11 -0
  142. package/dist/types/services/task/constants.d.ts +20 -0
  143. package/dist/types/services/task/contact.d.ts +4 -0
  144. package/dist/types/services/task/dialer.d.ts +30 -0
  145. package/dist/types/services/task/digital/Digital.d.ts +23 -0
  146. package/dist/types/services/task/state-machine/TaskStateMachine.d.ts +1442 -0
  147. package/dist/types/services/task/state-machine/actions.d.ts +10 -0
  148. package/dist/types/services/task/state-machine/constants.d.ts +107 -0
  149. package/dist/types/services/task/state-machine/guards.d.ts +103 -0
  150. package/dist/types/services/task/state-machine/index.d.ts +13 -0
  151. package/dist/types/services/task/state-machine/types.d.ts +277 -0
  152. package/dist/types/services/task/state-machine/uiControlsComputer.d.ts +9 -0
  153. package/dist/types/services/task/taskDataNormalizer.d.ts +10 -0
  154. package/dist/types/services/task/types.d.ts +790 -66
  155. package/dist/types/services/task/voice/Voice.d.ts +241 -0
  156. package/dist/types/services/task/voice/WebRTC.d.ts +54 -0
  157. package/dist/types/services/task/voice/wxAppOfferObservability.d.ts +39 -0
  158. package/dist/types/services/task/voice/wxAppVoiceMethods.d.ts +68 -0
  159. package/dist/types/services/wxAppDiagnosticLogging.d.ts +63 -0
  160. package/dist/types/services/wxAppTelephonyUtils.d.ts +5 -0
  161. package/dist/types/types.d.ts +258 -11
  162. package/dist/types/utils/PageCache.d.ts +20 -3
  163. package/dist/types/webex.d.ts +1 -0
  164. package/dist/types.js +204 -6
  165. package/dist/types.js.map +1 -1
  166. package/dist/utils/PageCache.js +19 -5
  167. package/dist/utils/PageCache.js.map +1 -1
  168. package/dist/webex.js +22 -2
  169. package/dist/webex.js.map +1 -1
  170. package/docs/adr/0001-spec-source-policy.md +97 -0
  171. package/docs/adr/0002-consult-transfer-list-policy.md +345 -0
  172. package/docs/adr/0003-repo-standards-migration.md +104 -0
  173. package/docs/adr/index.md +35 -0
  174. package/docs/architecture.md +460 -0
  175. package/docs/getting-started.md +142 -0
  176. package/docs/index.md +53 -0
  177. package/docs/specs/README.md +98 -0
  178. package/package.json +17 -12
  179. package/schemas/repo-context.schema.json +796 -0
  180. package/src/cc.ts +1439 -105
  181. package/src/config.ts +13 -0
  182. package/src/constants.ts +53 -1
  183. package/src/docs/README.md +727 -0
  184. package/src/index.ts +72 -16
  185. package/src/metrics/MetricsManager.ts +16 -0
  186. package/src/metrics/behavioral-events.ts +218 -0
  187. package/src/metrics/constants.ts +63 -4
  188. package/src/metrics/docs/README.md +710 -0
  189. package/src/services/AddressBook.ts +17 -6
  190. package/src/services/AnswerCallOnWebexService.ts +239 -0
  191. package/src/services/ApiAiAssistant.ts +494 -15
  192. package/src/services/EntryPoint.ts +59 -60
  193. package/src/services/Queue.ts +29 -12
  194. package/src/services/UserPreference.ts +509 -0
  195. package/src/services/WebCallingService.ts +362 -40
  196. package/src/services/WebexCrossClientService.ts +298 -0
  197. package/src/services/WxAppTelephonyMercurySync.ts +142 -0
  198. package/src/services/agent/docs/README.md +673 -0
  199. package/src/services/config/Util.ts +54 -84
  200. package/src/services/config/constants.ts +64 -86
  201. package/src/services/config/docs/README.md +530 -0
  202. package/src/services/config/index.ts +116 -277
  203. package/src/services/config/types.ts +238 -125
  204. package/src/services/constants.ts +18 -0
  205. package/src/services/core/Err.ts +3 -0
  206. package/src/services/core/Utils.ts +151 -37
  207. package/src/services/core/WebexRequest.ts +3 -1
  208. package/src/services/core/aqm-reqs.ts +18 -12
  209. package/src/services/core/constants.ts +8 -0
  210. package/src/services/core/docs/README.md +993 -0
  211. package/src/services/core/types.ts +33 -1
  212. package/src/services/core/websocket/WebSocketManager.ts +37 -8
  213. package/src/services/core/websocket/connection-service.ts +5 -1
  214. package/src/services/core/websocket/types.ts +1 -1
  215. package/src/services/docs/README.md +765 -0
  216. package/src/services/index.ts +4 -0
  217. package/src/services/task/Task.ts +1211 -0
  218. package/src/services/task/TaskFactory.ts +82 -0
  219. package/src/services/task/TaskManager.ts +1551 -584
  220. package/src/services/task/TaskUtils.ts +316 -25
  221. package/src/services/task/WebexCallingUtils.ts +136 -0
  222. package/src/services/task/constants.ts +21 -0
  223. package/src/services/task/contact.ts +30 -0
  224. package/src/services/task/dialer.ts +80 -0
  225. package/src/services/task/digital/Digital.ts +102 -0
  226. package/src/services/task/docs/README.md +1569 -0
  227. package/src/services/task/state-machine/TaskStateMachine.ts +1320 -0
  228. package/src/services/task/state-machine/actions.ts +741 -0
  229. package/src/services/task/state-machine/constants.ts +172 -0
  230. package/src/services/task/state-machine/docs/README.md +1388 -0
  231. package/src/services/task/state-machine/guards.ts +442 -0
  232. package/src/services/task/state-machine/index.ts +28 -0
  233. package/src/services/task/state-machine/types.ts +258 -0
  234. package/src/services/task/state-machine/uiControlsComputer.ts +1135 -0
  235. package/src/services/task/taskDataNormalizer.ts +137 -0
  236. package/src/services/task/types.ts +974 -70
  237. package/src/services/task/voice/Voice.ts +1878 -0
  238. package/src/services/task/voice/WebRTC.ts +194 -0
  239. package/src/services/task/voice/wxAppOfferObservability.ts +204 -0
  240. package/src/services/task/voice/wxAppVoiceMethods.ts +575 -0
  241. package/src/services/wxAppDiagnosticLogging.ts +286 -0
  242. package/src/services/wxAppTelephonyUtils.ts +14 -0
  243. package/src/types.ts +323 -13
  244. package/src/utils/AGENTS.md +291 -0
  245. package/src/utils/PageCache.ts +38 -5
  246. package/src/utils/docs/README.md +413 -0
  247. package/src/webex.js +10 -0
  248. package/test/unit/fixtures/aiSummaryTestUtils.ts +40 -0
  249. package/test/unit/spec/cc.ts +4046 -181
  250. package/test/unit/spec/index.ts +891 -0
  251. package/test/unit/spec/logger-proxy.ts +70 -0
  252. package/test/unit/spec/metrics/MetricsManager.ts +25 -0
  253. package/test/unit/spec/metrics/behavioral-events.ts +60 -0
  254. package/test/unit/spec/services/AddressBook.ts +37 -6
  255. package/test/unit/spec/services/AnswerCallOnWebexService.ts +264 -0
  256. package/test/unit/spec/services/ApiAiAssistant.ts +442 -23
  257. package/test/unit/spec/services/EntryPoint.ts +87 -40
  258. package/test/unit/spec/services/Queue.ts +123 -12
  259. package/test/unit/spec/services/UserPreference.ts +401 -0
  260. package/test/unit/spec/services/WebCallingService.ts +484 -49
  261. package/test/unit/spec/services/WebexCrossClientService.ts +509 -0
  262. package/test/unit/spec/services/WxAppTelephonyMercurySync.ts +136 -0
  263. package/test/unit/spec/services/config/Util.ts +501 -0
  264. package/test/unit/spec/services/config/index.ts +318 -548
  265. package/test/unit/spec/services/core/Utils.ts +447 -8
  266. package/test/unit/spec/services/core/WebexRequest.ts +8 -7
  267. package/test/unit/spec/services/core/aqm-reqs.ts +142 -1
  268. package/test/unit/spec/services/core/websocket/WebSocketManager.ts +132 -56
  269. package/test/unit/spec/services/core/websocket/connection-service.ts +3 -1
  270. package/test/unit/spec/services/task/AutoWrapup.ts +63 -0
  271. package/test/unit/spec/services/task/Task.ts +2723 -0
  272. package/test/unit/spec/services/task/TaskFactory.ts +116 -0
  273. package/test/unit/spec/services/task/TaskManager.ts +4800 -1586
  274. package/test/unit/spec/services/task/TaskUtils.ts +307 -0
  275. package/test/unit/spec/services/task/WebexCallingUtils.ts +153 -0
  276. package/test/unit/spec/services/task/contact.ts +33 -0
  277. package/test/unit/spec/services/task/dialer.ts +190 -0
  278. package/test/unit/spec/services/task/digital/Digital.ts +105 -0
  279. package/test/unit/spec/services/task/state-machine/TaskStateMachine.ts +4060 -0
  280. package/test/unit/spec/services/task/state-machine/guards.ts +839 -0
  281. package/test/unit/spec/services/task/state-machine/types.ts +18 -0
  282. package/test/unit/spec/services/task/state-machine/uiControlsComputer.ts +3101 -0
  283. package/test/unit/spec/services/task/taskTestUtils.ts +87 -0
  284. package/test/unit/spec/services/task/voice/Voice.ts +2355 -0
  285. package/test/unit/spec/services/task/voice/WebRTC.ts +235 -0
  286. package/test/unit/spec/services/task/voice/wxAppOfferObservability.ts +361 -0
  287. package/test/unit/spec/services/task/voice/wxAppVoiceMethods.ts +719 -0
  288. package/test/unit/spec/services/wxAppDiagnosticLogging.ts +179 -0
  289. package/test/unit/spec/wellnessSampleUtils.ts +288 -0
  290. package/typedoc.md +1 -1
  291. package/umd/contact-center.min.js +2 -2
  292. package/umd/contact-center.min.js.map +1 -1
  293. package/dist/services/task/index.js +0 -1525
  294. package/dist/services/task/index.js.map +0 -1
  295. package/dist/types/services/task/index.d.ts +0 -650
  296. package/src/services/task/index.ts +0 -1801
  297. package/test/unit/spec/services/task/index.ts +0 -2184
@@ -0,0 +1,993 @@
1
+ ---
2
+ type: Module Spec
3
+ title: 'Core service specification'
4
+ description: Responsibilities, boundaries, design, invariants, and verification for the Contact Center core transport module (authenticated HTTP, the notification WebSocket, AQM request correlation, reconnect and keepalive, and shared error helpers).
5
+ tags: [module, specification]
6
+ ---
7
+ <!-- sdd-generated-metadata
8
+ doc_kind: module-spec
9
+ generated_from: module-spec@0.3.0
10
+ generated_by: claude-code
11
+ approved_by: rarajes2@cisco.com
12
+ updated_at: 2026-11-17T03:03:58Z
13
+ validation_status: pass-with-warnings
14
+ -->
15
+
16
+ # Core service
17
+
18
+ This source-local document at `src/services/core/docs/README.md` owns the stable specification for
19
+ **the core service** of `@webex/contact-center`. Core infrastructure components include WebSocket
20
+ management, HTTP requests, error handling, and utilities that the agent, config, task, dialer, and
21
+ plugin layers build on. Ground every claim in package evidence and link to the
22
+ [package architecture](../../../../docs/architecture.md) instead of repeating broader facts. The
23
+ parent [services specification](../../docs/README.md) owns the composition of these pieces into the
24
+ `Services` singleton.
25
+
26
+ Related context: [documentation index](../../../../docs/index.md) ·
27
+ [package agent instructions](../../../../AGENTS.md)
28
+
29
+ ## Metadata
30
+
31
+ | Field | Value |
32
+ |---|---|
33
+ | Owner | @webex/web-sdk |
34
+ | Source path | `src/services/core` |
35
+ | Resource kind | module |
36
+ | Status | Active |
37
+ | Last verified | 2026-11-16 at `0b8c34db7f` |
38
+ | Module id | `core` |
39
+ | Parent spec | [src/services](../../docs/README.md) |
40
+ | Doc kind | Module spec |
41
+ | Coverage score | Pending coverage assessment |
42
+ | Validation status | pass-with-warnings — assessed 2026-11-17; validator runtime 01a1e76f-2293-79a0-9f8f-f060038448dd; 0 Blocking, 0 Important, 4 Minor findings. |
43
+
44
+ ## Applicability
45
+
46
+ | Condition ID | Status | Evidence or reason | Owned section |
47
+ | ------------ | ------ | ------------------ | ------------- |
48
+ | `module.has_tiers` | N/A | The package defines no module tiers (`.sdd/manifest.json` profile sets has_tiers to false) | Tier |
49
+ | `module.has_ui` | N/A | No rendering code; every surface is a class, function, or event | UI use-case flow |
50
+ | `module.crosses_service_boundaries` | Applicable | `src/services/core/websocket/WebSocketManager.ts` calls the notification subscribe API and opens a WebSocket; `src/services/core/WebexRequest.ts` calls the WCC API gateway and the support log-upload service | Cross-boundary use-case flow |
51
+ | `module.holds_client_state` | Applicable | Socket, welcome, worker, pending-bind, timer, and connection flags in `src/services/core/websocket/WebSocketManager.ts`, `src/services/core/aqm-reqs.ts`, and `src/services/core/websocket/connection-service.ts` | Client state model |
52
+ | `module.enforces_domain_rules` | Applicable | The wss allow-list check, the duplicate-pending rejection, and the log-redaction rules in `src/services/core/websocket/WebSocketManager.ts` and `src/services/core/aqm-reqs.ts` | Business rules and invariants |
53
+ | `module.is_concurrent_async` | Applicable | Event-emitter fan-out, a keepalive Web Worker, and timer-driven reconnect in `src/services/core/websocket/connection-service.ts` and `src/services/core/websocket/keepalive.worker.js` | Concurrency and reactive flow |
54
+ | `module.owns_persistence` | N/A | Nothing in the module writes storage; all state is in memory | Data, schema, and migration discipline |
55
+ | `module.stateful_transitions` | Applicable | Socket lifecycle and connection-lost, reconnected, and restore-failed transitions in `src/services/core/websocket/connection-service.ts` | State machine |
56
+ | `module.exposes_wire_protocol` | Applicable | Subscribe request and response, the keepalive frame, the worker message contract, and the AQM bind matching in `src/services/core/websocket/WebSocketManager.ts` and `src/services/core/aqm-reqs.ts` | Protocol and wire format |
57
+ | `module.ui_multi_screen` | N/A | No UI | UI flow |
58
+ | `module.large_data_model` | N/A | The module's types (`src/services/core/types.ts`, `src/services/core/GlobalTypes.ts`, `src/services/core/websocket/types.ts`) are small request, message, and connection-state shapes | Data model |
59
+ | `module.returns_caller_errors` | Applicable | Err.Details and Err.Message rejections from `src/services/core/aqm-reqs.ts`, and the helpers in `src/services/core/Utils.ts` | Caller-visible failure modes |
60
+ | `module.module_specific_conventions` | Applicable | Error-helper, constants, redaction, and listener rules recorded under Module-specific rules, enforced by `src/services/core/Utils.ts` and `src/services/core/aqm-reqs.ts` | Module-specific rules |
61
+ | `module.published_package` | N/A | `src/index.ts` exports no core symbol; the module is internal to the package | Export stability |
62
+ | `module.embedded_in_host` | N/A | The package-level host integration is owned by the package root module | Host integration and theming |
63
+ | `module.has_design_tradeoff` | Applicable | HTTP initiation with WebSocket completion in `src/services/core/aqm-reqs.ts`; transport-only recovery in `src/services/core/websocket/connection-service.ts` | Key design trade-off |
64
+ | `module.has_submodules` | N/A | The websocket folder is part of this module; the plugin's module_tree.py reports no child module | Sub-modules |
65
+
66
+ ## Evidence register
67
+
68
+ | Evidence | What it establishes |
69
+ | -------- | ------------------- |
70
+ | `src/services/core/WebexRequest.ts` | Singleton `WebexRequest`: `getInstance`, `request` (service, resource, method, body, optional headers), and `uploadLogs` with metrics |
71
+ | `src/services/core/aqm-reqs.ts` | `AqmReqs`: `req`, `reqEmpty`, bind keys, pending maps, duplicate rejection, HTTP failure masking, timeout, and redaction |
72
+ | `src/services/core/types.ts` | `Req`, `Conf`, `ConfEmpty`, `Res`, `ResEmpty`, `CbRes`, `Pending`, `Timeout`, and the RTD request types |
73
+ | `src/services/core/websocket/WebSocketManager.ts` | Subscribe registration, the `wss` allow-list check, socket handlers, keepalive worker wiring, welcome resolution, multi-login close, and `message`/`socketClose` events |
74
+ | `src/services/core/websocket/connection-service.ts` | Liveness timers, reconnect interval, restore failure, and the `connectionLost` event; the member subsections under Class and component relationships are justified by this file and `src/services/core/websocket/WebSocketManager.ts` |
75
+ | `src/services/core/websocket/keepalive.worker.js` | The worker script, its `start`/`terminate` inputs, and its `keepalive`/`closeSocket` outputs |
76
+ | `src/services/core/websocket/types.ts` | `ConnectionServiceOptions`, `ConnectionLostDetails`, `ConnectionProp` |
77
+ | `src/services/core/constants.ts` | Timer values, `ALLOWED_ROUTING_NOTIFS_DOMAINS`, participant constants, and method-name constants |
78
+ | `src/services/core/Utils.ts`, `src/services/core/Err.ts`, `src/services/core/GlobalTypes.ts` | Error helpers, the `Err` classes and error-id types, and `Msg`, `Failure`, `TaskError`, `AugmentedError` |
79
+ | `src/services/index.ts`, `src/cc.ts` | Consumers: construction order, the second RTD `WebSocketManager`, `connectWebsocket`, `handleConnectionLost`, and the `allowAutomatedRelogin` relogin policy |
80
+ | `src/services/constants.ts`, `src/services/config/types.ts`, `src/types.ts` | `WCC_API_GATEWAY`, `SUBSCRIBE_API`, `RTD_SUBSCRIBE_API`, `CC_EVENTS`, `SubscribeResponse`, `WelcomeResponse`, and the shared request types |
81
+ | `test/unit/spec/services/core/WebexRequest.ts`, `test/unit/spec/services/core/aqm-reqs.ts`, `test/unit/spec/services/core/Utils.ts` | Unit cases for request delegation, log upload, AQM settlement and redaction, and the error and URL helpers |
82
+ | `test/unit/spec/services/core/websocket/WebSocketManager.ts`, `test/unit/spec/services/core/websocket/connection-service.ts` | Unit cases for URL validation, the INT header, close paths, multi-login, timers, and reconnect |
83
+ | `src/services/core/WebexRequest.ts`, `src/services/core/websocket/WebSocketManager.ts`, `src/services/core/aqm-reqs.ts`, `src/services/core/websocket/connection-service.ts` (Data flow extension subsections) | One sequence subsection per operation group of the Data flow inventory: WebexRequest (request and uploadLogs), Subscribe and connect, Correlated request, and Connection lifecycle |
84
+ | `src/services/index.ts` (no feature gate) | `Services` constructs `WebSocketManager`, `AqmReqs`, and `ConnectionService` unconditionally; no rollout flag gates Core. No test observes this absence |
85
+ | `jest.config.js` | The 85% global branch, function, line, and statement threshold |
86
+
87
+ ## Purpose and boundary
88
+
89
+ Core is the foundational infrastructure layer that all other services depend on. It owns authenticated HTTP to the WCC API Gateway with log upload support, the realtime WebSocket lifecycle with automatic reconnection and keepalive management, AQM request correlation (HTTP requests whose responses/failures are correlated via WebSocket notifications), and shared error normalization: standardized error extraction, logging via `LoggerProxy`, and log upload.
90
+
91
+ Boundary:
92
+
93
+ - Responsibility: the four concerns above, plus the shared consult and dial-number helpers in
94
+ `src/services/core/Utils.ts`.
95
+ - In scope: every file under `src/services/core`, including `websocket/`.
96
+ - Out of scope: agent credentials, the agent profile, and the silent-relogin decision (the
97
+ ContactCenter plugin in `src/cc.ts`); composing the services (`src/services/index.ts`, parent spec);
98
+ the meaning of individual AQM operations (the agent, task, and dialer modules that call `req`).
99
+ - Consumers: `Services` constructs `WebSocketManager`, `AqmReqs`, and `ConnectionService`; `src/cc.ts`
100
+ calls `initWebSocket`, `close`, and listens to `message` and `connectionLost`; `TaskManager`
101
+ listens to `message` on both sockets; the agent, contact, and dialer factories call `req`; many
102
+ service files call `WebexRequest`, `getErrorDetails`, `generateTaskErrorObject`, and the consult
103
+ helpers.
104
+
105
+ ## Structure and key files
106
+
107
+ ```text
108
+ services/core/
109
+ ├── aqm-reqs.ts # AQM request handler
110
+ ├── constants.ts # Core constants
111
+ ├── Err.ts # Error classes
112
+ ├── GlobalTypes.ts # Failure, Msg<T>, etc.
113
+ ├── types.ts # Request/response types
114
+ ├── Utils.ts # Utility functions
115
+ ├── WebexRequest.ts # HTTP client
116
+ └── websocket/
117
+ ├── WebSocketManager.ts # Main WS handler
118
+ ├── connection-service.ts # Connection lifecycle
119
+ ├── keepalive.worker.js # Keepalive worker
120
+ └── types.ts # WS types
121
+ ```
122
+
123
+ | Component | File | Description |
124
+ |---|---|---|
125
+ | `WebSocketManager` | [`WebSocketManager.ts`](../websocket/WebSocketManager.ts) | Manages the WebSocket connection lifecycle including initialization, message dispatch, keepalive worker integration, and graceful shutdown. Validates the subscribe/register `webSocketUrl` against the RoutingNotifs allow-list before opening a socket. Emits `message` events for incoming data and `socketClose` when the connection drops while reconnect is allowed. |
126
+ | `ConnectionService` | [`connection-service.ts`](../websocket/connection-service.ts) | Orchestrates reconnection logic and keepalive heartbeats on top of `WebSocketManager`. Detects connection loss/recovery and emits `connectionLost` details; ContactCenter owns any `silentRelogin()` policy. |
127
+ | `WebexRequest` | [`WebexRequest.ts`](../WebexRequest.ts) | Singleton HTTP client that forwards service/resource/method/body options to the authenticated host request API and provides `uploadLogs` diagnostics. |
128
+ | `AqmReqs` | [`aqm-reqs.ts`](../aqm-reqs.ts) | Factory for creating request methods that send HTTP requests and wait for correlated WebSocket notifications (success or failure): the AQM request/response pattern and WebSocket notification binding, with the pending maps and timeout. Used by routing and task services to implement their API methods. |
129
+ | `Utils` | [`Utils.ts`](../Utils.ts) | Shared utility functions including `getErrorDetails()` for standardized error handling, `generateTaskErrorObject()` for task-specific errors, and `createErrDetailsObject()` for constructing error detail objects; also `getStationLoginErrorData`, `isAllowedUrlHost`, `isValidDialNumber`, `stripDialPlanChars`, and the consult utilities (`getConsultedAgentId`, `getDestAgentIdForCBT`, `calculateDestAgentId`, `calculateDestType`, `buildConsultConferenceParamData`, `deriveConsultTransferDestinationType`). |
130
+ | `Err` | [`Err.ts`](../Err.ts) | Error class definitions: `Err.Message` and `Err.Details` error classes and the typed error-id unions. `Err.Details` carries structured error metadata (status, type, trackingId) for consistent error propagation. |
131
+ | `constants` | [`constants.ts`](../constants.ts) | Timeout values, interval durations, participant types, interaction states, method name constants, and the `ALLOWED_ROUTING_NOTIFS_DOMAINS` WebSocket host allow-list used throughout the core layer. Any new constants for core should be defined here. |
132
+ | `GlobalTypes` | [`GlobalTypes.ts`](../GlobalTypes.ts) | `Msg`, `Failure`, `TaskError`, `AugmentedError` type definitions. |
133
+ | `types` | [`types.ts`](../types.ts) | `Pending`, `Req`, `Conf`, `Res` types for AqmReqs, plus the internal RTD request types. |
134
+ | keepalive worker | [`keepalive.worker.js`](../websocket/keepalive.worker.js) | Web Worker for periodic keepalive and offline detection, exported as a script string. |
135
+ | websocket `types` | [`types.ts`](../websocket/types.ts) | `ConnectionServiceOptions`, `ConnectionLostDetails`, `ConnectionProp`. |
136
+
137
+ Files outside the source layout above:
138
+
139
+ | Path | Responsibility |
140
+ | ---- | -------------- |
141
+ | `src/services/core/docs/README.md` | This module specification |
142
+ | test/unit/spec/services/core (directory) | Unit tests mirroring the source layout, including the websocket folder |
143
+
144
+ ## Public surface
145
+
146
+ The module is internal to the package: `src/index.ts` exports none of it. Its consumption boundary is
147
+ contract `contact-center-core-transport` (internal SDK contract, canonical source
148
+ `src/services/core/aqm-reqs.ts`), indexed in the
149
+ [package architecture](../../../../docs/architecture.md).
150
+
151
+ | Surface | Consumer | Compatibility commitment | Source |
152
+ | ------- | -------- | ------------------------ | ------ |
153
+ | `contact-center-core-transport`: `AqmReqs` (`req`, `reqEmpty`) and the `Req` configuration | Agent, contact, and dialer factories | Internal; additive config fields only, every in-package caller updated in the same change | `src/services/core/aqm-reqs.ts`, `src/services/core/types.ts` |
154
+ | `contact-center-core-transport`: `WebexRequest.getInstance`, `request`, `uploadLogs` | `src/cc.ts`, config and other services, the error helpers | Internal; `request` returns or rejects with the host result unchanged | `src/services/core/WebexRequest.ts` |
155
+ | `contact-center-core-transport`: `WebSocketManager` (`initWebSocket`, `close`, `handleConnectionLost`, `shouldReconnect`, `isSocketClosed`, events `message` and `socketClose`) | `Services`, `src/cc.ts`, `TaskManager`, `AqmReqs`, `ConnectionService` | Internal; event names are string literals that listeners depend on | `src/services/core/websocket/WebSocketManager.ts` |
156
+ | `contact-center-core-transport`: `ConnectionService` (`setConnectionProp`, event `connectionLost` with `ConnectionLostDetails`) | `src/cc.ts` | Internal; ContactCenter reads `isConnectionLost` and `isSocketReconnected` | `src/services/core/websocket/connection-service.ts`, `src/services/core/websocket/types.ts` |
157
+ | `contact-center-core-transport`: error and utility helpers, `Err` classes, `Msg`, `Failure`, `AugmentedError` | Agent, config, task, and plugin code | Internal; error `message` and `data` shapes are observed by callers | `src/services/core/Utils.ts`, `src/services/core/Err.ts`, `src/services/core/GlobalTypes.ts` |
158
+
159
+ | Event | Data | Description |
160
+ |---|---|---|
161
+ | `message` | string (JSON) | WebSocket message received |
162
+ | `socketClose` | - | Socket closed while reconnect is allowed |
163
+ | `connectionLost` | `ConnectionLostDetails` | Emitted by `ConnectionService` on lost, recovered, reconnected, and restore-failed transitions, and on every keepalive echo |
164
+
165
+ Generic message wrapper used throughout the SDK. All WebSocket messages and AQM responses conform to this shape:
166
+ `Msg<T>` in [GlobalTypes.ts](../GlobalTypes.ts) carries `type`, `orgId`, `trackingId`, and a `data` payload of type `T`, so a typed event such as a login success is declared as `Msg<{agentId, status, ...}>` and arrives as `{type, orgId, trackingId, data: {agentId, status, ...}}`.
167
+
168
+ Do not remove or reinterpret exported symbols/events without a documented consumer migration.
169
+
170
+ ## Dependencies
171
+
172
+ | Dependency | Why it is required | Failure behavior |
173
+ | ---------- | ------------------ | ---------------- |
174
+ | Webex SDK service catalog and authenticated request API (`webex.request`, contracts `webex-core-plugin-runtime` and `wxcc-api-gateway`) | Every REST call and the subscribe registration; the host resolves the `service` key and adds authentication | Rejections propagate unchanged through `WebexRequest.request`; `AqmReqs` maps them (CORE-R-010) |
175
+ | Notification WebSocket (contract `wxcc-websocket-notifications`) | Delivers the welcome event, keepalive echoes, and every AQM result | Close and error handlers; recovery per Connection lifecycle |
176
+ | `webex.internal.support.submitLogs` (contract `webex-internal-support`) | `uploadLogs` diagnostics | Logged, tracked as `UPLOAD_LOGS_FAILED`, and rethrown |
177
+ | `webex.credentials.getOrgId`, `webex.internal.services.isIntegrationEnvironment` | The `X-ORGANIZATION-ID` header on the subscribe call in INT environments | A missing `isIntegrationEnvironment` is treated as production (no header) |
178
+ | Browser WebSocket, Worker, URL and network-status APIs | Socket, keepalive worker (`Blob` + `URL.createObjectURL`), URL validation, `navigator.onLine` | Offline reconnect attempts throw and retry on the next interval |
179
+ | LoggerProxy and log upload | Every diagnostic line and the error helpers' upload | Fire and forget in the helpers |
180
+ | `MetricsManager` (`src/metrics/MetricsManager.ts`) | `UPLOAD_LOGS_SUCCESS` and `UPLOAD_LOGS_FAILED` behavioral events | Not awaited |
181
+ | `src/services/constants.ts`, `src/services/config/types.ts` | `WCC_API_GATEWAY`, `SUBSCRIBE_API`, `CC_EVENTS.WELCOME`, `SubscribeResponse`, `WelcomeResponse` | Compile-time |
182
+ | `src/types.ts` | Shared `WebexSDK`, `HTTP_METHODS`, `RequestBody`, `IHttpResponse`, `LogsMetaData`, `UploadLogsResponse`, `SubscribeRequest`, `WebexRequestPayload`, `LoginOption` types | Compile-time |
183
+ | `src/services/task/types.ts` | Interaction and destination types for the consult helpers in `Utils.ts` | Compile-time |
184
+
185
+ ## Requirements
186
+
187
+ | ID | WHAT | WHY | Source Evidence | Test / Example Evidence | Assumptions / Gaps | Confidence |
188
+ |---|---|---|---|---|---|---|
189
+ | CORE-R-001 | WebexRequest must delegate service/resource/method/body options to the authenticated host request API and return or reject with the host result unchanged. | All Contact Center REST clients share host-owned authentication and service routing without duplicating credential logic. | `src/services/core/WebexRequest.ts` | `test/unit/spec/services/core/WebexRequest.ts` | Authorization-header masking belongs to `AqmReqs` HTTP-failure handling, not `WebexRequest.request`. | PRESENT |
190
+ | CORE-R-002 | `initWebSocket` requires `{body: SubscribeRequest, resource: string}` and resolves only after WebSocket welcome or rejects on register/connect failure. | Subscription resource selection and readiness are required for a valid realtime session. | `src/services/core/websocket/WebSocketManager.ts` | `test/unit/spec/services/core/websocket/WebSocketManager.ts` | No welcome timeout: a socket that opens but never sends the welcome leaves the promise pending (`WELCOME_TIMEOUT` is defined but unused). | PRESENT |
191
+ | CORE-R-003 | AqmReqs must be constructed with the primary WebSocket manager and settle generated request promises from `notifSuccess`/`notifFail` binds or `TIMEOUT_REQ`. | HTTP acknowledgement alone does not represent backend operation completion. | `src/services/core/aqm-reqs.ts` | `test/unit/spec/services/core/aqm-reqs.ts` | None. | PRESENT |
192
+ | CORE-R-004 | ConnectionService must emit transport-state details and retry `initWebSocket({body, resource})`; ContactCenter owns relogin policy. | Separating transport detection from agent recovery prevents Core from mutating package-level session state. | `src/services/core/websocket/connection-service.ts` | `test/unit/spec/services/core/websocket/connection-service.ts` | None. | PRESENT |
193
+ | CORE-R-005 | The keepalive worker must use `KEEPALIVE_WORKER_INTERVAL` as its interval and `CLOSE_SOCKET_TIMEOUT` as its close-socket timeout, and AQM requests default to `TIMEOUT_REQ` unless disabled/overridden (values in the timer table under Concurrency and reactive flow). | Accurate timing is required for predictable recovery and request failure behavior. | `src/services/core/constants.ts`, `src/services/core/websocket/WebSocketManager.ts` | `test/unit/spec/services/core/aqm-reqs.ts` | No unit case asserts the worker `start` message values; the AQM default is asserted by the default-timeout case. | WEAK |
194
+ | CORE-R-007 | AQM routing-failure logging never emits the raw routing message payload or error verbatim; the failure-bind path logs only a fixed redacted diagnostic regardless of `redactSensitiveLogs`. When an AQM request additionally sets `redactSensitiveLogs`, timeout logs must also omit the request URL, bind key, and response while preserving settlement and cleanup behavior. | Dynamic request paths and routing messages can contain participant identifiers or phone numbers that must not enter diagnostic logs. | `src/services/core/aqm-reqs.ts`, `src/services/core/types.ts` | `test/unit/spec/services/core/aqm-reqs.ts` | The timeout flag is internal and opt-in; ordinary AQM logging remains backward compatible while routing-failure logging is unconditionally redacted. | PRESENT |
195
+ | CORE-R-008 | `WebSocketManager` opens a socket only for a subscribe/register `webSocketUrl` that parses as a `wss` URL whose host equals, or is a subdomain of, an entry in `ALLOWED_ROUTING_NOTIFS_DOMAINS`; a malformed, non-`wss`, or non-allow-listed URL is rejected with an error and no socket is opened. | A server-controlled subscribe response could otherwise direct the realtime connection to an untrusted or non-secure endpoint. | `src/services/core/websocket/WebSocketManager.ts`, `src/services/core/constants.ts` | `test/unit/spec/services/core/websocket/WebSocketManager.ts` | The allow-list is a fixed domain set; subdomain matching is exact suffix matching on the parsed hostname. | PRESENT |
196
+ | CORE-R-009 | When a pending request already holds the success bind key (or the failure bind key) and the new request's `timeout` is not `'disabled'`, the generated function rejects at once with `Err.Details('Service.aqm.reqs.Pending')` and sends no HTTP request. | The bind key is the only correlation handle, so two concurrent requests with the same bind could not be told apart; the error text says multiple requests are not allowed. | `src/services/core/aqm-reqs.ts`, `src/services/core/Err.ts` | None found | No unit case covers the duplicate rejection. | WEAK |
197
+ | CORE-R-010 | On an HTTP rejection AqmReqs clears all three bind entries, masks `headers.Authorization` to `*`, and rejects with `c.err(error)` when `err` is a function, `Err.Message(c.err)` when it is a string, and `Err.Message('Service.aqm.reqs.GenericRequestError')` otherwise. On timeout it masks the stored response's `Authorization` header and rejects with `Err.Details('Service.aqm.reqs.Timeout', {key, response})`. | The bearer token must not reach logs or surfaced errors, and each operation module chooses its own error mapping. | `src/services/core/aqm-reqs.ts` | `test/unit/spec/services/core/aqm-reqs.ts` | None. | PRESENT |
198
+ | CORE-R-011 | A `notifCancel` bind resolves the same promise as the success bind and is cleared with it. | Some operations finish with an alternate event (for example a participant leaving instead of a drop success), and the caller must still settle once. | `src/services/core/aqm-reqs.ts`, `src/services/core/types.ts` | `test/unit/spec/services/core/aqm-reqs.ts` | None. | PRESENT |
199
+ | CORE-R-012 | The subscribe call adds `X-ORGANIZATION-ID` (set to the org id) only when `webex.internal.services.isIntegrationEnvironment()` is true and an org id exists. | The in-code comment: the header is only required for INT environments. | `src/services/core/websocket/WebSocketManager.ts` | `test/unit/spec/services/core/websocket/WebSocketManager.ts` | None. | PRESENT |
200
+ | CORE-R-013 | An incoming `AGENT_MULTI_LOGIN` message closes the socket with `shouldReconnect` false and reason `multiLogin`, so no `socketClose` event and no reconnect follow. | A second login of the same agent replaces this session; reconnecting would fight it. | `src/services/core/websocket/WebSocketManager.ts` | `test/unit/spec/services/core/websocket/WebSocketManager.ts` | None. | PRESENT |
201
+ | CORE-R-014 | `uploadLogs(metaData)` submits diff logs with a fresh `feedbackId`, tracks `UPLOAD_LOGS_SUCCESS` or `UPLOAD_LOGS_FAILED`, resolves `{trackingid, feedbackId}` plus any returned `url`, `userId`, `correlationId`, and rethrows a failure. | The JSDoc: logs are uploaded to the backend for diagnostics; the `feedbackId` and `correlationId` let support find them. | `src/services/core/WebexRequest.ts` | `test/unit/spec/services/core/WebexRequest.ts` | None. | PRESENT |
202
+ | CORE-R-015 | `getErrorDetails` and `generateTaskErrorObject` keep the error shapes and the logging and log-upload side effects specified under Caller-visible failure modes. | Callers rely on one error shape per flow for metrics, UI messages, and station-login field hints. | `src/services/core/Utils.ts` | `test/unit/spec/services/core/Utils.ts` | `generateTaskErrorObject` has no unit case in this module's tests. | PRESENT |
203
+
204
+ ## Design overview
205
+
206
+ Stack: TypeScript/JavaScript, WebSocket, Web Worker keepalive, EventEmitter, Webex request client, Jest 27.
207
+
208
+ Core separates four responsibilities:
209
+
210
+ 1. `WebexRequest` wraps the authenticated host request API and service-catalog routing.
211
+ 2. `WebSocketManager` registers a subscription using both `body` and `resource`, validates the returned `webSocketUrl` against the `ALLOWED_ROUTING_NOTIFS_DOMAINS` allow-list before connecting the socket, owns the keepalive worker, and emits raw messages/socket lifecycle events.
212
+ 3. `AqmReqs` registers bind matchers on the primary WebSocket, sends HTTP through WebexRequest, and settles requests only from matching notifications, HTTP failure, or timeout.
213
+ 4. `ConnectionService` observes message/socket liveness, emits connection-state details, and retries socket initialization. ContactCenter listens to those details and owns optional silent relogin.
214
+
215
+ Component instantiation order (`Services` constructor in `src/services/index.ts`, after the plugin
216
+ has called `WebexRequest.getInstance({webex})` in `src/cc.ts`):
217
+
218
+ 1. **WebSocketManager** ([WebSocketManager.ts](../websocket/WebSocketManager.ts)) - Creates keepalive worker (not started); a second instance, `rtdWebSocketManager`, is created for the RTD socket and is not wired to `AqmReqs` or `ConnectionService`
219
+ 2. **AqmReqs** ([src/services/core/aqm-reqs.ts](../aqm-reqs.ts)) - Initialized with WebSocketManager reference
220
+ 3. **Service layers** (agent, contact, dialer) - Created with AqmReqs reference; config is created without it
221
+ 4. **ConnectionService** ([connection-service.ts](../websocket/connection-service.ts)) - Wires event listeners immediately
222
+
223
+ The AQM (Agent Queue Manager) layer provides a request/response pattern over HTTP + WebSocket. Services like **routing** and **contact** use `AqmReqs` to define API methods that:
224
+
225
+ 1. Send an HTTP request to the contact center backend via `WebexRequest`
226
+ 2. Wait for a correlated WebSocket notification indicating success or failure
227
+ 3. Return the typed result or throw a structured error
228
+
229
+ This decouples the request initiation (HTTP) from the asynchronous result delivery (WebSocket), which matches the contact center backend's event-driven architecture.
230
+
231
+ ```typescript
232
+ const aqmReqs = new AqmReqs(webSocketManager);
233
+ const setState = aqmReqs.req((p: {data: Agent.StateChange}) => ({
234
+ host: WCC_API_GATEWAY,
235
+ url: '/v1/agents/session/state',
236
+ data: p.data,
237
+ method: HTTP_METHODS.PUT,
238
+ notifSuccess: {
239
+ bind: {
240
+ type: CC_EVENTS.AGENT_STATE_CHANGE,
241
+ data: {type: CC_EVENTS.AGENT_STATE_CHANGE_SUCCESS},
242
+ },
243
+ msg: {} as Agent.StateChangeSuccess,
244
+ },
245
+ notifFail: {
246
+ bind: {
247
+ type: CC_EVENTS.AGENT_STATE_CHANGE,
248
+ data: {type: CC_EVENTS.AGENT_STATE_CHANGE_FAILED},
249
+ },
250
+ errId: 'Service.aqm.agent.stateChange',
251
+ },
252
+ }));
253
+ await setState({data: stateChangePayload});
254
+ ```
255
+
256
+ The production `stateChange` method in `src/services/agent/index.ts` has this shape plus an `err`
257
+ mapper. `req` returns `(payload, cbRes?) => Promise`, and `reqEmpty` returns `(cbRes?) => Promise`
258
+ for configurations without parameters; the optional `cbRes` callback receives the raw HTTP
259
+ acknowledgement.
260
+
261
+ `WebexRequest` ([WebexRequest.ts](../WebexRequest.ts)) is a singleton HTTP client that all services
262
+ use to make authenticated REST API calls to the contact center backend. Its constructor is private;
263
+ the static `instance` is created by the first `getInstance({webex})` call that passes a `WebexSDK`,
264
+ and later calls, with or without options, return it. It does not resolve URLs, format requests, or
265
+ parse responses itself: `request({service, resource, method, body, headers})` forwards the service
266
+ key used by `webex.request` to resolve the target host, the API path within the service (for example
267
+ `v1/notification/subscribe`), the `HTTP_METHODS` value, the optional `RequestBody`, and `headers`
268
+ (only when given), and returns the host's `Promise<IHttpResponse>`.
269
+ `uploadLogs(metaData: LogsMetaData = {})` resolves an `UploadLogsResponse` (CORE-R-014).
270
+
271
+ ```typescript
272
+ // Get singleton
273
+ const webexReq = WebexRequest.getInstance({webex});
274
+
275
+ // Make request
276
+ const response = await webexReq.request({
277
+ service: WCC_API_GATEWAY, // resolved to base URL by Webex SDK
278
+ resource: '/v1/endpoint', // appended as path
279
+ method: HTTP_METHODS.POST,
280
+ body: { key: 'value' }, // optional request payload
281
+ });
282
+
283
+ // Upload logs
284
+ await webexReq.uploadLogs({
285
+ correlationId: trackingId,
286
+ });
287
+ ```
288
+
289
+ `WebSocketManager` handles the raw WebSocket connection to the contact center backend. It is
290
+ instantiated by the `Services` layer; `src/cc.ts`, `TaskManager`, `AqmReqs`, and `ConnectionService`
291
+ all use the same instance directly.
292
+
293
+ ```typescript
294
+ // Initialize in Services
295
+ this.webSocketManager = new WebSocketManager({webex});
296
+
297
+ // Connect
298
+ const welcomeEvent = await webSocketManager.initWebSocket({
299
+ body: connectionConfig,
300
+ resource: SUBSCRIBE_API,
301
+ });
302
+
303
+ // Listen for messages
304
+ webSocketManager.on('message', (event) => {
305
+ const data = JSON.parse(event);
306
+ // Handle event
307
+ });
308
+
309
+ // Close
310
+ webSocketManager.close(false, 'Reason');
311
+ ```
312
+
313
+ ## Data flow and sequence coverage
314
+
315
+ Transport: REST over `webex.request` to the `wcc-api-gateway` service, and one JSON WebSocket per
316
+ `WebSocketManager` instance. Every AQM operation starts with HTTP and completes on the primary
317
+ socket.
318
+
319
+ | Operation group | Entry and outcome | Diagram or evidence | Failure and recovery coverage |
320
+ | --------------- | ----------------- | ------------------- | ----------------------------- |
321
+ | Authenticated REST | `WebexRequest.request`; resolves the host response | Diagram WebexRequest; `src/services/core/WebexRequest.ts` | Host/service rejection is propagated unchanged; AQM applies its own error mapping separately. |
322
+ | Diagnostics upload | `WebexRequest.uploadLogs`; resolves the feedback and tracking ids | Diagram WebexRequest (upload part); `src/services/core/WebexRequest.ts` | Failure tracked as `UPLOAD_LOGS_FAILED` and rethrown; no retry. |
323
+ | WebSocket subscribe/connect | `initWebSocket({body, resource})`; resolves the welcome data | Diagram Subscribe and connect; `src/services/core/websocket/WebSocketManager.ts` | Register rejection, URL rejection, connect failure, and welcome resolution. |
324
+ | AQM operation | Generated `req` function; resolves the matching notification | Diagram Correlated request; `src/services/core/aqm-reqs.ts` | Duplicate pending request (checked before any matcher is installed), cancel-bind resolution, HTTP failure, failure bind, and timeout reject. |
325
+ | Connection lifecycle and recovery | Keepalive, liveness timers, offline close, reconnect; emits `connectionLost` | Diagram Connection lifecycle; `src/services/core/websocket/connection-service.ts` | Offline attempts retry on the next interval; restored and restore-failed states are emitted to ContactCenter. |
326
+ | Error normalization | `getErrorDetails`, `generateTaskErrorObject` | getErrorDetails flow under Caller-visible failure modes; `src/services/core/Utils.ts` | Silent-relogin `AGENT_NOT_FOUND` skip; station-login field data. |
327
+
328
+ ### WebexRequest
329
+
330
+ ```mermaid
331
+ sequenceDiagram
332
+ participant Caller
333
+ participant WR as WebexRequest
334
+ participant Host as webex.request
335
+ participant API as WCC backend
336
+ Caller->>WR: request(service, resource, method, body)
337
+ WR->>Host: authenticated request(options)
338
+ Host->>API: HTTP request
339
+ alt success
340
+ API-->>Host: response
341
+ Host-->>WR: status/body/headers
342
+ WR-->>Caller: response
343
+ else host/service rejection
344
+ API-->>Host: error
345
+ Host-->>WR: same rejection
346
+ WR-->>Caller: same rejection
347
+ end
348
+ participant Support as webex.internal.support
349
+ Caller->>WR: uploadLogs({correlationId})
350
+ WR->>Support: submitLogs({...metaData, feedbackId}, undefined, {type: 'diff'})
351
+ alt uploaded
352
+ Support-->>WR: {trackingid, url?, userId?, correlationId?}
353
+ WR->>WR: track UPLOAD_LOGS_SUCCESS
354
+ WR-->>Caller: {trackingid, feedbackId, ...}
355
+ else upload fails
356
+ Support-->>WR: error
357
+ WR->>WR: track UPLOAD_LOGS_FAILED
358
+ WR-->>Caller: rethrow error
359
+ end
360
+ ```
361
+
362
+ ### Subscribe and connect
363
+
364
+ ```mermaid
365
+ sequenceDiagram
366
+ participant Caller
367
+ participant WSM as WebSocketManager
368
+ participant Host as webex.request
369
+ participant WS as Browser WebSocket
370
+ Caller->>WSM: initWebSocket({body, resource})
371
+ WSM->>Host: register(body, resource)
372
+ alt register rejects
373
+ Host-->>WSM: error
374
+ WSM-->>Caller: rethrow error (no socket opened)
375
+ else subscribe response
376
+ Host-->>WSM: WebSocket URL/subscription
377
+ WSM->>WSM: validate webSocketUrl against wss + allow-list
378
+ alt allow-listed wss URL
379
+ WSM->>WS: connect()
380
+ alt welcome
381
+ WS-->>WSM: Welcome event
382
+ WSM-->>Caller: WelcomeResponse
383
+ else connect failure
384
+ WSM-->>Caller: throw error
385
+ end
386
+ else malformed / non-wss / non-allow-listed URL
387
+ WSM-->>Caller: throw error (no socket opened)
388
+ end
389
+ end
390
+ loop Message handling
391
+ WS-->>WSM: onmessage(event)
392
+ WSM->>WSM: emit('message', event)
393
+ end
394
+ ```
395
+
396
+ The register step is `POST v1/notification/subscribe` (`SUBSCRIBE_API`) on `wcc-api-gateway`; the
397
+ response body carries `webSocketUrl` and `subscriptionId`. The RTD socket uses the same flow with
398
+ `RTD_SUBSCRIBE_API`.
399
+
400
+ ### Correlated request
401
+
402
+ ```mermaid
403
+ sequenceDiagram
404
+ participant Caller
405
+ participant AQM as AqmReqs
406
+ participant WR as WebexRequest
407
+ participant WS as Primary WebSocket
408
+ Caller->>AQM: generated request(payload)
409
+ AQM->>AQM: print bind keys, check pending requests
410
+ alt matching pending request already exists and timeout is enabled
411
+ AQM-->>Caller: Service.aqm.reqs.Pending
412
+ else request accepted
413
+ AQM->>AQM: install notifSuccess/notifFail/notifCancel matchers
414
+ AQM->>WR: request(config)
415
+ WR-->>AQM: HTTP acknowledgement only
416
+ alt success bind
417
+ WS-->>AQM: matching success notification
418
+ AQM-->>Caller: typed result
419
+ else cancel bind (notifCancel)
420
+ WS-->>AQM: matching cancel notification
421
+ AQM-->>Caller: typed result through the success handler
422
+ else failure bind or HTTP rejection
423
+ AQM-->>Caller: structured error
424
+ else timeout
425
+ AQM-->>Caller: Service.aqm.reqs.Timeout
426
+ end
427
+ AQM->>AQM: clear success, failure, and cancel binds
428
+ end
429
+ ```
430
+
431
+ ### Connection lifecycle
432
+
433
+ This diagram shows the connection lifecycle from component instantiation through keepalive,
434
+ connection loss, offline close, reconnect, and restore failure, including when each layer is created
435
+ and engaged and the method invocation sequence.
436
+
437
+ ```mermaid
438
+ sequenceDiagram
439
+ autonumber
440
+ participant CC as CC Plugin
441
+ participant Svc as Services
442
+ participant WSM as WebSocketManager
443
+ participant WS as WebSocket
444
+ participant CS as ConnectionService
445
+ participant KW as Keepalive Worker
446
+ participant BE as CC Backend
447
+
448
+ Note over CC,BE: INSTANTIATION: Services constructor (src/services/index.ts)
449
+ CC->>Svc: new Services({webex, connectionConfig})
450
+ Svc->>WSM: new WebSocketManager({webex})
451
+ Note right of WSM: Creates keepalive worker via Blob + URL.createObjectURL<br/>(Worker created but NOT started yet)
452
+ Svc->>CS: new ConnectionService({webSocketManager, subscribeRequest})
453
+ CS->>CS: setupEventListeners()
454
+ CS->>WSM: webSocketManager.on('message', onPing)
455
+ CS->>WSM: webSocketManager.on('socketClose', onSocketClose)
456
+
457
+ Note over CC,BE: REGISTRATION: cc.register() (src/cc.ts)
458
+ CC->>CS: connectionService.on('connectionLost', handleConnectionLost)
459
+ CC->>WSM: webSocketManager.on('message', handleWebsocketMessage)
460
+ CC->>WSM: initWebSocket({body: subscribeRequest, resource: SUBSCRIBE_API})
461
+
462
+ Note over WSM,KW: websocket.onopen handler (WebSocketManager.ts)
463
+ WSM->>WS: send({keepalive: 'true'}) - initial ping
464
+ WSM->>WSM: Setup keepaliveWorker.onmessage handler
465
+ WSM->>KW: postMessage({type: 'start', intervalDuration: 4000, closeSocketTimeout: 16000})
466
+ BE-->>WSM: WELCOME event
467
+ WSM->>CS: emit('message', welcomeEvent)
468
+ CS->>CS: onPing(welcomeEvent)
469
+ Note right of CS: setTimeout(handleConnectionLost, 8000)<br/>setTimeout(handleRestoreFailed, 50000)
470
+
471
+ Note over KW,BE: KEEPALIVE: Periodic pings every 4s (keepalive.worker.js)
472
+ loop Every 4 seconds
473
+ KW->>KW: checkNetworkStatus()
474
+ KW-->>WSM: postMessage({type: 'keepalive', onlineStatus})
475
+ WSM->>BE: send({keepalive: 'true'})
476
+ BE-->>WSM: {keepalive: 'true'}
477
+ WSM->>CS: emit('message', {keepalive: 'true'})
478
+ CS->>CS: onPing() - reset timers
479
+ CS->>CC: emit('connectionLost', all flags false, isKeepAlive true)
480
+ end
481
+
482
+ Note over CS,CC: CONNECTION LOST: No messages received within 8s
483
+ alt reconnectingTimer fires (WS_DISCONNECT_ALLOWED = 8s)
484
+ CS->>CS: handleConnectionLost()
485
+ CS->>CS: isConnectionLost = true
486
+ CS->>CC: emit('connectionLost', {isConnectionLost: true})
487
+ end
488
+
489
+ Note over KW,CS: OFFLINE DETECTION: Network goes offline
490
+ alt Browser goes offline (navigator.onLine = false)
491
+ KW->>KW: Start closeSocketTimeout timer (16s)
492
+ alt Socket doesn't close within 16s and connection is marked lost
493
+ KW-->>WSM: postMessage({type: 'closeSocket'})
494
+ WSM->>WSM: websocket.close()
495
+ WSM->>KW: postMessage({type: 'terminate'})
496
+ WSM->>CS: emit('socketClose')
497
+ end
498
+
499
+ Note over CS: onSocketClose() (connection-service.ts)
500
+ CS->>CS: clearTimerOnRestoreFailed()
501
+ CS->>CS: setInterval(handleSocketClose, 5000)
502
+
503
+ loop Every 5s (CONNECTIVITY_CHECK_INTERVAL)
504
+ CS->>CS: handleSocketClose() - check navigator.onLine
505
+ alt Browser back online
506
+ CS->>WSM: initWebSocket({body: subscribeRequest, resource: SUBSCRIBE_API})
507
+ WSM->>KW: postMessage({type: 'start', ...})
508
+ BE-->>WSM: WELCOME event
509
+ CS->>CS: clearInterval(reconnectInterval), isSocketReconnected = true
510
+ WSM->>CS: emit('message', keepalive)
511
+ CS->>CS: onPing() detects isSocketReconnected=true
512
+ CS->>CS: dispatchConnectionEvent(socketReconnected=true)
513
+ CS->>CC: emit('connectionLost', {isSocketReconnected: true})
514
+ CC->>CC: silentRelogin() when allowAutomatedRelogin is set
515
+ else Still offline
516
+ CS->>CS: Throw error, retry next interval
517
+ end
518
+ end
519
+ end
520
+
521
+ Note over CS,CC: RESTORE FAILED: no message within the recovery timeout
522
+ alt restoreTimer fires (LOST_CONNECTION_RECOVERY_TIMEOUT = 50s)
523
+ CS->>CS: handleRestoreFailed()
524
+ CS->>CS: isRestoreFailed = true
525
+ CS->>WSM: shouldReconnect = false
526
+ CS->>CS: clearInterval(reconnectInterval)
527
+ CS->>CC: emit('connectionLost', {isRestoreFailed: true})
528
+ end
529
+ ```
530
+
531
+ ContactCenter logs a lost connection and, on `isSocketReconnected`, calls `silentRelogin()` only when
532
+ `allowAutomatedRelogin` is configured; an `AGENT_NOT_FOUND` failure of that relogin is not logged or
533
+ uploaded by `getErrorDetails`.
534
+
535
+ ## Class and component relationships
536
+
537
+ Component roles and files are catalogued under Structure and key files; this section shows how the
538
+ classes depend on each other and the members that carry the lifecycle.
539
+
540
+ ```mermaid
541
+ classDiagram
542
+ class WebexRequest
543
+ class WebSocketManager
544
+ class AqmReqs
545
+ class ConnectionService
546
+ class ContactCenter
547
+ AqmReqs --> WebexRequest : authenticated HTTP
548
+ AqmReqs --> WebSocketManager : bind-matched completion
549
+ ConnectionService --> WebSocketManager : liveness + reconnect
550
+ ConnectionService --> ContactCenter : connectionLost details
551
+ ContactCenter --> WebSocketManager : registration lifecycle
552
+ ```
553
+
554
+ ### WebSocketManager members
555
+
556
+ `WebSocketManager` extends `EventEmitter`. Its public members are `initWebSocket`, `close`,
557
+ `handleConnectionLost`, and the flags `shouldReconnect` and `isSocketClosed`; `register`, `connect`,
558
+ and `webSocketOnCloseHandler` are private.
559
+
560
+ - `initWebSocket({body, resource})`: `register()` → POST `resource` on `wcc-api-gateway` → validate and store the WebSocket URL; `connect()` → Create WebSocket → Setup handlers (onopen, onmessage, onclose, onerror)
561
+ - `websocket.onopen`: Send initial keepalive ping; Wire `keepaliveWorker.onmessage` handler; **Start keepalive worker** via `postMessage({type: 'start', intervalDuration: KEEPALIVE_WORKER_INTERVAL, isSocketClosed, closeSocketTimeout: CLOSE_SOCKET_TIMEOUT})`
562
+ - `websocket.onmessage`: emits `message` with the raw string, resolves the pending welcome promise on `Welcome`, and closes without reconnect on `AGENT_MULTI_LOGIN`
563
+ - `close(shouldReconnect, reason = 'Unknown')`: acts only while the socket is open and `shouldReconnect` is still true; stores the new `shouldReconnect`, closes the socket, and terminates the worker
564
+ - `handleConnectionLost(details)`: stores `details.isConnectionLost`, which gates the worker's forced close
565
+ - `webSocketOnCloseHandler`: marks the socket closed, terminates the worker, and, only while `shouldReconnect` is true, emits `socketClose` and logs the reason (forced close, network issue, or missing keepalive)
566
+
567
+ ### ConnectionService members
568
+
569
+ Monitors WebSocket health via keepalive messages, detects disconnections, triggers reconnection attempts, and emits connection state events to the application layer. Extends `EventEmitter`.
570
+
571
+ The constructor takes `ConnectionServiceOptions` `{webSocketManager, subscribeRequest}` from
572
+ [websocket/types.ts](../websocket/types.ts), stores both, clears the four flags, and calls
573
+ `setupEventListeners()`.
574
+
575
+ | Property | Type | Description |
576
+ | --------------------- | -------------------------------- | ------------------------------------------------------------------------------------------------------------ |
577
+ | `connectionProp` | `ConnectionProp` | Runtime configuration object (for example `lostConnectionRecoveryTimeout`) used by reconnect/restore timers. |
578
+ | `wsDisconnectAllowed` | `number` | Timeout window before `handleConnectionLost` is triggered when no ping/message is received. |
579
+ | `reconnectingTimer` | `ReturnType<typeof setTimeout>` | Per-message timeout that schedules lost-connection detection. |
580
+ | `restoreTimer` | `ReturnType<typeof setTimeout>` | Timeout that marks restore failure if recovery does not complete in time. |
581
+ | `reconnectInterval` | `ReturnType<typeof setInterval>` | Periodic retry loop started after socket close to attempt reconnection. |
582
+ | `isConnectionLost` | `boolean` | Indicates that the connection has been marked as lost. |
583
+ | `isRestoreFailed` | `boolean` | Indicates that recovery has exceeded the configured restore timeout. |
584
+ | `isSocketReconnected` | `boolean` | Indicates that a reconnect attempt succeeded and socket is back. |
585
+ | `isKeepAlive` | `boolean` | Tracks whether the latest incoming message is a keepalive signal. |
586
+ | `webSocketManager` | `WebSocketManager` | Core WebSocket dependency used for event subscription and re-initialization. |
587
+ | `subscribeRequest` | `SubscribeRequest` | Cached subscribe payload reused during reconnect (`initWebSocket`). |
588
+
589
+ The only public method in the following list is `setConnectionProp`. The remaining methods are private implementation details documented for ownership and maintenance; they are not public API contracts.
590
+
591
+ 1. `setConnectionProp(prop: ConnectionProp): void` (public)
592
+ - **Purpose**: Updates connection-level runtime settings used by timers (mainly recovery timeout behavior).
593
+ - **Params**: `prop` - new connection config object.
594
+ - **Returns**: `void`.
595
+ - **Usage**: Intended to be called by higher layers when timeout behavior must be tuned after initialization; see Pitfalls and constraints for its current callers.
596
+ 2. `setupEventListeners(): void` (private)
597
+ - **Purpose**: Wires `WebSocketManager` events to internal handlers (`'message' -> onPing`, `'socketClose' -> onSocketClose`).
598
+ - **Params**: none.
599
+ - **Returns**: `void`.
600
+ - **Usage**: Invoked from the constructor once, during `ConnectionService` setup.
601
+ 3. `onPing(event: any): void` (private)
602
+ - **Purpose**: Handles every incoming socket message, resets timers, updates keepalive/recovery flags, and emits recovery events when state changes.
603
+ - **Params**: `event` - raw message payload (JSON string) received from the socket event stream.
604
+ - **Returns**: `void`.
605
+ - **Usage**: Triggered automatically by the `'message'` listener.
606
+ 4. `onSocketClose(): void` (private)
607
+ - **Purpose**: Starts the reconnect interval when socket close is detected.
608
+ - **Params**: none.
609
+ - **Returns**: `void`.
610
+ - **Usage**: Triggered automatically by the `'socketClose'` listener.
611
+ 5. `handleSocketClose(): Promise<void>` (private)
612
+ - **Purpose**: Performs one reconnect attempt; if browser is online, reinitializes WebSocket and marks socket as reconnected.
613
+ - **Params**: none.
614
+ - **Returns**: `Promise<void>` (rejects when browser is offline).
615
+ - **Usage**: Called repeatedly from `onSocketClose` interval loop.
616
+ 6. `handleConnectionLost(): void` (private)
617
+ - **Purpose**: Marks the connection as lost and dispatches a connection status event.
618
+ - **Params**: none.
619
+ - **Returns**: `void`.
620
+ - **Usage**: Scheduled by `onPing` via `reconnectingTimer` after inactivity.
621
+ 7. `handleRestoreFailed(): Promise<void>` (private)
622
+ - **Purpose**: Marks restore as failed, disables reconnect, emits failure state, and clears reconnect interval.
623
+ - **Params**: none.
624
+ - **Returns**: `Promise<void>`.
625
+ - **Usage**: Scheduled by `onPing` via `restoreTimer`.
626
+ 8. `clearTimerOnRestoreFailed(): Promise<void>` (private)
627
+ - **Purpose**: Stops active reconnect interval to avoid duplicate retries.
628
+ - **Params**: none.
629
+ - **Returns**: `Promise<void>`.
630
+ - **Usage**: Called from reconnect/failure paths whenever interval cleanup is needed.
631
+ 9. `updateConnectionData(): void` (private)
632
+ - **Purpose**: Resets transient connection flags (`isConnectionLost`, `isRestoreFailed`, `isSocketReconnected`) after recovery.
633
+ - **Params**: none.
634
+ - **Returns**: `void`.
635
+ - **Usage**: Called inside `onPing` before dispatching recovered state.
636
+ 10. `dispatchConnectionEvent(socketReconnected = false): void` (private)
637
+ - **Purpose**: Builds `ConnectionLostDetails`, forwards it to `WebSocketManager.handleConnectionLost`, and emits `'connectionLost'`.
638
+ - **Params**: `socketReconnected` - optional override used when reconnect is explicitly detected.
639
+ - **Returns**: `void`.
640
+ - **Usage**: Used by lost/recovered/restore-failed paths to publish uniform connection state.
641
+
642
+ `ConnectionLostDetails` ([websocket/types.ts](../websocket/types.ts)) has four booleans:
643
+ `isConnectionLost`, `isRestoreFailed`, `isSocketReconnected` (reported true only while
644
+ `WebSocketManager.isSocketClosed` is false), and `isKeepAlive`. A listener reads them in this order:
645
+
646
+ ```typescript
647
+ connectionService.on('connectionLost', (details: ConnectionLostDetails) => {
648
+ if (details.isConnectionLost) {
649
+ // Connection lost — waiting for recovery
650
+ } else if (details.isRestoreFailed) {
651
+ // Recovery timeout (50 s) exceeded
652
+ } else if (details.isSocketReconnected) {
653
+ // Socket successfully reconnected
654
+ }
655
+ });
656
+ ```
657
+
658
+ ## Use cases and flows
659
+
660
+ | Use case | Actor or caller | Primary steps and outcome | Failure or boundary behavior | Evidence |
661
+ | -------- | --------------- | ------------------------- | ---------------------------- | -------- |
662
+ | `UC-1` Authenticated REST | Any service | Pass the service key and request options to the host and return its response or rejection unchanged. | Rejection passes through unchanged | `src/services/core/WebexRequest.ts`, `test/unit/spec/services/core/WebexRequest.ts` |
663
+ | `UC-2` Subscribe/connect | `src/cc.ts` `connectWebsocket` | Register with `{body, resource}`, connect, and wait for welcome. | Register failure, URL rejection, and socket error reject | `src/services/core/websocket/WebSocketManager.ts`, `test/unit/spec/services/core/websocket/WebSocketManager.ts` |
664
+ | `UC-3` AQM correlation | Agent, contact, and dialer factories | Send HTTP but settle on matching notification/failure/timeout. | Duplicate pending, HTTP failure, failure bind, timeout | `src/services/core/aqm-reqs.ts`, `test/unit/spec/services/core/aqm-reqs.ts` |
665
+ | `UC-4` Reconnect | `ConnectionService` | Retry socket initialization and emit state for ContactCenter-owned recovery. | Offline retries; restore failure stops reconnect | `src/services/core/websocket/connection-service.ts`, `test/unit/spec/services/core/websocket/connection-service.ts` |
666
+ | `UC-5` Error normalization | Agent, config, and task code | Convert a caught error into an `Error` with `data`, log it, and upload logs | Silent-relogin `AGENT_NOT_FOUND` is not logged | `src/services/core/Utils.ts`, `test/unit/spec/services/core/Utils.ts` |
667
+ | `UC-6` Diagnostics upload | Error helpers and the plugin | `uploadLogs({correlationId})` returns the feedback and tracking ids | Failure tracked and rethrown | `src/services/core/WebexRequest.ts`, `test/unit/spec/services/core/WebexRequest.ts` |
668
+
669
+ ### Cross-boundary use-case flow
670
+
671
+ | Boundary | Transport and ordering | Compatibility | Timeout, retry, and recovery |
672
+ | -------- | ---------------------- | ------------- | ---------------------------- |
673
+ | Notification subscribe (`UC-2`) | HTTPS POST `v1/notification/subscribe` (or `v1/realtime/subscribe`) through `webex.request`, then the WebSocket | Response must carry a `wss` `webSocketUrl` on `cisco.com` or `ciscoccservice.com` | No timeout on welcome; reconnect only through `ConnectionService` for the primary socket |
674
+ | AQM operations (`UC-3`) | HTTPS through `WebexRequest`, result on the primary socket; binds are installed before the HTTP call | Bind fields must match the event `type` and nested `data` values | `TIMEOUT_REQ` or a per-request `timeout`; `'disabled'` waits forever; no retry |
675
+ | Keepalive (`UC-4`) | `{"keepalive":"true"}` text frame every `KEEPALIVE_WORKER_INTERVAL`; the backend echo resets the liveness timers | Frame shape fixed in `WebSocketManager.ts` | Lost-connection, forced-close, and reconnect timers from the timer table under Concurrency and reactive flow |
676
+ | Support log upload (`UC-6`) | `webex.internal.support.submitLogs(meta, undefined, {type: 'diff'})` | `feedbackId` from `crypto.randomUUID()` | No retry |
677
+
678
+ ## Client state model
679
+
680
+ WebSocketManager owns socket/welcome/worker state. AqmReqs owns pending success/failure/cancel bind maps until settlement or timeout. ConnectionService owns liveness/reconnect timers and flags, then emits state details. It does not own agent credentials, profile, or silent relogin.
681
+
682
+ | State or slice | Owner | Initial state | Transition triggers | Reset or persistence boundary |
683
+ | -------------- | ----- | ------------- | ------------------- | ----------------------------- |
684
+ | `url`, `websocket`, `isSocketClosed`, `shouldReconnect`, `isWelcomeReceived`, `welcomePromiseResolve`, `forceCloseWebSocketOnTimeout`, `isConnectionLost` | `WebSocketManager` | No URL, empty socket, `shouldReconnect` true | Register, `onopen`, `onmessage`, `onclose`, `close`, `handleConnectionLost` | Memory; each `initWebSocket` replaces the URL and socket |
685
+ | `pendingRequests`, `pendingNotifCancelrequest` | `AqmReqs` | Empty maps keyed by printed bind | Generated request call; cleared on success, failure, cancel, HTTP rejection, or timeout | Memory; one instance per `Services` |
686
+ | Liveness timers, `reconnectInterval`, and the four flags | `ConnectionService` | Flags false, no timers | Every `message`, `socketClose`, timer expiry | Memory; flags reset by `updateConnectionData` |
687
+ | `WebexRequest.instance` | `WebexRequest` class | Unset until the first `getInstance({webex})` | First call with `webex` | Process lifetime; never replaced |
688
+
689
+ ## Business rules and invariants
690
+
691
+ | ID | Invariant | WHY | Enforcement source | Test evidence |
692
+ | -- | --------- | --- | ------------------ | ------------- |
693
+ | `INV-001` | Core must preserve its typed public/event contracts and must not invent backend states or responses. | Callers trust that a resolved AQM promise is the backend's own notification (CORE-R-003). | `src/services/core/WebexRequest.ts`, `src/services/core/aqm-reqs.ts` | `test/unit/spec/services/core/aqm-reqs.ts` |
694
+ | `INV-002` | A subscribe/register `webSocketUrl` is trusted only when it is a `wss` URL on the `ALLOWED_ROUTING_NOTIFS_DOMAINS` allow-list; otherwise `WebSocketManager` throws and never opens a socket. | CORE-R-008 | `src/services/core/websocket/WebSocketManager.ts`, `src/services/core/Utils.ts` | `test/unit/spec/services/core/websocket/WebSocketManager.ts`, `test/unit/spec/services/core/Utils.ts` |
695
+
696
+ ## Concurrency and reactive flow
697
+
698
+ - Execution model: one event loop plus the keepalive Web Worker. The primary WebSocket fans messages to independent AqmReqs, ContactCenter, TaskManager, and ConnectionService listeners. AqmReqs clears all correlated bind entries on settlement. The keepalive worker posts status on its interval and may request closure after the close-socket timeout offline; reconnect attempts use their separate interval (all values in the timer table below). Listener registration/removal must preserve identity.
699
+ - Ordering guarantees: listeners run in registration order, so `ConnectionService` and `AqmReqs`
700
+ (registered in the `Services` constructor) see each message before the plugin's listener added in
701
+ `register()`. `AqmReqs.onMessage` settles at most one pending success or failure entry per message,
702
+ then checks every cancel entry.
703
+ - Idempotency and retry: AQM requests are never retried; a duplicate bind is rejected (CORE-R-009).
704
+ Reconnect attempts repeat until one succeeds or the restore timer fires.
705
+ - Shared-state protection: each piece of state has one owner (Client state model); `ConnectionService`
706
+ writes `WebSocketManager.shouldReconnect` only on restore failure.
707
+ - Blocking restrictions: keepalive and close detection run in the worker so they keep ticking while
708
+ the main thread is busy; the reconnect callback is `async` and never awaited by `setInterval`.
709
+
710
+ On the receiving side, `ConnectionService.onPing()` listens for all WebSocket messages and resets two timers on each message:
711
+ - **`reconnectingTimer`** (`WS_DISCONNECT_ALLOWED`) — if no message arrives within that window, marks connection as lost
712
+ - **`restoreTimer`** (`connectionProp.lostConnectionRecoveryTimeout`, default `LOST_CONNECTION_RECOVERY_TIMEOUT`) — if connection isn't restored within this window, marks restore as failed
713
+
714
+ When a keepalive response arrives after a lost-connection state, `ConnectionService` resets its flags and dispatches a recovery event. If the socket fully closes, `ConnectionService` retries `initWebSocket()` every `CONNECTIVITY_CHECK_INTERVAL`.
715
+
716
+ | Constant | Value | Purpose |
717
+ | ---------------------------------- | --------- | -------------------------------------------- |
718
+ | `LOST_CONNECTION_RECOVERY_TIMEOUT` | 50 000 ms | Max wait before declaring restore failed |
719
+ | `WS_DISCONNECT_ALLOWED` | 8 000 ms | Grace period before flagging connection lost |
720
+ | `CONNECTIVITY_CHECK_INTERVAL` | 5 000 ms | Interval between reconnection attempts |
721
+ | `KEEPALIVE_WORKER_INTERVAL` | 4 000 ms | Keepalive frame interval |
722
+ | `CLOSE_SOCKET_TIMEOUT` | 16 000 ms | Offline wait before the worker asks for a forced close |
723
+ | `TIMEOUT_REQ` | 20 000 ms | Default AQM request timeout; `WEBSOCKET_EVENT_TIMEOUT` (`src/services/constants.ts`) is not the AqmReqs default |
724
+
725
+ `CLOSE_SOCKET_TIMEOUT_DURATION`, `NOTIFS_RESOLVE_DELAY`, `PING_API_URL`, `WELCOME_TIMEOUT`, and
726
+ `RTD_PING_EVENT` are defined in `constants.ts` but not read by this module.
727
+
728
+ ## State machine
729
+
730
+ ```mermaid
731
+ stateDiagram-v2
732
+ [*] --> SocketClosed
733
+ SocketClosed --> Connecting: initWebSocket(body, resource)
734
+ Connecting --> Connected: welcome
735
+ Connecting --> SocketClosed: register/connect error
736
+ Connected --> ConnectionSuspect: liveness timer expires
737
+ ConnectionSuspect --> Reconnecting: socket close / retry
738
+ Reconnecting --> Connected: reconnect + message
739
+ Reconnecting --> Reconnecting: offline or retry failure
740
+ Connected --> SocketClosed: manual close
741
+ ConnectionSuspect --> Connected: message before restore timeout
742
+ ConnectionSuspect --> RestoreFailed: restore timer expires
743
+ Reconnecting --> RestoreFailed: restore timer expires
744
+ Connected --> SocketClosed: AGENT_MULTI_LOGIN (no reconnect)
745
+ RestoreFailed --> [*]
746
+ ```
747
+
748
+ - `Connected` is `ConnectionService` seeing messages; `ConnectionSuspect` is `isConnectionLost`;
749
+ `Reconnecting` is a running `reconnectInterval`; `RestoreFailed` sets `isRestoreFailed` and
750
+ `shouldReconnect` false, so a later close emits no `socketClose`.
751
+ - A manual or multi-login `close(false, ...)` sets `shouldReconnect` false, so no reconnect starts.
752
+ - Guard: `close` is a no-op once the socket is closed or `shouldReconnect` is already false.
753
+
754
+ ## Protocol and wire format
755
+
756
+ `WebSocketManager.initWebSocket` accepts `{body: SubscribeRequest, resource: string}`. Subscription uses the host Webex request API; the returned `webSocketUrl` must be a `wss` URL on the `ALLOWED_ROUTING_NOTIFS_DOMAINS` allow-list or the socket is not opened. AqmReqs operational HTTP uses the WebexRequest wrapper. AQM request configs carry `host`, `url`, optional `method`/`data`, `notifSuccess.bind`, optional `notifFail.bind`, optional cancel bind, and optional timeout. HTTP acknowledgement never substitutes for the matching WebSocket operation result.
757
+
758
+ The `service` field in request options is a **service identifier string** that the Webex SDK's internal service catalog (`this.webex.request()`) resolves to a base URL at runtime. All contact center API calls use:
759
+
760
+ ```typescript
761
+ import {WCC_API_GATEWAY} from '../constants';
762
+ // WCC_API_GATEWAY = 'wcc-api-gateway'
763
+ ```
764
+
765
+ This constant is defined in [`services/constants.ts`](../../constants.ts). The Webex SDK maps `'wcc-api-gateway'` to the appropriate contact center API gateway URL based on the environment. The `resource` is then appended as the path.
766
+
767
+ `request` resolves the host's `IHttpResponse` ([src/types.ts](../../../types.ts)): `statusCode`,
768
+ `body`, `headers` (with `trackingid`), `method`, and `url`.
769
+
770
+ | Message or frame | Version | Producer or serializer | Consumer or parser | Compatibility and ordering rule |
771
+ | ---------------- | ------- | ---------------------- | ------------------ | ------------------------------- |
772
+ | Subscribe request body `SubscribeRequest`, response `{webSocketUrl, subscriptionId}` | — | `src/cc.ts` (body), notification service (response) | `src/services/core/websocket/WebSocketManager.ts` | `webSocketUrl` must pass the `wss` allow-list check |
773
+ | Keepalive frame `{"keepalive":"true"}` and its echo | — | `src/services/core/websocket/WebSocketManager.ts` | `src/services/core/websocket/connection-service.ts`, `src/services/core/aqm-reqs.ts` (ignored) | Sent on open and on every worker tick |
774
+ | `Welcome` event | — | Notification service | `src/services/core/websocket/WebSocketManager.ts`, `src/services/core/aqm-reqs.ts` (logged and ignored) | Resolves `initWebSocket` with `data` |
775
+ | `AGENT_MULTI_LOGIN` event | — | Notification service | `src/services/core/websocket/WebSocketManager.ts` | Closes the socket without reconnect |
776
+ | AQM notification `Msg<T>` | — | Notification service | `src/services/core/aqm-reqs.ts` | Matched against `bind`: arrays mean any-of, objects recurse, scalars must be equal and truthy, and an optional `__typeMap` adds per-`type` field conditions |
777
+
778
+ Keepalive worker message contract, inbound (main thread → worker):
779
+
780
+ | Message Type | Fields | Effect |
781
+ | ------------ | -------------------------------------------------------------------------------------------- | ------------------------------------------------------------- |
782
+ | `start` | `intervalDuration` (worker default 4000ms; `WebSocketManager` sends 4000), `isSocketClosed`, `closeSocketTimeout` (worker default 5000ms; `WebSocketManager` sends 16000) | Starts periodic keepalive interval and resets offline handler |
783
+ | `terminate` | — | Clears the keepalive interval and resets offline handler |
784
+
785
+ Outbound (worker → main thread):
786
+
787
+ | Message Type | Fields | Trigger |
788
+ | ------------- | ----------------------- | ------------------------------------------------------------------------------------ |
789
+ | `keepalive` | `onlineStatus: boolean` | Every `intervalDuration` ms, and on browser online/offline events |
790
+ | `closeSocket` | — | When offline for longer than `closeSocketTimeout` and socket hasn't closed naturally |
791
+
792
+ Source: [`keepalive.worker.js`](../websocket/keepalive.worker.js) — a Web Worker script embedded as a string and loaded via `Blob` + `URL.createObjectURL` in `WebSocketManager`. It runs alongside the WebSocket to detect connection loss and keep the socket alive: it maintains the WebSocket connection with periodic pings and monitors network status. The worker starts on `onopen`; on each `keepalive` message `WebSocketManager` sends `{keepalive: 'true'}` to the backend. The worker also listens to browser `online`/`offline` events for immediate network change detection. `WebSocketManager` acts on `closeSocket` only when `ConnectionService` has already marked the connection lost, which is the only path that sets `forceCloseWebSocketOnTimeout`.
793
+
794
+ ## Caller-visible failure modes
795
+
796
+ | Condition | Signal or result | Caller behavior | Retry or recovery | Evidence |
797
+ | --------- | ---------------- | --------------- | ----------------- | -------- |
798
+ | Subscribe call rejects | `initWebSocket` rethrows the host error after an error log | `src/cc.ts` fails registration | Caller retries `register()` | `src/services/core/websocket/WebSocketManager.ts` |
799
+ | `webSocketUrl` missing, malformed, non-`wss`, or not allow-listed | `Error('Rejected webSocketUrl from RoutingNotifs registration: scheme or host not allow-listed')` | Registration fails; no socket | None | `src/services/core/websocket/WebSocketManager.ts` |
800
+ | Socket `onerror` before welcome | `initWebSocket` rejects with `undefined` | Registration fails | Caller retries | `src/services/core/websocket/WebSocketManager.ts` |
801
+ | Duplicate pending AQM bind | `Err.Details('Service.aqm.reqs.Pending', {key, msg})` | Wait for the first request | Retry after it settles | `src/services/core/aqm-reqs.ts` |
802
+ | AQM HTTP rejection | `c.err(error)`, `Err.Message(c.err)`, or `Err.Message('Service.aqm.reqs.GenericRequestError')`, with `Authorization` masked | Inspect structured details, preserve tracking id, and retry only when the operation is safe. | Caller decides | `src/services/core/aqm-reqs.ts` |
803
+ | AQM failure bind matched | `Err.Details(errId, msg)` or `notifFail.err(msg)` | Read `details.data.reason` | Caller decides | `src/services/core/aqm-reqs.ts` |
804
+ | AQM timeout | `Err.Details('Service.aqm.reqs.Timeout', {key, response})` | Follow the module-specific recovery path; never synthesize success. | Caller decides | `src/services/core/aqm-reqs.ts` |
805
+ | Log upload fails | Host error rethrown after `UPLOAD_LOGS_FAILED` | The error helpers do not await it | None | `src/services/core/WebexRequest.ts` |
806
+
807
+ This section documents shared error helpers in `Utils.ts` that normalize errors, enrich them with context, and ensure consistent logging/upload behavior across services.
808
+
809
+ `Failure` in [GlobalTypes.ts](../GlobalTypes.ts) is a specific `Msg<T>` for failure responses whose
810
+ `data` holds `agentId`, `trackingId`, `reasonCode`, `orgId`, and `reason`; `AugmentedError` is an
811
+ `Error` with an optional flexible `data` record for additional context. Access error details via
812
+ `error.details` cast to `Failure` and read `failure.data?.reason` and `failure.trackingId`.
813
+
814
+ ```mermaid
815
+ flowchart TD
816
+ A[Error caught] --> B[Cast error.details to Failure]
817
+ B --> C[Extract reason from failure.data.reason]
818
+ C --> D{Is silentRelogin + AGENT_NOT_FOUND?}
819
+ D -->|Yes| E[Skip logging/upload]
820
+ D -->|No| F[Log error with LoggerProxy]
821
+ F --> G[Upload logs via WebexRequest]
822
+ G --> H[Check if stationLogin]
823
+ H -->|Yes| I[Get field-specific error data]
824
+ H -->|No| J[Use generic error]
825
+ I --> K[Create Error with data property]
826
+ J --> K
827
+ K --> L["Return {error, reason}"]
828
+ ```
829
+
830
+ Beyond the flow above, `getErrorDetails(error, methodName, moduleName)` in [Utils.ts](../Utils.ts)
831
+ falls back to the reason `Error while performing ${methodName}`, logs
832
+ `${methodName} failed with reason: ${reason}` with the tracking id, and calls
833
+ `WebexRequest.getInstance().uploadLogs({correlationId})` with that tracking id. For `stationLogin`
834
+ the field data comes from `getStationLoginErrorData(failure, error.loginOption)` (a
835
+ `DUPLICATE_LOCATION` or `INVALID_DIAL_NUMBER` message and the login-option field name, else a generic
836
+ message and field `generic`), which is logged too. It returns `{error, reason}`, where `error` is
837
+ `new Error(reason)` with `data` `{message, fieldName}`.
838
+
839
+ `generateTaskErrorObject(error, methodName, moduleName)` takes `trackingId` from
840
+ `error.details.trackingId` or `error.trackingId`, and `errorMessage`, `errorType`, `errorData`, and
841
+ `reasonCode` from `error.details.msg`, falling back to `error.message` (else
842
+ `Error while performing ${methodName}`), `error.name` (else `Unknown Error`), an empty string, and
843
+ `0`. It logs `${methodName} failed: ${errorMessage} (${errorType})`, uploads logs, and returns an
844
+ `AugmentedError` whose message is `${errorType}: ${errorMessage}` plus ` (${errorData})` when present,
845
+ with `data` `{message, errorType, errorData, reasonCode, trackingId}`.
846
+
847
+ Standard error handler for SDK operations:
848
+
849
+ ```typescript
850
+ import {getErrorDetails} from './services/core/Utils';
851
+
852
+ try {
853
+ await operation();
854
+ } catch (error) {
855
+ const {error: detailedError, reason} = getErrorDetails(
856
+ error,
857
+ 'methodName', // Method name for logging
858
+ 'ModuleName' // Module name for logging
859
+ );
860
+
861
+ throw detailedError;
862
+ }
863
+ ```
864
+
865
+ Error handler for task operations:
866
+
867
+ ```typescript
868
+ import {generateTaskErrorObject} from './services/core/Utils';
869
+
870
+ try {
871
+ await taskOperation();
872
+ } catch (error) {
873
+ const taskError = generateTaskErrorObject(
874
+ error,
875
+ 'transfer',
876
+ 'TaskModule'
877
+ );
878
+ throw taskError;
879
+ }
880
+ ```
881
+
882
+ Building `Err` values directly ([Err.ts](../Err.ts)): `Err.Details` takes a typed id and its details;
883
+ `createErrDetailsObject` wraps a request payload as `Service.reqs.generic.failure`.
884
+
885
+ ```typescript
886
+ import * as Err from './Err';
887
+
888
+ const error = new Err.Details('Service.aqm.agent.stationLogin', {
889
+ status: 401,
890
+ type: 'UNAUTHORIZED',
891
+ trackingId: 'uuid',
892
+ });
893
+ ```
894
+
895
+ ```typescript
896
+ import {createErrDetailsObject} from './Utils';
897
+
898
+ const errDetails = createErrDetailsObject(webexRequestPayload);
899
+ // Returns Err.Details with trackingId and body
900
+ ```
901
+
902
+ ## Pitfalls and constraints
903
+
904
+ - `initWebSocket` requires both `body` and `resource`; omitting `resource` registers against no durable subscription endpoint.
905
+ - AqmReqs installs notification binds before HTTP and never resolves from acknowledgement; duplicate binds, timeout, and cleanup ordering are correctness-critical.
906
+ - `AqmReqs` calls `WebexRequest.getInstance()` without options, so `WebexRequest.getInstance({webex})`
907
+ must run first (the plugin does this before `Services.getInstance`); otherwise `webexRequest` is
908
+ undefined.
909
+ - `Req.headers` exists in `src/services/core/types.ts` but `AqmReqs` never forwards it to
910
+ `WebexRequest.request`.
911
+ - `setConnectionProp` has no production caller (only the unit test calls it), so the tenant's
912
+ `lostConnectionRecoveryTimeout` from the agent profile never changes the restore timer, which stays
913
+ at `LOST_CONNECTION_RECOVERY_TIMEOUT`.
914
+ - `ConnectionService` emits `connectionLost` on every keepalive echo with all state flags false;
915
+ listeners must branch on the flags, not on the event alone.
916
+ - An offline reconnect attempt throws inside the `setInterval` callback, so each offline tick leaves an
917
+ unhandled promise rejection; a failed `initWebSocket` during reconnect does the same.
918
+ - The RTD `WebSocketManager` has no `ConnectionService`: it never reconnects after a close.
919
+ - WebSocket not connecting — **Cause**: Subscribe API failed or invalid URL — **Solution**: Check subscribe response and WebSocket URL, including the `wss` scheme and allow-listed host.
920
+ - Messages not received — **Cause**: Event listener not registered — **Solution**: Ensure `on('message', handler)` called before connect
921
+ - Connection drops frequently — **Cause**: Keepalive not enabled or network issues — **Solution**: Verify worker-driven keepalive is running after socket `onopen`, and check network/offline transitions
922
+
923
+ ## Module-specific rules
924
+
925
+ - DO keep authentication and service resolution in the host Webex request layer; `WebexRequest.request` is a thin delegating wrapper.
926
+ - DO mask authorization headers in the `AqmReqs` HTTP-error/timeout paths before those details are logged or surfaced.
927
+ - DO enable `redactSensitiveLogs` for AQM requests whose dynamic URL or event payload can contain identity/PII.
928
+ - DO clear success/failure/cancel bind entries together when an AQM request settles.
929
+ - DON'T move silent-relogin policy into ConnectionService; it emits transport state only.
930
+ - DON'T treat timeout constants as feature flags or reuse one timer for another lifecycle purpose: the keepalive closure, lost-connection detection, reconnect interval, and recovery timeout in the timer table are separate controls and must not be conflated. Core evaluates no feature gate; `Services` constructs it unconditionally.
931
+ - Do: All core-level constants (timeouts, intervals, participant types, method names) are defined in [`constants.ts`](../constants.ts). Any new constants for the core layer should be added there.
932
+ - Do: use `getErrorDetails` for agent/config-style flows (agent service operations, station
933
+ login/logout flows) where backend failure payloads are transformed into a user-facing `Error` plus
934
+ `reason`, with optional station-login field metadata; use `generateTaskErrorObject` for
935
+ task/interaction flows (task service operations, interaction-related errors) where richer task error
936
+ metadata (`errorType`, `errorData`, `reasonCode`, `trackingId`) is required on the returned
937
+ `AugmentedError`.
938
+ - Do: Always Use Error Utilities instead of rethrowing the raw error:
939
+
940
+ ```typescript
941
+ // Correct
942
+ const {error: detailedError} = getErrorDetails(error, method, module);
943
+ throw detailedError;
944
+
945
+ // Wrong - loses context
946
+ throw error;
947
+ ```
948
+
949
+ - Do: Check Response Status where a caller needs exactly 200, as the config service does:
950
+
951
+ ```typescript
952
+ const response = await webexReq.request({...});
953
+
954
+ if (response.statusCode !== 200) {
955
+ throw new Error(`API call failed with ${response.statusCode}`);
956
+ }
957
+ ```
958
+
959
+ - Do: Extract TrackingId from either header spelling, as `getCommonErrorDetails` does:
960
+
961
+ ```typescript
962
+ const trackingId = response.headers?.trackingid ||
963
+ response.headers?.TrackingID;
964
+ ```
965
+
966
+ - Do not: remove or rename the `message`, `socketClose`, or `connectionLost` event names, or a
967
+ listener's bound function reference; removal with `off` needs the same reference.
968
+
969
+ ## Key design trade-off
970
+
971
+ | Chosen trade-off | Preserved invariant or benefit | Cost or limitation | Decision evidence |
972
+ | ---------------- | ------------------------------ | ------------------ | ----------------- |
973
+ | Request initiation stays HTTP while completion can arrive asynchronously over WebSocket | Explicit timers and correlation preserve backend fidelity (CORE-R-003) | Increased lifecycle complexity: bind keys, pending maps, and timeouts must be cleaned up together | `src/services/core/aqm-reqs.ts` |
974
+ | `ConnectionService` detects and reports transport state; ContactCenter decides on relogin | Core never mutates agent session state (CORE-R-004) | Recovery needs a listener in `src/cc.ts`; the RTD socket has none | `src/services/core/websocket/connection-service.ts`, `src/cc.ts` |
975
+
976
+ ## Verification
977
+
978
+ Unit tests mirror module paths under `test/unit/spec/services/core`. Preserve positive and negative paths, event ordering, timeout/recovery behavior, and the package's 85% global branch/function/line/statement threshold.
979
+
980
+ | Requirement or invariant | Test level | Positive evidence | Negative or boundary evidence | Gap |
981
+ | ------------------------ | ---------- | ----------------- | ----------------------------- | --- |
982
+ | `CORE-R-001`, `CORE-R-014` | Unit | `test/unit/spec/services/core/WebexRequest.ts` request and upload cases | `test/unit/spec/services/core/WebexRequest.ts` failure cases | None |
983
+ | `CORE-R-002`, `CORE-R-008`, `CORE-R-012`, `CORE-R-013`, `INV-002` | Unit | `test/unit/spec/services/core/websocket/WebSocketManager.ts` connect, welcome, INT header, multi-login cases | `test/unit/spec/services/core/websocket/WebSocketManager.ts` non-wss, non-allow-listed, register failure, error event; `test/unit/spec/services/core/Utils.ts` isAllowedUrlHost cases | No welcome-timeout case (none exists in code) |
984
+ | `CORE-R-003`, `CORE-R-010`, `CORE-R-011`, `INV-001` | Unit | `test/unit/spec/services/core/aqm-reqs.ts` notif success, notifCancel, participant-left cases | `test/unit/spec/services/core/aqm-reqs.ts` notif fail, err-function, HTTP failure masking, default timeout cases | None |
985
+ | `CORE-R-004` | Unit | `test/unit/spec/services/core/websocket/connection-service.ts` reconnect and ping cases | `test/unit/spec/services/core/websocket/connection-service.ts` connection lost and restore failed cases | Offline retry and the unhandled rejection are not covered |
986
+ | `CORE-R-005` | Unit (partial) | `test/unit/spec/services/core/aqm-reqs.ts` default-timeout case | None found | Keep timer-value assertions synchronized with constants; the worker `start` values are not asserted |
987
+ | `CORE-R-007` | Unit | `test/unit/spec/services/core/aqm-reqs.ts` redaction cases | `test/unit/spec/services/core/aqm-reqs.ts` failure without redactSensitiveLogs | None |
988
+ | `CORE-R-009` | None | None found | None found | No case for `Service.aqm.reqs.Pending` |
989
+ | `CORE-R-015` | Unit (partial) | `test/unit/spec/services/core/Utils.ts` getErrorDetails and getStationLoginErrorData cases | `test/unit/spec/services/core/Utils.ts` silent-relogin AGENT_NOT_FOUND case | `generateTaskErrorObject` has no unit case |
990
+
991
+ Run `yarn workspace @webex/contact-center build:src` and then `yarn workspace @webex/contact-center test:unit` from the workspace root. A module specification is
992
+ complete only when its public surface, invariants, failure modes, and test evidence agree with the
993
+ implementation; this module stays Partial until coverage review and independent validation run.