@webex/contact-center 3.13.0-next.11 → 3.13.0-next.13

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,1511 @@
1
+ # Task — 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 | `task` |
10
+ | Source path(s) | `src/services/task` |
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-10-19 |
15
+ | Validation status | Trust-boundary validation for server-derived transcript interactionId and EP-DN merge fields documented (2026-10-19); AI summary methods, delivery, and cleanup updates pending independent review (2026-10-06); prior follow-up validation passed (independent Claude fallback, 2026-07-21); 1 existing test-coverage gap; 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
+ Task is one of nine confirmed Contact Center SDK modules. Own task creation, media-specific behavior, call-control operations, lifecycle orchestration, task events, and integration with the task state machine. Existing reviewed documentation is migrated by meaning and code/tests remain the behavioral referee.
27
+
28
+ Manage task lifecycle including inbound/outbound calls, hold/resume, consult, transfer, conference, and wrapup.
29
+
30
+ - **Task Creation by Channel**: `TaskFactory.ts` chooses `WebRTC`, `Voice`, or `Digital` based on `MEDIA_CHANNEL` and `webCallingService.loginOption`, so each task class exposes the correct capabilities for the media type.
31
+
32
+ - **Task Orchestration**: `TaskManager.ts` owns task lifecycle wiring—initializes listeners, receives task events, creates/updates tasks, emits SDK events, and exposes task collections for consumers.
33
+
34
+ - **Event Emission and Public APIs**: Task objects register listeners, update context, emit SDK events (e.g., `task:*`), and expose public methods that delegate to `contact.ts` for call control and to the state machine for transition validation.
35
+
36
+ - **AQM Contact Operations**: `contact.ts` builds the AQM request surface for call control (accept, hold, consult, transfer, participant Drop, wrapup, end) and is the primary bridge from `Task`/`Voice`/`WebRTC`/`Digital` methods to WCC task APIs.
37
+
38
+ - **Outbound and Preview-Campaign Dialing**: `dialer.ts` exposes `startOutdial` plus `acceptPreviewContact`, `skipPreviewContact`, and `removePreviewContact`; ContactCenter publishes these operations through typed `cc` methods.
39
+
40
+ - **State Machine Driven UI Controls**: The `state-machine/` folder provides the XState engine (`TaskStateMachine.ts`) plus `actions.ts`, `guards.ts`, `uiControlsComputer.ts`, `constants.ts`, and `types.ts` to compute valid transitions and UI control state. Capability-level details live in `state-machine/ai-docs/task-state-machine-spec.md`.
41
+
42
+ This section describes how the task layer constructs tasks, initializes the state machine, and wires AQM calls to task methods. It provides context for how the state machine fits into the end-to-end flow.
43
+
44
+ - **Listener Setup**: Registers WebSocket listeners to receive CC events and map them to `TaskEvent` payloads.
45
+
46
+ - **Task Registry**: Creates tasks via `TaskFactory`, stores them in the task collection, and updates task data on incoming events.
47
+
48
+ - **Event Emission**: Re-emits `task:*` events on the task or `cc` object for SDK consumers.
49
+
50
+ - **Hydration/Recovery**: Handles state updates and transitions during reconnect/hydrate flows.
51
+
52
+ Example (backend event to state machine):
53
+
54
+ ```typescript
55
+ const payload = TaskManager.mapEventToTaskStateMachineEvent(event, taskData);
56
+ if (payload) {
57
+ task.sendStateMachineEvent(payload);
58
+ }
59
+ ```
60
+
61
+ - **`contact.ts`**: Builds the AQM request surface for call control (hold, consult, transfer, wrapup, end). Task methods delegate to these calls, then drive state transitions based on success/failure events.
62
+
63
+ - **`dialer.ts`**: Exposes `startOutdial` and the three preview-campaign AQM requests used by `cc.startOutdial()`, `cc.acceptPreviewContact()`, `cc.skipPreviewContact()`, and `cc.removePreviewContact()`.
64
+
65
+ Example (task method delegating to AQM):
66
+
67
+ ```typescript
68
+ // task.hold() -> contact.hold(...) -> stateMachine events on response
69
+ await contact.hold({interactionId});
70
+ stateMachineService.send({type: TaskEvent.HOLD_INITIATED, mediaResourceId});
71
+ ```
72
+
73
+ ## Purpose / Responsibility
74
+ Own task creation, media-specific behavior, call-control operations, lifecycle orchestration, task events, and integration with the task state machine.
75
+
76
+ ## Stack
77
+ TypeScript 5.4, EventEmitter, XState 5, @webex/calling, AQM/WebSocket integrations, Jest 27.
78
+
79
+ ## Folder / Package Structure
80
+ ```text
81
+ src/services/task/
82
+ ├── AutoWrapup.ts
83
+ ├── Task.ts
84
+ ├── TaskFactory.ts
85
+ ├── TaskManager.ts
86
+ ├── TaskUtils.ts
87
+ ├── constants.ts
88
+ ├── contact.ts
89
+ ├── dialer.ts
90
+ ├── digital/
91
+ ├── state-machine/
92
+ ├── taskDataNormalizer.ts
93
+ ├── types.ts
94
+ ├── voice/
95
+ ```
96
+
97
+ ```text
98
+ services/task/
99
+ ├── Task.ts # Task class (ITask implementation)
100
+ ├── TaskManager.ts # Singleton task manager
101
+ ├── contact.ts # Contact operations (AQM)
102
+ ├── dialer.ts # Outbound dialing (AQM)
103
+ ├── AutoWrapup.ts # Auto wrapup handler
104
+ ├── TaskUtils.ts # Helper functions
105
+ ├── types.ts # Task types and events
106
+ ├── constants.ts # Task constants
107
+ ├── TaskFactory.ts # Task factory
108
+ ├── taskDataNormalizer.ts # Task data normalization helpers
109
+ ├── digital/ # Digital task implementations
110
+ │ └── Digital.ts
111
+ ├── voice/ # Voice task implementations
112
+ │ ├── Voice.ts
113
+ │ └── WebRTC.ts
114
+ ├── state-machine/ # XState task lifecycle engine
115
+ │ ├── TaskStateMachine.ts
116
+ │ ├── actions.ts
117
+ │ ├── guards.ts
118
+ │ ├── uiControlsComputer.ts
119
+ │ ├── constants.ts
120
+ │ ├── types.ts
121
+ │ └── ai-docs/
122
+ │ ├── AGENTS.md
123
+ │ └── ARCHITECTURE.md
124
+ └── ai-docs/
125
+ ├── AGENTS.md # Usage documentation
126
+ └── ARCHITECTURE.md # Task service architecture
127
+ ```
128
+
129
+ ## Key Files (source of truth)
130
+ | File | Holds |
131
+ |---|---|
132
+ | `src/services/task/Task.ts` | Authoritative Task implementation or contract source. |
133
+ | `src/services/task/TaskManager.ts` | Authoritative Task implementation or contract source. |
134
+ | `src/services/task/TaskFactory.ts` | Authoritative Task implementation or contract source. |
135
+ | `src/services/task/contact.ts` | Authoritative Task implementation or contract source. |
136
+ | `src/services/task/dialer.ts` | Authoritative Task implementation or contract source. |
137
+ | `src/services/task/types.ts` | Authoritative Task implementation or contract source. |
138
+
139
+ ## Public Surface
140
+ | Contract ID | Type | Surface | Purpose | Compatibility / deprecation | Schema / detail link | Root index |
141
+ |---|---|---|---|---|---|---|
142
+ | `task.surface` | SDK / event / internal API | Exported Task/types/events plus application-facing task instances and call-control methods. | Stable module consumption boundary. | Additive changes by default; breaking package exports require a major-version transition. | `src/services/task/Task.ts` | `../../../../ai-docs/CONTRACTS.md` |
143
+ | `task.preview-campaign` | SDK/AQM API | `acceptPreviewContact`, `skipPreviewContact`, `removePreviewContact`, and `PreviewContactPayload`. | Accept, skip, or remove a reserved campaign preview contact; each method returns `Promise<TaskResponse>`. | Additive semver-public methods; removals or signature changes are breaking. | `src/cc.ts`, `src/services/task/dialer.ts`, `src/services/task/types.ts` | `../../../../ai-docs/CONTRACTS.md` |
144
+ | `task.consult-transfer-controls` | SDK task controls | `TaskUIControls.consultTransferDestinations` with ordered `consult` and `transfer` arrays. | Surface default destination availability on every Task without an extra policy method. | Additive semver-public field/types; array order is meaningful and the first item is the default. | `src/services/task/types.ts`, `src/services/task/state-machine/uiControlsComputer.ts` | `../../../../ai-docs/CONTRACTS.md` |
145
+ | `task.conference-participant-drop` | SDK/AQM API | `task.dropConferenceParticipant(payload: DropConferenceParticipantPayload): Promise<TaskResponse>`. | Remove a supported target from a voice conference after correlated routing completion. | Additive semver-public method and payload; removals or signature changes are breaking. | `src/services/task/voice/Voice.ts`, `src/services/task/contact.ts`, `src/services/task/types.ts` | `../../../../ai-docs/CONTRACTS.md` |
146
+ | `task.ai-summary` | SDK/RTD API | Post-call and mid-call summary request/response methods, feature enablement, and receiving-agent summary events. | Provide task-scoped generated summaries without exposing RTD correlation to SDK consumers. | Additive semver-public methods, types, and events; removals or signature changes are breaking. | `src/services/task/Task.ts`, `src/services/task/TaskManager.ts`, `src/services/task/types.ts`, `src/services/ApiAiAssistant.ts` | `../../../../ai-docs/CONTRACTS.md` |
147
+
148
+ Compatibility notes:
149
+ - Do not remove or reinterpret exported symbols/events without a documented consumer migration.
150
+
151
+ - `TASK_EVENTS` enum (`types.ts`)
152
+
153
+ - `TaskData`, `TaskId`, `TaskResponse`, `TaskUIControls` (`types.ts`)
154
+
155
+ - `AISummary`, `AISummaryResponse`, `AISummaryAction`, `AISummaryFeatureEnablement`, and `AISummaryCapabilities` (`types.ts`)
156
+
157
+ - `PreviewContactPayload` (`types.ts`) with `interactionId` and campaign-name `campaignId`
158
+
159
+ - `DropConferenceParticipantPayload` (`types.ts`) with a runtime-validated non-empty `participantId`
160
+
161
+ - `ITask`, `IVoice`, `IWebRTC`, `IDigital` (`types.ts`)
162
+
163
+ - `MEDIA_CHANNEL`, `TASK_CHANNEL_TYPE`, `VOICE_VARIANT` (`types.ts`)
164
+
165
+ - State machine: `TaskState`, `TaskEvent` (`state-machine/constants.ts`)
166
+
167
+ | Event | When Emitted |
168
+ |---|---|
169
+ | `task:incoming` | New task offered to agent |
170
+ | `task:hydrate` | Task data updated |
171
+ | `task:merged` | Tasks merged (EPDN transfer) |
172
+
173
+ | Event | When Emitted |
174
+ |---|---|
175
+ | `task:assigned` | Task assigned to agent |
176
+ | `task:media` | Media stream/track updates are available |
177
+ | `task:unassigned` | Task is unassigned from agent |
178
+ | `task:offerContact` | Contact offer received/updated |
179
+ | `task:offerConsult` | Consult offer received |
180
+ | `task:hold` | Task placed on hold |
181
+ | `task:resume` | Task resumed from hold |
182
+ | `task:end` | Task ended |
183
+ | `task:rejected` | Task rejected / failure path emitted |
184
+ | `task:wrapup` | Task entering wrapup |
185
+ | `task:wrappedup` | Wrapup completed |
186
+ | `task:consulting` | Consult is in progress |
187
+ | `task:consultAccepted` | Consult accepted by destination party |
188
+ | `task:consultCreated` | Consultation started |
189
+ | `task:consultEnd` | Consultation ended |
190
+ | `task:autoAnswered` | Task was auto-answered |
191
+ | `task:recordingStarted` / `task:recordingPaused` / `task:recordingResumed` | Recording lifecycle updates |
192
+ | `task:conferenceStarted` / `task:conferenceEnded` / `task:conferenceFailed` | Conference lifecycle updates |
193
+ | `task:participantJoined` / `task:participantLeft` | Conference participant updates |
194
+ | `task:switchCall` | Switched between consult and main call |
195
+ | `task:outdialFailed` | Outdial operation failed |
196
+ | `task:ui-controls-updated` | UI controls changed due to state transition |
197
+ | `task:midCallSummaryReceived` | Mid-call summary delivered to a receiving agent |
198
+ | `task:featureEnablement` | Per-task AI summary enablement flags received |
199
+ | `task:cleanup` | Internal cleanup signal emitted by state machine |
200
+
201
+ > Full list is defined in `TASK_EVENTS` (`types.ts`).
202
+
203
+ | Event | When Emitted |
204
+ |---|---|
205
+ | `REAL_TIME_TRANSCRIPTION` | A realtime transcript payload is received for the task interaction |
206
+ | `SUGGESTED_RESPONSE` | A final AI Assistant suggestion payload is received for the task interaction |
207
+
208
+ TaskManager also translates qualifying CC events into realtime-transcript start/stop requests through `apiAIAssistant.sendEvent`. The request is sent only when realtime transcripts are enabled and the server-derived `interactionId` is a non-empty string; an invalid id is rejected and logged without sending the event.
209
+
210
+ ### AI summary APIs
211
+
212
+ - `requestPostCallSummary(): Promise<AISummary>` requests a post-call summary.
213
+ - `sendPostCallSummaryResponse(response: AISummaryResponse): Promise<void>` reports the agent's post-call summary outcome.
214
+ - `requestMidCallSummary(action: AISummaryAction): Promise<AISummary>` requests a consult or transfer summary.
215
+ - `sendMidCallSummaryResponse(response: AISummaryResponse, action: AISummaryAction): Promise<void>` reports the corresponding mid-call outcome.
216
+
217
+ Summary requests require both the organization-level generated-summary flag and the task-level feature enablement flag. The dedicated request methods read the current organization flags directly from the existing `ApiAIAssistant.aiFeature` field, populated by ContactCenter from the agent configuration. They check `generatedSummaries.wrapUpSummariesEnabled` or `generatedSummaries.consultTransferSummariesEnabled`; missing flags disable the corresponding request. No separate feature-flags argument or task-local organization configuration is needed. A request resolves only after the event POST succeeds and the matching RTD payload arrives; otherwise it rejects with the applicable disabled, transport, or timeout error. Receiving-agent summaries are delivered separately through `task:midCallSummaryReceived`. Summary content is application data and must not be written to logs or metrics.
218
+
219
+ Task-level feature flags survive `updateTaskData()`, including interaction ID changes during consults or task re-keying. Flags remain available throughout wrapup for post-call summary requests, and TaskManager clears them when the task is removed after wrapup completion or another terminal lifecycle event. Session cleanup also clears them.
220
+
221
+ Each dedicated Task summary method owns its event selection, payload construction, metrics, and error handling. The request methods call `ApiAIAssistant.requestAndWaitForRtd()`. Both response methods read `interactionId` from the current task data and use `interaction.mainInteractionId` as `conversationId`, falling back to `interactionId`. They call `ApiAIAssistant.sendEvent()` directly without caching request IDs on the task.
222
+
223
+ TaskManager reads the receiving task directly from `taskCollection[summary.conversationId]`; the RTD conversation ID is the task's collection key (`task.data.interactionId`). It emits `task:midCallSummaryReceived` immediately when that task exists. Otherwise it stores the latest summary for that ID in an in-memory map without an expiry timer, so an RTD frame can wait for task creation. The common AQM event-processing path replays the stored payload after task creation, updates that register the task under that ID, or merge publication. Replay after creation or merge follows the public task event so consumers can attach listeners. Delivery removes the stored summary, and session cleanup clears all pending summaries.
224
+
225
+ `clearAISummaryState()` cancels pending summary requests, clears task feature enablement, and empties both pending maps. ContactCenter's `deregister()` removes the RTD message listener synchronously before asynchronous teardown. RTD listener registration and removal control inbound delivery; `setConfigFlags()` only supplies task configuration.
226
+
227
+ Initiate outbound call.
228
+
229
+ **Parameters**:
230
+
231
+ - `destination` (string): Phone number to call
232
+
233
+ - `origin` (string): Outbound ANI/caller ID
234
+
235
+ **Returns**: `Promise<TaskResponse>` (AQM response, not a Task instance)
236
+
237
+ **Example**:
238
+
239
+ > **Host-application example:** `updateCallStatus` represents consumer-owned UI handling. SDK package implementation must use `LoggerProxy` and must not log raw runtime values.
240
+
241
+ ```typescript
242
+ const response = await cc.startOutdial('+14155551234', '+18005551000');
243
+
244
+ // Outdial task object is created asynchronously via TaskManager.
245
+ // Listen on cc/task events instead of treating startOutdial response as an ITask.
246
+ cc.on('task:incoming', (task) => {
247
+ task.on('task:assigned', () => {
248
+ updateCallStatus('connected');
249
+ });
250
+
251
+ task.on('task:end', () => {
252
+ updateCallStatus('ended');
253
+ });
254
+ });
255
+ ```
256
+
257
+ Accept an incoming task.
258
+
259
+ **Returns**: `Promise<TaskResponse>`
260
+
261
+ **Example**:
262
+
263
+ ```typescript
264
+ cc.on('task:incoming', async (task) => {
265
+ await task.accept();
266
+ });
267
+ ```
268
+
269
+ Put task on hold or resume.
270
+
271
+ **Parameters**:
272
+
273
+ - Concrete `Task.hold()` / `Voice.hold()` and `Task.resume()` / `Voice.resume()` accept no parameters. The optional `mediaResourceId` exists only on the broader `ITask` compatibility declaration; the implementations derive the active media resource from task state.
274
+
275
+ **Returns**: `Promise<TaskResponse>`
276
+
277
+ **Example**:
278
+
279
+ ```typescript
280
+ // Put on hold
281
+ await task.hold();
282
+
283
+ // Resume
284
+ await task.resume();
285
+ ```
286
+
287
+ End the current task.
288
+
289
+ **Returns**: `Promise<TaskResponse>`
290
+
291
+ **Example**:
292
+
293
+ ```typescript
294
+ await task.end();
295
+ ```
296
+
297
+ Complete task with wrapup code.
298
+
299
+ **Parameters**:
300
+
301
+ - `wrapUpReason` (string, required): Wrapup reason text
302
+
303
+ - `auxCodeId` (string, required): Wrapup code ID
304
+
305
+ **Returns**: `Promise<TaskResponse>`
306
+
307
+ **Example**:
308
+
309
+ ```typescript
310
+ await task.wrapup({
311
+ wrapUpReason: 'Customer issue resolved',
312
+ auxCodeId: 'resolved-code',
313
+ });
314
+ ```
315
+
316
+ Transfer task to another destination.
317
+
318
+ **Parameters**:
319
+
320
+ - `to` (string): Agent ID, queue ID, or phone number
321
+
322
+ - `destinationType` ('queue' | 'agent' | 'dialNumber'): Destination type
323
+
324
+ **Returns**: `Promise<TaskResponse>`
325
+
326
+ **Example**:
327
+
328
+ ```typescript
329
+ // Transfer to queue
330
+ await task.transfer({
331
+ to: 'queue-123',
332
+ destinationType: 'queue',
333
+ });
334
+
335
+ // Transfer to agent
336
+ await task.transfer({
337
+ to: 'agent-456',
338
+ destinationType: 'agent',
339
+ });
340
+ ```
341
+
342
+ Start consultation.
343
+
344
+ **Parameters**:
345
+
346
+ - `to` (string): Agent/queue/phone to consult
347
+
348
+ - `destinationType` ('queue' | 'agent' | 'dialNumber' | 'entryPoint'): Type
349
+
350
+ **Returns**: `Promise<TaskResponse>`
351
+
352
+ **Example**:
353
+
354
+ ```typescript
355
+ await task.consult({
356
+ to: 'agent-456',
357
+ destinationType: 'agent',
358
+ });
359
+
360
+ // Later: complete transfer (consulting voice flow uses transfer())
361
+ await task.transfer({
362
+ to: 'queue-123',
363
+ destinationType: 'queue',
364
+ });
365
+ // Or end consult
366
+ await task.endConsult();
367
+ ```
368
+
369
+ End consultation without transfer.
370
+
371
+ **Parameters**:
372
+
373
+ - `consultEndPayload` (optional `ConsultEndPayload`)
374
+
375
+ **Returns**: `Promise<TaskResponse>`
376
+
377
+ Remove another participant from a voice conference.
378
+
379
+ **Parameters**:
380
+
381
+ - `participantId` (string, required): backend participant target identifier; blank and non-string values reject before AQM registration or telemetry.
382
+
383
+ **Returns**: `Promise<TaskResponse>` after `ParticipantLeftConference` is received for the latest `interaction.mainInteractionId || task.data.interactionId`.
384
+
385
+ **Failure**: `ParticipantDropConferenceFailed`, HTTP rejection, or the default 20-second AQM timeout rejects the promise. The operation does not add a task state-machine event or optimistically change the roster.
386
+
387
+ ```typescript
388
+ await task.dropConferenceParticipant({participantId});
389
+ ```
390
+
391
+ ### Complete TASK_EVENTS inventory
392
+
393
+ The public `TASK_EVENTS` enum contains 52 members; every member is listed below from `src/services/task/types.ts`.
394
+
395
+ | Constant | Event string |
396
+ |---|---|
397
+ | `TASK_INCOMING` | `task:incoming` |
398
+ | `TASK_ASSIGNED` | `task:assigned` |
399
+ | `TASK_MEDIA` | `task:media` |
400
+ | `TASK_UNASSIGNED` | `task:unassigned` |
401
+ | `TASK_HOLD` | `task:hold` |
402
+ | `TASK_RESUME` | `task:resume` |
403
+ | `TASK_CONSULT_END` | `task:consultEnd` |
404
+ | `TASK_CONSULT_QUEUE_CANCELLED` | `task:consultQueueCancelled` |
405
+ | `TASK_CONSULT_QUEUE_FAILED` | `task:consultQueueFailed` |
406
+ | `TASK_UI_CONTROLS_UPDATED` | `task:ui-controls-updated` |
407
+ | `TASK_WXAPP_MUTE_STATE_UPDATED` | `task:wxapp-mute-state-updated` |
408
+ | `TASK_CONSULT_ACCEPTED` | `task:consultAccepted` |
409
+ | `TASK_CONSULTING` | `task:consulting` |
410
+ | `TASK_CONSULT_CREATED` | `task:consultCreated` |
411
+ | `TASK_OFFER_CONSULT` | `task:offerConsult` |
412
+ | `TASK_END` | `task:end` |
413
+ | `TASK_WRAPUP` | `task:wrapup` |
414
+ | `TASK_WRAPPEDUP` | `task:wrappedup` |
415
+ | `TASK_CLEANUP` | `task:cleanup` |
416
+ | `TASK_RECORDING_STARTED` | `task:recordingStarted` |
417
+ | `TASK_RECORDING_PAUSED` | `task:recordingPaused` |
418
+ | `TASK_RECORDING_PAUSE_FAILED` | `task:recordingPauseFailed` |
419
+ | `TASK_RECORDING_RESUMED` | `task:recordingResumed` |
420
+ | `TASK_RECORDING_RESUME_FAILED` | `task:recordingResumeFailed` |
421
+ | `TASK_REJECT` | `task:rejected` |
422
+ | `TASK_OUTDIAL_FAILED` | `task:outdialFailed` |
423
+ | `TASK_HYDRATE` | `task:hydrate` |
424
+ | `TASK_OFFER_CONTACT` | `task:offerContact` |
425
+ | `TASK_AUTO_ANSWERED` | `task:autoAnswered` |
426
+ | `TASK_CONFERENCE_ESTABLISHING` | `task:conferenceEstablishing` |
427
+ | `TASK_CONFERENCE_STARTED` | `task:conferenceStarted` |
428
+ | `TASK_CONFERENCE_FAILED` | `task:conferenceFailed` |
429
+ | `TASK_CONFERENCE_ENDED` | `task:conferenceEnded` |
430
+ | `TASK_PARTICIPANT_JOINED` | `task:participantJoined` |
431
+ | `TASK_PARTICIPANT_LEFT` | `task:participantLeft` |
432
+ | `TASK_CONFERENCE_TRANSFERRED` | `task:conferenceTransferred` |
433
+ | `TASK_CONFERENCE_TRANSFER_FAILED` | `task:conferenceTransferFailed` |
434
+ | `TASK_CONFERENCE_END_FAILED` | `task:conferenceEndFailed` |
435
+ | `TASK_PARTICIPANT_LEFT_FAILED` | `task:participantLeftFailed` |
436
+ | `TASK_EXIT_CONFERENCE` | `task:exitConference` |
437
+ | `TASK_TRANSFER_CONFERENCE` | `task:transferConference` |
438
+ | `TASK_SWITCH_CALL` | `task:switchCall` |
439
+ | `TASK_MERGED` | `task:merged` |
440
+ | `TASK_POST_CALL_ACTIVITY` | `task:postCallActivity` |
441
+ | `TASK_MULTI_LOGIN_HYDRATE` | `task:multiLoginHydrate` |
442
+ | `TASK_CAMPAIGN_PREVIEW_RESERVATION` | `task:campaignPreviewReservation` |
443
+ | `TASK_CAMPAIGN_PREVIEW_ACCEPT_FAILED` | `task:campaignPreviewAcceptFailed` |
444
+ | `TASK_CAMPAIGN_PREVIEW_SKIP_FAILED` | `task:campaignPreviewSkipFailed` |
445
+ | `TASK_CAMPAIGN_PREVIEW_REMOVE_FAILED` | `task:campaignPreviewRemoveFailed` |
446
+ | `TASK_CAMPAIGN_CONTACT_UPDATED` | `task:campaignContactUpdated` |
447
+ | `TASK_MID_CALL_SUMMARY_RECEIVED` | `task:midCallSummaryReceived` |
448
+ | `TASK_FEATURE_ENABLEMENT` | `task:featureEnablement` |
449
+
450
+ ## Requires (dependencies)
451
+ - Services contact/dialer AQM factories
452
+ - WebSocket and RTD WebSocket managers
453
+ - WebCallingService, MetricsManager, and task state machine
454
+
455
+ ## Requirements
456
+ | ID | WHAT | WHY | Source Evidence | Test / Example Evidence | Assumptions / Gaps | Confidence |
457
+ |---|---|---|---|---|---|---|
458
+ | TASK-R-001 | Create only supported Voice/Digital Task implementations and throw `Unknown media type` for unsupported media. | Returning a generic task for unsupported channels would advertise controls the implementation cannot perform. | `src/services/task/TaskFactory.ts` | `test/unit/spec/services/task/TaskFactory.ts` | None; source and test evidence rechecked during the 2026-07-09 remediation; independent document revalidation pending. | PRESENT |
459
+ | TASK-R-002 | Concrete Task/Voice `hold()` and `resume()` implementations remain parameterless while `ITask` retains its optional compatibility parameter. | Documentation must distinguish the broad public interface from concrete runtime signatures. | `src/services/task/Task.ts` | `test/unit/spec/services/task/Task.ts` | None; source and test evidence rechecked during the 2026-07-09 remediation; independent document revalidation pending. | PRESENT |
460
+ | TASK-R-003 | Task and media subclasses must route contact/calling operations into typed state-machine events and emit the complete TASK_EVENTS contract. | Consumers coordinate UI and interaction lifecycle from those events. | `src/services/task/Task.ts` | `test/unit/spec/services/task/Task.ts` | None; source and test evidence rechecked during the 2026-07-09 remediation; independent document revalidation pending. | PRESENT |
461
+ | TASK-R-004 | TaskManager must consume primary/RTD streams and manage task creation, hydration, cleanup, campaign, and AI-assistant flows. | A single task owner prevents duplicate instances and inconsistent state across realtime sources. | `src/services/task/TaskManager.ts` | `test/unit/spec/services/task/TaskManager.ts` | None; source and test evidence rechecked during the 2026-07-09 remediation; independent document revalidation pending. | PRESENT |
462
+ | TASK-R-005 | The contact dependency belongs to Task/TaskFactory-created tasks; dialer is an AqmReqs request factory without that constructor. | Misattributing constructor dependencies causes invalid instantiation examples. | `src/services/task/TaskFactory.ts` | `test/unit/spec/services/task/dialer.ts` | None; source and test evidence rechecked during the 2026-07-09 remediation; independent document revalidation pending. | PRESENT |
463
+ | TASK-R-006 | Keep credentials and authentication outside Task; remote operations delegate through contact/dialer routing, AqmReqs, and Core/WebexRequest. | Task lifecycle objects should never duplicate host token handling or leak authentication state into interaction data. | `src/services/task/Task.ts`, `src/services/task/contact.ts`, `src/services/core/WebexRequest.ts` | `test/unit/spec/services/task/Task.ts`, `test/unit/spec/services/task/contact.ts` | None; authentication ownership is explicit. | PRESENT |
464
+ | TASK-R-007 | Route enabled preview-campaign accept, skip, and remove operations through the dialer AQM factory using `PreviewContactPayload`, returning `Promise<TaskResponse>` from the public ContactCenter methods. Before routing skip/remove, reject the operation when the matching task's disable flag is `'true'`. | Preview reservations require typed payloads and correlated backend completion, while campaign controls must block prohibited skip/remove requests before transport begins. | `src/cc.ts`, `src/services/task/dialer.ts`, `src/services/task/types.ts` | `test/unit/spec/cc.ts`, `test/unit/spec/services/task/dialer.ts` | Public delegation and dialer requests are covered; the `campaignPreviewSkipDisabled` and `campaignPreviewRemoveDisabled` early-exit guards lack direct unit coverage. Independent review identified this gap on 2026-07-15. | PRESENT |
465
+ | TASK-R-008 | Voice `dropConferenceParticipant` must validate the public target, resolve the latest main interaction, POST an empty body to the encoded participant-drop route, and settle only from `ParticipantLeftConference`, `ParticipantDropConferenceFailed`, HTTP failure, or the existing AQM timeout. | Participant removal is backend-authoritative and must preserve event-driven roster/state synchronization without exposing participant identifiers through telemetry or logs. | `src/services/task/voice/Voice.ts`, `src/services/task/contact.ts`, `src/services/task/types.ts` | `test/unit/spec/services/task/voice/Voice.ts`, `test/unit/spec/services/task/contact.ts`, `test/unit/spec/services/core/aqm-reqs.ts` | Backend authorization and media removal are remote-service responsibilities. | PRESENT |
466
+ | TASK-R-009 | ContactCenter must inject Desktop Profile collaboration policy into TaskFactory, and every created voice/digital Task must expose ordered Consult and Transfer destination categories through `TaskUIControls.consultTransferDestinations`. | Task consumers need one already-computed policy surface and must not fetch profile flags or duplicate destination decisions. | `src/cc.ts`, `src/services/task/TaskFactory.ts`, `src/services/task/types.ts` | `test/unit/spec/cc.ts`, `test/unit/spec/services/task/TaskFactory.ts` | Host-specific UI options may only further hide an SDK-allowed category. | PRESENT |
467
+ | TASK-R-010 | TaskManager must propagate backend owner promotion without electing an owner locally. `ContactOwnerChanged` resolves an exact task first, then one unique related task whose existing snapshot proves that the current Agent is active on `mainCall`, or whose incoming snapshot both names that Agent as `interaction.owner` and proves the same active-main-leg membership. Active membership requires a participant entry with `hasLeft !== true`. If no task exists, recovery is limited to that incoming owner=current-Agent proof: create the normal Task under the stable main interaction ID, silently HYDRATE its actor before listener installation, then process the original owner-change event so consumers receive one `task:hydrate` and no `task:incoming`. An owner-changing `ContactUpdated` uses the existing owner-change hydrate path only for an existing task, and a late `ParticipantLeftConference` cannot replace a confirmed active owner with the departed participant. | Every surviving agent must observe the backend-selected primary Agent immediately, including stale child-keyed and narrowly recoverable desynchronization cases, without duplicating tasks or exposing an uninitialized actor. | `src/services/task/TaskManager.ts` | `test/unit/spec/services/task/TaskManager.ts`, `test/unit/spec/services/task/Task.ts` | Backend owner selection and delivery of a complete owner-bearing `ContactOwnerChanged` payload remain remote responsibilities; missing-task `ContactUpdated` remains update-only. | PRESENT |
468
+ | TASK-R-011 | TaskManager must stamp `wrapUpRequired` once in `prepareEventContext` on `AGENT_WRAPUP`, `AGENT_CONSULT_CONFERENCE_ENDED`, `PARTICIPANT_LEFT_CONFERENCE`, and `AGENT_CONFERENCE_TRANSFERRED` before `updateTaskData` / mapper (mapper passes the already-stamped payload through). Voice `exitConference` stamps the same flag on `EXIT_CONFERENCE_SUCCESS` (that HTTP path skips TaskManager) using `shouldWrapUpForThisAgent`, then the same empty-pending self-exit fallback as leave (true unless this agent is a consulted non-owner). Voice pending-list precedence uses the correlated HTTP response only (a cached `agentsPendingWrapUp` is ignored when the response omits the list). `AGENT_WRAPUP` is always `true`. Conference-end uses explicit signals only (`agentsPendingWrapUp`, then `wrapUpRequired` / `isWrapUp`). A nonempty `agentsPendingWrapUp` is authoritative and wins over initiator fallback: `consultingAgentId === self` and actor `transferConferenceRequested` are honored only when the list is empty or absent. On participant leave: do not stamp when the actor ignores `PARTICIPANT_LEAVE` (`CONNECTED`, `HOLD_INITIATING`, `CONF_INITIATING`); stamp only in `HELD`, `RESUME_INITIATING`, `CONSULTING`, `CONSULT_INITIATING`, or `CONFERENCING` (or when no actor snapshot exists). A named other `participantId` is never self-leave (do not infer leave from a partial `participants` map); missing-map fallback applies only when `participantId` is absent (EP-DN), and when a previous task map exists it must have contained self. Remaining agents use explicit signals only; this agent left + nonempty pending uses `includes(self)`; this agent left + empty/absent pending stamps `true` unless this agent is a consulted non-owner. Remaining conference agents stay `false`. `setupAutoWrapupTimer()` still requires profile `autoWrapup !== false`, a valid interval, and a default reason. `PARTICIPANT_LEAVE` and Voice `EXIT_CONFERENCE_SUCCESS` into `WRAPPING_UP` do not transition-emit; the `WRAPPING_UP` entry still emits `task:wrapup`. `EXIT_CONFERENCE_SUCCESS` is handled in `CONNECTED`, `HELD`, and `CONFERENCING`. `TASK_WRAPUP` is handled in `HOLD_INITIATING`, `RESUME_INITIATING`, `CONSULT_INITIATING`, and `CONF_INITIATING` (transition `updateTaskData` + `markEnded` only). Late `TASK_WRAPUP` in `WRAPPING_UP` always runs `updateTaskData` and runs `emitTaskWrapup` only when `context.taskData.wrapUpRequired` was not already `true`. | Consumers rely on `task:wrapup` and `task.autoWrapup` when wrap-up starts; those surfaces only activate when ingress task data already has `wrapUpRequired === true`. | `src/services/task/TaskManager.ts`, `src/services/task/voice/Voice.ts`, `src/services/task/Task.ts`, `src/services/task/state-machine/TaskStateMachine.ts` | `test/unit/spec/services/task/TaskManager.ts`, `test/unit/spec/services/task/voice/Voice.ts`, `test/unit/spec/services/task/Task.ts`, `test/unit/spec/services/task/state-machine/TaskStateMachine.ts` | Profile auto wrap-up, interval, and default reason remain agent-config responsibilities. | PRESENT |
469
+ | TASK-R-012 | TaskManager and TaskUtils validate server-derived inputs at trust boundaries before acting on them. `requestRealTimeTranscripts(eventType: string, interactionId: string): void` forwards the mapped transcript start/stop action to `apiAIAssistant.sendEvent` only when realtime transcripts are enabled and `interactionId` is a non-empty (trimmed) string; otherwise it rejects and logs the request without sending the event. `isEpDnConsultPendingConferenceMerge(taskData, selfAgentId): boolean` normalizes server-pushed `interaction.state`, participant `consultState`, and `callProcessingDetails.hasCustomerLeft` against fixed allow-sets, so unexpected or malformed remote values cannot drive the EP-DN conference-merge decision. | Untrusted realtime payloads must not emit AI-assistant events with malformed identifiers or let out-of-range server fields force a conference-merge outcome. | `src/services/task/TaskManager.ts`, `src/services/task/TaskUtils.ts` | `test/unit/spec/services/task/TaskManager.ts`, `test/unit/spec/services/task/TaskUtils.ts` | None; trust-boundary validation is covered by unit tests. | PRESENT |
470
+
471
+ ## Design Overview
472
+ Task separates its stable consumption boundary from collaborators so ownership and failure behavior stay explicit. A shared Task base preserves a stable API while media-specific subclasses and a separate state engine enforce capability differences.
473
+
474
+ | Channel | Description |
475
+ |---|---|
476
+ | `telephony` | Voice calls |
477
+ | `chat` | Web chat |
478
+ | `email` | Email interactions |
479
+ | `social` | Social media |
480
+ | `sms` | Unsupported by TaskFactory; throws `Unknown media type` |
481
+ | `facebook` | Unsupported by TaskFactory; throws `Unknown media type` |
482
+ | `whatsapp` | Unsupported by TaskFactory; throws `Unknown media type` |
483
+
484
+ If enabled in agent profile, wrapup completes automatically after timeout. The timer starts only when ingress task data has `wrapUpRequired === true` (TASK-R-011).
485
+
486
+ > **Host-application example:** `updateWrapupStatus` is a consumer-owned UI callback, not SDK package logging.
487
+
488
+ ```typescript
489
+ task.on('task:wrappedup', () => {
490
+ updateWrapupStatus('completed');
491
+ });
492
+ ```
493
+
494
+ > **Purpose**: Technical documentation for task lifecycle management.
495
+
496
+ TaskManager is a singleton that:
497
+
498
+ 1. Listens for WebSocket task events
499
+
500
+ 2. Creates/manages Task objects
501
+
502
+ 3. Routes events to appropriate tasks
503
+
504
+ 4. Handles WebRTC call mapping
505
+
506
+ ```typescript
507
+ // Singleton access
508
+ const taskManager = TaskManager.getTaskManager(contact, webCallingService, webSocketManager);
509
+ ```
510
+
511
+ Returns an object of AQM request methods wired to `TASK_API` and `TASK_MESSAGE_TYPE`.
512
+
513
+ **Methods**
514
+
515
+ - `accept`
516
+
517
+ - `hold`
518
+
519
+ - `unHold`
520
+
521
+ - `pauseRecording`
522
+
523
+ - `resumeRecording`
524
+
525
+ - `consult`
526
+
527
+ - `consultEnd`
528
+
529
+ - `consultAccept`
530
+
531
+ - `blindTransfer`
532
+
533
+ - `vteamTransfer`
534
+
535
+ - `consultTransfer`
536
+
537
+ - `end`
538
+
539
+ - `wrapup`
540
+
541
+ - `cancelTask`
542
+
543
+ - `cancelCtq`
544
+
545
+ - `consultConference`
546
+
547
+ - `dropConferenceParticipant`
548
+
549
+ - `exitConference`
550
+
551
+ - `conferenceTransfer`
552
+
553
+ **Notes**
554
+
555
+ - Uses `WCC_API_GATEWAY`.
556
+
557
+ - Consult with `DESTINATION_TYPE.QUEUE` uses `TIMEOUT_REQ` = `'disabled'` for the request timeout.
558
+
559
+ Returns an object of AQM request methods for outbound dialing.
560
+
561
+ **Methods**
562
+
563
+ - `startOutdial` (success: `CC_EVENTS.AGENT_OFFER_CONTACT`, failure: `CC_EVENTS.AGENT_OUTBOUND_FAILED`)
564
+
565
+ - Task/TaskFactory-created task instances receive `contact: ReturnType<typeof routingContact>`; `dialer.ts` has no such constructor and is an AqmReqs factory.
566
+
567
+ - Uses:
568
+
569
+ - `contact.vteamTransfer` / `contact.blindTransfer` in `transfer(...)`.
570
+
571
+ - While in consulting state, `transfer(...)` internally routes through consult-transfer behavior.
572
+
573
+ - `contact.end` in `end()`.
574
+
575
+ - `contact.wrapup` in `wrapup(...)`.
576
+
577
+ Uses `contact` for:
578
+
579
+ - `hold`, `unHold`
580
+
581
+ - `pauseRecording`, `resumeRecording`
582
+
583
+ - `consult`, `consultEnd`, `consultTransfer`
584
+
585
+ - `consultConference`, `exitConference`, `conferenceTransfer`
586
+
587
+ - `dropConferenceParticipant` (Voice only; base Task rejects as unsupported)
588
+
589
+ Uses `contact.accept` in `accept()`.
590
+
591
+ TaskManager maintains a map of active tasks:
592
+
593
+ ```typescript
594
+ private taskCollection: Record<TaskId, ITask> = {};
595
+
596
+ // Tasks indexed by interactionId
597
+ this.taskCollection[interactionId] = task;
598
+
599
+ // Retrieve task
600
+ const task = this.taskCollection[interactionId];
601
+ ```
602
+
603
+ TaskManager uses a staged pipeline in `registerTaskListeners()`:
604
+
605
+ ```typescript
606
+ this.webSocketManager.on('message', (event) => {
607
+ // 1) Parse and validate message
608
+ const message = TaskManager.parseWebSocketMessage(event);
609
+ if (!message) return;
610
+
611
+ // 2) Build event context (task, payload, mapped state-machine event)
612
+ const eventContext = this.prepareEventContext(message);
613
+ if (!eventContext) return;
614
+
615
+ // 3) Handle lifecycle changes (create/update/remove task)
616
+ const actions = this.handleTaskLifecycleEvent(eventContext);
617
+ const {task} = actions;
618
+ if (!task) return;
619
+
620
+ // 4) Keep task.data synchronized
621
+ const {payload, stateMachineEvent} = eventContext;
622
+ if (payload) this.updateTaskData(task, payload);
623
+
624
+ // 5) Drive state machine (which emits TASK_EVENTS)
625
+ if (stateMachineEvent) {
626
+ task.sendStateMachineEvent(stateMachineEvent);
627
+ }
628
+ });
629
+ ```
630
+
631
+ `TaskManager.handleRealtimeWebsocketEvent()` handles payloads arriving on the realtime subscription socket used for AI features. It:
632
+
633
+ 1. Parses the JSON websocket envelope
634
+
635
+ 2. Reads `conversationId` from `payload.data.data.conversationId` and resolves the owning task
636
+
637
+ 3. Emits the payload type and `payload.data` on the task for `REAL_TIME_TRANSCRIPTION`
638
+
639
+ 4. Does the same for `SUGGESTED_RESPONSE`
640
+
641
+ 5. Logs and returns when JSON parsing fails or the interaction has no task; other payload types, including `SUGGESTED_RESPONSE_ACKNOWLEDGE`, fall through without task emission
642
+
643
+ This keeps transcript and suggestion delivery aligned on the same per-task event surface.
644
+
645
+ **wxApp outdial `ContactEnded` / `AgentOutboundFailed` mapping:** Applies only when the current agent is a **wxApp-managed** outdial (`enableWxBetterTogether` + agent participant `deviceType: wxApp`). Pre-accept decline maps to `CONTACT_ENDED` when `wxAppAnswerPending` is false and `agentsPendingWrapUp` is empty — even if the backend sends misleading `interaction.state: wrapUp`. Post-accept wxApp agent end remaps to `OUTBOUND_FAILED` / `AGENT_ENDS` when `wxAppAnswerPending`, `agentsPendingWrapUp`, or `interaction.state === 'wrapUp'` indicates wrapup. **Non-wxApp** agent-terminated `AgentOutboundFailed` (`AGENT_ENDS` / `terminatingParty: Agent`) stays on `OUTBOUND_FAILED` so the OFFERED-state `shouldWrapUp` path runs; `suppressOutdialFailedPopup` on `taskData` skips the outdial-failed modal only. Non-wxApp `ContactEnded` keeps the legacy path. Other failure reasons (`CUSTOMER_BUSY`, etc.) still use `OUTBOUND_FAILED` with the popup. See `TaskManager.isWxAppManagedOutdialTask`, `isAgentTerminatedOutdialWrapup`, and `task-state-machine-spec.md`.
646
+
647
+ **wxApp consumer contract (WXCC-6026):** Hosts enable `enableWxBetterTogether` at init (Phase 1 init-only; re-init to change), bind UI to `task.uiControls` (including optional `main.keypad`), and call **`task.accept()`**, **`task.decline()`**, **`task.toggleMute({ muted? })`**, **`task.transmitDtmf({ dtmf })`**. SDK routes wxApp telephony internally on `Voice`. Shared-line `lineOwnerId` defaults from the wxApp agent participant when omitted.
648
+
649
+ **wxApp OFFERED diagnostics:** `Voice.updateUiControls` delegates offer-decision logging and deferred participant-mismatch WARN/metric to `voice/wxAppOfferObservability.ts` (500 ms grace; observability only). After usersub publish, `TaskManager.refreshWxAppOfferObservabilityForAllTasks()` re-invokes the observer without emitting UI controls. `removeTaskFromCollection` calls `disposeWxAppOfferObservability()` so a pending grace timer cannot emit after the task is dropped (including `CONTACT_MERGED` child removal). Dispose is terminal: the observer sets a disposed guard (timer cancel plus no-op `handleUiControlsUpdate`) so a later `updateUiControls` / refresh cannot schedule a new grace timer.
650
+
651
+ **wxApp offer UI (`uiControlsComputer`):** `wxAppAcceptInFlight` disables accept/decline during the accept REST call. `wxAppAnswerPending` additionally disables accept and decline for **inbound** offers until ASSIGN; wxApp **outdial** keeps decline enabled during the post-accept "Calling…" phase so `cancelTask` remains available.
652
+
653
+ **wxApp decline observability:** Inbound wxApp offers decline via telephony `rejectCall` (`runWxAppReject` → `WXAPP_TASK_DECLINE_*`). wxApp outdial cancellations use CC routing `cancelTask` (`runWxAppOutdialDecline` → additive `WXAPP_TASK_DECLINE_*` plus existing `TASK_DECLINE_*`).
654
+
655
+ **wxApp mute backfill guard (`Voice.syncWxAppMuteFromCallDetails`):** Skips telephony `GET /calls/{callId}` when the interaction is terminated or the task is a pre-accept wxApp OFFERED offer (`wxAppAnswerPending` false). Post-accept OFFERED and engaged CONNECTED sync still run. `isWxAppEngagedForControls` and `getWebexCallingCallId` exclude `TERMINATED` and `COMPLETED`. Expected 400 / "Call not found" / `101002` responses are not logged as errors.
656
+
657
+ For BROWSER login, TaskManager integrates with WebCalling:
658
+
659
+ ```mermaid
660
+ flowchart TD
661
+ A[AgentContactReserved event] --> B[Determine media + loginOption]
662
+ B --> C[TaskFactory chooses Voice/WebRTC class]
663
+ C --> D[Create Task object]
664
+ D --> E[Store in taskCollection]
665
+ E --> F[Send TASK_INCOMING to state machine]
666
+ F --> G[Emit task:incoming]
667
+ H[Independent LINE_EVENTS.INCOMING_CALL] --> I[Find current non-preview telephony task]
668
+ I --> J[Map call ID to interaction ID]
669
+ J --> K[Send TASK_INCOMING association event]
670
+ ```
671
+
672
+ ```typescript
673
+ // WebCallingService maps call IDs to interaction IDs
674
+ this.webCallingService.mapCallToTask(callId, interactionId);
675
+
676
+ // Task uses call for media operations
677
+ this.webCallingService.answerCall(localAudioStream: LocalMicrophoneStream, taskId: string);
678
+ ```
679
+
680
+ AutoWrapup handles automatic task completion:
681
+
682
+ ```typescript
683
+ // AutoWrapup.ts
684
+ export default class AutoWrapup {
685
+ private timer: ReturnType<typeof setTimeout> | null = null;
686
+ private readonly interval: number;
687
+
688
+ start(onComplete: () => void) {
689
+ this.timer = setTimeout(onComplete, this.interval);
690
+ }
691
+
692
+ clear() {
693
+ if (this.timer) {
694
+ clearTimeout(this.timer);
695
+ this.timer = null;
696
+ }
697
+ }
698
+
699
+ getTimeLeft() {}
700
+ isRunning() {}
701
+ getTimeLeftSeconds() {}
702
+ }
703
+ ```
704
+
705
+ Each task operation maps to an AQM request:
706
+
707
+ ```typescript
708
+ // contact.ts
709
+ export default function routingContact(routing: AqmReqs) {
710
+ return {
711
+ accept: routing.req((p) => ({
712
+ url: '/v1/tasks/.../accept',
713
+ notifSuccess: { bind: { type: CC_EVENTS.AGENT_CONTACT_ASSIGNED }},
714
+ notifFail: { bind: { type: CC_EVENTS.AGENT_CONTACT_ASSIGN_FAILED }},
715
+ })),
716
+
717
+ hold: routing.req((p) => ({...})),
718
+ unHold: routing.req((p) => ({...})),
719
+ consultAccept: routing.req((p) => ({...})),
720
+ cancelTask: routing.req((p) => ({...})),
721
+ cancelCtq: routing.req((p) => ({...})),
722
+ end: routing.req((p) => ({...})),
723
+ wrapup: routing.req((p) => ({...})),
724
+ blindTransfer: routing.req((p) => ({...})),
725
+ consult: routing.req((p) => ({...})),
726
+ consultTransfer: routing.req((p) => ({...})),
727
+ // ... more operations
728
+ };
729
+ }
730
+ ```
731
+
732
+ Helper functions for task state analysis:
733
+
734
+ ```typescript
735
+ // TaskUtils.ts
736
+
737
+ // Check if participant is in main interaction
738
+ isParticipantInMainInteraction(task, agentId);
739
+
740
+ // Check if conference is in progress
741
+ getIsConferenceInProgress(taskData);
742
+
743
+ // Check if agent is primary
744
+ isPrimary(task, agentId);
745
+
746
+ // Check if secondary EPDN agent
747
+ isSecondaryEpDnAgent(interaction);
748
+
749
+ // Decide whether an EP-DN consult has merged to conference before a second
750
+ // agent joins the main leg; server-pushed interaction.state, participant
751
+ // consultState, and callProcessingDetails.hasCustomerLeft are normalized
752
+ // against fixed allow-sets, so out-of-range remote values cannot drive the merge.
753
+ isEpDnConsultPendingConferenceMerge(taskData, selfAgentId);
754
+ ```
755
+
756
+ | Metric | Type | When Tracked |
757
+ |---|---|---|
758
+ | `TASK_ACCEPT_SUCCESS` | behavioral, business | Task accepted |
759
+ | `TASK_HOLD_SUCCESS` | operational | Hold succeeded |
760
+ | `TASK_END_SUCCESS` | behavioral, business | Task ended |
761
+ | `TASK_WRAPUP_SUCCESS` | operational | Wrapup completed |
762
+ | `TASK_TRANSFER_SUCCESS` | behavioral, business | Transfer completed |
763
+ | `TASK_OUTDIAL_SUCCESS` | behavioral, business | Outdial completed |
764
+ | `TASK_CONFERENCE_PARTICIPANT_DROP_SUCCESS` | operational, behavioral, business | Participant Drop completed |
765
+
766
+ ## Data Flow
767
+ 1. **WebSocket event arrives** → `TaskManager` maps CC event to `TaskEvent`.
768
+
769
+ 2. **Task creation** (if new) → `TaskFactory` builds `Voice`/`WebRTC`/`Digital`.
770
+
771
+ 3. **State machine actor starts** → `Task` wires emitters + UI control updates.
772
+
773
+ 4. **Task method called** (e.g., hold/transfer) → delegates to `contact.ts` or `dialer.ts`.
774
+
775
+ 5. **State transitions** → guards/actions update context and emit `task:*` events.
776
+
777
+ 6. **SDK consumers update UI** → `TaskUIControls` reflect the latest state.
778
+
779
+ ```mermaid
780
+ flowchart TD
781
+ A[WebSocket event arrives] --> B[TaskManager maps CC event to TaskEvent]
782
+ B --> C{Task exists?}
783
+ C -- No --> D[TaskFactory creates Voice/WebRTC/Digital]
784
+ C -- Yes --> E[Use existing task]
785
+ D --> F[Task initializes state machine actor]
786
+ E --> F
787
+ F --> G[Task method called (hold/transfer/etc)]
788
+ G --> H[contact.ts or dialer.ts API call]
789
+ H --> I[State machine transition]
790
+ I --> J[Actions + guards update context]
791
+ J --> K[Emit task:* events]
792
+ K --> L[TaskUIControls updated for SDK UI]
793
+ ```
794
+
795
+ ## Sequence Diagram(s)
796
+ Sequence coverage:
797
+
798
+ | Operation group | Diagram | Failure / recovery coverage |
799
+ |---|---|---|
800
+ | Incoming task creation | Incoming task | Unsupported media or incomplete event context prevents publication of a partial task. |
801
+ | Voice hold/resume | Hold or resume | Invalid state rejects before transport; failure notification/HTTP error/timeout sends the matching failure event and throws. |
802
+ | Consult/transfer/conference | Consult and transfer | Backend failure notifications drive explicit failure actions and preserve stable call context. |
803
+ | Participant Drop | Participant Drop | Validation rejects locally; AQM success/failure/HTTP/timeout paths settle and clean up without optimistic state changes. |
804
+ | Wrapup/end | Wrapup or end | Validation and backend failures throw; backend events retain distinct WRAPPING_UP/COMPLETED/TERMINATED outcomes. |
805
+ | WebRTC and digital accept | Channel-specific accept | WebRTC media/calling failure and Digital AQM failure follow different rejection paths. |
806
+
807
+ ### Incoming task
808
+
809
+ ```mermaid
810
+ sequenceDiagram
811
+ participant Backend
812
+ participant WS as Primary WebSocket
813
+ participant TM as TaskManager
814
+ participant TF as TaskFactory
815
+ participant Task
816
+ participant CC as ContactCenter
817
+ participant App as Application
818
+ Backend-->>WS: AgentContactReserved event
819
+ WS-->>TM: message event
820
+ TM->>TM: parse and prepare event context
821
+ alt task is new and media is supported
822
+ TM->>TF: createTask(data, dependencies)
823
+ TF-->>TM: Voice / WebRTC / Digital
824
+ TM->>Task: initialize and store
825
+ TM->>Task: send mapped TaskEvent
826
+ TM-->>CC: emit TASK_INCOMING
827
+ CC-->>App: task:incoming
828
+ opt a BROWSER telephony INCOMING_CALL arrives
829
+ TM->>TM: map call ID to current telephony task
830
+ TM->>Task: send TASK_INCOMING for call/task association
831
+ end
832
+ else unsupported media
833
+ TF-->>TM: throw Unknown media type
834
+ else invalid/unmapped event
835
+ TM->>TM: ignore without publishing a partial task
836
+ end
837
+ ```
838
+
839
+ ### Hold or resume
840
+
841
+ ```mermaid
842
+ sequenceDiagram
843
+ participant App
844
+ participant Voice
845
+ participant Actor as Task state-machine actor
846
+ participant Contact as routingContact
847
+ participant AQM as AqmReqs
848
+ participant WR as WebexRequest
849
+ participant WS as Primary WebSocket
850
+ App->>Voice: hold() or resume()
851
+ Voice->>Voice: derive media resource and validate CONNECTED/HELD state
852
+ alt invalid state
853
+ Voice-->>App: throw before transport
854
+ else valid state
855
+ Voice->>Actor: HOLD_INITIATED or UNHOLD_INITIATED
856
+ Voice->>Contact: hold/unHold({interactionId, data: {mediaResourceId}})
857
+ Contact->>AQM: generated request with success/failure binds
858
+ AQM->>WR: authenticated HTTP request
859
+ WR-->>AQM: acknowledgement only
860
+ alt matching success notification
861
+ WS-->>AQM: AGENT_CONTACT_HELD/UNHELD
862
+ AQM-->>Voice: TaskResponse
863
+ Voice->>Actor: HOLD_SUCCESS or UNHOLD_SUCCESS
864
+ Voice-->>App: resolve
865
+ else matching failure, HTTP rejection, or timeout
866
+ WS-->>AQM: failure notification or no completion
867
+ Voice->>Actor: HOLD_FAILED or UNHOLD_FAILED
868
+ Voice-->>App: throw detailed error
869
+ end
870
+ end
871
+ ```
872
+
873
+ ### Consult and transfer
874
+
875
+ ```mermaid
876
+ sequenceDiagram
877
+ participant App
878
+ participant Voice
879
+ participant Actor as Task state-machine actor
880
+ participant Contact as routingContact
881
+ participant WS as Primary WebSocket
882
+ App->>Voice: consult/transfer/conference operation
883
+ Voice->>Actor: initiating event
884
+ Voice->>Contact: correlated AQM operation
885
+ alt matching success notification
886
+ WS-->>Contact: consult/transfer/conference success
887
+ Contact-->>Voice: TaskResponse
888
+ Voice->>Actor: success event and updated call context
889
+ Voice-->>App: resolve
890
+ else failure/cancel/timeout
891
+ WS-->>Contact: failure or cancel notification
892
+ Voice->>Actor: matching failure/end event
893
+ Voice-->>App: throw while preserving stable main/consult context
894
+ end
895
+ ```
896
+
897
+ ### Participant Drop
898
+
899
+ ```mermaid
900
+ sequenceDiagram
901
+ participant App
902
+ participant Voice
903
+ participant Contact as routingContact
904
+ participant AQM as AqmReqs
905
+ participant Backend
906
+ participant WS as Primary WebSocket
907
+ participant TM as TaskManager/state machine
908
+ App->>Voice: dropConferenceParticipant({participantId})
909
+ alt participantId is invalid
910
+ Voice-->>App: reject before metrics, HTTP, or bind registration
911
+ else valid target
912
+ Voice->>Voice: select latest main interaction ID
913
+ Voice->>Contact: participant Drop request
914
+ Contact->>AQM: POST encoded path with empty body and sensitive-log redaction
915
+ AQM->>Backend: authenticated HTTP initiation
916
+ alt ParticipantLeftConference
917
+ Backend-->>WS: ParticipantLeftConference
918
+ WS-->>AQM: correlated success
919
+ AQM-->>Voice: TaskResponse
920
+ WS-->>TM: existing PARTICIPANT_LEAVE mapping updates roster/conference state
921
+ Voice-->>App: resolve
922
+ else ParticipantDropConferenceFailed, HTTP failure, or timeout
923
+ AQM-->>Voice: structured rejection
924
+ Voice-->>App: reject without participant data in logs/metrics
925
+ end
926
+ end
927
+ ```
928
+
929
+ `ParticipantLeftConference` is authoritative for both a customer hangup and an
930
+ agent-initiated customer Drop. The task removes only participants absent from
931
+ the latest interaction snapshot. TaskManager first uses the exact interaction
932
+ key, then the existing reservation fallback, and finally one unique task whose
933
+ `interaction.mainInteractionId`, interaction-level `parentInteractionId`, or
934
+ `callProcessingDetails.parentInteractionId` matches an identifier carried by the
935
+ lifecycle event. Object aliases are deduplicated and all aliases are removed
936
+ during terminal cleanup; ambiguous related-interaction matches are ignored
937
+ without logging participant data. Events carrying none of those correlation
938
+ identifiers are not routed. `ContactMerged` removes the EP-DN child task,
939
+ hydrates the main-interaction task, and publishes the existing `task:merged`
940
+ event so consumers can rebind to the surviving task object.
941
+
942
+ Dropping an Agent while that Agent is consulting continues through the existing
943
+ `PARTICIPANT_LEAVE` transition, which clears consult state and emits the normal
944
+ participant-left and task-end lifecycle. `PARTICIPANT_LEAVE` is handled in
945
+ `HELD`, `RESUME_INITIATING`, `CONSULTING`, `CONSULT_INITIATING`, and
946
+ `CONFERENCING`; `CONNECTED`, `HOLD_INITIATING`, and `CONF_INITIATING` ignore the
947
+ event. The current Agent is treated as departed only when the event names that
948
+ Agent or the updated participants map omits that Agent (EP-DN removal). Remaining
949
+ in the map with `hasLeft`, or disappearing only from `mainCall` media, is
950
+ non-terminal. A consulted Agent receiving `AgentConsultEnded` continues through
951
+ `CONSULT_END`; current-agent departure is evaluated before consult-initiator
952
+ recovery and does not use mainCall membership as self-departure evidence.
953
+ Accepted consultees emit `task:consultEnd` and `task:end`, while an unaccepted
954
+ OFFERED consultee retains the existing consult-end-only signal. A surviving
955
+ consult initiator still returns to the main-call state selected by the existing
956
+ guards. The state-machine transition table lives in
957
+ `src/services/task/state-machine/ai-docs/task-state-machine-spec.md`
958
+ `TASK_STATE_MACHINE-R-008`.
959
+
960
+ Primary-Agent promotion remains backend-authoritative and follows the two-event
961
+ desktop contract. `ContactOwnerChanged` updates the promoted Agent; TaskManager
962
+ prefers an exact task, then one unique related task resolved through nested
963
+ main/parent identifiers, the task collection key, or the `mainCall` media-map
964
+ identity. A related candidate is eligible when its current
965
+ snapshot contains the current Agent's participant entry with `hasLeft !== true`
966
+ and membership on the `mType: mainCall` leg. The incoming snapshot can provide
967
+ that evidence only when it also names the current Agent as `interaction.owner`;
968
+ this permits an authoritative promotion payload to repair a stale child-keyed
969
+ snapshot while still excluding consult-only tasks. The update keeps the
970
+ surviving main interaction identity even when the notification names a
971
+ promoted-Agent child interaction. Conflicting main identifiers, ambiguous
972
+ matches, and a canonical key occupied by a distinct task are ignored rather
973
+ than replacing an existing task.
974
+
975
+ If no related task exists, TaskManager recovers only the promoted current Agent
976
+ from a non-terminal telephony `ContactOwnerChanged` payload that provides the same
977
+ active-main-leg evidence. It creates the normal Task through TaskFactory under the
978
+ stable main interaction ID, sends an internal HYDRATE before installing external
979
+ listeners, and then processes the original owner-change event. Consumers
980
+ therefore receive one `task:hydrate`, never a synthetic `task:incoming`, and a
981
+ later canonical contact or merge event reuses the same task rather than creating
982
+ an alias. Missing, partial, departed, consult-only, non-promoted, and ambiguous
983
+ payloads are ignored for recovery.
984
+
985
+ For other surviving Agents, a `ContactUpdated` whose non-empty
986
+ `interaction.owner` differs from the current owner is delivered through the
987
+ existing `CONTACT_OWNER_CHANGED`/`task:hydrate` path; same-owner or owner-less
988
+ updates remain data-only, and a missing task is not created from `ContactUpdated`.
989
+ If a later `ParticipantLeftConference` still names the departed participant as
990
+ owner, an already confirmed owner is retained only when the new roster proves
991
+ that confirmed owner remains active on `mainCall` and explicitly names the
992
+ incoming owner as `participantId` or marks it `hasLeft`. Main-call omission alone
993
+ is not departure evidence. The SDK never chooses the successor locally.
994
+
995
+ In the Contact Center sample roster, non-owner and Supervisor targets remain
996
+ visible but non-actionable; the UI does not display a separate read-only label.
997
+ The roster is visible whenever the viewing agent remains active on the main leg
998
+ and at least one supported non-customer participant (Agent, EP-DN, or Supervisor)
999
+ is visible. Consequently, Customer-only calls use the original 1-to-1 UI, while
1000
+ a single Agent remains visible after the Customer leaves. Dropping the last
1001
+ non-customer participant while the Customer remains restores the 1-to-1 UI.
1002
+ Terminated tasks and viewing-agent departure hide the roster immediately.
1003
+
1004
+ The current consult leg may additionally contribute a pending EP-DN row before
1005
+ conference merge. The sample displays its `dn`, then its participant/media key
1006
+ as a fallback, and deduplicates the row once it joins the main leg. The owner can
1007
+ see a disabled Drop action until merge; other active main-call agents see the
1008
+ same row without an action. Consult-only Agent targets remain excluded.
1009
+
1010
+ ### Wrapup or end
1011
+
1012
+ ```mermaid
1013
+ sequenceDiagram
1014
+ participant App
1015
+ participant Task
1016
+ participant Contact as routingContact
1017
+ participant WS as Primary WebSocket
1018
+ participant Actor as Task state-machine actor
1019
+ App->>Task: wrapup(payload) or end()
1020
+ alt invalid wrapup payload or missing task data
1021
+ Task-->>App: throw validation error
1022
+ else valid request
1023
+ Task->>Contact: wrapup/end({interactionId, data})
1024
+ alt matching success notification
1025
+ WS-->>Contact: wrapup/end success
1026
+ Contact-->>Task: TaskResponse
1027
+ WS-->>Actor: backend event selects WRAPPING_UP/COMPLETED/TERMINATED
1028
+ Task-->>App: resolve
1029
+ else failure, HTTP rejection, or timeout
1030
+ Contact-->>Task: structured rejection
1031
+ Task-->>App: throw detailed error
1032
+ end
1033
+ end
1034
+ ```
1035
+
1036
+ ### Channel-specific accept
1037
+
1038
+ ```mermaid
1039
+ sequenceDiagram
1040
+ participant App
1041
+ participant TF as TaskFactory
1042
+ participant WebRTC
1043
+ participant Digital
1044
+ participant Calling as WebCallingService
1045
+ participant Contact as routingContact
1046
+ TF-->>App: WebRTC or Digital task
1047
+ alt WebRTC accept
1048
+ App->>WebRTC: accept()
1049
+ WebRTC->>WebRTC: getUserMedia(audio)
1050
+ WebRTC->>Calling: answerCall(localAudioStream, interactionId)
1051
+ alt media/calling succeeds
1052
+ WebRTC-->>App: resolve
1053
+ else media/calling failure
1054
+ WebRTC-->>App: throw detailed error
1055
+ end
1056
+ else Digital accept
1057
+ App->>Digital: accept()
1058
+ Digital->>Contact: accept({interactionId})
1059
+ alt AQM success notification
1060
+ Contact-->>Digital: TaskResponse
1061
+ Digital-->>App: resolve
1062
+ else failure or timeout
1063
+ Digital-->>App: throw detailed error
1064
+ end
1065
+ end
1066
+ ```
1067
+
1068
+ ## Class / Component Relationships
1069
+ - **Hierarchy**: `Task` (base) → `Voice` → `WebRTC`; `Digital` extends `Task`.
1070
+
1071
+ - **`Task` (base)**: Holds task data, emits SDK events, and provides default (unsupported) implementations for call control APIs.
1072
+
1073
+ - **`Voice`**: Adds hold/resume and consult-related capabilities for telephony tasks.
1074
+
1075
+ - **`WebRTC`**: Overrides `accept/decline` for WebRTC calls and hooks media events.
1076
+
1077
+ - **`Digital`**: Implements `accept` and refreshes digital task data/UI controls.
1078
+
1079
+ | Component | File | Responsibility |
1080
+ |---|---|---|
1081
+ | `TaskManager` | `task/TaskManager.ts` | Task lifecycle coordination |
1082
+ | `Task` | `task/Task.ts` | Individual task operations |
1083
+ | `contact` | `task/contact.ts` | AQM request definitions |
1084
+ | `dialer` | `task/dialer.ts` | Outbound call initiation |
1085
+ | `AutoWrapup` | `task/AutoWrapup.ts` | Auto wrapup timer |
1086
+ | `taskDataNormalizer` | `task/taskDataNormalizer.ts` | Normalizes backend task payloads |
1087
+ | `TaskUtils` | `task/TaskUtils.ts` | Utility functions |
1088
+ | `state-machine` | `task/state-machine/*` | Task state transitions, guards, and UI control computation |
1089
+
1090
+ **File:** `Task.ts`
1091
+
1092
+ **Properties**
1093
+
1094
+ - `data: TaskData`
1095
+
1096
+ - `webCallMap: Record<TaskId, CallId>`
1097
+
1098
+ - `stateMachineService?: ActorRefFrom<TaskStateMachine>`
1099
+
1100
+ - `state?: SnapshotFrom<TaskStateMachine>`
1101
+
1102
+ - `autoWrapup?: AutoWrapup`
1103
+
1104
+ - `uiControls: TaskUIControls` (getter)
1105
+
1106
+ **Methods**
1107
+
1108
+ - `accept(): Promise<TaskResponse>` (abstract)
1109
+
1110
+ - `decline(): Promise<TaskResponse>` (default: unsupportedMethodError)
1111
+
1112
+ - `pauseRecording(): Promise<TaskResponse>` (default: unsupportedMethodError)
1113
+
1114
+ - `resumeRecording(resumeRecordingPayload: ResumeRecordingPayload): Promise<TaskResponse>` (default: unsupportedMethodError)
1115
+
1116
+ - `consult(consultPayload: ConsultPayload): Promise<TaskResponse>` (default: unsupportedMethodError)
1117
+
1118
+ - `endConsult(consultEndPayload?: ConsultEndPayload): Promise<TaskResponse>` (default: unsupportedMethodError)
1119
+
1120
+ - `consultTransfer(consultTransferPayload?: ConsultTransferPayLoad): Promise<TaskResponse>` (default: unsupportedMethodError)
1121
+
1122
+ - `consultConference(): Promise<TaskResponse>` (default: unsupportedMethodError)
1123
+
1124
+ - `exitConference(): Promise<TaskResponse>` (default: unsupportedMethodError)
1125
+
1126
+ - `transferConference(): Promise<TaskResponse>` (default: unsupportedMethodError)
1127
+
1128
+ - `switchCall(): Promise<TaskResponse>` (default: unsupportedMethodError)
1129
+
1130
+ - `toggleMute(): Promise<void>` (default: unsupportedMethodError)
1131
+
1132
+ - `unregisterWebCallListeners(): void` (default: no-op + log)
1133
+
1134
+ - `cancelAutoWrapupTimer(): void`
1135
+
1136
+ - Concrete `Task.hold()` / `Voice.hold()` are parameterless; the `ITask` compatibility interface permits `hold(mediaResourceId?: string)`.
1137
+
1138
+ - Concrete `Task.resume()` / `Voice.resume()` are parameterless; the `ITask` compatibility interface permits `resume(mediaResourceId?: string)`.
1139
+
1140
+ - `holdResume(): Promise<TaskResponse>` (default: unsupportedMethodError)
1141
+
1142
+ - `sendStateMachineEvent(event: TaskEventPayload): void`
1143
+
1144
+ - `updateTaskData(updatedData: TaskData, shouldOverwrite = false): ITask`
1145
+
1146
+ - `transfer(transferPayload: TransferPayLoad): Promise<TaskResponse>`
1147
+
1148
+ - `end(): Promise<TaskResponse>`
1149
+
1150
+ - `wrapup(wrapupPayload: WrapupPayLoad): Promise<TaskResponse>`
1151
+
1152
+ **File:** `voice/Voice.ts`
1153
+
1154
+ **Notes**
1155
+
1156
+ - Extends `Task`.
1157
+
1158
+ - Provides `hold()` and `resume()` that delegate to `holdResume()`.
1159
+
1160
+ - Explicitly overrides `accept()` and `decline()` to throw `unsupportedMethodError`.
1161
+
1162
+ - `WebRTC` then overrides these methods with concrete implementations.
1163
+
1164
+ **File:** `voice/WebRTC.ts`
1165
+
1166
+ **Notes**
1167
+
1168
+ - Extends `Voice`.
1169
+
1170
+ - Overrides `accept()` and `decline()` for WebRTC calls.
1171
+
1172
+ - Emits `TASK_EVENTS.TASK_MEDIA` on remote media (`CALL_EVENT_KEYS.REMOTE_MEDIA`).
1173
+
1174
+ - Overrides `unregisterWebCallListeners()`.
1175
+
1176
+ **File:** `digital/Digital.ts`
1177
+
1178
+ **Notes**
1179
+
1180
+ - Extends `Task`.
1181
+
1182
+ - Implements `accept()`.
1183
+
1184
+ - Overrides `updateTaskData()` to refresh digital task data and UI controls.
1185
+
1186
+ **File:** `TaskFactory.ts`
1187
+
1188
+ **API**
1189
+
1190
+ - `createTask(contact, webCallingService, data, configFlags, wrapupData?, agentId?, agentName?): Task`
1191
+
1192
+ **Behavior**
1193
+
1194
+ - Chooses `WebRTC` vs `Voice` for `MEDIA_CHANNEL.TELEPHONY` based on `webCallingService.loginOption`.
1195
+
1196
+ - Chooses `Digital` for `MEDIA_CHANNEL.CHAT`, `MEDIA_CHANNEL.EMAIL`, `MEDIA_CHANNEL.SOCIAL`.
1197
+
1198
+ - Throws `Error` for unknown media types.
1199
+
1200
+ ```mermaid
1201
+ classDiagram
1202
+ class Task {
1203
+ <<abstract>>
1204
+ # contact
1205
+ # metricsManager
1206
+ + data: TaskData
1207
+ + webCallMap: Record~TaskId, CallId~
1208
+ + stateMachineService
1209
+ + state
1210
+ # currentUiControls: TaskUIControls
1211
+ # uiControlConfig: UIControlConfig
1212
+ + autoWrapup: AutoWrapup
1213
+ + accept() TaskResponse
1214
+ + transfer(payload) TaskResponse
1215
+ + end() TaskResponse
1216
+ + wrapup(payload) TaskResponse
1217
+ + updateTaskData(updatedData, shouldOverwrite) ITask
1218
+ + sendStateMachineEvent(event) void
1219
+ + hold() TaskResponse
1220
+ + resume() TaskResponse
1221
+ + holdResume() TaskResponse
1222
+ + consult(payload) TaskResponse
1223
+ + endConsult(payload) TaskResponse
1224
+ + consultTransfer(payload) TaskResponse
1225
+ + consultConference() TaskResponse
1226
+ + exitConference() TaskResponse
1227
+ + transferConference() TaskResponse
1228
+ + pauseRecording() TaskResponse
1229
+ + resumeRecording(payload) TaskResponse
1230
+ + toggleMute() void
1231
+ + unregisterWebCallListeners() void
1232
+ + cancelAutoWrapupTimer() void
1233
+ }
1234
+
1235
+ class Voice {
1236
+ + accept() TaskResponse
1237
+ + decline() TaskResponse
1238
+ + hold() TaskResponse
1239
+ + resume() TaskResponse
1240
+ + holdResume() TaskResponse
1241
+ + pauseRecording() TaskResponse
1242
+ + resumeRecording(payload) TaskResponse
1243
+ + consult(payload) TaskResponse
1244
+ + endConsult(payload) TaskResponse
1245
+ + transfer(payload) TaskResponse
1246
+ + consultConference() TaskResponse
1247
+ + exitConference() TaskResponse
1248
+ + transferConference() TaskResponse
1249
+ }
1250
+
1251
+ class WebRTC {
1252
+ - localAudioStream: LocalMicrophoneStream
1253
+ - webCallingService: WebCallingService
1254
+ + accept() TaskResponse
1255
+ + decline() TaskResponse
1256
+ + toggleMute() void
1257
+ + unregisterWebCallListeners() void
1258
+ }
1259
+
1260
+ class Digital {
1261
+ + accept() TaskResponse
1262
+ + updateTaskData(newData, shouldOverwrite) IDigital
1263
+ }
1264
+
1265
+ class TaskFactory {
1266
+ + createTask(contact, webCallingService, data, configFlags, wrapupData, agentId, agentName) Task
1267
+ }
1268
+
1269
+ Task <|-- Voice
1270
+ Voice <|-- WebRTC
1271
+ Task <|-- Digital
1272
+
1273
+ TaskFactory ..> Task : creates
1274
+ TaskFactory ..> Voice : creates
1275
+ TaskFactory ..> WebRTC : creates
1276
+ TaskFactory ..> Digital : creates
1277
+ ```
1278
+
1279
+ ## Use Cases
1280
+ - **UC-1 Incoming task creation:** TaskManager maps a backend offer/reservation, TaskFactory creates a supported Voice/WebRTC/Digital task, and ContactCenter emits the typed incoming event. Evidence: `src/services/task/TaskManager.ts`, `src/services/task/TaskFactory.ts`, `test/unit/spec/services/task`.
1281
+ - **UC-2 Accept/hold/resume:** the Task or Voice method delegates the remote operation and sends the matching typed event to its actor; concrete hold/resume implementations are parameterless. Evidence: `src/services/task/Task.ts`, `src/services/task/voice/Voice.ts`, `test/unit/spec/services/task`.
1282
+ - **UC-3 Consult/transfer/conference:** Voice coordinates contact routing with initiating/stable actor states and emits the corresponding complete `TASK_EVENTS` contract. Evidence: `src/services/task/voice/Voice.ts`, `src/services/task/types.ts`, `test/unit/spec/services/task`.
1283
+ - **UC-4 Wrapup/end:** backend end/wrapup notifications drive WRAPPING_UP and final COMPLETED/TERMINATED outcomes without collapsing them into one result. Evidence: `src/services/task/Task.ts`, `src/services/task/state-machine/TaskStateMachine.ts`, `test/unit/spec/services/task`.
1284
+ - **UC-5 WebRTC and digital behavior:** TaskFactory selects channel-specific subclasses; unsupported SMS/Facebook/WhatsApp values throw `Unknown media type`. Evidence: `src/services/task/TaskFactory.ts`, `test/unit/spec/services/task/TaskFactory.ts`.
1285
+
1286
+ > **Host-application example:** This consumer callback performs task operations without logging raw interaction data.
1287
+
1288
+ ```typescript
1289
+ // Listen for incoming tasks
1290
+ cc.on('task:incoming', async (task) => {
1291
+ // Accept the task
1292
+ await task.accept();
1293
+
1294
+ // Task operations
1295
+ await task.hold();
1296
+ await task.resume();
1297
+ await task.end();
1298
+ await task.wrapup({
1299
+ wrapUpReason: 'Resolved',
1300
+ auxCodeId: 'wrapup-code',
1301
+ });
1302
+ });
1303
+ ```
1304
+
1305
+ ## State Model
1306
+ Each Task owns an XState actor and current task data. TaskManager maps backend notifications into actor events; backend task data remains authoritative for hydration. Stable interaction states and initiating/terminal states are defined by the nested task-state-machine module.
1307
+
1308
+ ## Business Rules & Invariants
1309
+ - TaskFactory creates only implemented media subclasses and throws for unsupported media values.
1310
+ - Concrete Task/Voice `hold()` and `resume()` methods are parameterless even though the broader `ITask` declaration retains an optional media-resource parameter.
1311
+ - Task event names come from `TASK_EVENTS`; actor transition names come from `TaskEvent`, and callers must not substitute raw strings.
1312
+ - Task owns no credentials or authentication policy; contact/dialer factories delegate authenticated requests through AqmReqs and Core/WebexRequest.
1313
+ - Preview skip/remove delegation is conditional: `campaignPreviewSkipDisabled === 'true'` or `campaignPreviewRemoveDisabled === 'true'` causes ContactCenter to throw before the dialer starts an HTTP or WebSocket-correlated AQM operation. Accept has no equivalent pre-guard.
1314
+
1315
+ ## Concurrency & Reactive Flow
1316
+ - Remote contact/dialer operations complete asynchronously through AQM correlation. Backend WebSocket notifications are separately mapped by TaskManager and delivered to the owning actor in arrival order.
1317
+
1318
+ ## State Machine
1319
+ ```mermaid
1320
+ stateDiagram-v2
1321
+ [*] --> IDLE
1322
+ IDLE --> OFFERED: task offer
1323
+ OFFERED --> CONNECTED: assignment / accept
1324
+ CONNECTED --> HELD: hold succeeds
1325
+ HELD --> CONNECTED: resume succeeds
1326
+ CONNECTED --> CONSULTING: consult succeeds
1327
+ HELD --> CONSULTING: consult succeeds
1328
+ CONSULTING --> CONFERENCING: conference succeeds
1329
+ CONNECTED --> WRAPPING_UP: wrapup required after end
1330
+ HELD --> WRAPPING_UP: wrapup required after end
1331
+ WRAPPING_UP --> COMPLETED: wrapup complete
1332
+ CONNECTED --> TERMINATED: end without wrapup
1333
+ COMPLETED --> [*]
1334
+ TERMINATED --> [*]
1335
+ ```
1336
+
1337
+ - **Factory**: `TaskFactory.ts` selects `WebRTC`, `Voice`, or `Digital` based on `MEDIA_CHANNEL` and `webCallingService.loginOption`.
1338
+
1339
+ - **Initialization**: `Task.ts` creates a state machine actor using `createTaskStateMachine(...)`, wires action overrides (emitters), and starts the actor.
1340
+
1341
+ - **Task State**: The task holds `stateMachineService` and uses it to send `TaskEvent` payloads.
1342
+
1343
+ Example (state machine init inside a task object):
1344
+
1345
+ ```typescript
1346
+ const machine = createTaskStateMachine(uiControlConfig, {
1347
+ actions: {
1348
+ emitTaskIncoming: ({event}) => task.emit('task:incoming', task),
1349
+ },
1350
+ });
1351
+ const actor = createActor(machine);
1352
+ actor.start();
1353
+ ```
1354
+
1355
+ `Task` delegates lifecycle transitions and control-state derivation to the state machine:
1356
+
1357
+ - Transition graph: `state-machine/TaskStateMachine.ts`
1358
+
1359
+ - Transition conditions: `state-machine/guards.ts`
1360
+
1361
+ - Context mutation and integration hooks: `state-machine/actions.ts`
1362
+
1363
+ - UI control derivation: `state-machine/uiControlsComputer.ts`
1364
+
1365
+ For state-machine-specific implementation guidance, use:
1366
+
1367
+ - `../state-machine/ai-docs/task-state-machine-spec.md`
1368
+
1369
+ - **Active lifecycle + intermediate states**:
1370
+
1371
+ - `IDLE`, `OFFERED`, `CONNECTED`
1372
+
1373
+ - `HOLD_INITIATING`, `HELD`, `RESUME_INITIATING`
1374
+
1375
+ - `CONSULT_INITIATING`, `CONSULTING`, `CONF_INITIATING`
1376
+
1377
+ - `CONFERENCING`, `WRAPPING_UP`, `COMPLETED`, `TERMINATED`
1378
+
1379
+ - **Future placeholders (defined, not currently implemented in transitions)**:
1380
+
1381
+ - `CONSULT_INITIATED`, `CONSULT_COMPLETED`, `POST_CALL`, `PARKED`, `MONITORING`
1382
+
1383
+ ### Signature and ownership clarifications
1384
+
1385
+ - `Task.endConsult(consultEndPayload)` requires a payload at the base class; `Voice.endConsult(consultEndPayload?)` accepts it optionally.
1386
+ - `ITask.hold(mediaResourceId?)` and `ITask.resume(mediaResourceId?)` are compatibility-interface shapes; current concrete Task/Voice methods accept no argument.
1387
+ - TaskFactory supports the media implementations present in its switch and throws for unsupported media values rather than silently constructing a generic task.
1388
+
1389
+ ## Protocol / Wire Format
1390
+ - Request, response, and event payload ownership is anchored in `src/services/task/Task.ts`. HTTP initiates backend work where applicable; WebSocket messages provide realtime events and, for AQM flows, correlated completion.
1391
+
1392
+ ## Error Handling & Failure Modes
1393
+ | Condition | Signal (error/code/result) | Caller recovery |
1394
+ |---|---|---|
1395
+ | Dependency rejection | Typed/rethrown error or failure event | Inspect structured details, preserve tracking id, and retry only when the operation is safe. |
1396
+ | Timeout or missing async completion | Timeout/recovery state | Follow the module-specific recovery path; never synthesize success. |
1397
+
1398
+ > **Host-application example:** `showTransferFailure` represents consumer-owned error presentation. SDK package implementation must use `LoggerProxy` and avoid logging raw runtime values.
1399
+
1400
+ ```typescript
1401
+ try {
1402
+ await task.transfer({
1403
+ to: 'queue-123',
1404
+ destinationType: 'queue',
1405
+ });
1406
+ } catch (error) {
1407
+ showTransferFailure(error);
1408
+ }
1409
+ ```
1410
+
1411
+ **Cause**: Agent not available or TaskManager not initialized
1412
+
1413
+ **Solution**:
1414
+
1415
+ 1. Ensure `cc.register()` completed
1416
+
1417
+ 2. Ensure `cc.stationLogin()` completed
1418
+
1419
+ 3. Ensure agent state is Available
1420
+
1421
+ **Cause**: Task state doesn't allow operation
1422
+
1423
+ **Solution**: Check task state before operation:
1424
+
1425
+ ```typescript
1426
+ if (task.uiControls.main.hold.isEnabled) {
1427
+ await task.hold();
1428
+ }
1429
+
1430
+ // During a consult, use the consult-leg controls instead.
1431
+ if (task.uiControls.consult.hold.isEnabled) {
1432
+ // Render or enable the consult-leg hold action.
1433
+ }
1434
+ ```
1435
+
1436
+ **Cause**: Call not mapped to task
1437
+
1438
+ **Solution**: Ensure BROWSER login and mercury connected:
1439
+
1440
+ ```typescript
1441
+ await webex.internal.mercury.connect();
1442
+ await cc.stationLogin({ loginOption: 'BROWSER', ... });
1443
+ ```
1444
+
1445
+ ## Pitfalls
1446
+ - Concrete `Task`/`Voice` hold and resume methods are parameterless even though the broader `ITask` declaration retains an optional compatibility argument.
1447
+ - AQM HTTP acknowledgement never completes a task operation; success/failure binds or timeout settle the promise and must stay aligned with actor events.
1448
+ - Primary and RTD WebSockets have different ownership: TaskManager uses the RTD stream for transcript/suggestion events and must not emit acknowledgement payloads as public suggestions.
1449
+
1450
+ ## Module Do's / Don'ts
1451
+ - DO send initiating and success/failure events to the task actor around remote Voice operations.
1452
+ - DO let TaskFactory select Voice/WebRTC/Digital from media type and login option.
1453
+ - DON'T create a generic task for unsupported media or treat `startOutdial()` as returning an ITask.
1454
+ - DON'T derive hold/resume completion from the HTTP response.
1455
+
1456
+ ## Key Design Trade-off
1457
+ - A shared Task base preserves a stable API while media-specific subclasses and a separate state engine enforce capability differences.
1458
+
1459
+ ## Test-Case Strategy (module)
1460
+ Use `test/unit/spec/services/task/Task.ts`, `TaskFactory.ts`, `TaskManager.ts`, media-specific suites, contact/dialer suites, and state-machine suites. Cover concrete-versus-interface method signatures, every TASK_EVENTS group, unsupported media rejection, primary/RTD event ownership, injected state actions, preview-campaign accept/skip/remove payloads and failure paths, the disabled skip/remove pre-guards, Participant Drop validation/correlation/privacy, primary-owner promotion propagation, and success/failure/timeout paths.
1461
+
1462
+ | Behavior / Requirement | Existing test evidence | Gap |
1463
+ |---|---|---|
1464
+ | `TASK-R-001` | `test/unit/spec/services/task/TaskFactory.ts` | None. |
1465
+ | `TASK-R-002` | `test/unit/spec/services/task/Task.ts`, `test/unit/spec/services/task/voice/Voice.ts` | None. |
1466
+ | `TASK-R-003` | `test/unit/spec/services/task/Task.ts`, `test/unit/spec/services/task/state-machine/TaskStateMachine.ts` | Keep event-catalog parity checks synchronized with `TASK_EVENTS`. |
1467
+ | `TASK-R-004` | `test/unit/spec/services/task/TaskManager.ts` | None. |
1468
+ | `TASK-R-005` | `test/unit/spec/services/task/TaskFactory.ts`, `test/unit/spec/services/task/dialer.ts` | None. |
1469
+ | `TASK-R-006` | `test/unit/spec/services/task/contact.ts`, `test/unit/spec/services/core/WebexRequest.ts` | Authentication ownership is verified across routing/Core boundaries. |
1470
+ | `TASK-R-007` | `test/unit/spec/cc.ts`, `test/unit/spec/services/task/dialer.ts` | Add direct tests proving disabled skip/remove flags throw before dialer invocation; keep public signatures, metrics/error handling, and AQM request contracts synchronized. |
1471
+ | `TASK-R-008` | `test/unit/spec/services/task/Task.ts`, `test/unit/spec/services/task/voice/Voice.ts`, `test/unit/spec/services/task/contact.ts`, `test/unit/spec/services/core/aqm-reqs.ts`, `test/unit/spec/services/task/TaskManager.ts` | None. |
1472
+ | `TASK-R-009` | `test/unit/spec/cc.ts`, `test/unit/spec/services/task/TaskFactory.ts`, `test/unit/spec/services/task/state-machine/uiControlsComputer.ts` | None. |
1473
+ | `TASK-R-010` | `test/unit/spec/services/task/TaskManager.ts`, `test/unit/spec/services/task/Task.ts` | None. |
1474
+ | `TASK-R-011` | `test/unit/spec/services/task/TaskManager.ts`, `test/unit/spec/services/task/voice/Voice.ts`, `test/unit/spec/services/task/Task.ts`, `test/unit/spec/services/task/state-machine/TaskStateMachine.ts` | None. |
1475
+ | `TASK-R-012` | `test/unit/spec/services/task/TaskManager.ts`, `test/unit/spec/services/task/TaskUtils.ts` | None. |
1476
+
1477
+ ## Traceability
1478
+ - Repo architecture: `../../../../ai-docs/ARCHITECTURE.md` · Registry: `../../../../ai-docs/SPEC_INDEX.md`
1479
+ - Coverage state and contracts baseline: `../../../../.sdd/manifest.json`
1480
+
1481
+ - Task creation: `TaskFactory.ts`
1482
+
1483
+ - Task APIs and behavior: `Task.ts`, `voice/Voice.ts`, `voice/WebRTC.ts`, `digital/Digital.ts`
1484
+
1485
+ - Task management: `TaskManager.ts`
1486
+
1487
+ - Shared task types: `types.ts`, `constants.ts`
1488
+
1489
+ - Task lifecycle state machine: `state-machine/TaskStateMachine.ts`
1490
+
1491
+ - State machine types/events: `state-machine/constants.ts`, `state-machine/types.ts`
1492
+
1493
+ - [TaskManager.ts](../TaskManager.ts) - Manager implementation
1494
+
1495
+ - [types.ts](../types.ts) - Type definitions
1496
+
1497
+ - [../state-machine/ai-docs/task-state-machine-spec.md](../state-machine/ai-docs/task-state-machine-spec.md) - State machine implementation guide
1498
+
1499
+ - [../state-machine/ai-docs/task-state-machine-spec.md](../state-machine/ai-docs/task-state-machine-spec.md) - State machine internals
1500
+
1501
+ - [cc.ts](../../../cc.ts) - Main plugin
1502
+
1503
+ - [TaskManager.ts](../TaskManager.ts) - Manager
1504
+
1505
+ - [contact.ts](../contact.ts) - Contact operations
1506
+
1507
+ - [types.ts](../types.ts) - Type definitions
1508
+
1509
+ - [../state-machine/ai-docs/task-state-machine-spec.md](../state-machine/ai-docs/task-state-machine-spec.md) - State machine guide
1510
+
1511
+ - [../state-machine/ai-docs/task-state-machine-spec.md](../state-machine/ai-docs/task-state-machine-spec.md) - State machine architecture