@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,765 @@
1
+ ---
2
+ type: Module Spec
3
+ title: 'Services specification'
4
+ description: Responsibilities, boundaries, composition order, transport patterns, state, invariants, and verification for the Contact Center services layer and its top-level data, calling, AI assistant, and wxApp services.
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
+ # Services
17
+
18
+ This source-local document at `src/services/docs/README.md` owns the stable specification for
19
+ **Services**, the `src/services` module of `@webex/contact-center`: the `Services` composition root
20
+ in `src/services/index.ts`, the shared constants in `src/services/constants.ts`, and the top-level
21
+ service classes beside them (AddressBook, EntryPoint, Queue, UserPreference, ApiAIAssistant,
22
+ WebCallingService, and the wxApp Better Together services). Agent, config, core, and task are
23
+ sub-modules with their own specifications. Ground every claim in package evidence and link to the
24
+ [package architecture](../../../docs/architecture.md) instead of repeating broader facts. No service
25
+ specification exists because this package is a library. The parent specification is the
26
+ [Contact Center SDK package spec](../../docs/README.md).
27
+
28
+ Related context: [documentation index](../../../docs/index.md) ·
29
+ [package agent instructions](../../../AGENTS.md)
30
+
31
+ ## Metadata
32
+
33
+ | Field | Value |
34
+ | --- | --- |
35
+ | Owner | @webex/web-sdk |
36
+ | Source path | `src/services` |
37
+ | Resource kind | module |
38
+ | Status | Active |
39
+ | Last verified | 2026-11-16 at `0b8c34db7f` |
40
+ | Module id | `services` |
41
+ | Parent spec | [Contact Center SDK package spec](../../docs/README.md) |
42
+ | Doc kind | Module spec |
43
+ | Coverage score | Pending coverage assessment |
44
+ | Validation status | pass-with-warnings — assessed 2026-11-17; validator runtime 01a1e76f-2293-79a0-9f8f-f060038448dd; 0 Blocking, 0 Important, 4 Minor findings. |
45
+
46
+ ## Applicability
47
+
48
+ | Condition ID | Status | Evidence or reason | Owned section |
49
+ | --- | --- | --- | --- |
50
+ | `module.has_tiers` | N/A | No tier policy exists in `package.json` or under src | Tier |
51
+ | `module.has_ui` | N/A | Every service in `src/services/index.ts` and its siblings returns promises or emits events; nothing renders | UI use-case flow |
52
+ | `module.crosses_service_boundaries` | Applicable | `src/services/AddressBook.ts`, `src/services/ApiAiAssistant.ts`, `src/services/WebexCrossClientService.ts`, and `src/services/AnswerCallOnWebexService.ts` call WCC, AI Assistant, usersub, and Hydra over HTTP; `src/services/WebCallingService.ts` drives the calling SDK | Cross-boundary use-case flow |
53
+ | `module.holds_client_state` | Applicable | The Services singleton in `src/services/index.ts`, voice connection state in `src/services/WebCallingService.ts`, usersub refresh state in `src/services/WebexCrossClientService.ts`, and pending RTD requests in `src/services/ApiAiAssistant.ts` | Client state model |
54
+ | `module.enforces_domain_rules` | Applicable | Composition order in `src/services/index.ts`, the RTMS allow-list in `src/services/WebCallingService.ts`, and wellness and transcript input validation in `src/services/ApiAiAssistant.ts` | Business rules and invariants |
55
+ | `module.is_concurrent_async` | Applicable | Promise-based HTTP calls, line registration with a timeout in `src/services/WebCallingService.ts`, and timer-driven refresh in `src/services/WebexCrossClientService.ts` | Concurrency and reactive flow |
56
+ | `module.owns_persistence` | N/A | No service under src/services writes storage; durable records stay in the backends | Data, schema, and migration discipline |
57
+ | `module.stateful_transitions` | Applicable | Singleton creation in `src/services/index.ts` and the voice line and Mobius socket states in `src/services/WebCallingService.ts` | State machine |
58
+ | `module.exposes_wire_protocol` | Applicable | Request bodies and query strings built in `src/services/Queue.ts`, `src/services/EntryPoint.ts`, `src/services/ApiAiAssistant.ts`, and `src/services/WebexCrossClientService.ts` | Protocol and wire format |
59
+ | `module.ui_multi_screen` | N/A | No UI | UI flow |
60
+ | `module.large_data_model` | N/A | Data types are owned by `src/types.ts` (parent spec) and the sub-module type files | Data model |
61
+ | `module.returns_caller_errors` | Applicable | Services rethrow request errors or throw validation errors, for example in `src/services/AddressBook.ts` and `src/services/ApiAiAssistant.ts` | Caller-visible failure modes |
62
+ | `module.module_specific_conventions` | Applicable | The AQM-versus-direct-REST split and the shared data-service shape in `src/services/Queue.ts` and siblings | Module-specific rules |
63
+ | `module.published_package` | N/A | The package export contract is owned by the parent spec; `src/index.ts` re-exports some of these classes | Export stability |
64
+ | `module.embedded_in_host` | N/A | No host embed or theme surface | Host integration and theming |
65
+ | `module.has_design_tradeoff` | Applicable | Two backend interaction patterns coexist: `src/services/core/aqm-reqs.ts` versus the direct calls in `src/services/AddressBook.ts` | Key design trade-off |
66
+ | `module.has_submodules` | Applicable | agent, config, core, and task under src/services each own a canonical spec (module_tree.py) | Sub-modules |
67
+
68
+ ## Evidence register
69
+
70
+ | Evidence | What it establishes |
71
+ | --- | --- |
72
+ | `src/services/index.ts` | The `Services` singleton and its constructor wiring (What Services creates, in Design overview); a code comment on the RTD manager says its reconnection logic is still to be implemented |
73
+ | `src/services/constants.ts` | `WCC_API_GATEWAY`, `POST_AUTH`, the RTMS domain constants, `ALLOWED_RTMS_DOMAIN`, API path constants, `WEB_RTC_PREFIX`, `WEBSOCKET_EVENT_TIMEOUT`, `METHODS`, and the AI Assistant URL template and environment map |
74
+ | `src/cc.ts` | The READY callback that creates this module's collaborators, the wellness context provider, and the station-login and wxApp call sites (parent spec) |
75
+ | `src/services/AddressBook.ts`, `src/services/EntryPoint.ts`, `src/services/Queue.ts` | Direct REST paginated list services, their default policies, cache use, metrics, and error propagation |
76
+ | `src/services/UserPreference.ts` | Direct REST CRUD for user preferences |
77
+ | `src/services/ApiAiAssistant.ts` | AI Assistant events, real-time assistance, historic transcripts, wellness actions, and RTD request correlation |
78
+ | `src/services/WebCallingService.ts` | Browser calling over `@webex/calling`, line registration, voice connection state, call-to-task mapping |
79
+ | `src/services/WebexCrossClientService.ts`, `src/services/AnswerCallOnWebexService.ts`, `src/services/WxAppTelephonyMercurySync.ts`, `src/services/wxAppDiagnosticLogging.ts`, `src/services/wxAppTelephonyUtils.ts` | wxApp Better Together: usersub publish, Hydra telephony REST, Mercury mute sync, diagnostics, call-not-found classification |
80
+ | `src/services/core/Utils.ts` | `isAllowedUrlHost` (hostname equals or ends with `.` plus an allowed domain) and `getErrorDetails` used by these services |
81
+ | `test/unit/spec/cc.ts` | READY calls `Services.getInstance` (mocked); no direct test of the `Services` constructor |
82
+ | `test/unit/spec/services/AddressBook.ts`, `test/unit/spec/services/EntryPoint.ts`, `test/unit/spec/services/Queue.ts`, `test/unit/spec/services/UserPreference.ts` | Request shapes, defaults, overrides, cache behavior, metrics, and failures of the data services |
83
+ | `test/unit/spec/services/ApiAiAssistant.ts`, `test/unit/spec/services/WebCallingService.ts` | Wellness, transcript validation, RTD correlation; line registration, RTMS fallback, voice state |
84
+ | `test/unit/spec/services/WebexCrossClientService.ts`, `test/unit/spec/services/AnswerCallOnWebexService.ts`, `test/unit/spec/services/WxAppTelephonyMercurySync.ts`, `test/unit/spec/services/wxAppDiagnosticLogging.ts` | The wxApp Better Together services |
85
+ | `test/unit/spec/services/task/TaskManager.ts` | `TaskManager.getTaskManager` takes the collaborators that ContactCenter passes from this module |
86
+ | `src/services/task/TaskManager.ts`, `src/services/task/Task.ts`, `src/services/agent/index.ts`, `src/services/task/contact.ts`, `src/services/task/dialer.ts`, `src/services/core/aqm-reqs.ts` | Sub-module code consulted for the composition and factory facts; their behavior is specified in the sub-module specs |
87
+ | `jest.config.js` | The 85% global coverage threshold over branches, functions, lines, and statements |
88
+ | `src/services/index.ts`, `src/services/core/aqm-reqs.ts`, `src/services/AddressBook.ts`, `src/services/ApiAiAssistant.ts`, `src/services/WebCallingService.ts`, `src/services/WebexCrossClientService.ts`, `src/services/AnswerCallOnWebexService.ts`, `src/services/WxAppTelephonyMercurySync.ts` | Justify the extension subsections under Data flow and sequence coverage: one per operation group these files implement (READY composition, direct REST, correlated AQM, wellness action, RTD-correlated request, browser line registration, usersub publish and refresh, Hydra telephony call, Mercury mute sync, WebSocket fan-out) |
89
+
90
+ ## Purpose and boundary
91
+
92
+ - Responsibility: Own composition and bootstrap order for backend request, realtime, data, and WebRTC service collaborators.
93
+ - In scope: the `Services` composition root and its singleton lifetime; the shared service
94
+ constants; the paginated data services and UserPreference; ApiAIAssistant; WebCallingService; the
95
+ wxApp Better Together services and their diagnostics.
96
+ - Out of scope: agent operations, configuration fetching, transport and AQM correlation, and task
97
+ lifecycle (the sub-modules below); the public `ContactCenter` class, its READY callback and event
98
+ re-emission, and the package exports (the parent spec); pagination contracts and `PageCache`
99
+ (the [Utils module spec](../../utils/docs/README.md)); telemetry (`MetricsManager`, the
100
+ [Metrics module spec](../../metrics/docs/README.md)).
101
+ - Consumers: `ContactCenter` in `src/cc.ts`, which holds the instances; applications through
102
+ `cc.addressBook`, `cc.queue`, `cc.userPreference`, `cc.apiAIAssistant`, `cc.getEntryPoints()`,
103
+ `cc.getQueues()`, and `cc.getVoiceConnectionState()`; TaskManager, Task, and Voice in the task
104
+ sub-module, which use ApiAIAssistant, WebCallingService, and AnswerCallOnWebexService.
105
+
106
+ The `src/services/` directory is the service layer of the `@webex/contact-center` SDK. It sits between the public plugin class (`cc.ts`) and the backend APIs/WebSocket. Every backend interaction — HTTP requests, WebSocket messages, agent operations, task lifecycle, configuration fetching — flows through this layer. The `ContactCenter` plugin class (`cc.ts`) is the **only public entry point**. It delegates all backend work to the services layer.
107
+
108
+ This specification resolves:
109
+
110
+ - Understanding service composition and which service owns which responsibility
111
+ - Determining the correct instantiation/bootstrap order for services
112
+ - Tracing request flow from `cc.ts` through services to the backend
113
+ - Choosing between AqmReqs and direct REST patterns for a new method
114
+ - Adding a new paginated data service (AddressBook/Queue/EntryPoint pattern) or a direct REST service such as UserPreference
115
+ - Adding a new AqmReqs method to agent, task, or dialer factories
116
+ - Routing to the correct sub-module spec for task/agent/config/core changes
117
+ - Clarifying what the Services singleton creates vs what `cc.ts` creates
118
+ - Debugging **cross-service interactions** or **bootstrap failures**
119
+
120
+ ## Structure and key files
121
+
122
+ | Path | Responsibility |
123
+ | --- | --- |
124
+ | `src/services/index.ts` | Central `Services` class that instantiates and provides access to the transport-facing service modules via `Services.getInstance()` |
125
+ | `src/services/constants.ts` | Shared constants (gateway id, API paths, WebRTC domains/prefixes, timeout, method-name constants, AI Assistant URLs) |
126
+ | `src/services/AddressBook.ts` | Address book entries — `getEntries()`, a standalone REST-based paginated service that caches eligible pages |
127
+ | `src/services/EntryPoint.ts` | Profile-scoped entry-point dial-number mappings (uncached), a standalone REST-based paginated service |
128
+ | `src/services/Queue.ts` | Queues — `getQueues()`, a standalone REST-based paginated service with the consult/transfer default policy, whose default policy bypasses its cache |
129
+ | `src/services/UserPreference.ts` | Direct REST CRUD service exposed as `cc.userPreference`; it resolves the default user from agent configuration and does not use PageCache |
130
+ | `src/services/ApiAiAssistant.ts` | `ApiAIAssistant` — existing transcript/suggestion requests plus direct, session-validated wellness custom-event reporting, and RTD request correlation |
131
+ | `src/services/WebCallingService.ts` | Browser-based voice calling via `@webex/calling`: line registration and deregistration, call answer/mute/decline, voice connection state |
132
+ | `src/services/WebexCrossClientService.ts` | WxApp Better Together: usersub cross-client publish (`answer-calls-on-wxcc`) and refresh for wxApp toast suppression, orchestrated from `cc.ts` when `enableWxBetterTogether` is active |
133
+ | `src/services/AnswerCallOnWebexService.ts` | WxApp Better Together: Hydra telephony REST (answer/reject/mute/DTMF/GET call) for wxApp thick-client calls |
134
+ | `src/services/WxAppTelephonyMercurySync.ts` | WxApp Better Together: Mercury mute sync for wxApp calls |
135
+ | `src/services/wxAppDiagnosticLogging.ts` | `[CC wxApp]` diagnostic log helpers and accept-reason derivation |
136
+ | `src/services/wxAppTelephonyUtils.ts` | `isWxAppCallNotFoundError` for the expected mute-backfill race |
137
+ | `src/services/docs/README.md` | This module specification |
138
+ | `test/unit/spec/services/AddressBook.ts` and the other top-level files in that folder | Unit tests that mirror the top-level service files |
139
+
140
+ The directories `src/services/agent`, `src/services/config`, `src/services/core`, and
141
+ `src/services/task` are the sub-modules listed next; their files are catalogued in their own specs. Pagination contracts and `PageCache` live in `src/utils` (Utils module spec).
142
+
143
+ ## Sub-modules
144
+
145
+ Each sub-module owns its own module specification. Load the relevant sub-module spec before making
146
+ changes there.
147
+
148
+ | Sub-module | Responsibility | Specification |
149
+ | --- | --- | --- |
150
+ | `src/services/agent` | **Agent** — station login/logout, state changes, buddy agents, relogin — uses the AqmReqs factory pattern (`routingAgent`); keywords: login, logout, state change, buddy agents, station, RONA | [Agent module spec](../agent/docs/README.md) |
151
+ | `src/services/config` | **Config** — agent profile aggregation (org and user desktop-login config, aux codes, site, teams, and the dial plan when enabled), org settings, outdial ANI entries; keywords: profile, register, teams, aux codes, desktop profile, org settings, dial plan | [Config module spec](../config/docs/README.md) |
152
+ | `src/services/core` | **Core** — HTTP requests (`WebexRequest`), WebSocket management (`WebSocketManager`), connection lifecycle (`ConnectionService`), AQM request/response correlation (`AqmReqs`), error handling (`Utils`, `Err`); keywords: websocket, HTTP, connection, reconnect, aqm, utils, errors, keepalive | [Core module spec](../core/docs/README.md) |
153
+ | `src/services/task` | **Task** — task lifecycle (accept, hold, transfer, conference, wrapup), contact operations (`routingContact`), outbound dialing (`aqmDialer`), voice and digital tasks; keywords: task, hold, transfer, conference, wrapup, outdial, consult, accept, decline. The task state machine (`task/state-machine/`) is part of the Task service, not a separate service; its own spec is routed from the task spec. Load it when working on state transitions, guards, or actions | [Task module spec](../task/docs/README.md) |
154
+
155
+ ## Public surface
156
+
157
+ | Contract ID | Surface | Consumer | Compatibility commitment | Source |
158
+ | --- | --- | --- | --- | --- |
159
+ | `contact-center-services` | `Services.getInstance({webex, connectionConfig})` and its readonly collaborator fields (`agent`, `config`, `contact`, `dialer`, `webSocketManager`, `rtdWebSocketManager`, `connectionService`) | `ContactCenter` only (`@private`, `@ignore`) | Internal; one instance per process | `src/services/index.ts` |
160
+ | `contact-center-services` | WebCallingService, WebexCrossClientService, AnswerCallOnWebexService, WxAppTelephonyMercurySync | `ContactCenter` and the task sub-module | Internal | `src/services/WebCallingService.ts`, `src/services/WebexCrossClientService.ts`, `src/services/AnswerCallOnWebexService.ts`, `src/services/WxAppTelephonyMercurySync.ts` |
161
+ | `contact-center-sdk` | `AddressBook.getEntries(params?)` through `cc.addressBook` | Applications | Semver-public: `AddressBook` is exported by `src/index.ts`; returns `AddressBookEntriesResponse` | `src/services/AddressBook.ts`, `src/index.ts` |
162
+ | `contact-center-sdk` | Existing `Queue.getQueues(ContactServiceQueueSearchParams)` and `EntryPoint.getEntryPoints(EntryPointSearchParams)` with paginated responses, through `cc.queue`, `cc.getQueues()`, and `cc.getEntryPoints()`; they apply consult/transfer telephony eligibility, profile views, and backend name ordering as overridable defaults, and EntryPoint returns the dial-number mapping projection | Applications | The defaults live on the existing methods and signatures; there is no specialized method or replacement signature | `src/services/Queue.ts`, `src/services/EntryPoint.ts`, `src/types.ts` |
163
+ | `contact-center-sdk` | `UserPreference` and `cc.userPreference`: direct REST CRUD for user preferences, separate from PageCache-based pagination services | Applications | Additive semver-public API; removals or signature changes are breaking | `src/services/UserPreference.ts`, `src/services/config/types.ts`, `src/index.ts` |
164
+ | `contact-center-sdk` | `ApiAIAssistant` through `cc.apiAIAssistant`, including `requestWellnessBreak` and `respondToWellnessBreak`, which submit validated `WellnessBreakAction` custom events through direct HTTP | Applications and the task sub-module | Additive semver-public behavior; exact action/event payload is backend-owned; `requestAndWaitForRtd`, `resolveFromRtdEvent`, `clearAllRtdRequests`, and `aiFeature` are marked internal | `src/services/ApiAiAssistant.ts`, `src/types.ts`, `src/index.ts` |
165
+ | `contact-center-cc-events` | `voice:connectionStateChange` (`VOICE_CONNECTION_EVENTS.STATE_CHANGE`) from WebCallingService, which ContactCenter re-triggers alongside `cc.getVoiceConnectionState()` | Applications | Published event name | `src/services/WebCallingService.ts`, `src/services/config/types.ts` |
166
+
167
+ All three contracts are indexed in the [package architecture](../../../docs/architecture.md).
168
+ Compatibility note: do not remove or reinterpret exported symbols/events without a documented consumer migration.
169
+
170
+ Use [`constants.ts`](../constants.ts) as the canonical source for service-level naming and routing constants:
171
+
172
+ - `WCC_API_GATEWAY` — service identifier used by `WebexRequest` calls
173
+ - `SUBSCRIBE_API`, `RTD_SUBSCRIBE_API` — notification and realtime subscription paths used by `ConnectionService` and `cc.ts`
174
+ - `LOGIN_API`, `STATE_CHANGE_API` — API path constants that nothing imports today; the agent factory writes its URLs inline
175
+ - `WEB_RTC_PREFIX` — `webrtc-` prefix that `cc.ts` puts before the agent id to form the browser device id
176
+ - `WEBSOCKET_EVENT_TIMEOUT` — defined as `20000` ms in `src/services/constants.ts` but not used by AqmReqs; active AQM correlation defaults to Core's `TIMEOUT_REQ = 20000`
177
+ - `DEFAULT_RTMS_DOMAIN`, `WCC_CALLING_RTMS_DOMAIN` — RTMS/WebRTC domain constants
178
+ - `ALLOWED_RTMS_DOMAIN` — trusted RTMS domain suffix (`rtmsprod.net`); a catalog-provided RTMS host is used only when its hostname equals or is a subdomain of this value, otherwise `DEFAULT_RTMS_DOMAIN` is used
179
+ - `POST_AUTH`, `DEREGISTER_WEBCALLING_LINE_MSG`, `METHODS` — catalog wait key, log message, and method name constants used by `WebCallingService`
180
+ - `AI_ASSISTANT_API_URLS`, `AI_ASSISTANT_BASE_URL_TEMPLATE`, `AI_ASSISTANT_ENV_MAP` — AI Assistant paths and the gateway-host-to-environment map used by `ApiAIAssistant`
181
+
182
+ ## Dependencies
183
+
184
+ | Dependency | Why it is required | Failure behavior |
185
+ | --- | --- | --- |
186
+ | Host Webex SDK (`webex`) | Host Webex SDK READY lifecycle and authenticated request facilities: `webex.request`, `webex.credentials.getOrgId()`, `webex.internal.services`, `webex.internal.device`, `webex.internal.mercury` | Request errors propagate to the caller; a missing catalog host or Mercury is handled per service (Caller-visible failure modes) |
187
+ | `WebexRequest` (core sub-module) | `WebexRequest` initialized by ContactCenter before `Services.getInstance()`; the data services, UserPreference, AgentConfigService, and AqmReqs send through it | Rejections are rethrown unchanged |
188
+ | WCC API gateway and WebSockets (contracts `wxcc-api-gateway`, `wxcc-websocket-notifications`) | WCC REST endpoints plus primary Contact Center and RTD WebSocket transports | HTTP errors reject; socket loss is handled by ConnectionService for the primary socket only |
189
+ | `@webex/calling` (contract `webex-calling-sdk`) | `@webex/calling` for browser calling: `createClient`, the line, and `ICall` events | Registration rejects on line error or after 20 seconds |
190
+ | Mercury (contract `webex-internal-mercury`) | wxApp mute and unmute events | Subscription is skipped and a failure metric is tracked when Mercury is absent |
191
+ | AI Assistant, usersub, and Hydra telephony services | Wellness and AI events, cross-client state, wxApp call control | Errors are wrapped by `getErrorDetails` (AI, Hydra) or rethrown (usersub) |
192
+ | `MetricsManager` (metrics module) | `timeEvent` and `trackEvent` around every backend call | Telemetry only |
193
+
194
+ ## Requirements
195
+
196
+ | ID | WHAT | WHY | Source Evidence | Test / Example Evidence | Assumptions / Gaps | Confidence |
197
+ | --- | --- | --- | --- | --- | --- | --- |
198
+ | SERVICES-R-001 | Build the Services singleton with agent/config/contact/dialer, two WebSocket managers, AqmReqs, and ConnectionService after WebexRequest is initialized. | Every AQM and transport collaborator depends on one shared authenticated host and primary message stream. | `src/services/index.ts` | `test/unit/spec/cc.ts` | The Services constructor has no direct test; the ContactCenter test mocks `Services.getInstance` and asserts only that READY calls it. | PRESENT |
199
+ | SERVICES-R-002 | Keep direct REST services, including UserPreference, separate from AQM request factories. | Direct data/config/user-preference calls complete from HTTP while AQM operations require correlated WebSocket completion. | `src/services/index.ts`, `src/services/UserPreference.ts` | `test/unit/spec/services/AddressBook.ts`, `test/unit/spec/services/UserPreference.ts` | None. | PRESENT |
200
+ | SERVICES-R-003 | Construct TaskManager, UserPreference, and other non-Services collaborators in ContactCenter's READY callback, not in `register()`. | Registration is a connection boundary; changing construction timing can duplicate listeners or access uninitialized host services. | `src/cc.ts` | `test/unit/spec/cc.ts`, `test/unit/spec/services/UserPreference.ts` | None. | PRESENT |
201
+ | SERVICES-R-004 | Pass ApiAIAssistant, contact routing, WebCallingService, primary WebSocket, and RTD WebSocket into TaskManager. | Voice, task, transcript, and suggestion behavior depend on the complete collaborator set. | `src/cc.ts` | `test/unit/spec/services/task/TaskManager.ts` | None. | PRESENT |
202
+ | SERVICES-R-005 | Inherit authenticated request identity from the host Webex SDK through Core/WebexRequest or the host `webex.request` with `addAuthHeader`; Services must not store, parse, or refresh credentials. | One host-owned authentication boundary avoids duplicate token handling and credential leakage across composed services. | `src/services/index.ts`, `src/services/core/WebexRequest.ts`, `src/services/ApiAiAssistant.ts`, `src/services/AnswerCallOnWebexService.ts` | `test/unit/spec/services/core/WebexRequest.ts` | None; authentication ownership is explicit. | PRESENT |
203
+ | SERVICES-R-006 | Treat Services composition as unconditionally created by the ContactCenter READY callback; Services owns no rollout or feature-flag decision. | Capability flags belong to the consuming config/task/calling collaborators, so the composition root must not silently gate construction. | `src/services/index.ts`, `src/cc.ts` | `test/unit/spec/cc.ts` | None; rollout applicability is explicitly N/A for Services. | PRESENT |
204
+ | SERVICES-R-007 | `Queue.getQueues` applies the inbound, active, telephony filter, desktop-profile views (`desktopProfileFilter`, `agentView`, `firstLevelView`), and `name,ASC` defaults while keeping its parameter and full-record response types; caller-supplied filter (an empty string removes it), sort, or `desktopProfileFilter` override the defaults; `sortOrder` without `sortBy` sorts by name; the default policy bypasses the simple-page cache. `EntryPoint.getEntryPoints` requests the dial-number mapping with SDK-owned `desktopProfileFilter=true` and `includeEntryPointName=true`, merges caller attributes into the required mapping fields, sorts by `entryPointName,ASC` unless the caller sorts another field, and maps each record to `id`, `name`, and an optional `number`. | Defaults on the established methods let thin consumers request consult/transfer lists without a parallel API, while existing parameters preserve specialized behavior for other consumers; the EntryPoint projection gives callers the dialled number a transfer needs. | `src/services/Queue.ts`, `src/services/EntryPoint.ts`, `src/types.ts` | `test/unit/spec/services/Queue.ts`, `test/unit/spec/services/EntryPoint.ts`, `test/unit/spec/cc.ts` | The backend honors the view flags and combined CMS sort value. | PRESENT |
205
+ | SERVICES-R-008 | ApiAIAssistant wellness requests must accept no public identity or context-mutating input, read effective enablement and non-empty SDK-owned organization/agent/session context from a read-only provider supplied at construction, then POST the exact `WellnessBreakAction` custom-event body directly to `/event`; only HTTP 202 resolves successfully. Public action unions derive from exported `as const` action-value objects. | SDK-owned live context prevents callers from supplying stale/different login identities to action calls, one value/type source prevents wire drift, and direct HTTP matches the AI event endpoint rather than AQM completion semantics. | `src/services/ApiAiAssistant.ts`, `src/types.ts`, `src/index.ts`, `src/cc.ts` | `test/unit/spec/services/ApiAiAssistant.ts`, `test/unit/spec/cc.ts` | None. | PRESENT |
206
+ | SERVICES-R-009 | `WebCallingService.getRTMSDomain()` returns a catalog-provided RTMS hostname only when it equals `ALLOWED_RTMS_DOMAIN` (`rtmsprod.net`) or is a subdomain of it; a parseable but non-allow-listed host, or a catalog value that is not a valid URL, falls back to `DEFAULT_RTMS_DOMAIN`. The rejected host is logged as a diagnostic before fallback. | The u2c service catalog is an untrusted input at the calling trust boundary; allow-listing the RTMS host prevents WebRTC registration against an attacker-controlled domain. | `src/services/WebCallingService.ts`, `src/services/constants.ts` | `test/unit/spec/services/WebCallingService.ts` | The `@webex/calling` client accepts the resolved domain string. | PRESENT |
207
+ | SERVICES-R-010 | `ApiAIAssistant.fetchHistoricTranscripts(agentId: string, interactionId: string): Promise<HistoricTranscriptsResponse>` validates both caller-supplied identifiers before building the authenticated request, accepting only non-empty strings matching the identifier format `^[A-Za-z0-9_-]{1,128}$`. Invalid inputs reject with a typed error and no request is sent. | `agentId`/`interactionId` are caller-controlled inputs on an authenticated request boundary; validating them before use rejects malformed identifiers instead of forwarding them to the backend. | `src/services/ApiAiAssistant.ts` | `test/unit/spec/services/ApiAiAssistant.ts` | Real-time transcription feature flag must already be enabled; format validation runs after that gate. | PRESENT |
208
+ | SERVICES-R-011 | `WebCallingService.registerWebCallingLine()` retires any earlier registration first, rejects with `WebCallingService Registration timed out` after 20000 ms (line status `error`, reason `REGISTRATION_TIMEOUT`, retryable), and emits `voice:connectionStateChange` with a copy of the state on every change; the state is `ready` only when browser voice is required, the line is registered or reconnected, and the Mobius socket is not disconnected. | Consumers query `cc.getVoiceConnectionState()` and subscribe to the event; the snapshot keeps Mobius socket status separate from Contact Center WebSocket health, and `cc.setAgentState()` blocks Available only when browser voice is required and not ready. | `src/services/WebCallingService.ts`, `src/constants.ts`, `src/cc.ts` | `test/unit/spec/services/WebCallingService.ts` | None. | PRESENT |
209
+ | SERVICES-R-012 | `WebexCrossClientService.setManageWebexCallingInWxcc(enable)` publishes a usersub `cross-client-state` composition with `answer-calls-on-wxcc` for app name `wxcc`, TTL 900 s by default; while enabled it republishes 60 s before expiry and retries a failed refresh up to 3 times 30 s apart; `teardown()` stops refresh and clears the active flag. It throws before publishing when the user id or device URL is missing. | Webex App reads the `wxcc` cross-client state to suppress its native calling toasts while Contact Center answers the call, and the state expires unless refreshed. | `src/services/WebexCrossClientService.ts` | `test/unit/spec/services/WebexCrossClientService.ts` | None. | PRESENT |
210
+ | SERVICES-R-013 | `AnswerCallOnWebexService` POSTs answer, reject, mute, unmute, and transmitDtmf to the Hydra `telephony/calls` resource and GETs call details, adding `lineOwnerId` only when given; failures reject with a structured error marked `isWxAppTelephonyError` carrying `trackingId` and `status` when present, and `getCallDetails` does not log an expected call-not-found response as an error. | The wxApp thick-client answer path controls the Webex App call over REST, separate from WebRTC, and the mute backfill can race call creation. | `src/services/AnswerCallOnWebexService.ts`, `src/services/wxAppTelephonyUtils.ts` | `test/unit/spec/services/AnswerCallOnWebexService.ts` | None. | PRESENT |
211
+ | SERVICES-R-014 | `WxAppTelephonyMercurySync.subscribe(agentId, onMuteChange)` replaces any earlier subscription, listens to `event:telephony_calls.muted` and `event:telephony_calls.unmuted`, base64-decodes `actorId` and `callId`, and calls back only when all fields are present and the decoded actor id ends with the agent id; without Mercury it tracks a failure metric and does not subscribe. | Mute state changed in Webex App must be mirrored to the Contact Center task for Agent Desktop parity, without reacting to another user's calls. | `src/services/WxAppTelephonyMercurySync.ts` | `test/unit/spec/services/WxAppTelephonyMercurySync.ts` | None. | PRESENT |
212
+ | SERVICES-R-015 | `UserPreference.getUserPreference(params?)` defaults the user id to the agent id from the agent configuration; create requires `data.userId`, update (PUT) and delete require a `userId`, and each method throws an `Error` before any request when the id is missing. | User preferences are per-user records; a request without a user id would target the wrong resource. | `src/services/UserPreference.ts`, `src/cc.ts` | `test/unit/spec/services/UserPreference.ts` | None. | PRESENT |
213
+ | SERVICES-R-016 | `AddressBook.getEntries(params?)` uses `params.addressBookId` or the agent profile address book, sorts by `name,ASC` by default, and throws `AddressBook: addressBookId is not available for the current agent.` before any request when neither exists. | The code validates the address book id early to avoid bad requests, and agents normally browse their own address book. | `src/services/AddressBook.ts`, `src/cc.ts` | `test/unit/spec/services/AddressBook.ts` | None. | PRESENT |
214
+
215
+ ## Design overview
216
+
217
+ `Services` is a singleton composition root for transport-facing capabilities only. It constructs two `WebSocketManager` instances (primary Contact Center and RTD), creates `AqmReqs` on the primary manager, then creates config, agent, contact, dialer, and ConnectionService collaborators.
218
+
219
+ The `Services` class is the central composition root. It uses a singleton pattern:
220
+
221
+ ```typescript
222
+ const services = Services.getInstance({
223
+ webex: this.$webex,
224
+ connectionConfig: this.getConnectionConfig(),
225
+ });
226
+ ```
227
+
228
+ What Services creates in its constructor:
229
+
230
+ | Component | How Created | Purpose |
231
+ | --- | --- | --- |
232
+ | `webSocketManager` | `new WebSocketManager({webex})` | WebSocket transport for real-time messages |
233
+ | `rtdWebSocketManager` | `new WebSocketManager({webex})` | Separate RTD WebSocket for realtime transcription, AI, and wellness events |
234
+ | `aqmReq` (internal) | `new AqmReqs(webSocketManager)` | Correlates HTTP requests with WebSocket notifications |
235
+ | `config` | `new AgentConfigService()` | REST-based profile aggregation |
236
+ | `agent` | `routingAgent(aqmReq)` | Agent operations factory |
237
+ | `contact` | `routingContact(aqmReq)` | Task/contact operations factory |
238
+ | `dialer` | `aqmDialer(aqmReq)` | Outbound dialing factory |
239
+ | `connectionService` | `new ConnectionService({webSocketManager, subscribeRequest})` | WebSocket lifecycle management |
240
+
241
+ Understanding the instantiation order is essential — getting it wrong causes runtime errors. Services does not create `WebexRequest`, which is initialized by `cc.ts` before `Services.getInstance()`, nor `MetricsManager`, an independent singleton initialized by `cc.ts`. ContactCenter owns the broader READY-time graph: in its READY callback it creates WebCallingService, the three wxApp services, ApiAIAssistant, MetricsManager, TaskManager (through `TaskManager.getTaskManager`, receiving ApiAIAssistant, contact routing, calling, and both WebSocket managers, and then AnswerCallOnWebexService), EntryPoint, AddressBook, Queue, and UserPreference, in the order of the READY composition diagram. None of these collaborators is created by `register()`; registration attaches runtime listeners and connects the primary socket after READY initialization, and line registration is conditional on a `BROWSER` login with WebRTC enabled.
242
+
243
+ AQM factory shape (`routingAgent`, `routingContact`, `aqmDialer`): agent and task operations use a
244
+ factory pattern where each method is defined as a `routing.req()` call. Each entry returns a
245
+ request description: `url` and `host` (`WCC_API_GATEWAY`) define the HTTP endpoint, `data` is the
246
+ request body (POST by default, GET if no data, unless `method` is set), `err` builds an `Err.Details`
247
+ from the HTTP failure, `notifSuccess.bind` names the WebSocket event type and data type that mean
248
+ success, and `notifFail.bind` names the failure event with an `errId` that maps to an `Err.Details`
249
+ error identifier (for example `Service.aqm.agent.stationLoginFailed`). The generated function
250
+ returns a `Promise` that settles when the correlated WebSocket notification arrives. Reference
251
+ files: [`agent/index.ts`](../agent/index.ts) — agent operations; [`task/contact.ts`](../task/contact.ts) —
252
+ task operations; [`task/dialer.ts`](../task/dialer.ts) — outbound dialing. The correlation itself is
253
+ specified in the core sub-module.
254
+
255
+ AddressBook, Queue, and EntryPoint have no sub-module of their own; they are specified here. They share direct REST, pagination, logging, metrics, and error propagation, but cache policy is service-owned: AddressBook/Queue use PageCache when eligible and EntryPoint always fetches its profile-scoped mapping. These services share the direct REST and pagination pattern, with service-specific request mapping and cache policy:
256
+
257
+ | Aspect | Pattern |
258
+ | --- | --- |
259
+ | **Class structure** | Standalone class with `WebexRequest`, `WebexSDK`, and `MetricsManager`; cache-enabled services additionally own `PageCache` |
260
+ | **Constructor** | `constructor(webex: WebexSDK)` — gets singletons via `.getInstance()`; AddressBook also takes a `getAddressBookId` function |
261
+ | **HTTP calls** | `this.webexRequest.request({service: WCC_API_GATEWAY, resource, method: HTTP_METHODS.GET})` |
262
+ | **Endpoints** | Uses `endPointMap` functions from `config/constants.ts` to build URL paths |
263
+ | **Pagination** | Query params with `page` and `pageSize` |
264
+ | **Caching** | AddressBook/Queue may use `PageCache<T>` for eligible pages; EntryPoint always fetches because its request is desktop-profile scoped |
265
+ | **Consult/transfer policy** | Existing Queue and EntryPoint methods apply telephony eligibility, profile views, and backend name ordering by default and accept overrides through their existing query parameters; Queue returns the full-record response unchanged and EntryPoint maps the dial-number records |
266
+ | **Metrics** | `timeEvent` on API call start, `trackEvent` on success/failure |
267
+ | **Logging** | `LoggerProxy` with `{module: 'ClassName', method: 'methodName'}` context |
268
+ | **Error handling** | try/catch with `LoggerProxy.error` + `metricsManager.trackEvent` for failures, then re-throw so callers receive the error |
269
+
270
+ Success metrics are tracked only for search requests or page 0, to reduce metric volume; Queue's
271
+ default filter makes every default call a search request. Reference files:
272
+
273
+ - [`AddressBook.ts`](../AddressBook.ts) — includes `addressBookId` parameter
274
+ - [`Queue.ts`](../Queue.ts) — includes additional query params (sortBy, sortOrder, etc.)
275
+ - [`EntryPoint.ts`](../EntryPoint.ts) — profile-scoped dial-number mapping without PageCache
276
+
277
+ `UserPreference.ts` is a separate direct REST CRUD pattern. It resolves a default user id from `agentConfig`, supports explicit user ids where applicable, and intentionally does not share PageCache behavior with the three paginated services.
278
+
279
+ ApiAIAssistant wellness reporting is also direct REST, but it reads live context through a read-only provider supplied by ContactCenter at construction rather than a separate factory or context setter. It fails closed unless wellness is effectively enabled and the SDK owns a current organization, agent, and session; public action calls do not accept identity fields.
280
+
281
+ ApiAIAssistant resolves its base URL by looking up the `WCC_API_GATEWAY` host in
282
+ `AI_ASSISTANT_ENV_MAP` and filling `AI_ASSISTANT_BASE_URL_TEMPLATE`; an unknown host fails with
283
+ `AI_ASSISTANT_BASE_URL_NOT_AVAILABLE`. It sends through `webex.request` with `addAuthHeader`, not
284
+ through `WebexRequest`, as do AnswerCallOnWebexService (Hydra) and WebexCrossClientService (usersub).
285
+
286
+ **WebCallingService** follows a different pattern: EventEmitter-based call lifecycle orchestration around `@webex/calling` (`createClient`, line registration/deregistration, `ICall` events), `callTaskMap` tracking, and async registration flows with timeout handling. The line `REGISTERED` listener remains attached for the lifetime of a registered line so recovery registration events restore readiness; deregistration removes it with all other line listeners. Before registering the calling line it resolves the RTMS domain from the u2c service catalog through `getRTMSDomain()`, which trusts the catalog host only when it is on the `ALLOWED_RTMS_DOMAIN` allow-list and otherwise falls back to `DEFAULT_RTMS_DOMAIN`. It tracks browser voice readiness from line lifecycle and Mobius socket events; consumers query `cc.getVoiceConnectionState()` and subscribe to `voice:connectionStateChange`. The snapshot keeps Mobius socket status separate from Contact Center WebSocket health. `cc.setAgentState()` is guarded only when browser WebRTC registration is required.
287
+
288
+ ContactCenter calls `registerWebCallingLine()` at station login and silent relogin only when the
289
+ login option is `BROWSER`, the agent profile has `webRtcEnabled`, and `disableWebRTCRegistration`
290
+ is not set.
291
+
292
+ ## Data flow and sequence coverage
293
+
294
+ Call styles: synchronous composition at READY; HTTPS request and response for direct REST (through
295
+ `WebexRequest` or `webex.request`); HTTP initiation plus a correlated primary-WebSocket notification
296
+ for AQM; in-process events from `@webex/calling` and Mercury.
297
+
298
+ | Operation group | Entry and outcome | Diagram or evidence | Failure and recovery coverage |
299
+ | --- | --- | --- | --- |
300
+ | READY-time composition | Host READY; ContactCenter builds WebexRequest, Services, and the other collaborators | READY composition diagram; `src/services/index.ts` | Invalid initialization prevents use of the incomplete graph. |
301
+ | Direct REST | A data, config, or user-preference call through `WebexRequest`; resolves the response body | Direct REST request diagram; `src/services/AddressBook.ts` | HTTP/service rejection is returned directly to the caller. |
302
+ | AQM | An agent, contact, or dialer factory call; resolves the correlated notification | Correlated AQM operation diagram; `src/services/core/aqm-reqs.ts` | HTTP rejection, matching failure notification, and timeout reject the operation. |
303
+ | Wellness action | `requestWellnessBreak()` or `respondToWellnessBreak({action})`; resolves on HTTP 202 | Wellness action diagram; `src/services/ApiAiAssistant.ts` | Invalid action, disabled flag, or missing org, agent, or session rejects before HTTP; a non-202 status or network error rejects with a structured error |
304
+ | RTD-correlated request | `requestAndWaitForRtd(options)` from a task AI summary; resolves the matching RTD payload | RTD-correlated request diagram; `src/services/ApiAiAssistant.ts` | HTTP failure removes the pending entry and rejects; the timer rejects with the caller's timeout error; a newer request with the same key replaces the timer; clearing rejects every pending request |
305
+ | Browser line registration | `registerWebCallingLine()`; resolves on line `REGISTERED` | Browser line registration diagram; `src/services/WebCallingService.ts` | Timeout, line error, superseded registration |
306
+ | usersub publish and refresh | `setManageWebexCallingInWxcc(enable)`; resolves after the publish | usersub publish and refresh diagram; `src/services/WebexCrossClientService.ts` | Missing user id or device URL throws; publish failure rejects; a failed refresh retries after 30 s up to 3 times; teardown during a publish discards its result |
307
+ | Hydra telephony call | Answer, reject, mute, unmute, DTMF, or call details for a wxApp call; resolves the response | Hydra telephony call diagram; `src/services/AnswerCallOnWebexService.ts` | Missing Hydra URL rejects; failures reject marked `isWxAppTelephonyError`; an expected call-not-found from call details rejects without an error log |
308
+ | Mercury mute sync | `subscribe(agentId, onMuteChange)`; calls back on each matching mute or unmute event | Mercury mute sync diagram; `src/services/WxAppTelephonyMercurySync.ts` | Missing Mercury skips the subscription with a failure metric; events with missing fields or another actor are dropped |
309
+ | WebSocket fan-out | Each primary or RTD message reaches its listeners | WebSocket fan-out block; `src/services/index.ts` | Malformed RTD messages are left to TaskManager |
310
+
311
+ There are two distinct backend patterns used across services. AQM factories return functions whose HTTP request is initiation and whose promise settles on correlated primary-WebSocket notifications. Direct config/data services return authenticated REST responses. AQM is used by `routingAgent`, `routingContact`, and `aqmDialer`: the factory sends an HTTP REST request to the backend and waits for a correlated WebSocket notification. Key detail: **The HTTP request goes directly to the backend. The WebSocket only carries the notification back.** This is NOT request-over-WebSocket. Direct REST is used by `AgentConfigService`, `AddressBook`, `Queue`, `EntryPoint`, and `UserPreference` through `WebexRequest`, and by ApiAIAssistant, AnswerCallOnWebexService, and WebexCrossClientService through `webex.request`; they make direct HTTP calls and return the response.
312
+
313
+ Direct REST: caller → AgentConfigService/AddressBook/EntryPoint/Queue/UserPreference → WebexRequest → response.
314
+
315
+ AQM: caller → routing factory → AqmReqs → WebexRequest HTTP acknowledgement → matching primary-WebSocket success/failure → promise settlement.
316
+
317
+ Realtime task/AI: the primary WebSocket reaches TaskManager directly; RTD messages reach ContactCenter, which handles wellness offers and forwards the rest to `TaskManager.handleRealtimeWebsocketEvent` → Task/state machine → typed application event.
318
+
319
+ ### READY composition
320
+
321
+ ```mermaid
322
+ sequenceDiagram
323
+ participant Host
324
+ participant CC as ContactCenter
325
+ participant S as Services
326
+ participant TM as TaskManager
327
+ Host-->>CC: READY
328
+ CC->>CC: initialize WebexRequest
329
+ CC->>S: getInstance(webex, connectionConfig)
330
+ S->>S: primary WS + RTD WS + AqmReqs + config/agent/contact/dialer + ConnectionService
331
+ CC->>CC: create calling + wxApp services + AI assistant + metrics
332
+ CC->>TM: getTaskManager(AI, contact, calling, primary WS, RTD WS)
333
+ CC->>CC: create data services + UserPreference
334
+ ```
335
+
336
+ ### Direct REST request
337
+
338
+ ```mermaid
339
+ sequenceDiagram
340
+ participant Caller
341
+ participant Service as Config/data service
342
+ participant WR as WebexRequest
343
+ participant Host as Authenticated Webex request
344
+ Caller->>Service: typed REST operation
345
+ Service->>WR: request(service + resource + method)
346
+ WR->>Host: resolve service and send request
347
+ alt HTTP success
348
+ Host-->>WR: response
349
+ WR-->>Service: typed response
350
+ Service-->>Caller: result
351
+ else service/HTTP rejection
352
+ Host-->>WR: error
353
+ WR-->>Service: same rejection
354
+ Service-->>Caller: reject
355
+ end
356
+ ```
357
+
358
+ ### Correlated AQM operation
359
+
360
+ ```mermaid
361
+ sequenceDiagram
362
+ participant Caller
363
+ participant Factory as agent/contact/dialer
364
+ participant AQM as AqmReqs
365
+ participant HTTP as WebexRequest
366
+ participant WS as Primary WebSocket
367
+ Caller->>Factory: typed operation
368
+ Factory->>AQM: generated request function(payload)
369
+ AQM->>HTTP: authenticated request(config)
370
+ HTTP-->>AQM: acknowledgement
371
+ alt matching success notification
372
+ WS-->>AQM: notifSuccess.bind match
373
+ AQM-->>Caller: typed response
374
+ else matching failure or timeout
375
+ WS-->>AQM: notifFail.bind match
376
+ AQM-->>Caller: structured rejection
377
+ end
378
+ ```
379
+
380
+ ### Wellness action
381
+
382
+ ```mermaid
383
+ sequenceDiagram
384
+ participant App as Application
385
+ participant AI as ApiAIAssistant
386
+ participant P as ContactCenter context provider
387
+ participant SVC as AI Assistant event API
388
+ App->>AI: requestWellnessBreak() or respondToWellnessBreak({action})
389
+ alt response action is not ACCEPTED, REJECTED, or NO_RESPONSE
390
+ AI-->>App: reject WELLNESS_BREAK_ACTION_INVALID
391
+ else action accepted for sending
392
+ AI->>P: read isWellnessBreakEnabled, agentId, agentSessionId
393
+ alt disabled, or org, agent, or session missing
394
+ AI-->>App: reject WELLNESS_BREAK_NOT_ENABLED or a REQUIRED reason
395
+ else context valid
396
+ AI->>SVC: POST /event, CUSTOM_EVENT WellnessBreakAction
397
+ alt status 202
398
+ SVC-->>AI: 202
399
+ AI-->>App: resolve; the outcome arrives later as a wellness notification
400
+ else other status or network error
401
+ AI-->>App: reject structured error
402
+ end
403
+ end
404
+ end
405
+ ```
406
+
407
+ ### RTD-correlated request
408
+
409
+ ```mermaid
410
+ sequenceDiagram
411
+ participant T as Task AI summary
412
+ participant AI as ApiAIAssistant
413
+ participant SVC as AI Assistant event API
414
+ participant TM as TaskManager
415
+ T->>AI: requestAndWaitForRtd(eventType, correlationId, timeoutMs)
416
+ AI->>AI: clear the timer of an earlier request with the same key, store request, start timer
417
+ AI->>SVC: sendEvent, POST /event
418
+ alt HTTP failure
419
+ AI->>AI: remove pending request
420
+ AI-->>T: reject the HTTP error
421
+ else matching RTD event before the timer
422
+ TM->>AI: resolveFromRtdEvent(type, correlationId, payload)
423
+ AI-->>T: resolve payload
424
+ else timer fires
425
+ AI-->>T: reject createTimeoutError()
426
+ else RTD lifecycle ends
427
+ TM->>AI: clearAllRtdRequests()
428
+ AI-->>T: reject RTD request cleared
429
+ end
430
+ ```
431
+
432
+ ### Browser line registration
433
+
434
+ ```mermaid
435
+ sequenceDiagram
436
+ participant CC as ContactCenter
437
+ participant W as WebCallingService
438
+ participant Cat as u2c catalog
439
+ participant L as calling line
440
+ CC->>W: registerWebCallingLine()
441
+ W->>W: retire earlier registration, line status connecting
442
+ W->>Cat: waitForCatalog(postauth), get RTMS host
443
+ alt host on rtmsprod.net allow-list
444
+ Cat-->>W: catalog hostname
445
+ else not allow-listed or invalid URL
446
+ W->>W: log, use DEFAULT_RTMS_DOMAIN
447
+ end
448
+ W->>L: createClient, attach listeners, register()
449
+ alt REGISTERED before 20 s
450
+ L-->>W: REGISTERED
451
+ W-->>CC: resolve, emit voice:connectionStateChange
452
+ else line error or timeout
453
+ W->>W: line status error, emit state
454
+ W-->>CC: reject
455
+ else superseded by a newer registration
456
+ W-->>CC: resolve without registering this line
457
+ end
458
+ ```
459
+
460
+ ### usersub publish and refresh
461
+
462
+ ```mermaid
463
+ sequenceDiagram
464
+ participant CC as ContactCenter
465
+ participant X as WebexCrossClientService
466
+ participant U as usersub publish
467
+ CC->>X: setManageWebexCallingInWxcc(enable, options)
468
+ alt user id or device URL missing
469
+ X-->>CC: throw, failure metric when tracked
470
+ else preflight passes
471
+ X->>U: POST publish cross-client-state answer-calls-on-wxcc, ttl 900
472
+ alt publish fails
473
+ X-->>CC: reject, failure metric when tracked
474
+ else teardown ran during the publish
475
+ X-->>CC: resolve without changing state
476
+ else success with enable true
477
+ X->>X: active, refresh timer at ttl minus 60 s
478
+ loop while enabled
479
+ X->>U: republish
480
+ opt refresh fails
481
+ X->>X: retry after 30 s, at most 3 retries
482
+ end
483
+ end
484
+ else success with enable false
485
+ X->>X: inactive, timers cleared
486
+ end
487
+ end
488
+ ```
489
+
490
+ ### Hydra telephony call
491
+
492
+ ```mermaid
493
+ sequenceDiagram
494
+ participant V as Voice task for a wxApp call
495
+ participant H as AnswerCallOnWebexService
496
+ participant S as Hydra telephony calls
497
+ V->>H: answerCall, rejectCall, muteCall, unmuteCall, transmitDtmf, or getCallDetails
498
+ alt no Hydra URL in the catalog
499
+ H-->>V: reject Telephony base URL is unavailable
500
+ else URL resolved
501
+ H->>S: POST answer, reject, mute, unmute, transmitDtmf, or GET the call, lineOwnerId when given
502
+ alt success
503
+ S-->>H: response
504
+ H-->>V: response, or the call details body
505
+ else call details returns call not found
506
+ H-->>V: reject marked wxApp error, no error log
507
+ else other failure
508
+ H->>H: log trackingId and status
509
+ H-->>V: reject structured error marked isWxAppTelephonyError
510
+ end
511
+ end
512
+ ```
513
+
514
+ ### Mercury mute sync
515
+
516
+ ```mermaid
517
+ sequenceDiagram
518
+ participant CC as ContactCenter
519
+ participant M as WxAppTelephonyMercurySync
520
+ participant Me as Mercury
521
+ CC->>M: subscribe(agentId, onMuteChange)
522
+ M->>M: remove earlier listeners
523
+ alt Mercury unavailable
524
+ M->>M: log error, track subscribe-failed metric
525
+ else Mercury present
526
+ M->>Me: listen to telephony_calls.muted and telephony_calls.unmuted
527
+ Me-->>M: actorId, callId, muted
528
+ alt a field is missing
529
+ M->>M: drop, missing_mercury_event_fields
530
+ else decoded actorId does not end with agentId
531
+ M->>M: drop, actor_id_mismatch
532
+ else matching event
533
+ M-->>CC: onMuteChange(decoded callId, muted)
534
+ end
535
+ end
536
+ ```
537
+
538
+ ### WebSocket fan-out
539
+
540
+ WebSocket messages are fanned out to multiple independent listeners on `WebSocketManager`:
541
+
542
+ ```text
543
+ CC Backend
544
+ → primary WebSocket message arrives at Services.webSocketManager
545
+ → WebSocketManager emits 'message'
546
+ → AqmReqs listener (`aqm-reqs.ts`) — correlates pending request notifications
547
+ → cc.ts listener (`cc.ts`) — handles plugin-level events:
548
+ → allow-listed CC events and wellness offers use `this.emit(...)` (EventEmitter API)
549
+ → task notifications from TaskManager use `this.trigger(...)` (WebexPlugin API)
550
+ → TaskManager listener (`TaskManager.ts`) — processes task events for task lifecycle/state
551
+ → ConnectionService listener (`connection-service.ts`) — processes connection/keepalive events
552
+ → RTD WebSocket message arrives at Services.rtdWebSocketManager
553
+ → cc.ts RTD listener — wellness offers, otherwise TaskManager.handleRealtimeWebsocketEvent
554
+ ```
555
+
556
+ ## Class and component relationships
557
+
558
+ ```mermaid
559
+ classDiagram
560
+ class ContactCenter
561
+ class Services
562
+ class WebSocketManager
563
+ class AqmReqs
564
+ class ConnectionService
565
+ class AgentConfigService
566
+ class TaskManager
567
+ class ApiAIAssistant
568
+ class WebCallingService
569
+ class AnswerCallOnWebexService
570
+ class WebexRequest
571
+ ContactCenter --> Services
572
+ Services --> WebSocketManager : primary + RTD
573
+ Services --> AqmReqs : primary WS correlation
574
+ Services --> ConnectionService
575
+ Services --> AgentConfigService
576
+ ContactCenter --> ApiAIAssistant
577
+ ContactCenter --> TaskManager
578
+ ContactCenter --> UserPreference
579
+ ContactCenter --> WebCallingService
580
+ TaskManager --> ApiAIAssistant
581
+ TaskManager --> WebCallingService
582
+ TaskManager --> AnswerCallOnWebexService
583
+ TaskManager --> WebSocketManager : primary + RTD
584
+ AqmReqs --> WebexRequest : sends HTTP
585
+ AqmReqs --> WebSocketManager : listens for notifications
586
+ AgentConfigService --> WebexRequest : direct REST
587
+ ```
588
+
589
+ Per-method use of the Services fields by ContactCenter (the other relationships are the edges above):
590
+
591
+ ```text
592
+ cc.ts
593
+ ├─ uses → Services.agent (stationLogin, stateChange, logout, buddyAgents, reload)
594
+ ├─ uses → Services.config (getAgentConfig, getWellbeingBreakIdleCode, getOutdialAniEntries)
595
+ ├─ uses → Services.contact (passed to TaskManager, which forwards task operations)
596
+ └─ uses → Services.dialer (startOutdial, acceptPreviewContact, skipPreviewContact, removePreviewContact)
597
+ ```
598
+
599
+ ## Use cases and flows
600
+
601
+ | Use case | Actor or caller | Primary steps and outcome | Failure or boundary behavior | Evidence |
602
+ | --- | --- | --- | --- | --- |
603
+ | `UC-001` | ContactCenter at READY | Compose services: create the transport/factory singleton once per SDK host | A second `getInstance` returns the first instance and ignores its options | `src/services/index.ts`, `test/unit/spec/cc.ts` |
604
+ | `UC-002` | Application or ContactCenter | Direct REST: configuration, data, and user-preference services return authenticated HTTP results directly | The HTTP error is logged, tracked, and rethrown | `src/services/config/index.ts`, `src/services/UserPreference.ts`, `test/unit/spec/services/config/index.ts`, `test/unit/spec/services/UserPreference.ts` |
605
+ | `UC-003` | ContactCenter or TaskManager | AQM operation: initiate HTTP and settle only on matching WebSocket notification or timeout | Failure notification or timeout rejects | `src/services/core/aqm-reqs.ts`, `test/unit/spec/services/core/aqm-reqs.ts` |
606
+ | `UC-004` | Backend through the sockets | Task/AI realtime: TaskManager consumes the primary stream directly and RTD events forwarded by ContactCenter, with ApiAIAssistant/calling collaborators | Unknown RTD correlation ids resolve nothing | `src/services/task/TaskManager.ts`, `test/unit/spec/services/task/TaskManager.ts` |
607
+ | `UC-005` | Agent application | Wellness action reporting: validate the current profile/session context and submit a direct AI custom event that completes only on HTTP 202 | Disabled, missing context, invalid action, or non-202 rejects | `src/services/ApiAiAssistant.ts`, `test/unit/spec/services/ApiAiAssistant.ts` |
608
+ | `UC-006` | ContactCenter at station login | Browser voice: register the calling line and report voice readiness | Timeout or line error rejects; RTMS host falls back to the default | `src/services/WebCallingService.ts`, `test/unit/spec/services/WebCallingService.ts` |
609
+ | `UC-007` | ContactCenter after station login with `enableWxBetterTogether` | wxApp Better Together: publish `answer-calls-on-wxcc`, subscribe to Mercury mute sync, and route wxApp call control through Hydra | Missing user id, device URL, or Mercury; publish failure; teardown on logout | `src/services/WebexCrossClientService.ts`, `src/services/WxAppTelephonyMercurySync.ts`, `src/services/AnswerCallOnWebexService.ts`, `test/unit/spec/services/WebexCrossClientService.ts` |
610
+
611
+ ### Cross-boundary use-case flow
612
+
613
+ - WCC API gateway (data services, UserPreference): HTTPS through `WebexRequest` with service
614
+ `wcc-api-gateway`; no retry in this module; the error is rethrown after a failure metric.
615
+ EntryPoint also sends `X-ORGANIZATION-ID` and `x-ignore-internal-data: false` headers.
616
+ - AI Assistant: HTTPS POST to `/event` or `/transcripts/list` on the environment host resolved from
617
+ the gateway; an optional `timeout` is passed through for RTD-correlated requests; errors are wrapped
618
+ by `getErrorDetails`.
619
+ - usersub: POST `publish` on service `usersub`; refreshed on a timer while enabled (SERVICES-R-012).
620
+ - Hydra telephony: HTTPS on the Hydra service URL plus `/telephony/calls`; no retry; errors are marked as wxApp
621
+ telephony errors (SERVICES-R-013).
622
+ - Calling SDK and Mobius: in-process `@webex/calling` client; registration times out after 20 s and
623
+ line and socket events update the voice state (SERVICES-R-011).
624
+ - Mercury: in-process event subscription; events for other actors are dropped (SERVICES-R-014).
625
+
626
+ ## Client state model
627
+
628
+ | State or slice | Owner | Initial state | Transition triggers | Reset or persistence boundary |
629
+ | --- | --- | --- | --- | --- |
630
+ | `Services.instance` | `Services` (static) | Unset | The first `getInstance` call constructs the composed graph synchronously; later calls return it | Never reset in code; lives for the process |
631
+ | Voice connection state (`status`, `lineStatus`, `mobiusSocketStatus`, `reason`, `retryable`) | `WebCallingService` | `not-required`, `unknown`, `unknown` | Browser-voice flag, line events, Mobius socket events, registration timeout or error | `deregisterWebCallingLine()` restores the default state and emits once if it changed |
632
+ | `callTaskMap`, current call | `WebCallingService` | Empty | `mapCallToTask`, incoming call | `cleanUpCall()` and deregistration |
633
+ | `answerCallsState`, refresh timers, generation | `WebexCrossClientService` | false, none, 0 | Successful publish, refresh timers | `teardown()` |
634
+ | Mercury subscription (agent id, handlers) | `WxAppTelephonyMercurySync` | None | `subscribe` | `unsubscribe()` |
635
+ | Pending RTD requests, `aiFeature` | `ApiAIAssistant` | Empty, unset | `requestAndWaitForRtd`, `setAIFeatureFlags` | Settled on event, timeout, or `clearAllRtdRequests()` |
636
+
637
+ ## Business rules and invariants
638
+
639
+ | ID | Invariant | WHY | Enforcement source | Test evidence |
640
+ | --- | --- | --- | --- | --- |
641
+ | `INV-001` | The first singleton construction fixes the host SDK and connection configuration for that Services instance. | One composed graph per process keeps every factory on the same sockets | `src/services/index.ts` | `test/unit/spec/cc.ts` |
642
+ | `INV-002` | The primary WebSocket manager is used for AQM correlation and Contact Center events; the RTD manager remains a distinct TaskManager dependency. | Swapping or omitting either stream loses task or AI events | `src/services/index.ts`, `src/cc.ts` | `test/unit/spec/services/task/TaskManager.ts` |
643
+ | `INV-003` | Untrusted external inputs are validated at the service trust boundary: catalog-provided RTMS hosts must pass the `ALLOWED_RTMS_DOMAIN` allow-list before use, and caller-supplied `agentId`/`interactionId` must match the accepted identifier format before an authenticated transcript request is built. | Catalog hosts and caller ids cross a trust boundary | `src/services/WebCallingService.ts`, `src/services/ApiAiAssistant.ts` | `test/unit/spec/services/WebCallingService.ts`, `test/unit/spec/services/ApiAiAssistant.ts` |
644
+ | `INV-004` | ApiAIAssistant evaluates the current effective wellness flag and identities through its constructor-supplied read-only provider; the public object exposes no context mutator, and the Services singleton itself remains unconditionally composed. | Callers cannot inject identities into wellness actions | `src/services/ApiAiAssistant.ts` | `test/unit/spec/services/ApiAiAssistant.ts` |
645
+ | `INV-005` | Only the newest WebCallingService registration may change state: listeners from a retired registration are ignored and a superseded registration resolves without touching the line. | Overlapping station logins must not leave two lines or a stale error | `src/services/WebCallingService.ts` | `test/unit/spec/services/WebCallingService.ts` |
646
+
647
+ ## Concurrency and reactive flow
648
+
649
+ - Execution model: `getInstance` composition is synchronous in the JavaScript execution turn. Direct REST promises can proceed independently, while each AQM promise remains pending until its matching primary-WebSocket notification, HTTP failure, or timeout.
650
+ - Ordering guarantees: none across services; each service awaits its own request. WebCallingService
651
+ serializes registrations with a generation counter (INV-005).
652
+ - Idempotency and retry: no service retries an HTTP call except the usersub refresh (up to 3 tries,
653
+ 30 s apart); `requestAndWaitForRtd` replaces an earlier pending request with the same event type
654
+ and correlation id.
655
+ - Shared-state protection: single-threaded event loop; generation counters in WebCallingService and
656
+ WebexCrossClientService discard results of stale async work.
657
+ - Blocking restrictions: nothing blocks; timers are `setTimeout` only (registration 20 s, RTD
658
+ `timeoutMs`, usersub refresh at TTL minus 60 s).
659
+
660
+ ## State machine
661
+
662
+ ```mermaid
663
+ stateDiagram-v2
664
+ [*] --> NotCreated
665
+ NotCreated --> Composed: first getInstance(options)
666
+ Composed --> Composed: later getInstance returns singleton
667
+ ```
668
+
669
+ Browser voice line status (WebCallingService):
670
+
671
+ ```mermaid
672
+ stateDiagram-v2
673
+ [*] --> unknown
674
+ unknown --> connecting: registerWebCallingLine
675
+ connecting --> registered: line REGISTERED
676
+ connecting --> error: line error or 20 s timeout
677
+ registered --> reconnecting: line RECONNECTING
678
+ reconnecting --> reconnected: line RECONNECTED
679
+ registered --> unregistered: line UNREGISTERED
680
+ reconnected --> unregistered: line UNREGISTERED
681
+ error --> connecting: registerWebCallingLine
682
+ unregistered --> connecting: registerWebCallingLine
683
+ registered --> unknown: deregisterWebCallingLine
684
+ error --> unknown: deregisterWebCallingLine
685
+ ```
686
+
687
+ The overall voice `status` is derived, not stored separately: `not-required` when browser voice is
688
+ not required, `ready` when the line is registered or reconnected and the Mobius socket is not
689
+ disconnected, otherwise `unavailable`.
690
+
691
+ ## Protocol and wire format
692
+
693
+ Request, response, and event payload ownership for the composed transports is anchored in `src/services/index.ts`. HTTP initiates backend work where applicable; WebSocket messages provide realtime events and, for AQM flows, correlated completion. Wellness actions POST `CUSTOM_EVENT` / `WellnessBreakAction` bodies directly to `/event` and accept only status 202; wellness offers arrive as `Wellness_Break_Handler` notifications on the primary or RTD WebSocket, which ContactCenter validates and emits.
694
+
695
+ | Message or frame | Version | Producer or serializer | Consumer or parser | Compatibility and ordering rule |
696
+ | --- | --- | --- | --- | --- |
697
+ | Queue list query | v2 `contact-service-queue` | `src/services/Queue.ts` | WCC gateway | `filter`, `attributes`, `search`, `sort` as field plus ASC or DESC, `desktopProfileFilter`, `provisioningView`, `singleObjectResponse`, `agentView`, `firstLevelView` appended in that order when set |
698
+ | Entry-point dial-number query | v3 `dial-number` | `src/services/EntryPoint.ts` | WCC gateway | `attributes` always includes `id,dialledNumber,entryPointId,entryPointName`; `desktopProfileFilter=true` and `includeEntryPointName=true` always sent |
699
+ | Address book entry query | v2 `address-book/{bookId}/entry` | `src/services/AddressBook.ts` | WCC gateway | `sort=name,ASC` unless overridden |
700
+ | AI Assistant event | none | `src/services/ApiAiAssistant.ts` | AI Assistant service | Body `agentId`, `orgId`, `eventType`, `eventName`, optional `publishTimestamp`, `eventDetails.data`; wellness data carries `action`, `agentSessionId`, `actionTimeStamp` |
701
+ | usersub cross-client state | none | `src/services/WebexCrossClientService.ts` | Webex App | `users`, `compositions[{type: cross-client-state, ttl, composition.devices[{deviceId, appName, state}]}]` |
702
+ | Mercury telephony mute events | none | Webex telephony | `src/services/WxAppTelephonyMercurySync.ts` | `data.actorId` and `data.callId` base64, `data.muted` boolean |
703
+
704
+ ## Caller-visible failure modes
705
+
706
+ | Condition | Signal or result | Caller behavior | Retry or recovery | Evidence |
707
+ | --- | --- | --- | --- | --- |
708
+ | No address book id | `Error('AddressBook: addressBookId is not available for the current agent.')` | Pass `addressBookId` or check the profile | None | `src/services/AddressBook.ts` |
709
+ | No user id for a preference call | `Error` starting `UserPreference: userId` | Log in or pass the id | None | `src/services/UserPreference.ts` |
710
+ | Wellness disabled, missing org, agent, or session, invalid action, or non-202 status | Structured error with reasons such as `WELLNESS_BREAK_NOT_ENABLED` or `WELLNESS_BREAK_ACTION_UNEXPECTED_STATUS_` followed by the status code | Do not retry until the session or flag changes | None | `src/services/ApiAiAssistant.ts` |
711
+ | AI feature off, bad ids, or unknown gateway host | `REAL_TIME_TRANSCRIPTION_NOT_ENABLED`, `SUGGESTED_RESPONSES_NOT_ENABLED`, `INVALID_AGENT_ID_OR_INTERACTION_ID`, `AI_ASSISTANT_BASE_URL_NOT_AVAILABLE` | Check flags and inputs | None | `src/services/ApiAiAssistant.ts` |
712
+ | RTD-correlated request times out or is cleared | The caller's `createTimeoutError()` result, or `Error('RTD request cleared')` | The task reports the summary failure | A new request may be sent | `src/services/ApiAiAssistant.ts` |
713
+ | Calling line registration timeout | `Error('WebCallingService Registration timed out')`, state `error` with `retryable: true` | Retry station login or registration | Caller-owned | `src/services/WebCallingService.ts` |
714
+ | wxApp telephony failure | Structured error with `isWxAppTelephonyError`, `trackingId`, `status` | Task layer decides | None | `src/services/AnswerCallOnWebexService.ts` |
715
+ | usersub publish preflight failure | `Error('User ID is unavailable for cross-client publish')` or the device URL variant | ContactCenter rolls back the flag | Refresh retries only after a successful enable | `src/services/WebexCrossClientService.ts` |
716
+
717
+ ## Pitfalls and constraints
718
+
719
+ - The RTD `WebSocketManager` has no ConnectionService; a code comment in `src/services/index.ts`
720
+ says its reconnection logic is still to be implemented, and ContactCenter connects it only when an AI feature or wellness is
721
+ enabled.
722
+ - `WEBSOCKET_EVENT_TIMEOUT`, `LOGIN_API`, and `STATE_CHANGE_API` are exported but unused; changing
723
+ them changes nothing.
724
+
725
+ ## Module-specific rules
726
+
727
+ - Do: initialize `WebexRequest` before obtaining the Services singleton.
728
+ - Do: preserve separate primary and RTD WebSocket ownership when changing composition.
729
+ - Don't: add feature-flag decisions to the Services composition root.
730
+ - Do: follow the shared data-service shape (Design overview table) for a new paginated service,
731
+ and decide its cache policy explicitly against the Utils module spec.
732
+ - Do: add a new AqmReqs method as a `routing.req()` entry in the agent, contact, or dialer factory,
733
+ with both `notifSuccess` and `notifFail` binds.
734
+
735
+ ## Key design trade-off
736
+
737
+ | Chosen trade-off | Preserved invariant or benefit | Cost or limitation | Decision evidence |
738
+ | --- | --- | --- | --- |
739
+ | Two backend interaction patterns coexist: direct REST for immediate responses and AQM HTTP-plus-WebSocket correlation for asynchronous completion. | Operations whose result the backend reports asynchronously settle only on the real outcome | Two transport models to keep apart; an AQM call needs a connected primary socket | `src/services/core/aqm-reqs.ts` |
740
+
741
+ ## Verification
742
+
743
+ Unit tests mirror module paths under `test/unit/spec/services`. Preserve positive and negative paths, event ordering, timeout/recovery behavior, and the package's 85% global branch/function/line/statement threshold. Run them with `yarn workspace @webex/contact-center test:unit` from the workspace root.
744
+
745
+ | Requirement or invariant | Test level | Positive evidence | Negative or boundary evidence | Gap |
746
+ | --- | --- | --- | --- | --- |
747
+ | `SERVICES-R-001`, `INV-001` | Unit (incidental) | `test/unit/spec/cc.ts` READY calls the mocked Services.getInstance | None found | Add a focused Services singleton composition test if constructor wiring changes; no test calls `Services.getInstance` twice. |
748
+ | `SERVICES-R-002` | Unit | `test/unit/spec/services/config/index.ts`, `test/unit/spec/services/UserPreference.ts`, `test/unit/spec/services/core/aqm-reqs.ts` | `test/unit/spec/services/core/aqm-reqs.ts` failure and timeout cases | Coverage is split across direct and AQM owners. |
749
+ | `SERVICES-R-003` | Unit | `test/unit/spec/cc.ts`, `test/unit/spec/services/UserPreference.ts` | None found | None. |
750
+ | `SERVICES-R-004`, `INV-002` | Unit | `test/unit/spec/services/task/TaskManager.ts`, `test/unit/spec/cc.ts` | None found | None. |
751
+ | `SERVICES-R-005` | Unit | `test/unit/spec/services/core/WebexRequest.ts` | None found | None. |
752
+ | `SERVICES-R-006` | Unit | `test/unit/spec/cc.ts` | None found | None. |
753
+ | `SERVICES-R-007` | Unit | `test/unit/spec/services/Queue.ts`, `test/unit/spec/services/EntryPoint.ts`, `test/unit/spec/cc.ts` default and override cases | `test/unit/spec/services/Queue.ts` empty-filter, sort-order-only, and undefined-override cases | None. |
754
+ | `SERVICES-R-008`, `INV-004` | Unit | `test/unit/spec/services/ApiAiAssistant.ts` exact REQUESTED body with 202 | `test/unit/spec/services/ApiAiAssistant.ts` disabled context, missing organization, network failure, unsupported action | None. |
755
+ | `SERVICES-R-009`, `INV-003` | Unit | `test/unit/spec/services/WebCallingService.ts` custom allow-listed RTMS host | `test/unit/spec/services/WebCallingService.ts` invalid URL and non-allow-listed host fallback | No case for a catalog host exactly equal to `rtmsprod.net`; the existing allow-listed case is a subdomain. |
756
+ | `SERVICES-R-010`, `INV-003` | Unit | `test/unit/spec/services/ApiAiAssistant.ts` historic transcripts with mapped base URL | `test/unit/spec/services/ApiAiAssistant.ts` empty and disallowed-character identifiers, disabled feature | No over-length (more than 128 characters) identifier case. |
757
+ | `SERVICES-R-011`, `INV-005` | Unit | `test/unit/spec/services/WebCallingService.ts` register, reconnect, and Mobius cases | `test/unit/spec/services/WebCallingService.ts` timeout, failure, and superseded cases | None |
758
+ | `SERVICES-R-012` | Unit | `test/unit/spec/services/WebexCrossClientService.ts` publish and refresh cases | `test/unit/spec/services/WebexCrossClientService.ts` missing user id, device URL, retry, and teardown cases | None |
759
+ | `SERVICES-R-013` | Unit | `test/unit/spec/services/AnswerCallOnWebexService.ts` each POST and GET case | `test/unit/spec/services/AnswerCallOnWebexService.ts` failure and call-not-found cases | None |
760
+ | `SERVICES-R-014` | Unit | `test/unit/spec/services/WxAppTelephonyMercurySync.ts` subscribe and callback cases | `test/unit/spec/services/WxAppTelephonyMercurySync.ts` mismatch, missing fields, no Mercury | None |
761
+ | `SERVICES-R-015` | Unit | `test/unit/spec/services/UserPreference.ts` CRUD success cases | `test/unit/spec/services/UserPreference.ts` missing user id and API error cases | None |
762
+ | `SERVICES-R-016` | Unit | `test/unit/spec/services/AddressBook.ts` default and custom parameter cases | `test/unit/spec/services/AddressBook.ts` API error case | The missing-address-book-id error has no direct case |
763
+
764
+ A module specification is complete only when its public surface, invariants, failure modes, and
765
+ test evidence agree with the implementation.