@webex/contact-center 3.13.0-next.12 → 3.13.0-next.14

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 (37) hide show
  1. package/ai-docs/contact-center-spec.md +387 -0
  2. package/dist/cc.js +7 -7
  3. package/dist/cc.js.map +1 -1
  4. package/dist/services/core/Utils.js +21 -2
  5. package/dist/services/core/Utils.js.map +1 -1
  6. package/dist/services/core/aqm-reqs.js +1 -1
  7. package/dist/services/core/aqm-reqs.js.map +1 -1
  8. package/dist/services/core/websocket/connection-service.js +18 -1
  9. package/dist/services/core/websocket/connection-service.js.map +1 -1
  10. package/dist/services/core/websocket/keepalive.worker.js +0 -9
  11. package/dist/services/core/websocket/keepalive.worker.js.map +1 -1
  12. package/dist/services/task/TaskManager.js +9 -1
  13. package/dist/services/task/TaskManager.js.map +1 -1
  14. package/dist/services/task/TaskUtils.js +7 -4
  15. package/dist/services/task/TaskUtils.js.map +1 -1
  16. package/dist/types/services/core/Utils.d.ts +9 -0
  17. package/dist/types/services/core/websocket/keepalive.worker.d.ts +1 -1
  18. package/dist/webex.js +1 -1
  19. package/package.json +2 -2
  20. package/src/cc.ts +19 -11
  21. package/src/services/core/Utils.ts +19 -0
  22. package/src/services/core/ai-docs/core-spec.md +808 -0
  23. package/src/services/core/aqm-reqs.ts +1 -1
  24. package/src/services/core/websocket/connection-service.ts +21 -2
  25. package/src/services/core/websocket/keepalive.worker.js +0 -9
  26. package/src/services/task/TaskManager.ts +12 -1
  27. package/src/services/task/TaskUtils.ts +10 -9
  28. package/src/services/task/ai-docs/task-spec.md +1511 -0
  29. package/test/unit/spec/cc.ts +124 -0
  30. package/test/unit/spec/services/core/Utils.ts +27 -0
  31. package/test/unit/spec/services/core/aqm-reqs.ts +18 -0
  32. package/test/unit/spec/services/core/websocket/connection-service.ts +29 -0
  33. package/test/unit/spec/services/core/websocket/keepalive.worker.ts +18 -0
  34. package/test/unit/spec/services/task/TaskManager.ts +52 -0
  35. package/test/unit/spec/services/task/TaskUtils.ts +51 -0
  36. package/umd/contact-center.min.js +2 -2
  37. package/umd/contact-center.min.js.map +1 -1
@@ -0,0 +1,808 @@
1
+ # Core — SPEC
2
+
3
+ > Start here → root [`AGENTS.md`](../../../../AGENTS.md) · router [`SPEC_INDEX.md`](../../../../ai-docs/SPEC_INDEX.md) · system [`ARCHITECTURE.md`](../../../../ai-docs/ARCHITECTURE.md). This is the module's canonical specification.
4
+
5
+ ## Metadata
6
+
7
+ | Field | Value |
8
+ |---|---|
9
+ | Module id | `core` |
10
+ | Source path(s) | `src/services/core` |
11
+ | Doc kind | Module spec |
12
+ | Coverage score | Partial (manifest-authoritative); 15/15 required document fields present |
13
+ | Generated from | `module-spec` @ SDLC template library `0.2.1` |
14
+ | generated_by / approved_by / updated_at | Codex generator / developer-approved follow-up review remediation / 2026-07-21 |
15
+ | Validation status | Follow-up validation passed (independent Claude fallback, 2026-07-21); coverage remains Partial |
16
+
17
+ ## Evidence Rules
18
+ Every requirement cites stable source and test file paths. Code/tests are the behavioral referee; routed source text supplies explicit intent and rationale. Missing or contradictory evidence blocks promotion.
19
+
20
+ ## Source Material Register
21
+ | Source material | Scope | Decision | Detail location or disposition |
22
+ |---|---|---|---|
23
+ | Reviewed prior module guides and architecture material | overview / architecture / API / tests | used and code-checked | Content is placed by meaning throughout this specification; exact routing remains in the manifest. |
24
+
25
+ ## Overview
26
+ Core is one of nine confirmed Contact Center SDK modules. Own authenticated HTTP, realtime WebSocket lifecycle, AQM request correlation, reconnect/keepalive behavior, and shared error normalization. Existing reviewed documentation is migrated by meaning and code/tests remain the behavioral referee.
27
+
28
+ The Core service provides the foundational infrastructure layer that all other services depend on:
29
+
30
+ - **WebSocket Communication**: Real-time bidirectional messaging with the contact center backend, including automatic reconnection and keepalive management
31
+
32
+ - **HTTP Request Handling**: Authenticated REST API calls to WCC API Gateway with built-in error handling and log upload support
33
+
34
+ - **AQM Request/Response Pattern**: A structured pattern used by the routing and contact layers to send HTTP requests to the contact center backend and correlate responses/failures via WebSocket notifications
35
+
36
+ - **Error Handling & Logging**: Standardized error extraction, logging via `LoggerProxy`, and log upload utilities that all services use for consistent error reporting
37
+
38
+ | Component | File | Description |
39
+ |---|---|---|
40
+ | `WebSocketManager` | [`WebSocketManager.ts`](../websocket/WebSocketManager.ts) | Manages the WebSocket connection lifecycle including initialization, message dispatch, and graceful shutdown. Validates the subscribe/register `webSocketUrl` against the RoutingNotifs allow-list before opening a socket. Emits `message` events for incoming data and `socketClose` when the connection drops while reconnect is allowed. |
41
+ | `ConnectionService` | [`connection-service.ts`](../websocket/connection-service.ts) | Orchestrates reconnection logic and keepalive heartbeats on top of `WebSocketManager`. Detects connection loss/recovery and emits `connectionLost` details; ContactCenter owns any `silentRelogin()` policy. |
42
+ | `WebexRequest` | [`WebexRequest.ts`](../WebexRequest.ts) | Singleton HTTP client that forwards service/resource/method/body options to the authenticated host request API and provides `uploadLogs` diagnostics. |
43
+ | `AqmReqs` | [`aqm-reqs.ts`](../aqm-reqs.ts) | Factory for creating request methods that send HTTP requests and wait for correlated WebSocket notifications (success or failure). Used by routing and task services to implement their API methods. |
44
+ | `Utils` | [`Utils.ts`](../Utils.ts) | Shared utility functions including `getErrorDetails()` for standardized error handling, `generateTaskErrorObject()` for task-specific errors, `createErrDetailsObject()` for constructing error detail objects, and `sanitizeForObservability()` for constraining untrusted remote strings before they reach logs or metrics. |
45
+ | `Err` | [`Err.ts`](../Err.ts) | Error class definitions. `Err.Details` carries structured error metadata (status, type, trackingId) for consistent error propagation. |
46
+ | `constants` | [`constants.ts`](../constants.ts) | Timeout values, interval durations, participant types, interaction states, method name constants, and the `ALLOWED_ROUTING_NOTIFS_DOMAINS` WebSocket host allow-list used throughout the core layer. Any new constants for core should be defined here. |
47
+
48
+ ## Purpose / Responsibility
49
+ Own authenticated HTTP, realtime WebSocket lifecycle, AQM request correlation, reconnect/keepalive behavior, and shared error normalization.
50
+
51
+ ## Stack
52
+ TypeScript/JavaScript, WebSocket, Web Worker keepalive, EventEmitter, Webex request client, Jest 27.
53
+
54
+ ## Folder / Package Structure
55
+ ```text
56
+ src/services/core/
57
+ ├── Err.ts
58
+ ├── GlobalTypes.ts
59
+ ├── Utils.ts
60
+ ├── WebexRequest.ts
61
+ ├── aqm-reqs.ts
62
+ ├── constants.ts
63
+ ├── types.ts
64
+ ├── websocket/
65
+ ```
66
+
67
+ ```text
68
+ services/core/
69
+ ├── aqm-reqs.ts # AQM request handler
70
+ ├── constants.ts # Core constants
71
+ ├── Err.ts # Error classes
72
+ ├── GlobalTypes.ts # Failure, Msg<T>, etc.
73
+ ├── types.ts # Request/response types
74
+ ├── Utils.ts # Utility functions
75
+ ├── WebexRequest.ts # HTTP client
76
+ └── websocket/
77
+ ├── WebSocketManager.ts # Main WS handler
78
+ ├── connection-service.ts # Connection lifecycle
79
+ ├── keepalive.worker.js # Keepalive worker
80
+ └── types.ts # WS types
81
+ ```
82
+
83
+ ## Key Files (source of truth)
84
+ | File | Holds |
85
+ |---|---|
86
+ | `src/services/core/WebexRequest.ts` | Authoritative Core implementation or contract source. |
87
+ | `src/services/core/aqm-reqs.ts` | Authoritative Core implementation or contract source. |
88
+ | `src/services/core/Utils.ts` | Authoritative Core implementation or contract source. |
89
+ | `src/services/core/Err.ts` | Authoritative Core implementation or contract source. |
90
+ | `src/services/core/websocket/WebSocketManager.ts` | Authoritative Core implementation or contract source. |
91
+ | `src/services/core/websocket/connection-service.ts` | Authoritative Core implementation or contract source. |
92
+
93
+ ## Public Surface
94
+ | Contract ID | Type | Surface | Purpose | Compatibility / deprecation | Schema / detail link | Root index |
95
+ |---|---|---|---|---|---|---|
96
+ | `core.surface` | SDK / event / internal API | Internal WebexRequest, WebSocketManager, ConnectionService, AqmReqs, and shared error/request types and helpers. | Stable module consumption boundary. | Additive changes by default; breaking package exports require a major-version transition. | `src/services/core/WebexRequest.ts` | `../../../../ai-docs/CONTRACTS.md` |
97
+
98
+ Compatibility notes:
99
+ - Do not remove or reinterpret exported symbols/events without a documented consumer migration.
100
+
101
+ | Event | Data | Description |
102
+ |---|---|---|
103
+ | `message` | string (JSON) | WebSocket message received |
104
+ | `socketClose` | - | Socket closed while reconnect is allowed |
105
+
106
+ Generic message wrapper used throughout the SDK. All WebSocket messages and AQM responses conform to this shape:
107
+
108
+ ```typescript
109
+ export type Msg<T = any> = {
110
+ type: string; // Message/Event type identifier
111
+ orgId: string; // Organization identifier
112
+ trackingId: string; // Unique tracking identifier
113
+ data: T; // Message/Event payload data
114
+ };
115
+
116
+ // Usage — the payload type goes into `data`
117
+ export type LoginSuccess = Msg<{
118
+ agentId: string;
119
+ status: string;
120
+ // ...
121
+ }>;
122
+ // Resulting shape: { type, orgId, trackingId, data: { agentId, status, ... } }
123
+ ```
124
+
125
+ ### ConnectionService internal surface — not public contracts
126
+
127
+ The only public method in the following list is `setConnectionProp`. The remaining methods are private implementation details documented for ownership and maintenance; they are not public API contracts.
128
+
129
+ 1. `setConnectionProp(prop: ConnectionProp): void` (public)
130
+
131
+ - **Purpose**: Updates connection-level runtime settings used by timers (mainly recovery timeout behavior).
132
+
133
+ - **Params**: `prop` - new connection config object.
134
+
135
+ - **Returns**: `void`.
136
+
137
+ - **Usage**: Called by higher layers when timeout behavior must be tuned after initialization.
138
+
139
+ 2. `setupEventListeners(): void` (private)
140
+
141
+ - **Purpose**: Wires `WebSocketManager` events to internal handlers (`'message' -> onPing`, `'socketClose' -> onSocketClose`).
142
+
143
+ - **Params**: none.
144
+
145
+ - **Returns**: `void`.
146
+
147
+ - **Usage**: Invoked from the constructor once, during `ConnectionService` setup.
148
+
149
+ 3. `onPing(event: any): void` (private)
150
+
151
+ - **Purpose**: Handles every incoming socket message, resets timers, updates keepalive/recovery flags, and emits recovery events when state changes. Parses the payload defensively: a malformed (non-JSON) remote message is logged and ignored without throwing, and timers/reconnect state are left unchanged for that message.
152
+
153
+ - **Params**: `event` - raw message payload (JSON string) received from the socket event stream.
154
+
155
+ - **Returns**: `void`.
156
+
157
+ - **Usage**: Triggered automatically by the `'message'` listener.
158
+
159
+ 4. `onSocketClose(): void` (private)
160
+
161
+ - **Purpose**: Starts the reconnect interval when socket close is detected.
162
+
163
+ - **Params**: none.
164
+
165
+ - **Returns**: `void`.
166
+
167
+ - **Usage**: Triggered automatically by the `'socketClose'` listener.
168
+
169
+ 5. `handleSocketClose(): Promise<void>` (private)
170
+
171
+ - **Purpose**: Performs one reconnect attempt; if browser is online, reinitializes WebSocket and marks socket as reconnected.
172
+
173
+ - **Params**: none.
174
+
175
+ - **Returns**: `Promise<void>` (rejects when browser is offline).
176
+
177
+ - **Usage**: Called repeatedly from `onSocketClose` interval loop.
178
+
179
+ 6. `handleConnectionLost(): void` (private)
180
+
181
+ - **Purpose**: Marks the connection as lost and dispatches a connection status event.
182
+
183
+ - **Params**: none.
184
+
185
+ - **Returns**: `void`.
186
+
187
+ - **Usage**: Scheduled by `onPing` via `reconnectingTimer` after inactivity.
188
+
189
+ 7. `handleRestoreFailed(): Promise<void>` (private)
190
+
191
+ - **Purpose**: Marks restore as failed, disables reconnect, emits failure state, and clears reconnect interval.
192
+
193
+ - **Params**: none.
194
+
195
+ - **Returns**: `Promise<void>`.
196
+
197
+ - **Usage**: Scheduled by `onPing` via `restoreTimer`.
198
+
199
+ 8. `clearTimerOnRestoreFailed(): Promise<void>` (private)
200
+
201
+ - **Purpose**: Stops active reconnect interval to avoid duplicate retries.
202
+
203
+ - **Params**: none.
204
+
205
+ - **Returns**: `Promise<void>`.
206
+
207
+ - **Usage**: Called from reconnect/failure paths whenever interval cleanup is needed.
208
+
209
+ 9. `updateConnectionData(): void` (private)
210
+
211
+ - **Purpose**: Resets transient connection flags (`isConnectionLost`, `isRestoreFailed`, `isSocketReconnected`) after recovery.
212
+
213
+ - **Params**: none.
214
+
215
+ - **Returns**: `void`.
216
+
217
+ - **Usage**: Called inside `onPing` before dispatching recovered state.
218
+
219
+ 10. `dispatchConnectionEvent(socketReconnected = false): void` (private)
220
+
221
+ - **Purpose**: Builds `ConnectionLostDetails`, forwards it to `WebSocketManager.handleConnectionLost`, and emits `'connectionLost'`.
222
+
223
+ - **Params**: `socketReconnected` - optional override used when reconnect is explicitly detected.
224
+
225
+ - **Returns**: `void`.
226
+
227
+ - **Usage**: Used by lost/recovered/restore-failed paths to publish uniform connection state.
228
+
229
+ ```typescript
230
+ type ConnectionLostDetails = {
231
+ isConnectionLost: boolean;
232
+ isRestoreFailed: boolean;
233
+ isSocketReconnected: boolean;
234
+ isKeepAlive: boolean;
235
+ };
236
+
237
+ connectionService.on('connectionLost', (details: ConnectionLostDetails) => {
238
+ if (details.isConnectionLost) {
239
+ // Connection lost — waiting for recovery
240
+ } else if (details.isRestoreFailed) {
241
+ // Recovery timeout (50 s) exceeded
242
+ } else if (details.isSocketReconnected) {
243
+ // Socket successfully reconnected
244
+ }
245
+ });
246
+ ```
247
+
248
+ ## Requires (dependencies)
249
+ - Webex SDK service catalog and authenticated request API
250
+ - Browser WebSocket, Worker, URL and network-status APIs
251
+ - LoggerProxy and log upload
252
+
253
+ ## Requirements
254
+ | ID | WHAT | WHY | Source Evidence | Test / Example Evidence | Assumptions / Gaps | Confidence |
255
+ |---|---|---|---|---|---|---|
256
+ | CORE-R-001 | WebexRequest must delegate service/resource/method/body options to the authenticated host request API and return or reject with the host result unchanged. | All Contact Center REST clients share host-owned authentication and service routing without duplicating credential logic. | `src/services/core/WebexRequest.ts` | `test/unit/spec/services/core/WebexRequest.ts` | Authorization-header masking belongs to `AqmReqs` HTTP-failure handling, not `WebexRequest.request`. | PRESENT |
257
+ | CORE-R-002 | `initWebSocket` requires `{body: SubscribeRequest, resource: string}` and resolves only after WebSocket welcome or rejects on register/connect failure. | Subscription resource selection and readiness are required for a valid realtime session. | `src/services/core/websocket/WebSocketManager.ts` | `test/unit/spec/services/core/websocket/WebSocketManager.ts` | None; source and test evidence rechecked during the 2026-07-09 remediation; independent document revalidation pending. | PRESENT |
258
+ | CORE-R-003 | AqmReqs must be constructed with the primary WebSocket manager and settle generated request promises from `notifSuccess`/`notifFail` binds or `TIMEOUT_REQ`. | HTTP acknowledgement alone does not represent backend operation completion. | `src/services/core/aqm-reqs.ts` | `test/unit/spec/services/core/aqm-reqs.ts` | None; source and test evidence rechecked during the 2026-07-09 remediation; independent document revalidation pending. | PRESENT |
259
+ | CORE-R-004 | ConnectionService must emit transport-state details and retry `initWebSocket({body, resource})`; ContactCenter owns relogin policy. | Separating transport detection from agent recovery prevents Core from mutating package-level session state. | `src/services/core/websocket/connection-service.ts` | `test/unit/spec/services/core/websocket/connection-service.ts` | None; source and test evidence rechecked during the 2026-07-09 remediation; independent document revalidation pending. | PRESENT |
260
+ | CORE-R-005 | The keepalive worker must use the configured 4-second interval and 16-second close-socket timeout; AQM defaults to 20 seconds unless disabled/overridden. | Accurate timing is required for predictable recovery and request failure behavior. | `src/services/core/constants.ts` | `test/unit/spec/services/core/websocket/WebSocketManager.ts` | None; source and test evidence rechecked during the 2026-07-09 remediation; independent document revalidation pending. | PRESENT |
261
+ | CORE-R-006 | Treat Core timeout, keepalive, and recovery constants as fixed behavior controls, not rollout flags; Core owns no feature-gate evaluation. | Conflating operational constants with rollout policy could disable transport or correlation paths unexpectedly. | `src/services/core/constants.ts`, `src/services/index.ts` | `test/unit/spec/services/core/websocket/WebSocketManager.ts` | None; rollout applicability is explicitly N/A for Core. | PRESENT |
262
+ | CORE-R-007 | AQM routing-failure logging never emits the raw routing message payload or error verbatim; the failure-bind path logs only a fixed redacted diagnostic regardless of `redactSensitiveLogs`. When an AQM request additionally sets `redactSensitiveLogs`, timeout logs must also omit the request URL, bind key, and response while preserving settlement and cleanup behavior. | Dynamic request paths and routing messages can contain participant identifiers or phone numbers that must not enter diagnostic logs. | `src/services/core/aqm-reqs.ts`, `src/services/core/types.ts` | `test/unit/spec/services/core/aqm-reqs.ts` | The timeout flag is internal and opt-in; ordinary AQM logging remains backward compatible while routing-failure logging is unconditionally redacted. | PRESENT |
263
+ | CORE-R-008 | `WebSocketManager` opens a socket only for a subscribe/register `webSocketUrl` that parses as a `wss` URL whose host equals, or is a subdomain of, an entry in `ALLOWED_ROUTING_NOTIFS_DOMAINS`; a malformed, non-`wss`, or non-allow-listed URL is rejected with an error and no socket is opened. | A server-controlled subscribe response could otherwise direct the realtime connection to an untrusted or non-secure endpoint. | `src/services/core/websocket/WebSocketManager.ts`, `src/services/core/constants.ts` | `test/unit/spec/services/core/websocket/WebSocketManager.ts` | The allow-list is a fixed domain set; subdomain matching is exact suffix matching on the parsed hostname. | PRESENT |
264
+ | CORE-R-009 | `ConnectionService.onPing` parses the remote socket payload inside a guarded block; a malformed (non-JSON) message is logged via `LoggerProxy` and ignored without throwing, while a valid payload still drives keepalive, reconnect, and restore behavior. | A malformed server-pushed ping must not throw an unhandled error that disrupts the connection liveness loop. | `src/services/core/websocket/connection-service.ts` | `test/unit/spec/services/core/websocket/connection-service.ts` | None. | PRESENT |
265
+ | CORE-R-010 | `AqmReqs` type-map discrimination matches a message type only when the conditions map carries that type as an own enumerable property (`Object.prototype.hasOwnProperty`); inherited prototype keys (e.g. `toString`, `constructor`) in a server-controlled message type can no longer satisfy the discriminator. | A server-controlled message type should not resolve a notification bind through an inherited prototype key it never declared. | `src/services/core/aqm-reqs.ts` | `test/unit/spec/services/core/aqm-reqs.ts` | The guard applies to the condition lookup; condition fields themselves are compared by strict equality as before. | PRESENT |
266
+ | CORE-R-011 | The keepalive worker script contains no console logging; status and lifecycle are communicated only via `postMessage` and worker events. | The package forbids console logging in implementation; the worker is still implementation despite being an embedded script string. | `src/services/core/websocket/keepalive.worker.js` | `test/unit/spec/services/core/websocket/keepalive.worker.ts` | None. | PRESENT |
267
+ | CORE-R-012 | `sanitizeForObservability(value: unknown): string` returns a sanitized string with CR/LF and other control characters removed and the length capped (200 characters), and returns an empty string for non-string input, so untrusted remote values written to logs or metrics cannot inject new log lines or control sequences while legitimate values pass through effectively unchanged. | Remote event types and free-text reasons reach diagnostic logs and metrics; unconstrained values enable log/metrics injection. | `src/services/core/Utils.ts` | `test/unit/spec/services/core/Utils.ts` | Callers in other modules (e.g. ContactCenter logging/metrics) apply this helper at their trust boundary. | PRESENT |
268
+
269
+ ## Design Overview
270
+ Core separates four responsibilities:
271
+
272
+ 1. `WebexRequest` wraps the authenticated host request API and service-catalog routing.
273
+ 2. `WebSocketManager` registers a subscription using both `body` and `resource`, validates the returned `webSocketUrl` against the `ALLOWED_ROUTING_NOTIFS_DOMAINS` allow-list before connecting the socket, owns the keepalive worker, and emits raw messages/socket lifecycle events.
274
+ 3. `AqmReqs` registers bind matchers on the primary WebSocket, sends HTTP through WebexRequest, and settles requests only from matching notifications, HTTP failure, or timeout.
275
+ 4. `ConnectionService` observes message/socket liveness, emits connection-state details, and retries socket initialization. ContactCenter listens to those details and owns optional silent relogin.
276
+
277
+ ```typescript
278
+ const aqmReqs = new AqmReqs(webSocketManager);
279
+ const setState = aqmReqs.req((p: {data: Agent.StateChange}) => ({
280
+ host: WCC_API_GATEWAY,
281
+ url: '/v1/agents/session/state',
282
+ data: p.data,
283
+ method: HTTP_METHODS.PUT,
284
+ notifSuccess: {
285
+ bind: {
286
+ type: CC_EVENTS.AGENT_STATE_CHANGE,
287
+ data: {type: CC_EVENTS.AGENT_STATE_CHANGE_SUCCESS},
288
+ },
289
+ msg: {} as Agent.StateChangeSuccess,
290
+ },
291
+ notifFail: {
292
+ bind: {
293
+ type: CC_EVENTS.AGENT_STATE_CHANGE,
294
+ data: {type: CC_EVENTS.AGENT_STATE_CHANGE_FAILED},
295
+ },
296
+ errId: 'Service.aqm.agent.stateChange',
297
+ },
298
+ }));
299
+ await setState({data: stateChangePayload});
300
+ ```
301
+
302
+ `CLOSE_SOCKET_TIMEOUT` is 16000 ms. `CONNECTIVITY_CHECK_INTERVAL` drives reconnect attempts separately. `TIMEOUT_REQ` is the 20000 ms default AQM timeout; `WEBSOCKET_EVENT_TIMEOUT` is not the active AqmReqs default. Routing-failure diagnostics are always redacted to a fixed message that omits the raw payload and error. A request configuration may additionally set internal `redactSensitiveLogs: true` to redact timeout diagnostics (request URL, bind key, and response); neither redaction changes correlation, errors, timing, or cleanup.
303
+
304
+ ## Data Flow
305
+ ```mermaid
306
+ flowchart LR
307
+ Service[Agent/contact/dialer request] --> AQM[AqmReqs generated function]
308
+ AQM --> Bind[Register success/failure bind matchers]
309
+ AQM --> WR[WebexRequest authenticated HTTP]
310
+ WR --> Backend[WCC backend]
311
+ Backend --> Ack[HTTP acknowledgement]
312
+ Backend --> WS[Primary WebSocket notification]
313
+ WS --> Match{Bind matches?}
314
+ Match -->|success| Resolve[Resolve typed response]
315
+ Match -->|failure| Reject[Reject structured error]
316
+ Bind -->|TIMEOUT_REQ| Reject
317
+ ```
318
+
319
+ ```mermaid
320
+ flowchart TD
321
+ Message[WebSocket message] --> WSM[WebSocketManager emits message]
322
+ WSM --> CS[ConnectionService resets liveness timers]
323
+ CS --> Lost{Lost/recovered state changed?}
324
+ Lost -->|yes| Emit[Emit connectionLost details]
325
+ Emit --> CC[ContactCenter recovery policy]
326
+ SocketClose[Socket close] --> Retry[Retry every CONNECTIVITY_CHECK_INTERVAL]
327
+ Retry --> Init[initWebSocket body + SUBSCRIBE_API resource]
328
+ ```
329
+
330
+ ## Sequence Diagram(s)
331
+ Sequence coverage:
332
+
333
+ | Operation group | Diagram | Failure / recovery coverage |
334
+ |---|---|---|
335
+ | Authenticated REST | WebexRequest | Host/service rejection is propagated unchanged; AQM applies its own error mapping separately. |
336
+ | WebSocket subscribe/connect | Subscribe and connect | Register/connect rejection and welcome resolution. |
337
+ | AQM operation | Correlated request | Duplicate pending request, HTTP failure, failure bind, and timeout reject. |
338
+ | Reconnect | Connection recovery | Offline attempts retry on the next interval; restored and restore-failed states are emitted to ContactCenter. |
339
+
340
+ ### WebexRequest
341
+
342
+ ```mermaid
343
+ sequenceDiagram
344
+ participant Caller
345
+ participant WR as WebexRequest
346
+ participant Host as webex.request
347
+ participant API as WCC backend
348
+ Caller->>WR: request(service, resource, method, body)
349
+ WR->>Host: authenticated request(options)
350
+ Host->>API: HTTP request
351
+ alt success
352
+ API-->>Host: response
353
+ Host-->>WR: status/body/headers
354
+ WR-->>Caller: response
355
+ else host/service rejection
356
+ API-->>Host: error
357
+ Host-->>WR: same rejection
358
+ WR-->>Caller: same rejection
359
+ end
360
+ ```
361
+
362
+ ### Subscribe and connect
363
+
364
+ ```mermaid
365
+ sequenceDiagram
366
+ participant Caller
367
+ participant WSM as WebSocketManager
368
+ participant Host as webex.request
369
+ participant WS as Browser WebSocket
370
+ Caller->>WSM: initWebSocket({body, resource})
371
+ WSM->>Host: register(body, resource)
372
+ Host-->>WSM: WebSocket URL/subscription
373
+ WSM->>WSM: validate webSocketUrl against wss + allow-list
374
+ alt allow-listed wss URL
375
+ WSM->>WS: connect()
376
+ alt welcome
377
+ WS-->>WSM: Welcome event
378
+ WSM-->>Caller: WelcomeResponse
379
+ else connect failure
380
+ WSM-->>Caller: throw error
381
+ end
382
+ else malformed / non-wss / non-allow-listed URL
383
+ WSM-->>Caller: throw error (no socket opened)
384
+ end
385
+ ```
386
+
387
+ ### Correlated request
388
+
389
+ ```mermaid
390
+ sequenceDiagram
391
+ participant Caller
392
+ participant AQM as AqmReqs
393
+ participant WR as WebexRequest
394
+ participant WS as Primary WebSocket
395
+ Caller->>AQM: generated request(payload)
396
+ AQM->>AQM: install notifSuccess/notifFail matchers
397
+ alt matching pending request already exists and timeout is enabled
398
+ AQM-->>Caller: Service.aqm.reqs.Pending
399
+ else request accepted
400
+ AQM->>WR: request(config)
401
+ WR-->>AQM: HTTP acknowledgement only
402
+ alt success bind
403
+ WS-->>AQM: matching success notification
404
+ AQM-->>Caller: typed result
405
+ else failure bind or HTTP rejection
406
+ AQM-->>Caller: structured error
407
+ else timeout
408
+ AQM-->>Caller: Service.aqm.reqs.Timeout
409
+ end
410
+ end
411
+ ```
412
+
413
+ ### Connection recovery
414
+
415
+ ```mermaid
416
+ sequenceDiagram
417
+ participant WSM as WebSocketManager
418
+ participant CS as ConnectionService
419
+ participant CC as ContactCenter
420
+ WSM-->>CS: socketClose/message events
421
+ CS->>CS: update timers and reconnect state
422
+ alt browser online during retry interval
423
+ CS->>WSM: initWebSocket({body: subscribeRequest, resource: SUBSCRIBE_API})
424
+ WSM-->>CS: welcome/message
425
+ CS-->>CC: connectionLost({isSocketReconnected: true})
426
+ CC->>CC: decide whether to silentRelogin()
427
+ else browser offline or reconnect fails
428
+ CS->>CS: retain interval; retry on next CONNECTIVITY_CHECK_INTERVAL
429
+ opt recovery timeout expires
430
+ CS-->>CC: connectionLost({isRestoreFailed: true})
431
+ end
432
+ end
433
+ ```
434
+
435
+ ## Class / Component Relationships
436
+ ```mermaid
437
+ classDiagram
438
+ class WebexRequest
439
+ class WebSocketManager
440
+ class AqmReqs
441
+ class ConnectionService
442
+ class ContactCenter
443
+ AqmReqs --> WebexRequest : authenticated HTTP
444
+ AqmReqs --> WebSocketManager : bind-matched completion
445
+ ConnectionService --> WebSocketManager : liveness + reconnect
446
+ ConnectionService --> ContactCenter : connectionLost details
447
+ ContactCenter --> WebSocketManager : registration lifecycle
448
+ ```
449
+
450
+ ## Use Cases
451
+ - **UC-1 Authenticated REST:** pass the service key and request options to the host and return its response or rejection unchanged. Evidence: `src/services/core/WebexRequest.ts`, `test/unit/spec/services/core/WebexRequest.ts`.
452
+ - **UC-2 Subscribe/connect:** register with `{body, resource}`, connect, and wait for welcome. Evidence: `src/services/core/websocket/WebSocketManager.ts`, `test/unit/spec/services/core/websocket/WebSocketManager.ts`.
453
+ - **UC-3 AQM correlation:** send HTTP but settle on matching notification/failure/timeout. Evidence: `src/services/core/aqm-reqs.ts`, `test/unit/spec/services/core/aqm-reqs.ts`.
454
+ - **UC-4 Reconnect:** retry socket initialization and emit state for ContactCenter-owned recovery. Evidence: `src/services/core/websocket/connection-service.ts`, `test/unit/spec/services/core/websocket/connection-service.ts`.
455
+
456
+ ## State Model
457
+ WebSocketManager owns socket/welcome/worker state. AqmReqs owns pending success/failure/cancel bind maps until settlement or timeout. ConnectionService owns liveness/reconnect timers and flags, then emits state details. It does not own agent credentials, profile, or silent relogin.
458
+
459
+ ## Business Rules & Invariants
460
+ - Core must preserve its typed public/event contracts and must not invent backend states or responses. Enforced in `src/services/core/WebexRequest.ts`.
461
+ - A subscribe/register `webSocketUrl` is trusted only when it is a `wss` URL on the `ALLOWED_ROUTING_NOTIFS_DOMAINS` allow-list; otherwise `WebSocketManager` throws and never opens a socket. Enforced in `src/services/core/websocket/WebSocketManager.ts`.
462
+ - AQM routing-failure logs never contain the raw routing payload or error verbatim. Enforced in `src/services/core/aqm-reqs.ts`.
463
+ - Remote socket payloads are parsed defensively: `ConnectionService.onPing` never throws on malformed input and logs-and-ignores it. Enforced in `src/services/core/websocket/connection-service.ts`.
464
+ - AQM type-map discrimination only honors own enumerable keys of the conditions map, so inherited prototype keys in a server-controlled message type cannot satisfy a bind. Enforced in `src/services/core/aqm-reqs.ts`.
465
+ - Untrusted remote strings are passed through `sanitizeForObservability` before being written to logs or metrics. Enforced in `src/services/core/Utils.ts`.
466
+ - Rollout applicability is N/A for Core: keepalive, timeout, and reconnect constants control behavior, while Services constructs Core without a feature gate.
467
+
468
+ ## Concurrency & Reactive Flow
469
+ The primary WebSocket fans messages to independent AqmReqs, ContactCenter, TaskManager, and ConnectionService listeners. AqmReqs clears all correlated bind entries on settlement. The keepalive worker posts status every 4000 ms and may request closure after 16000 ms offline; reconnect attempts use their separate interval. Listener registration/removal must preserve identity.
470
+
471
+ ## State Machine
472
+ ```mermaid
473
+ stateDiagram-v2
474
+ [*] --> SocketClosed
475
+ SocketClosed --> Connecting: initWebSocket(body, resource)
476
+ Connecting --> Connected: welcome
477
+ Connecting --> SocketClosed: register/connect error
478
+ Connected --> ConnectionSuspect: liveness timer expires
479
+ ConnectionSuspect --> Reconnecting: socket close / retry
480
+ Reconnecting --> Connected: reconnect + message
481
+ Reconnecting --> Reconnecting: offline or retry failure
482
+ Connected --> SocketClosed: manual close
483
+ ```
484
+
485
+ ## Protocol / Wire Format
486
+ `WebSocketManager.initWebSocket` accepts `{body: SubscribeRequest, resource: string}`. Subscription uses the host Webex request API; the returned `webSocketUrl` must be a `wss` URL on the `ALLOWED_ROUTING_NOTIFS_DOMAINS` allow-list or the socket is not opened. AqmReqs operational HTTP uses the WebexRequest wrapper. AQM request configs carry `host`, `url`, optional `method`/`data`, `notifSuccess.bind`, optional `notifFail.bind`, optional cancel bind, and optional timeout. HTTP acknowledgement never substitutes for the matching WebSocket operation result.
487
+
488
+ ## Error Handling & Failure Modes
489
+ | Condition | Signal (error/code/result) | Caller recovery |
490
+ |---|---|---|
491
+ | Dependency rejection | Typed/rethrown error or failure event | Inspect structured details, preserve tracking id, and retry only when the operation is safe. |
492
+ | Timeout or missing async completion | Timeout/recovery state | Follow the module-specific recovery path; never synthesize success. |
493
+
494
+ Standard error handler for SDK operations:
495
+
496
+ ```typescript
497
+ import {getErrorDetails} from './services/core/Utils';
498
+
499
+ try {
500
+ await operation();
501
+ } catch (error) {
502
+ const {error: detailedError, reason} = getErrorDetails(
503
+ error,
504
+ 'methodName', // Method name for logging
505
+ 'ModuleName' // Module name for logging
506
+ );
507
+
508
+ // getErrorDetails automatically:
509
+ // 1. Logs the error
510
+ // 2. Uploads logs (unless AGENT_NOT_FOUND in silentRelogin)
511
+ // 3. Extracts reason from error.details
512
+ // 4. Creates Error with reason as message
513
+
514
+ throw detailedError;
515
+ }
516
+ ```
517
+
518
+ Error handler for task operations:
519
+
520
+ ```typescript
521
+ import {generateTaskErrorObject} from './services/core/Utils';
522
+
523
+ try {
524
+ await taskOperation();
525
+ } catch (error) {
526
+ const taskError = generateTaskErrorObject(
527
+ error,
528
+ 'transfer',
529
+ 'TaskModule'
530
+ );
531
+ throw taskError;
532
+ }
533
+ ```
534
+
535
+ A specific `Msg<T>` for failure responses. Access error details via `failure.data`:
536
+
537
+ ```typescript
538
+ export type Failure = Msg<{
539
+ agentId: string;
540
+ trackingId: string;
541
+ reasonCode: number;
542
+ orgId: string;
543
+ reason: string;
544
+ }>;
545
+
546
+ // Usage in catch
547
+ const failure = error.details as Failure;
548
+ LoggerProxy.error(`Operation failed: ${failure.data?.reason}`, {
549
+ module: 'MyService',
550
+ method: 'myMethod',
551
+ trackingId: failure?.trackingId,
552
+ });
553
+ ```
554
+
555
+ Error interface with a flexible data field for additional context:
556
+
557
+ ```typescript
558
+ export interface AugmentedError extends Error {
559
+ data?: Record<string, any>;
560
+ }
561
+ ```
562
+
563
+ ```typescript
564
+ import * as Err from './Err';
565
+
566
+ const error = new Err.Details('Service.aqm.agent.login', {
567
+ status: 401,
568
+ type: 'UNAUTHORIZED',
569
+ trackingId: 'uuid',
570
+ });
571
+ ```
572
+
573
+ ```typescript
574
+ import {createErrDetailsObject} from './Utils';
575
+
576
+ const errDetails = createErrDetailsObject(webexRequestPayload);
577
+ // Returns Err.Details with trackingId and body
578
+ ```
579
+
580
+ ```typescript
581
+ // Correct
582
+ const {error: detailedError} = getErrorDetails(error, method, module);
583
+ throw detailedError;
584
+
585
+ // Wrong - loses context
586
+ throw error;
587
+ ```
588
+
589
+ This section documents shared error helpers in `Utils.ts` that normalize errors, enrich them with context, and ensure consistent logging/upload behavior across services.
590
+
591
+ ```typescript
592
+ // Msg - Generic message interface (GlobalTypes.ts)
593
+ export type Msg<T = any> = {
594
+ type: string;
595
+ orgId: string;
596
+ trackingId: string;
597
+ data: T;
598
+ };
599
+
600
+ // Failure - Backend error structure (GlobalTypes.ts)
601
+ // Built on Msg<T> with specific error data fields
602
+ export type Failure = Msg<{
603
+ agentId: string;
604
+ trackingId: string;
605
+ reasonCode: number;
606
+ orgId: string;
607
+ reason: string;
608
+ }>;
609
+
610
+ // AugmentedError - Extended Error with flexible data field (GlobalTypes.ts)
611
+ export interface AugmentedError extends Error {
612
+ data?: Record<string, any>;
613
+ }
614
+ ```
615
+
616
+ ```mermaid
617
+ flowchart TD
618
+ A[Error caught] --> B[Cast error.details to Failure]
619
+ B --> C[Extract reason from failure.data.reason]
620
+ C --> D{Is silentRelogin + AGENT_NOT_FOUND?}
621
+ D -->|Yes| E[Skip logging/upload]
622
+ D -->|No| F[Log error with LoggerProxy]
623
+ F --> G[Upload logs via WebexRequest]
624
+ G --> H[Check if stationLogin]
625
+ H -->|Yes| I[Get field-specific error data]
626
+ H -->|No| J[Use generic error]
627
+ I --> K[Create Error with data property]
628
+ J --> K
629
+ K --> L["Return {error, reason}"]
630
+ ```
631
+
632
+ Use this helper for agent/config-style flows where backend failure payloads are transformed into a user-facing `Error` plus `reason`, with optional station-login field metadata.
633
+
634
+ ```typescript
635
+ export const getErrorDetails = (error: any, methodName: string, moduleName: string) => {
636
+ let errData = {message: '', fieldName: ''};
637
+
638
+ const failure = error.details as Failure;
639
+ const reason = failure?.data?.reason ?? `Error while performing ${methodName}`;
640
+
641
+ // Log error (unless AGENT_NOT_FOUND in silentRelogin)
642
+ if (!(reason === 'AGENT_NOT_FOUND' && methodName === 'silentRelogin')) {
643
+ LoggerProxy.error(`${methodName} failed with reason: ${reason}`, {
644
+ module: moduleName,
645
+ method: methodName,
646
+ trackingId: failure?.trackingId,
647
+ });
648
+
649
+ // Upload logs
650
+ WebexRequest.getInstance().uploadLogs({
651
+ correlationId: failure?.trackingId,
652
+ });
653
+ }
654
+
655
+ // For stationLogin, extract field-specific error data (message + fieldName)
656
+ if (methodName === 'stationLogin') {
657
+ errData = getStationLoginErrorData(failure, error.loginOption);
658
+ }
659
+
660
+ const err = new Error(reason);
661
+ // @ts-ignore - custom property for backward compatibility
662
+ err.data = errData;
663
+
664
+ return {error: err, reason};
665
+ };
666
+ ```
667
+
668
+ Use this helper for task/interaction flows where richer task error metadata (`errorType`, `errorData`, `reasonCode`, `trackingId`) is required on the returned `AugmentedError`.
669
+
670
+ ```typescript
671
+ export const generateTaskErrorObject = (
672
+ error: any,
673
+ methodName: string,
674
+ moduleName: string
675
+ ): AugmentedError => {
676
+ const trackingId = error?.details?.trackingId || error?.trackingId || '';
677
+ const errorMsg = error?.details?.msg;
678
+
679
+ const errorMessage = errorMsg?.errorMessage || error.message || 'Error';
680
+ const errorType = errorMsg?.errorType || error.name || 'Unknown Error';
681
+ const errorData = errorMsg?.errorData || '';
682
+ const reasonCode = errorMsg?.reasonCode || 0;
683
+
684
+ LoggerProxy.error(`${methodName} failed: ${errorMessage} (${errorType})`, {
685
+ module: moduleName,
686
+ method: methodName,
687
+ trackingId,
688
+ });
689
+ WebexRequest.getInstance().uploadLogs({correlationId: trackingId});
690
+
691
+ const reason = `${errorType}: ${errorMessage}${errorData ? ` (${errorData})` : ''}`;
692
+ const err: AugmentedError = new Error(reason);
693
+ err.data = {
694
+ message: errorMessage,
695
+ errorType,
696
+ errorData,
697
+ reasonCode,
698
+ trackingId,
699
+ };
700
+
701
+ return err;
702
+ };
703
+ ```
704
+
705
+ ```typescript
706
+ // Use getErrorDetails for:
707
+ // - Agent service operations
708
+ // - Station login/logout flows
709
+ //
710
+ // Use generateTaskErrorObject for:
711
+ // - Task service operations
712
+ // - Interaction-related errors
713
+ ```
714
+
715
+ **Cause**: Subscribe API failed or invalid URL
716
+
717
+ **Solution**: Check subscribe response and WebSocket URL
718
+
719
+ **Cause**: Event listener not registered
720
+
721
+ **Solution**: Ensure `on('message', handler)` called before connect
722
+
723
+ **Cause**: Keepalive not enabled or network issues
724
+
725
+ **Solution**: Verify worker-driven keepalive is running after socket `onopen`, and check network/offline transitions
726
+
727
+ ## Pitfalls
728
+ - `initWebSocket` requires both `body` and `resource`; omitting `resource` registers against no durable subscription endpoint.
729
+ - AqmReqs installs notification binds before HTTP and never resolves from acknowledgement; duplicate binds, timeout, and cleanup ordering are correctness-critical.
730
+ - AQM routing-failure logs are always redacted; sensitive AQM configurations must also use the opt-in `redactSensitiveLogs` flag so dynamic URLs and responses are not included in timeout logs.
731
+ - Do not open the WebSocket directly from a subscribe/register response; the `webSocketUrl` must first pass `wss` scheme and allow-listed host validation.
732
+ - Keepalive closure (16 seconds), lost-connection detection (8 seconds), reconnect interval (5 seconds), and recovery timeout (50 seconds) are separate controls and must not be conflated.
733
+
734
+ ## Module Do's / Don'ts
735
+ - DO keep authentication and service resolution in the host Webex request layer; `WebexRequest.request` is a thin delegating wrapper.
736
+ - DO mask authorization headers in the `AqmReqs` HTTP-error/timeout paths before those details are logged or surfaced.
737
+ - DO enable `redactSensitiveLogs` for AQM requests whose dynamic URL or event payload can contain identity/PII.
738
+ - DO clear success/failure/cancel bind entries together when an AQM request settles.
739
+ - DON'T move silent-relogin policy into ConnectionService; it emits transport state only.
740
+ - DON'T treat timeout constants as feature flags or reuse one timer for another lifecycle purpose.
741
+
742
+ ```typescript
743
+ const response = await webexReq.request({...});
744
+
745
+ if (response.statusCode !== 200) {
746
+ throw new Error(`API call failed with ${response.statusCode}`);
747
+ }
748
+ ```
749
+
750
+ ```typescript
751
+ const trackingId = response.headers?.trackingid ||
752
+ response.headers?.TrackingID;
753
+ ```
754
+
755
+ ## Key Design Trade-off
756
+ - Request initiation stays HTTP while completion can arrive asynchronously over WebSocket; explicit timers and correlation preserve backend fidelity but increase lifecycle complexity.
757
+
758
+ ## Test-Case Strategy (module)
759
+ Unit tests mirror module paths under `test/unit/spec/services/core`. Preserve positive and negative paths, event ordering, timeout/recovery behavior, and the package's 85% global branch/function/line/statement threshold.
760
+
761
+ | Behavior / Requirement | Existing test evidence | Gap |
762
+ |---|---|---|
763
+ | `CORE-R-001` | `test/unit/spec/services/core/WebexRequest.ts` | None. |
764
+ | `CORE-R-002` | `test/unit/spec/services/core/websocket/WebSocketManager.ts` | None. |
765
+ | `CORE-R-003` | `test/unit/spec/services/core/aqm-reqs.ts` | None. |
766
+ | `CORE-R-004` | `test/unit/spec/services/core/websocket/connection-service.ts` | None. |
767
+ | `CORE-R-005` | `test/unit/spec/services/core/websocket/WebSocketManager.ts` | Keep timer-value assertions synchronized with constants. |
768
+ | `CORE-R-006` | `test/unit/spec/services/core/websocket/WebSocketManager.ts` | Feature-gate absence is verified from construction/source rather than a dedicated negative test. |
769
+ | `CORE-R-007` | `test/unit/spec/services/core/aqm-reqs.ts` | None. |
770
+ | `CORE-R-008` | `test/unit/spec/services/core/websocket/WebSocketManager.ts` | None. |
771
+ | `CORE-R-009` | `test/unit/spec/services/core/websocket/connection-service.ts` | None. |
772
+ | `CORE-R-010` | `test/unit/spec/services/core/aqm-reqs.ts` | None. |
773
+ | `CORE-R-011` | `test/unit/spec/services/core/websocket/keepalive.worker.ts` | None. |
774
+ | `CORE-R-012` | `test/unit/spec/services/core/Utils.ts` | None. |
775
+
776
+ ## Traceability
777
+ - Repo architecture: `../../../../ai-docs/ARCHITECTURE.md` · Registry: `../../../../ai-docs/SPEC_INDEX.md`
778
+ - Coverage state and contracts baseline: `../../../../.sdd/manifest.json`
779
+
780
+ - [Root Orchestrator AGENTS.md](../../../../AGENTS.md) - Task routing, critical rules, cross-service patterns
781
+
782
+ - [WebSocketManager.ts](../websocket/WebSocketManager.ts)
783
+
784
+ - [WebexRequest.ts](../WebexRequest.ts)
785
+
786
+ - [Utils.ts](../Utils.ts)
787
+
788
+ - [GlobalTypes.ts](../GlobalTypes.ts)
789
+
790
+ - [Root Orchestrator AGENTS.md](../../../../AGENTS.md) — Task routing, critical rules, cross-service patterns
791
+
792
+ - [WebSocketManager.ts](../websocket/WebSocketManager.ts) — WebSocket lifecycle, keepalive worker integration
793
+
794
+ - [connection-service.ts](../websocket/connection-service.ts) — Reconnection logic, connection state events
795
+
796
+ - [keepalive.worker.js](../websocket/keepalive.worker.js) — Web Worker for periodic keepalive and offline detection
797
+
798
+ - [WebexRequest.ts](../WebexRequest.ts) — Singleton HTTP request handler
799
+
800
+ - [Utils.ts](../Utils.ts) — `getErrorDetails`, `generateTaskErrorObject`, consult utilities
801
+
802
+ - [Err.ts](../Err.ts) — `Err.Message` and `Err.Details` error classes
803
+
804
+ - [aqm-reqs.ts](../aqm-reqs.ts) — AQM request/response pattern, WebSocket notification binding
805
+
806
+ - [GlobalTypes.ts](../GlobalTypes.ts) — `Msg`, `Failure`, `AugmentedError` type definitions
807
+
808
+ - [types.ts](../types.ts) — `Pending`, `Req`, `Conf`, `Res` types for AqmReqs