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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/.repo-context.json +704 -0
  2. package/.sdd/manifest.json +1065 -339
  3. package/AGENTS.md +935 -60
  4. package/dist/webex.js +1 -1
  5. package/docs/adr/0001-spec-source-policy.md +97 -0
  6. package/{ai-docs/features/consult-transfer-list-policy/spec/feature-spec.md → docs/adr/0002-consult-transfer-list-policy.md} +227 -244
  7. package/docs/adr/0003-repo-standards-migration.md +104 -0
  8. package/docs/adr/index.md +35 -0
  9. package/docs/architecture.md +460 -0
  10. package/docs/getting-started.md +142 -0
  11. package/docs/index.md +53 -0
  12. package/docs/specs/README.md +98 -0
  13. package/package.json +10 -9
  14. package/schemas/repo-context.schema.json +796 -0
  15. package/src/docs/README.md +727 -0
  16. package/src/metrics/docs/README.md +710 -0
  17. package/src/services/agent/docs/README.md +673 -0
  18. package/src/services/config/docs/README.md +530 -0
  19. package/src/services/core/docs/README.md +993 -0
  20. package/src/services/docs/README.md +765 -0
  21. package/src/services/task/docs/README.md +1569 -0
  22. package/src/services/task/state-machine/docs/README.md +1388 -0
  23. package/src/utils/AGENTS.md +6 -4
  24. package/src/utils/docs/README.md +413 -0
  25. package/umd/contact-center.min.js +2 -2
  26. package/umd/contact-center.min.js.map +1 -1
  27. package/ai-docs/ARCHITECTURE.md +0 -168
  28. package/ai-docs/CONTRACTS.md +0 -64
  29. package/ai-docs/GETTING_STARTED.md +0 -168
  30. package/ai-docs/GLOSSARY.md +0 -43
  31. package/ai-docs/README.md +0 -138
  32. package/ai-docs/REVIEW_CHECKLIST.md +0 -41
  33. package/ai-docs/RULES.md +0 -444
  34. package/ai-docs/SECURITY.md +0 -52
  35. package/ai-docs/SERVICE_STATE.md +0 -52
  36. package/ai-docs/SPEC_INDEX.md +0 -65
  37. package/ai-docs/adr/0001-spec-source-policy.md +0 -55
  38. package/ai-docs/adr/README.md +0 -8
  39. package/ai-docs/adr/_adr-template.md +0 -31
  40. package/ai-docs/contact-center-spec.md +0 -388
  41. package/ai-docs/features/contact-owner-change-refactor.md +0 -78
  42. package/ai-docs/features/generated-spec-conformance-fidelity-remediation/spec/feature-spec.md +0 -117
  43. package/ai-docs/features/residual-warning-coverage-completion/spec/feature-spec.md +0 -203
  44. package/ai-docs/features/validator-code-fidelity-drift-fix/spec/feature-spec.md +0 -315
  45. package/ai-docs/patterns/event-driven-patterns.md +0 -485
  46. package/ai-docs/patterns/testing-patterns.md +0 -480
  47. package/ai-docs/patterns/typescript-patterns.md +0 -365
  48. package/ai-docs/templates/README.md +0 -102
  49. package/ai-docs/templates/documentation/create-agents-md.md +0 -240
  50. package/ai-docs/templates/documentation/create-architecture-md.md +0 -295
  51. package/ai-docs/templates/existing-service/bug-fix.md +0 -254
  52. package/ai-docs/templates/existing-service/feature-enhancement.md +0 -450
  53. package/ai-docs/templates/new-method/00-master.md +0 -80
  54. package/ai-docs/templates/new-method/01-requirements.md +0 -232
  55. package/ai-docs/templates/new-method/02-implementation.md +0 -295
  56. package/ai-docs/templates/new-method/03-tests.md +0 -201
  57. package/ai-docs/templates/new-method/04-validation.md +0 -141
  58. package/ai-docs/templates/new-service/00-master.md +0 -109
  59. package/ai-docs/templates/new-service/01-pre-questions.md +0 -159
  60. package/ai-docs/templates/new-service/02-code-generation.md +0 -346
  61. package/ai-docs/templates/new-service/03-integration.md +0 -178
  62. package/ai-docs/templates/new-service/04-test-generation.md +0 -205
  63. package/ai-docs/templates/new-service/05-validation.md +0 -145
  64. package/src/metrics/ai-docs/AGENTS.md +0 -350
  65. package/src/metrics/ai-docs/ARCHITECTURE.md +0 -338
  66. package/src/metrics/ai-docs/metrics-spec.md +0 -971
  67. package/src/services/agent/ai-docs/AGENTS.md +0 -240
  68. package/src/services/agent/ai-docs/ARCHITECTURE.md +0 -304
  69. package/src/services/agent/ai-docs/agent-spec.md +0 -505
  70. package/src/services/ai-docs/AGENTS.md +0 -386
  71. package/src/services/ai-docs/services-spec.md +0 -512
  72. package/src/services/config/ai-docs/AGENTS.md +0 -250
  73. package/src/services/config/ai-docs/ARCHITECTURE.md +0 -413
  74. package/src/services/config/ai-docs/config-spec.md +0 -669
  75. package/src/services/core/ai-docs/AGENTS.md +0 -381
  76. package/src/services/core/ai-docs/ARCHITECTURE.md +0 -698
  77. package/src/services/core/ai-docs/core-spec.md +0 -797
  78. package/src/services/task/ai-docs/AGENTS.md +0 -457
  79. package/src/services/task/ai-docs/ARCHITECTURE.md +0 -595
  80. package/src/services/task/ai-docs/task-spec.md +0 -1501
  81. package/src/services/task/state-machine/ai-docs/AGENTS.md +0 -460
  82. package/src/services/task/state-machine/ai-docs/ARCHITECTURE.md +0 -1156
  83. package/src/services/task/state-machine/ai-docs/task-state-machine-spec.md +0 -2247
  84. package/src/utils/ai-docs/utils-spec.md +0 -391
@@ -0,0 +1,1569 @@
1
+ ---
2
+ type: Module Spec
3
+ title: 'Task service specification'
4
+ description: Responsibilities, boundaries, design, invariants, and verification for the task service module (task creation, call control, lifecycle orchestration, and task events).
5
+ tags: [module, specification]
6
+ ---
7
+ <!-- sdd-generated-metadata
8
+ doc_kind: module-spec
9
+ generated_from: module-spec@0.3.0
10
+ generated_by: claude-code
11
+ approved_by: rarajes2@cisco.com
12
+ updated_at: 2026-11-17T03:03:58Z
13
+ validation_status: pass-with-warnings
14
+ -->
15
+
16
+ # Task service
17
+
18
+ This source-local document at `src/services/task/docs/README.md` owns the stable specification for
19
+ **the task service** of `@webex/contact-center`: the `Task`, `Voice`, `WebRTC`, and `Digital` task
20
+ objects, the `TaskManager` that owns their lifecycle, the `TaskFactory` that builds them, and the
21
+ `contact.ts` and `dialer.ts` AQM request factories behind call control. Ground every claim in package
22
+ evidence and link to the [package architecture](../../../../docs/architecture.md) instead of repeating
23
+ broader facts. No service specification exists because this package is a library. The XState engine
24
+ is a sub-module with its own [state machine specification](../state-machine/docs/README.md).
25
+
26
+ Related context: [documentation index](../../../../docs/index.md) ·
27
+ [package agent instructions](../../../../AGENTS.md)
28
+
29
+ ## Metadata
30
+
31
+ | Field | Value |
32
+ | ----------------- | ----- |
33
+ | Owner | @webex/web-sdk |
34
+ | Source path | `src/services/task` |
35
+ | Resource kind | module |
36
+ | Status | Active |
37
+ | Last verified | 2026-11-16 at `0b8c34db7f` |
38
+ | Module id | `task` |
39
+ | Parent spec | [Services specification](../../docs/README.md) |
40
+ | Doc kind | Module spec |
41
+ | Coverage score | Pending coverage assessment |
42
+ | Validation status | pass-with-warnings — assessed 2026-11-17; validator runtime 01a1e76f-2293-79a0-9f8f-f060038448dd; 0 Blocking, 0 Important, 4 Minor findings. |
43
+
44
+ ## Applicability
45
+
46
+ | Condition ID | Status | Evidence or reason | Owned section |
47
+ | ------------------------------------ | ---------- | ------------------ | ------------- |
48
+ | `module.has_tiers` | N/A | No tier policy exists in `package.json` or under src | Tier |
49
+ | `module.has_ui` | N/A | The module renders nothing; it exposes TaskUIControls state through `src/services/task/types.ts` for host applications to render | UI use-case flow |
50
+ | `module.crosses_service_boundaries` | Applicable | `src/services/task/contact.ts` and `src/services/task/dialer.ts` call the WCC API gateway through AqmReqs; `src/services/task/TaskManager.ts` consumes the primary and RTD WebSockets and Webex Calling line events | Cross-boundary use-case flow |
51
+ | `module.holds_client_state` | Applicable | `src/services/task/TaskManager.ts` keeps the task collection and two pending AI maps; each `src/services/task/Task.ts` instance keeps task data, an actor, and UI controls | Client state model |
52
+ | `module.enforces_domain_rules` | Applicable | Media-type selection in `src/services/task/TaskFactory.ts`, owner-change correlation and wrap-up stamping in `src/services/task/TaskManager.ts`, and state guards in `src/services/task/voice/Voice.ts` | Business rules and invariants |
53
+ | `module.is_concurrent_async` | Applicable | Every call-control method is async and settles on WebSocket-correlated AQM completion; `src/services/task/AutoWrapup.ts` runs a timer | Concurrency and reactive flow |
54
+ | `module.owns_persistence` | N/A | Nothing under `src/services/task/TaskManager.ts` or its siblings writes storage; all state is in memory | Data, schema, and migration discipline |
55
+ | `module.stateful_transitions` | Applicable | Each task owns an XState actor created in `src/services/task/Task.ts` from `src/services/task/state-machine/index.ts` | State machine |
56
+ | `module.exposes_wire_protocol` | Applicable | `src/services/task/contact.ts` and `src/services/task/dialer.ts` define REST routes and success or failure notification binds; `src/services/task/types.ts` defines the WebSocket payload shapes | Protocol and wire format |
57
+ | `module.ui_multi_screen` | N/A | No UI | UI flow |
58
+ | `module.large_data_model` | N/A | TaskData and Interaction in `src/services/task/types.ts` are backend payload mirrors the module does not own or migrate | Data model |
59
+ | `module.returns_caller_errors` | Applicable | Task methods reject with getErrorDetails errors, validation errors, and Unsupported operation errors in `src/services/task/Task.ts` | Caller-visible failure modes |
60
+ | `module.module_specific_conventions` | Applicable | Initiating and success or failure actor events around remote Voice operations in `src/services/task/voice/Voice.ts` | Module-specific rules |
61
+ | `module.published_package` | N/A | The package, not this module, is published; `src/index.ts` re-exports Task and the task types and is specified by the package spec | Export stability |
62
+ | `module.embedded_in_host` | N/A | No host theme or mount API | Host integration and theming |
63
+ | `module.has_design_tradeoff` | Applicable | A shared abstract base in `src/services/task/Task.ts` with media subclasses and a separate state engine | Key design trade-off |
64
+ | `module.has_submodules` | Applicable | `src/services/task/state-machine/index.ts` is the root of the child module src/services/task/state-machine | Sub-modules |
65
+
66
+ ## Evidence register
67
+
68
+ | Evidence | What it establishes |
69
+ | -------- | ------------------- |
70
+ | `src/services/task/Task.ts` | Abstract base: data, actor, UI controls, auto wrap-up, AI summary methods, transfer, end, wrapup, and the default `Unsupported operation` implementations |
71
+ | `src/services/task/voice/Voice.ts` | Telephony task: hold and resume, recording, consult, transfer, conference, Participant Drop, switch call, and the wxApp telephony routing |
72
+ | `src/services/task/voice/WebRTC.ts` | BROWSER telephony task: `getUserMedia` accept, decline, mute, and remote-media events |
73
+ | `src/services/task/digital/Digital.ts` | Chat, email, and social task with AQM accept |
74
+ | `src/services/task/voice/wxAppVoiceMethods.ts`, `src/services/task/voice/wxAppOfferObservability.ts`, `src/services/task/WebexCallingUtils.ts` | wxApp accept, reject, mute, DTMF, line-owner resolution, and OFFERED-state diagnostics |
75
+ | `src/services/task/TaskFactory.ts` | Media and login-option dispatch to the task subclasses and the `Unknown media type` error |
76
+ | `src/services/task/TaskManager.ts` | Singleton, primary WebSocket pipeline, RTD routing, task collection, owner-change recovery, wrap-up stamping, merge, cleanup, and AI summary buffering |
77
+ | `src/services/task/contact.ts`, `src/services/task/dialer.ts`, `src/services/task/constants.ts` | AQM routes, notification binds, timeouts, and route constants |
78
+ | `src/services/task/types.ts` | `TASK_EVENTS` (52 members), `TaskData`, `TaskUIControls`, payload types, and the `ITask`, `IVoice`, `IWebRTC`, `IDigital` interfaces |
79
+ | `src/services/task/AutoWrapup.ts`, `src/services/task/TaskUtils.ts`, `src/services/task/taskDataNormalizer.ts` | Wrap-up timer, task-state helpers, and string-to-boolean payload normalization |
80
+ | `src/cc.ts` | ContactCenter wiring: `getTaskManager`, config flags, RTD listener, preview-campaign guards, `startOutdial`, and `deregister` cleanup |
81
+ | `src/services/ApiAiAssistant.ts` | `requestAndWaitForRtd`, `resolveFromRtdEvent`, `clearAllRtdRequests`, `sendEvent`, and `aiFeature` used by the summary methods |
82
+ | `src/services/core/aqm-reqs.ts`, `src/services/core/constants.ts` | AQM correlation, `TIMEOUT_REQ` 20000 ms, and the `'disabled'` timeout value |
83
+ | `test/unit/spec/services/task/TaskManager.ts` | 191 jest tests (2026-11-16 run), including owner propagation, conference events, auto-answer, and state machine integration |
84
+ | `test/unit/spec/services/task/Task.ts`, `test/unit/spec/services/task/voice/Voice.ts`, `test/unit/spec/services/task/voice/WebRTC.ts`, `test/unit/spec/services/task/digital/Digital.ts` | Task base and AI summary (105 jest tests), Voice (92), WebRTC, and Digital cases |
85
+ | `test/unit/spec/services/task/TaskFactory.ts`, `test/unit/spec/services/task/contact.ts`, `test/unit/spec/services/task/dialer.ts`, `test/unit/spec/services/task/AutoWrapup.ts`, `test/unit/spec/services/task/TaskUtils.ts`, `test/unit/spec/services/task/WebexCallingUtils.ts` | Factory (6 jest tests), AQM factory, timer, and helper cases |
86
+ | `test/unit/spec/services/task/voice/wxAppVoiceMethods.ts`, `test/unit/spec/services/task/voice/wxAppOfferObservability.ts` | wxApp telephony and diagnostics cases |
87
+ | `test/unit/spec/cc.ts` | ContactCenter delegation to the dialer and TaskManager |
88
+ | `src/services/task/types.ts` (extension subsections) | Justifies the per-method `###` subsections under Public surface and the per-operation `###` subsections under Data flow and sequence coverage and Design overview: each names a current method, event group, or operation defined in this file, `src/services/task/Task.ts`, or `src/services/task/TaskManager.ts` |
89
+ | `src/services/task/taskDataNormalizer.ts` | No unit test file targets it directly; it runs inside every TaskManager pipeline case |
90
+
91
+ ## Purpose and boundary
92
+
93
+ - Responsibility: Own task creation, media-specific behavior, call-control operations, lifecycle
94
+ orchestration, task events, and integration with the task state machine. Manage task lifecycle
95
+ including inbound/outbound calls, hold/resume, consult, transfer, conference, and wrapup.
96
+ - In scope: the task classes and their public methods; TaskManager's WebSocket pipeline, task
97
+ collection, and task-level RTD routing; the AQM route definitions for task and dialer operations;
98
+ auto wrap-up; the AI summary request and response methods; the wxApp (Webex App "better together")
99
+ telephony routing on `Voice`; the creation and action wiring of each task's actor.
100
+ - Out of scope: the transition graph, guards, actions, UI-control computation, and the table that maps
101
+ each CC event to a `TaskEvent` (the [state machine sub-module](../state-machine/docs/README.md),
102
+ contract `contact-center-task-state-machine`); AQM correlation, HTTP, and socket lifecycle (the core
103
+ module, contract `contact-center-core-transport`); the `cc.*` public methods that wrap the dialer,
104
+ including `cc.startOutdial` and the preview-campaign methods (the [package specification](../../../docs/README.md),
105
+ contract `contact-center-sdk`); `ApiAIAssistant`, `WebCallingService`, and `AnswerCallOnWebexService`
106
+ (the services module, contract `contact-center-services`); the event-name enums in
107
+ `src/services/config/types.ts` (the config module, contract `contact-center-cc-events`).
108
+ - Consumers: `src/cc.ts`, which creates the TaskManager and re-emits its task events on `webex.cc`;
109
+ host applications, which receive `ITask` objects and call their methods; Contact Center widgets that
110
+ bind to `task.uiControls`.
111
+
112
+ ## Structure and key files
113
+
114
+ ```text
115
+ src/services/task/
116
+ ├── Task.ts
117
+ ├── TaskManager.ts
118
+ ├── TaskFactory.ts
119
+ ├── contact.ts
120
+ ├── dialer.ts
121
+ ├── AutoWrapup.ts
122
+ ├── TaskUtils.ts
123
+ ├── WebexCallingUtils.ts
124
+ ├── taskDataNormalizer.ts
125
+ ├── types.ts
126
+ ├── constants.ts
127
+ ├── digital/
128
+ │ └── Digital.ts
129
+ ├── voice/
130
+ │ ├── Voice.ts
131
+ │ ├── WebRTC.ts
132
+ │ ├── wxAppVoiceMethods.ts
133
+ │ └── wxAppOfferObservability.ts
134
+ ├── state-machine/
135
+ └── docs/
136
+ └── README.md
137
+ ```
138
+
139
+ | Path | Responsibility |
140
+ | ---- | -------------- |
141
+ | `src/services/task/Task.ts` | Abstract base class: data reconciliation, actor creation, UI controls, auto wrap-up, AI summary methods, `transfer`, `end`, `wrapup` |
142
+ | `src/services/task/voice/Voice.ts` | Telephony subclass (PSTN and wxApp variants); the call-control surface |
143
+ | `src/services/task/voice/WebRTC.ts` | BROWSER telephony subclass over `WebCallingService` |
144
+ | `src/services/task/voice/wxAppVoiceMethods.ts` | wxApp accept, reject, outdial decline, mute, DTMF, and error mapping helpers |
145
+ | `src/services/task/voice/wxAppOfferObservability.ts` | OFFERED-state wxApp decision logging and participant-mismatch grace timer |
146
+ | `src/services/task/digital/Digital.ts` | Chat, email, and social subclass |
147
+ | `src/services/task/TaskFactory.ts` | Subclass selection (Task creation and state machine initialization) |
148
+ | `src/services/task/TaskManager.ts` | Task collection owner and event pipeline |
149
+ | `src/services/task/contact.ts` | `routingContact(aqm)` AQM request factory for task operations |
150
+ | `src/services/task/dialer.ts` | `aqmDialer(aqm)` AQM request factory for outdial and campaign preview |
151
+ | `src/services/task/AutoWrapup.ts` | Auto wrap-up timer |
152
+ | `src/services/task/TaskUtils.ts` | Conference, consult, owner, campaign, and auto-answer helpers; `createSummaryError` |
153
+ | `src/services/task/WebexCallingUtils.ts` | wxApp device details and engagement checks |
154
+ | `src/services/task/taskDataNormalizer.ts` | `normalizeTaskData`: coerces known string booleans in incoming payloads |
155
+ | `src/services/task/types.ts` | Public task events, payloads, interfaces, and enums (contract `contact-center-task-events`) |
156
+ | `src/services/task/constants.ts` | Routes, timeouts, method names, preserved fields, transcript event map |
157
+ | `src/services/task/docs/README.md` | This specification |
158
+ | `test/unit/spec/services/task/taskTestUtils.ts` | Shared fixtures for the task unit suites |
159
+
160
+ ## Sub-modules
161
+
162
+ | Sub-module | Responsibility | Specification |
163
+ | ---------- | -------------- | ------------- |
164
+ | `src/services/task/state-machine` | XState task lifecycle engine: `TaskState` and `TaskEvent`, the transition graph, guards, actions, `computeUIControls`, and the CC-event to `TaskEvent` mapping table (contract `contact-center-task-state-machine`) | [state-machine/docs/README.md](../state-machine/docs/README.md) |
165
+
166
+ `Task` delegates lifecycle transitions and control-state derivation to the state machine:
167
+
168
+ - Transition graph: `state-machine/TaskStateMachine.ts`
169
+ - Transition conditions: `state-machine/guards.ts`
170
+ - Context mutation and integration hooks: `state-machine/actions.ts`
171
+ - UI control derivation: `state-machine/uiControlsComputer.ts`
172
+
173
+ For state-machine-specific implementation guidance, use the
174
+ [state machine specification](../state-machine/docs/README.md). This module owns the actor's creation
175
+ and the action overrides that turn actor actions into `TASK_EVENTS` (Task creation and state machine
176
+ initialization). `TaskManager.mapEventToTaskStateMachineEvent` lives in `TaskManager.ts`, but its
177
+ CC-event to `TaskEvent` mapping is specified in the state machine specification (Backend CC event
178
+ mapping) and not restated here.
179
+
180
+ ## Public surface
181
+
182
+ | Surface | Consumer | Compatibility commitment | Source |
183
+ | ------- | -------- | ------------------------ | ------ |
184
+ | Contract `contact-center-task-events`: the `TASK_EVENTS` enum (52 members) and the payloads emitted on `task` and re-emitted on `cc` (Task events) | Host applications, widgets, `src/cc.ts` | Additive changes by default; do not remove or reinterpret exported events without a documented consumer migration | `src/services/task/types.ts` |
185
+ | Contract `contact-center-sdk`: Task, Voice, WebRTC, and Digital instances and their call-control methods (`ITask`, `IVoice`, `IWebRTC`, `IDigital` in contract `contact-center-task-events`) | Host applications receiving `task:incoming` | Additive; breaking package exports require a major-version transition | `src/services/task/types.ts`, `src/services/task/Task.ts`, `src/index.ts` |
186
+ | Contract `contact-center-task-events`: `TaskData`, `TaskId`, `TaskResponse`, `TaskUIControls`, `MEDIA_CHANNEL`, `TASK_CHANNEL_TYPE`, `VOICE_VARIANT`, `DESTINATION_TYPE`, re-exported by contract `contact-center-sdk` | TypeScript consumers through `src/index.ts` | Additive | `src/services/task/types.ts` |
187
+ | Contract `contact-center-task-events`: preview-campaign payload `PreviewContactPayload` (`interactionId`, campaign-name `campaignId`) and the dialer requests behind the contract `contact-center-sdk` methods `cc.acceptPreviewContact`, `cc.skipPreviewContact`, `cc.removePreviewContact` | `src/cc.ts` | Additive semver-public methods; removals or signature changes are breaking | `src/services/task/dialer.ts`, `src/services/task/types.ts` |
188
+ | Contract `contact-center-task-events`: `TaskUIControls.consultTransferDestinations` with ordered `consult` and `transfer` arrays (values computed by contract `contact-center-task-state-machine`) | Widgets | Additive; array order is meaningful and the first item is the default | `src/services/task/types.ts` |
189
+ | Contract `contact-center-task-events`: `task.dropConferenceParticipant(payload: DropConferenceParticipantPayload): Promise<TaskResponse>`; `participantId` is validated at runtime as a non-empty string | Host applications | Additive semver-public method and payload | `src/services/task/voice/Voice.ts`, `src/services/task/types.ts` |
190
+ | Contract `contact-center-task-events`: AI summary methods, `aiSummaryCapabilities`, the `AISummary`, `AISummaryResponse`, `AISummaryAction`, `AISummaryFeatureEnablement`, and `AISummaryCapabilities` types, `task:midCallSummaryReceived`, and `task:featureEnablement` | Host applications | Additive semver-public methods, types, and events | `src/services/task/Task.ts`, `src/services/task/TaskManager.ts` |
191
+
192
+ ### Task events
193
+
194
+ The public `TASK_EVENTS` enum contains 52 members; every member is listed below from `src/services/task/types.ts`, followed by the two AI Assistant events TaskManager emits on the task. "task, then `cc`" means the task emits the event and TaskManager re-emits it for ContactCenter to trigger on `webex.cc`.
195
+
196
+ | Event | Constant | Emitted on | When emitted |
197
+ | ----- | -------- | ---------- | ------------ |
198
+ | `task:incoming` | `TASK_INCOMING` | task, then `cc` | New task offered to agent |
199
+ | `task:assigned` | `TASK_ASSIGNED` | task | Task assigned to agent |
200
+ | `task:media` | `TASK_MEDIA` | task (WebRTC) | Media stream/track updates are available (remote media track) |
201
+ | `task:unassigned` | `TASK_UNASSIGNED` | — | Declared but never emitted; `AgentContactUnassigned` maps to no actor event |
202
+ | `task:hold` | `TASK_HOLD` | task | Task placed on hold |
203
+ | `task:resume` | `TASK_RESUME` | task | Task resumed from hold |
204
+ | `task:consultEnd` | `TASK_CONSULT_END` | task | Consultation ended |
205
+ | `task:consultQueueCancelled` | `TASK_CONSULT_QUEUE_CANCELLED` | task | Queue consultation cancelled |
206
+ | `task:consultQueueFailed` | `TASK_CONSULT_QUEUE_FAILED` | task | Queue consultation failed |
207
+ | `task:ui-controls-updated` | `TASK_UI_CONTROLS_UPDATED` | task | UI controls changed due to state transition or task data |
208
+ | `task:wxapp-mute-state-updated` | `TASK_WXAPP_MUTE_STATE_UPDATED` | task (Voice) | wxApp mute state changed from Webex App (Mercury sync or call details) |
209
+ | `task:consultAccepted` | `TASK_CONSULT_ACCEPTED` | task | Consult accepted by destination party |
210
+ | `task:consulting` | `TASK_CONSULTING` | task | Consult is in progress |
211
+ | `task:consultCreated` | `TASK_CONSULT_CREATED` | task | Consultation started |
212
+ | `task:offerConsult` | `TASK_OFFER_CONSULT` | task | Consult offer received |
213
+ | `task:end` | `TASK_END` | task | Task ended |
214
+ | `task:wrapup` | `TASK_WRAPUP` | task | Task entering wrapup, only when `wrapUpRequired` is true |
215
+ | `task:wrappedup` | `TASK_WRAPPEDUP` | task | Wrapup completed |
216
+ | `task:cleanup` | `TASK_CLEANUP` | task (internal) | Internal cleanup signal emitted by state machine |
217
+ | `task:recordingStarted` | `TASK_RECORDING_STARTED` | task | Recording started |
218
+ | `task:recordingPaused` | `TASK_RECORDING_PAUSED` | task | Recording paused |
219
+ | `task:recordingPauseFailed` | `TASK_RECORDING_PAUSE_FAILED` | task (Voice) | Recording pause attempt failed |
220
+ | `task:recordingResumed` | `TASK_RECORDING_RESUMED` | task | Recording resumed |
221
+ | `task:recordingResumeFailed` | `TASK_RECORDING_RESUME_FAILED` | task (Voice) | Recording resume attempt failed |
222
+ | `task:rejected` | `TASK_REJECT` | task | Task rejected / failure path emitted; the payload is the reason |
223
+ | `task:outdialFailed` | `TASK_OUTDIAL_FAILED` | task | Outdial operation failed |
224
+ | `task:hydrate` | `TASK_HYDRATE` | task, then `cc` | Task data updated (hydrate and owner change) |
225
+ | `task:offerContact` | `TASK_OFFER_CONTACT` | task | Contact offer received/updated |
226
+ | `task:autoAnswered` | `TASK_AUTO_ANSWERED` | task | Task was auto-answered |
227
+ | `task:conferenceEstablishing` | `TASK_CONFERENCE_ESTABLISHING` | — | Declared but never emitted |
228
+ | `task:conferenceStarted` | `TASK_CONFERENCE_STARTED` | task | Conference started |
229
+ | `task:conferenceFailed` | `TASK_CONFERENCE_FAILED` | task | Conference failed to start |
230
+ | `task:conferenceEnded` | `TASK_CONFERENCE_ENDED` | task | Conference ended |
231
+ | `task:participantJoined` | `TASK_PARTICIPANT_JOINED` | task | Participant joined the conference |
232
+ | `task:participantLeft` | `TASK_PARTICIPANT_LEFT` | task | Participant left the conference |
233
+ | `task:conferenceTransferred` | `TASK_CONFERENCE_TRANSFERRED` | — | Declared but never emitted |
234
+ | `task:conferenceTransferFailed` | `TASK_CONFERENCE_TRANSFER_FAILED` | task (Voice) | Conference transfer failed |
235
+ | `task:conferenceEndFailed` | `TASK_CONFERENCE_END_FAILED` | — | Declared but never emitted |
236
+ | `task:participantLeftFailed` | `TASK_PARTICIPANT_LEFT_FAILED` | — | Declared but never emitted |
237
+ | `task:exitConference` | `TASK_EXIT_CONFERENCE` | task (Voice) | Agent initiated exit from conference |
238
+ | `task:transferConference` | `TASK_TRANSFER_CONFERENCE` | task (Voice) | Agent initiated conference transfer |
239
+ | `task:switchCall` | `TASK_SWITCH_CALL` | task (Voice) | Switched between consult and main call |
240
+ | `task:merged` | `TASK_MERGED` | `cc` only | Tasks merged (EPDN transfer) |
241
+ | `task:postCallActivity` | `TASK_POST_CALL_ACTIVITY` | task (by TaskManager) | `ParticipantPostCallActivity` received |
242
+ | `task:multiLoginHydrate` | `TASK_MULTI_LOGIN_HYDRATE` | task, then `cc` | Multi-login task update on assignment or consult |
243
+ | `task:campaignPreviewReservation` | `TASK_CAMPAIGN_PREVIEW_RESERVATION` | task, then `cc` | Campaign preview contact offered to the agent |
244
+ | `task:campaignPreviewAcceptFailed` | `TASK_CAMPAIGN_PREVIEW_ACCEPT_FAILED` | task | Accepting a campaign preview contact failed |
245
+ | `task:campaignPreviewSkipFailed` | `TASK_CAMPAIGN_PREVIEW_SKIP_FAILED` | task | Skipping a campaign preview contact failed |
246
+ | `task:campaignPreviewRemoveFailed` | `TASK_CAMPAIGN_PREVIEW_REMOVE_FAILED` | task | Removing a campaign preview contact failed |
247
+ | `task:campaignContactUpdated` | `TASK_CAMPAIGN_CONTACT_UPDATED` | task (by TaskManager) | Campaign contact updated after skip or remove |
248
+ | `task:midCallSummaryReceived` | `TASK_MID_CALL_SUMMARY_RECEIVED` | task (by TaskManager) | Mid-call summary delivered to a receiving agent |
249
+ | `task:featureEnablement` | `TASK_FEATURE_ENABLEMENT` | task (by TaskManager) | Per-task AI summary enablement flags received |
250
+ | `REAL_TIME_TRANSCRIPTION` | `CC_EVENTS.REAL_TIME_TRANSCRIPTION` | task (by TaskManager) | A realtime transcript payload is received for the task interaction |
251
+ | `SUGGESTED_RESPONSE` | `CC_EVENTS.SUGGESTED_RESPONSE` | task (by TaskManager) | A `SUGGESTED_RESPONSE` AI Assistant payload is received for the task interaction |
252
+
253
+ ### `task.accept()`
254
+
255
+ Accept an incoming task.
256
+
257
+ **Returns**: `Promise<TaskResponse>`
258
+
259
+ **Example**:
260
+
261
+ ```typescript
262
+ cc.on('task:incoming', async (task) => {
263
+ await task.accept();
264
+ });
265
+ ```
266
+
267
+ ### `task.hold()` / `task.resume()`
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
+ ### `task.end()`
288
+
289
+ End the current task.
290
+
291
+ **Returns**: `Promise<TaskResponse>`
292
+
293
+ **Example**:
294
+
295
+ ```typescript
296
+ await task.end();
297
+ ```
298
+
299
+ ### `task.wrapup(params)`
300
+
301
+ Complete task with wrapup code.
302
+
303
+ **Parameters**:
304
+
305
+ - `wrapUpReason` (string, required): Wrapup reason text
306
+ - `auxCodeId` (string, required): Wrapup code ID
307
+
308
+ **Returns**: `Promise<TaskResponse>`
309
+
310
+ **Example**:
311
+
312
+ ```typescript
313
+ await task.wrapup({
314
+ wrapUpReason: 'Customer issue resolved',
315
+ auxCodeId: 'resolved-code',
316
+ });
317
+ ```
318
+
319
+ ### `task.transfer(params)`
320
+
321
+ Transfer task to another destination.
322
+
323
+ **Parameters**:
324
+
325
+ - `to` (string): Agent ID, queue ID, entry point ID, or phone number
326
+ - `destinationType` ('queue' | 'agent' | 'dialNumber' | 'entryPoint'): Destination type; `queue` and `entryPoint` use the vteam transfer route, the others the blind transfer route
327
+
328
+ **Returns**: `Promise<TaskResponse>`
329
+
330
+ **Example**:
331
+
332
+ ```typescript
333
+ // Transfer to queue
334
+ await task.transfer({
335
+ to: 'queue-123',
336
+ destinationType: 'queue',
337
+ });
338
+
339
+ // Transfer to agent
340
+ await task.transfer({
341
+ to: 'agent-456',
342
+ destinationType: 'agent',
343
+ });
344
+ ```
345
+
346
+ ### `task.consult(params)`
347
+
348
+ Start consultation.
349
+
350
+ **Parameters**:
351
+
352
+ - `to` (string): Agent/queue/phone to consult
353
+ - `destinationType` ('queue' | 'agent' | 'dialNumber' | 'entryPoint'): Type
354
+
355
+ **Returns**: `Promise<TaskResponse>`
356
+
357
+ **Example**:
358
+
359
+ ```typescript
360
+ await task.consult({
361
+ to: 'agent-456',
362
+ destinationType: 'agent',
363
+ });
364
+
365
+ // Later: complete transfer (consulting voice flow uses transfer())
366
+ await task.transfer({
367
+ to: 'queue-123',
368
+ destinationType: 'queue',
369
+ });
370
+ // Or end consult
371
+ await task.endConsult({isConsult: true, taskId: task.data.interactionId});
372
+ ```
373
+
374
+ ### `task.endConsult(consultEndPayload)`
375
+
376
+ End consultation without transfer.
377
+
378
+ **Parameters**:
379
+
380
+ - `consultEndPayload` (`ConsultEndPayload`: `isConsult` and `taskId` required, `isSecondaryEpDnAgent` and `queueId` optional). The base `Task.endConsult` requires the payload and `Voice.endConsult` declares it optional, but `contact.consultEnd` reads `isConsult` from it, so a call without a payload rejects.
381
+
382
+ **Returns**: `Promise<TaskResponse>`
383
+
384
+ ### `task.dropConferenceParticipant(payload)`
385
+
386
+ Remove another participant from a voice conference.
387
+
388
+ **Parameters**:
389
+
390
+ - `participantId` (string, required): backend participant target identifier; blank and non-string values reject before AQM registration or telemetry.
391
+
392
+ **Returns**: `Promise<TaskResponse>` after `ParticipantLeftConference` is received for the latest `interaction.mainInteractionId || task.data.interactionId`.
393
+
394
+ **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.
395
+
396
+ ```typescript
397
+ await task.dropConferenceParticipant({participantId});
398
+ ```
399
+
400
+ ### AI summary APIs
401
+
402
+ - `requestPostCallSummary(): Promise<AISummary>` requests a post-call summary.
403
+ - `sendPostCallSummaryResponse(response: AISummaryResponse): Promise<void>` reports the agent's post-call summary outcome.
404
+ - `requestMidCallSummary(action: AISummaryAction): Promise<AISummary>` requests a consult or transfer summary.
405
+ - `sendMidCallSummaryResponse(response: AISummaryResponse, action: AISummaryAction): Promise<void>` reports the corresponding mid-call outcome.
406
+
407
+ The gating and buffering rules are TASK-R-013 and TASK-R-014; the mechanism is in Design overview (AI summary delivery).
408
+
409
+ ## Dependencies
410
+
411
+ Stack: TypeScript 5.4, EventEmitter, XState 5, @webex/calling, AQM/WebSocket integrations, Jest 27.
412
+
413
+ | Dependency | Why it is required | Failure behavior |
414
+ | ---------- | ------------------ | ---------------- |
415
+ | Services contact/dialer AQM factories (`routingContact`, `aqmDialer` over core AqmReqs) | Every remote task operation; the contact dependency belongs to Task/TaskFactory-created tasks | Failure notification, HTTP rejection, or timeout rejects the promise (Caller-visible failure modes) |
416
+ | WebSocket and RTD WebSocket managers (core `WebSocketManager`) | Primary Contact Center notifications drive the pipeline; the RTD socket carries transcripts, suggestions, summaries, and feature enablement | Unparsable messages are logged and dropped; keepalives are ignored |
417
+ | WebCallingService, MetricsManager, and task state machine | BROWSER call answer, decline, mute, and call-to-task mapping; telemetry; the per-task actor | Calling errors reject `WebRTC` methods; metrics never block behavior; actor events are synchronous |
418
+ | `ApiAIAssistant` (services module) | Summary requests and responses, transcript start and stop events | Disabled, transport, and timeout errors reject the summary methods; transcript event failures are logged only |
419
+ | `AnswerCallOnWebexService` (services module) | wxApp telephony accept, reject, mute, DTMF, and call details | Errors are mapped by `mapWxAppVoiceError` and rethrown; a call-not-found error during mute sync is not logged |
420
+ | `xstate` 5.24.0, `@webex/calling` (workspace) | `createActor`, `LocalMicrophoneStream`, `LINE_EVENTS`, `CALL_EVENT_KEYS` | Import-time only |
421
+
422
+ ## Requirements
423
+
424
+ | ID | WHAT | WHY | Source Evidence | Test / Example Evidence | Assumptions / Gaps | Confidence |
425
+ | --- | --- | --- | --- | --- | --- | --- |
426
+ | 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` | The suite covers each supported subclass; no unit case asserts the `Unknown media type` throw. | Present |
427
+ | TASK-R-002 | Concrete Task/Voice `hold()` and `resume()` implementations remain parameterless while `ITask` retains its optional compatibility parameter. | Both methods delegate to `Voice.holdResume()`, which picks hold or resume and the main-call media resource from the actor state and the main media `isHold` flag, so a caller cannot target another media leg or invert the direction; the `ITask` parameter stays so existing TypeScript callers that pass one keep compiling. | `src/services/task/Task.ts`, `src/services/task/voice/Voice.ts` | `test/unit/spec/services/task/Task.ts`, `test/unit/spec/services/task/voice/Voice.ts` | The `Cannot hold call` and `Cannot resume call` state guards are not asserted. | Present |
428
+ | 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` | Five declared members have no emitter (Task events table). | Present |
429
+ | 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. | Present |
430
+ | TASK-R-005 | The contact dependency belongs to Task/TaskFactory-created tasks; dialer is an AqmReqs request factory without that constructor. | Each Task settles its call-control promises on binds for its own interaction through the injected `routingContact`; dialer requests are issued by ContactCenter before any Task exists, so an outdial or preview task is created later by TaskManager from backend events and delivered through `task:incoming`. | `src/services/task/TaskFactory.ts`, `src/services/task/dialer.ts` | `test/unit/spec/services/task/dialer.ts` | None. | Present |
431
+ | 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 |
432
+ | 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. | Present |
433
+ | 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 |
434
+ | 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 |
435
+ | 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. Reloaded or desynchronized clients may receive the authoritative promotion before normal task creation catches up; Agent Desktop supports the same recovery path. | `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 |
436
+ | 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`. The actor-side handling of `PARTICIPANT_LEAVE`, `EXIT_CONFERENCE_SUCCESS`, and late `TASK_WRAPUP` that consumes this flag is specified by the state machine sub-module. | 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` | `test/unit/spec/services/task/TaskManager.ts`, `test/unit/spec/services/task/voice/Voice.ts`, `test/unit/spec/services/task/Task.ts` | Profile auto wrap-up, interval, and default reason remain agent-config responsibilities. | Present |
437
+ | TASK-R-012 | `Task.updateTaskData` deep-merges incoming data but treats `interaction.media` and `interaction.participants` as complete snapshots, deleting entries the backend dropped. | The `pruneStaleInteractionMaps` comment: stale consult-leg media and participants left by a deep merge drove incorrect UI controls until a page refresh. | `src/services/task/Task.ts` | `test/unit/spec/services/task/Task.ts` | Every other field keeps the deep-merge path. | Present |
438
+ | TASK-R-013 | Summary requests require both the organization-level generated-summary flag (`ApiAIAssistant.aiFeature.generatedSummaries.wrapUpSummariesEnabled` or `consultTransferSummariesEnabled`; missing flags disable the corresponding request) and the task-level feature enablement flag (`aiSummaryCapabilities`). A request resolves only after the event POST succeeds and the matching RTD payload arrives within `AI_SUMMARY_DURATION_MS` (15000 ms); otherwise it rejects with `POST_CALL_SUMMARY_DISABLED`, `MID_CALL_SUMMARY_DISABLED`, `POST_CALL_SUMMARY_TIMEOUT`, `MID_CALL_SUMMARY_TIMEOUT`, or the transport error. | The `AI_SUMMARY_DURATION_MS` comment in `constants.ts` fixes the RTD result deadline at 15 seconds while the initiating HTTP acknowledgement keeps the 20-second service timeout; a summary must never be requested for an organization or task that has not enabled it. | `src/services/task/Task.ts`, `src/services/task/constants.ts`, `src/services/ApiAiAssistant.ts` | `test/unit/spec/services/task/Task.ts`, `test/unit/spec/services/ApiAiAssistant.ts` | None. | Present |
439
+ | TASK-R-014 | TaskManager buffers RTD feature-enablement frames that arrive before their task exists and receiving-agent summaries that arrive before the task exists or leaves `IDLE` or `OFFERED` (latest summary per conversation, no expiry timer); it applies the flags when the task is created or re-keyed, emits `task:midCallSummaryReceived` once the task is answered, drops a held summary when an unanswered task is removed, and empties both maps in `clearAISummaryState()`. Task-level feature flags survive `updateTaskData()`, including interaction ID changes during consults or task re-keying, remain available throughout wrapup for post-call summary requests, and are cleared when the task is removed or the session is cleaned up. | The code comments state that RTD feature frames can arrive before AQM creates the task and that a receiving summary is emitted only once the task is answered; an unanswered offer's summary must be dropped instead of emitted. | `src/services/task/TaskManager.ts`, `src/services/task/Task.ts` | `test/unit/spec/services/task/TaskManager.ts` | No expiry bounds the buffers; they are cleared only by delivery, removal, or session cleanup. | Present |
440
+
441
+ ## Design overview
442
+
443
+ Task separates its stable consumption boundary from collaborators so ownership and failure behavior
444
+ stay explicit. A shared Task base preserves a stable API while media-specific subclasses and a separate
445
+ state engine enforce capability differences.
446
+
447
+ - **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.
448
+ - **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 the [state machine specification](../state-machine/docs/README.md).
449
+
450
+ ### Task creation and state machine initialization
451
+
452
+ `TaskFactory.createTask(contact, webCallingService, data, configFlags, wrapupData?, agentId?, agentName?, answerCallOnWebexService?, apiAIAssistant?)`
453
+ returns a `Task`:
454
+
455
+ - Chooses `WebRTC` vs `Voice` for `MEDIA_CHANNEL.TELEPHONY` based on `webCallingService.loginOption`.
456
+ - Chooses `Digital` for `MEDIA_CHANNEL.CHAT`, `MEDIA_CHANNEL.EMAIL`, `MEDIA_CHANNEL.SOCIAL`.
457
+ - Throws `Error` for unknown media types (TASK-R-001).
458
+ - A missing `interaction.mediaType` defaults to telephony; `configFlags` supplies `isEndTaskEnabled`,
459
+ `isEndConsultEnabled`, `enableWxBetterTogether`, and the `consultTransfer` Desktop Profile policy,
460
+ and `callProcessingDetails.pauseResumeEnabled` (default true) sets `isRecordingEnabled` for voice.
461
+
462
+ | Channel | Description |
463
+ | ------- | ----------- |
464
+ | `telephony` | Voice calls |
465
+ | `chat` | Web chat |
466
+ | `email` | Email interactions |
467
+ | `social` | Social media |
468
+ | `sms` | Unsupported by TaskFactory; throws `Unknown media type` |
469
+ | `facebook` | Unsupported by TaskFactory; throws `Unknown media type` |
470
+ | `whatsapp` | Unsupported by TaskFactory; throws `Unknown media type` |
471
+
472
+ `Task.initializeStateMachine()` calls `createTaskStateMachine(this.uiControlConfig, {actions: this.getStateMachineActionOverrides()})`,
473
+ wraps it with `createActor` (held as `stateMachineService`, through which `sendStateMachineEvent` sends `TaskEvent` payloads), subscribes to snapshots (recording `state` and recomputing `uiControls`,
474
+ emitting `task:ui-controls-updated` on a state change or a control change), starts the actor, and
475
+ forces one initial UI-control emission. The action overrides are emitters such as `emitTaskIncoming`,
476
+ built by `createEmitSelfAction`, which optionally sync task data from the event and then emit the
477
+ `TASK_EVENTS` member on the task itself (see the [state machine specification](../state-machine/docs/README.md) for when each action runs).
478
+
479
+ ### TaskManager lifecycle orchestration
480
+
481
+ TaskManager is a singleton (`@internal`) with these responsibilities:
482
+
483
+ - **Listener Setup**: Registers WebSocket listeners to receive CC events and map them to `TaskEvent` payloads.
484
+ - **Task Registry**: Creates tasks via `TaskFactory`, stores them in the task collection, and updates task data on incoming events.
485
+ - **Event Emission**: Re-emits `task:*` events on the task or `cc` object for SDK consumers.
486
+ - **Hydration/Recovery**: Handles state updates and transitions during reconnect/hydrate flows.
487
+ - **WebRTC call mapping**: Handles WebRTC call mapping (Telephony and WebRTC integration).
488
+
489
+ `TaskManager.getTaskManager(apiAIAssistant, contact, webCallingService, webSocketManager, rtdWebSocketManager?)`
490
+ creates the singleton on first call and returns the same instance afterwards; `src/cc.ts` calls it
491
+ when the Webex SDK emits `ready`, and sets config flags, wrap-up data, agent ID, agent name, and the
492
+ WebRTC flag through setters once the agent configuration is fetched during registration.
493
+
494
+ TaskManager maintains a map of active tasks, `taskCollection: Record<TaskId, ITask>`, keyed by
495
+ `interactionId`; `getTask(taskId)` reads one entry and `getAllTasks()` returns a shallow copy. One Task
496
+ object can be reachable under an old and a new key while it is re-keyed; `updateTaskData` removes every
497
+ alias other than the new `interactionId`, and removal deletes all aliases.
498
+
499
+ TaskManager uses a staged pipeline in `registerTaskListeners()`. For each primary WebSocket `message`:
500
+ parse the JSON and drop keepalives (`parseWebSocketMessage`, which also runs `normalizeTaskData`); build
501
+ the event context, which resolves the task, adjusts the payload, and maps the CC event to a `TaskEvent`
502
+ (`prepareEventContext` and `mapEventToTaskStateMachineEvent`, whose mapping table is in the state machine
503
+ specification); handle lifecycle changes that create, update, or remove the task (`handleTaskLifecycleEvent`); keep
504
+ `task.data` synchronized (`updateTaskData`), also for events that map to no actor event; drive the state machine with `task.sendStateMachineEvent`,
505
+ which emits the `TASK_EVENTS`; then emit a buffered receiving summary once the task has left `IDLE` and
506
+ `OFFERED`, emit `task:postCallActivity` for `ParticipantPostCallActivity`, and send the realtime
507
+ transcript start or stop event for the CC event types in `TRANSCRIPT_EVENT_MAP`.
508
+
509
+ ### AQM call control integration
510
+
511
+ `routingContact(aqm: AqmReqs)` (`contact.ts`) returns an object of AQM request methods wired to `TASK_API` and `TASK_MESSAGE_TYPE`.
512
+
513
+ **Methods**
514
+
515
+ - `accept`
516
+ - `hold`
517
+ - `unHold`
518
+ - `pauseRecording`
519
+ - `resumeRecording`
520
+ - `consult`
521
+ - `consultEnd`
522
+ - `consultAccept`
523
+ - `blindTransfer`
524
+ - `vteamTransfer`
525
+ - `consultTransfer`
526
+ - `end`
527
+ - `wrapup`
528
+ - `cancelTask`
529
+ - `cancelCtq`
530
+ - `consultConference`
531
+ - `dropConferenceParticipant`
532
+ - `exitConference`
533
+ - `conferenceTransfer`
534
+
535
+ **Notes**
536
+
537
+ - Uses `WCC_API_GATEWAY`.
538
+ - Consult with `DESTINATION_TYPE.QUEUE` uses the timeout value `'disabled'` (no AQM timeout); every other consult uses `TIMEOUT_REQ` (20000 ms).
539
+
540
+ Each method is `aqm.req(...)` over a config that names the route under `TASK_API` (`/v1/tasks/`), the
541
+ `WCC_API_GATEWAY` host, the request body, and `notifSuccess` and `notifFail` binds on
542
+ `TASK_MESSAGE_TYPE` (`RoutingMessage`) with a CC event type and, for success, the interaction ID. For
543
+ example, `accept` posts `/v1/tasks/{interactionId}/accept` and settles on `AgentContactAssigned` or
544
+ `AgentContactAssignFailed` (the `CC_EVENTS.AGENT_CONTACT_ASSIGNED` and
545
+ `CC_EVENTS.AGENT_CONTACT_ASSIGN_FAILED` bind types). `hold`, `unHold`, `consultAccept`, `cancelTask`,
546
+ `cancelCtq`, `end`, `wrapup`, `blindTransfer`, `consult`, `consultTransfer`, and the other operations
547
+ follow the same `routingContact` shape; the full route and bind list is in Protocol and wire format.
548
+
549
+ `aqmDialer(aqm: AqmReqs)` (`dialer.ts`) returns an object of AQM request methods for outbound dialing.
550
+
551
+ - `startOutdial` (success: `CC_EVENTS.AGENT_OFFER_CONTACT`, failure: `CC_EVENTS.AGENT_OUTBOUND_FAILED`)
552
+ - `acceptPreviewContact`, `skipPreviewContact`, `removePreviewContact` (Protocol and wire format)
553
+
554
+ Usage in task classes:
555
+
556
+ - Task/TaskFactory-created task instances receive `contact: ReturnType<typeof routingContact>`; `dialer.ts` has no such constructor and is an AqmReqs factory.
557
+ - `Task` (`Task.ts`) uses:
558
+ - `contact.vteamTransfer` / `contact.blindTransfer` in `transfer(...)`.
559
+ - `contact.end` in `end()`.
560
+ - `contact.wrapup` in `wrapup(...)`.
561
+ - `Voice` (`voice/Voice.ts`) uses `contact` for:
562
+ - `hold`, `unHold`
563
+ - `pauseRecording`, `resumeRecording`
564
+ - `consult`, `consultEnd`, `consultTransfer`
565
+ - `consultConference`, `exitConference`, `conferenceTransfer`
566
+ - `dropConferenceParticipant` (Voice only; base Task rejects as unsupported)
567
+ - `cancelTask` for a wxApp outdial decline
568
+ - `Digital` (`digital/Digital.ts`) uses `contact.accept` in `accept()`.
569
+
570
+ `Voice.transfer` owns the consulting-state routing: when `interaction.state` is `consulting` it calls
571
+ `contact.consultTransfer`, and a queue consult is converted to an agent transfer to the agent that
572
+ accepted it (it rejects with `No agent has accepted this queue consult yet` when none has); otherwise it
573
+ calls the base `Task.transfer`, which chooses only between `vteamTransfer` and `blindTransfer`.
574
+
575
+ ### Telephony and WebRTC integration
576
+
577
+ For BROWSER login, TaskManager integrates with WebCalling:
578
+
579
+ ```mermaid
580
+ flowchart TD
581
+ A[AgentContactReserved event] --> B[Determine media + loginOption]
582
+ B --> C[TaskFactory chooses Voice/WebRTC class]
583
+ C --> D[Create Task object]
584
+ D --> E[Store in taskCollection]
585
+ E --> F[Send TASK_INCOMING to state machine]
586
+ F --> G[Emit task:incoming]
587
+ H[Independent LINE_EVENTS.INCOMING_CALL] --> I[Find current non-preview telephony task]
588
+ I --> J[Map call ID to interaction ID]
589
+ J --> K[Send TASK_INCOMING association event]
590
+ ```
591
+
592
+ `TaskManager.handleIncomingWebCall` maps the call with `webCallingService.mapCallToTask(callId, interactionId)`
593
+ and sends the `AgentContactReserved` mapping to that task's actor. `WebRTC.accept()` then gets a
594
+ microphone track with `getUserMedia({audio: true})`, wraps it in a `LocalMicrophoneStream`, and calls
595
+ `webCallingService.answerCall(localAudioStream, interactionId)`; it resolves without a `TaskResponse`.
596
+ `WebRTC.decline()` calls `declineCall(interactionId)` and removes its media listener, and
597
+ `toggleMute()` calls `muteUnmuteCall(localAudioStream)`. Task cleanup for a BROWSER telephony `WebRTC`
598
+ task unregisters its listeners and calls `webCallingService.cleanUpCall()`.
599
+
600
+ **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 the [state machine specification](../state-machine/docs/README.md).
601
+
602
+ **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.
603
+
604
+ Outside that wxApp routing, `Voice.accept()`, `Voice.decline()`, `Voice.toggleMute()`, and
605
+ `Voice.transmitDtmf()` throw `Unsupported operation`; `WebRTC` overrides `accept`, `decline`, and
606
+ `toggleMute` with the WebCallingService implementations above.
607
+
608
+ **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.
609
+
610
+ **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. `Voice` owns both flags and copies them into `uiControlConfig`; the computation itself belongs to the state machine sub-module.
611
+
612
+ **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_*`).
613
+
614
+ **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.
615
+
616
+ ### Participant departure and merge
617
+
618
+ `ParticipantLeftConference` is authoritative for both a customer hangup and an
619
+ agent-initiated customer Drop. The task removes only participants absent from
620
+ the latest interaction snapshot. TaskManager first uses the exact interaction
621
+ key, then the existing reservation fallback, and finally one unique task whose
622
+ `interaction.mainInteractionId`, interaction-level `parentInteractionId`, or
623
+ `callProcessingDetails.parentInteractionId` matches an identifier carried by the
624
+ lifecycle event. Object aliases are deduplicated and all aliases are removed
625
+ during terminal cleanup; ambiguous related-interaction matches are ignored
626
+ without logging participant data. Events carrying none of those correlation
627
+ identifiers are not routed. `ContactMerged` removes the EP-DN child task,
628
+ hydrates the main-interaction task, and publishes the existing `task:merged`
629
+ event so consumers can rebind to the surviving task object. When `ContactMerged` finds no main task,
630
+ TaskManager creates it and sends an internal `HYDRATE` before installing listeners (so the hydrate does
631
+ not reach widgets as a duplicate), then emits `task:merged`.
632
+
633
+ This module's part of a departure is the correlation above and the `wrapUpRequired` stamp
634
+ (TASK-R-011). Which states handle or ignore `PARTICIPANT_LEAVE`, when the current Agent counts as
635
+ departed, and the consult-end outcomes for consultees and consult initiators are specified in the
636
+ [state machine specification](../state-machine/docs/README.md) (contract `contact-center-task-state-machine`).
637
+
638
+ ### Contact owner change propagation
639
+
640
+ Owner-change propagation preserves the behavior required by Participant Drop: when the backend
641
+ promotes a new primary Agent, existing SDK tasks publish the updated owner through the existing
642
+ `task:hydrate` event so widgets immediately recompute the Primary label, icon, and Drop permission.
643
+ There is no public API, routing-event, state-machine transition, Participant Drop request, or widget
644
+ contract change. TASK-R-010 states the correlation and recovery rule; this subsection records the
645
+ mechanism and why each part exists.
646
+
647
+ - Remaining conference Agents receive `ContactUpdated`, not necessarily `ContactOwnerChanged`, so an
648
+ owner-changing `ContactUpdated` (non-empty `interaction.owner` that differs from the current owner)
649
+ maps to `CONTACT_OWNER_CHANGED`; the existing state-machine action synchronizes task data and emits
650
+ `task:hydrate`. Same-owner and owner-less updates remain data-only.
651
+ - Exact-ID lookup stays first because it is the existing lookup contract. The related-task fallback
652
+ also reads the task collection key and the `mainCall` media-map key because some supported
653
+ owner-change payloads identify the surviving call through a child top-level ID and omit
654
+ `mainInteractionId`.
655
+ - A local child task can be briefly stale when the owner-change payload first proves promotion, so the
656
+ incoming snapshot's owner proof can repair a stale child-keyed snapshot. The update keeps the
657
+ surviving main interaction identity even when the notification names a promoted-Agent child
658
+ interaction.
659
+ - Participant Drop can deliver owner-change and participant-left notifications in either order. A late
660
+ `ParticipantLeftConference` that still names the departed participant as owner keeps the already
661
+ confirmed owner only when the new roster proves that confirmed owner remains active on `mainCall`
662
+ and explicitly names the incoming owner as `participantId` or marks it `hasLeft`. Main-call omission
663
+ alone is not departure evidence.
664
+ - Recovery additionally requires a non-terminal telephony payload and a stable main interaction ID, and
665
+ does not use `toOwner`. A later canonical contact or merge event reuses the recovered task rather
666
+ than creating an alias.
667
+
668
+ Owner-change correlation and recovery retain the following protections. This list is the single home
669
+ for the owner-change ignore rules; an ignored event produces no task event:
670
+
671
+ - generic lifecycle-event correlation is unchanged; collection-key and media-key matching are enabled only for `ContactOwnerChanged`;
672
+ - only a task selected by the related-interaction fallback may be re-keyed;
673
+ - conflicting task/payload main IDs are ignored;
674
+ - a stable main key already owned by a different Task causes the event to be ignored;
675
+ - an exact child task is never normalized over a distinct main task;
676
+ - aliases of the same Task object are deduplicated before uniqueness is tested;
677
+ - consult-only and ambiguous matches are ignored: a related task is a candidate only when its snapshot shows the current Agent active on `mainCall`, or the incoming payload names the current Agent as `interaction.owner` with the same active main-leg membership, and more than one candidate is ambiguous; and
678
+ - recovery is skipped whenever any related task or canonical-key occupant already exists.
679
+
680
+ These protections prevent the scenario where an exact child task could be normalized to a main key and
681
+ silently replace the actual main Task, orphaning its listeners and resources. The resulting event flow
682
+ is the Owner change diagram in Data flow and sequence coverage; `ParticipantLeftConference` continues
683
+ through its existing event/state-machine path, and no Drop completion fabricates an owner (INV-005).
684
+
685
+ ### RTD and AI Assistant event routing
686
+
687
+ `TaskManager.handleRealtimeWebsocketEvent()` handles payloads arriving on the realtime subscription
688
+ socket used for AI features; `src/cc.ts` registers it on the RTD socket only when transcripts,
689
+ suggestions, a summary flag, or wellness breaks are enabled. It first routes the AI summary types:
690
+ `FEATURE_ENABLEMENT` frames are applied to the task named by `interactionId` (or buffered),
691
+ `POST_CALL_SUMMARY` and `MID_CALL_SUMMARY` resolve the pending `ApiAIAssistant` request for their
692
+ `conversationId`, and `MID_CALL_SUMMARY_RESPONSE_SUBSEQUENT_AGENT` delivers a receiving-agent summary.
693
+ For every other type it:
694
+
695
+ 1. Parses the JSON websocket envelope
696
+ 2. Reads `conversationId` from `payload.data.data.conversationId` and resolves the owning task
697
+ 3. Emits the payload type and `payload.data` on the task for `REAL_TIME_TRANSCRIPTION`
698
+ 4. Does the same for `SUGGESTED_RESPONSE`
699
+ 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
700
+
701
+ This keeps transcript and suggestion delivery aligned on the same per-task event surface.
702
+
703
+ TaskManager also sends a `GET_TRANSCRIPTS` custom event with action `START` (on `AgentContactAssigned`,
704
+ `AgentConsulting`, `AgentConsultConferenced`) or `STOP` (on `AgentWrapup`, `AgentConsultEnded`,
705
+ `ParticipantLeftConference`) when `aiFeature.realtimeTranscripts.enable` is true; failures are logged
706
+ and do not interrupt event processing.
707
+
708
+ ### AI summary delivery
709
+
710
+ The gating and deadline rule is TASK-R-013 and the buffering rule is TASK-R-014; this subsection
711
+ records the mechanism. The dedicated request methods read the current organization flags directly from the existing `ApiAIAssistant.aiFeature` field, populated by ContactCenter from the agent configuration. No separate feature-flags argument or task-local organization configuration is needed. Receiving-agent summaries are delivered separately through `task:midCallSummaryReceived`. Summary content is application data and must not be written to logs or metrics.
712
+
713
+ 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.
714
+
715
+ TaskManager reads the receiving task directly from `taskCollection[summary.conversationId]`; the RTD
716
+ conversation ID is the task's collection key (`task.data.interactionId`). The common AQM
717
+ event-processing path checks the receiving-summary map after every primary-socket event, so a held
718
+ summary follows the answer event (`AgentContactAssigned` or `AgentConsulting`); removal of an
719
+ unanswered task (RONA, decline, cancelled consult) is where it is dropped.
720
+
721
+ `task:featureEnablement` is emitted after the task's first published `task:incoming`, `task:hydrate`,
722
+ `task:assigned`, or `task:campaignPreviewReservation`, or right after `task:merged`. `Task.setFeatureEnablement` ignores a frame whose `interactionId` differs
723
+ from the task's.
724
+
725
+ `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.
726
+
727
+ ### Auto wrapup, data reconciliation, and telemetry
728
+
729
+ If enabled in agent profile, wrapup completes automatically after timeout. The timer starts only when ingress task data has `wrapUpRequired === true` (TASK-R-011).
730
+
731
+ AutoWrapup handles automatic task completion. `new AutoWrapup(interval, allowCancelAutoWrapup = false)`
732
+ keeps one `setTimeout`: `start(onComplete)` clears a running timer, records the start time, and calls
733
+ `onComplete` after `interval` ms; `clear()` cancels it; `getTimeLeft()`, `getTimeLeftSeconds()`
734
+ (rounded up), and `isRunning()` report progress. `Task.setupAutoWrapupTimer()` runs from the
735
+ constructor and every `updateTaskData`; it creates the timer only once, only when the profile
736
+ `wrapUpProps` has `autoWrapup !== false`, a positive `autoWrapupInterval`, and a default (or first)
737
+ wrap-up reason, and the timer calls `wrapup()` with that reason. `wrapup()` and task removal cancel it.
738
+
739
+ `Task.updateTaskData(updatedData, shouldOverwrite = false)` replaces the data when `shouldOverwrite` is
740
+ true and otherwise deep-merges it (arrays replace), prunes the `interaction.media` and
741
+ `interaction.participants` entries missing from the incoming snapshot (TASK-R-012), recomputes UI
742
+ controls, and re-checks auto wrap-up. TaskManager's own `updateTaskData` additionally carries the
743
+ consult destination agent and type from the actor context during a consult.
744
+
745
+ | Metric | Type | When Tracked |
746
+ | ------ | ---- | ------------ |
747
+ | `TASK_ACCEPT_SUCCESS` | operational, behavioral, business | Task accepted |
748
+ | `TASK_HOLD_SUCCESS` | operational, behavioral | Hold succeeded |
749
+ | `TASK_END_SUCCESS` | operational, behavioral, business | Task ended |
750
+ | `TASK_WRAPUP_SUCCESS` | operational, behavioral, business | Wrapup completed |
751
+ | `TASK_TRANSFER_SUCCESS` | operational, behavioral, business | Transfer completed |
752
+ | `TASK_OUTDIAL_SUCCESS` | behavioral, business, operational | Outdial completed (tracked by `src/cc.ts`) |
753
+ | `TASK_CONFERENCE_PARTICIPANT_DROP_SUCCESS` | operational, behavioral, business | Participant Drop completed |
754
+
755
+ Each success metric has a matching `_FAILED` metric; operations call `timeEvent` for both before the
756
+ request. AI summary methods track `AI_SUMMARY_*` operational metrics with a `failureCode`, and the wxApp
757
+ helpers track `WXAPP_TASK_*` operational and behavioral metrics.
758
+
759
+ ## Data flow and sequence coverage
760
+
761
+ Call style: in-process async method calls on Task objects; remote operations are HTTP requests through
762
+ AqmReqs and WebexRequest to the WCC API gateway whose completion arrives as a correlated notification
763
+ on the primary Contact Center WebSocket. TaskManager consumes that WebSocket, the RTD WebSocket, and
764
+ Webex Calling `LINE_EVENTS.INCOMING_CALL` events; wxApp telephony uses `AnswerCallOnWebexService` REST
765
+ calls.
766
+
767
+ | Operation group | Entry and outcome | Diagram or evidence | Failure and recovery coverage |
768
+ | --------------- | ----------------- | ------------------- | ----------------------------- |
769
+ | Incoming task creation | `AgentContactReserved` creates the task; `cc` emits `task:incoming` | Incoming task | Unsupported media or incomplete event context prevents publication of a partial task. |
770
+ | Voice hold/resume | `hold()` or `resume()` resolves after `AgentContactHeld` or `AgentContactUnheld` | Hold or resume | Invalid state rejects before transport; failure notification/HTTP error/timeout sends the matching failure event and throws. |
771
+ | Consult/transfer/conference | Voice consult, transfer, conference, exit, and switch operations | Consult and transfer | Backend failure notifications drive explicit failure actions and preserve stable call context; a queue consult has no AQM timeout and a queue consult transfer rejects locally until an agent accepts. |
772
+ | Participant Drop | `dropConferenceParticipant` resolves on `ParticipantLeftConference` | Participant Drop | Validation rejects locally; AQM success/failure/HTTP/timeout paths settle and clean up without optimistic state changes. |
773
+ | Wrapup/end | `wrapup()` or `end()` resolves on `AgentWrappedUp` or `AgentWrapup` | Wrapup or end | Validation and backend failures throw; backend events retain distinct WRAPPING_UP/COMPLETED/TERMINATED outcomes. |
774
+ | WebRTC and digital accept | `accept()` answers the call or posts the AQM accept | Channel-specific accept | WebRTC media/calling failure and Digital AQM failure follow different rejection paths. |
775
+ | wxApp telephony | `accept`, `decline`, `toggleMute`, `transmitDtmf` on a wxApp Voice task call `AnswerCallOnWebexService` | wxApp telephony | Validation errors and REST failures are mapped and rethrown; accept clears the answer-pending flag on failure; mute sync retries 3 times at 50 ms while the call ID is unknown |
776
+ | Outdial and preview campaign | `cc.startOutdial` and the three preview methods call `aqmDialer`; the task arrives through TaskManager | Outdial and preview campaign | Disabled skip or remove throws before transport; preview accept times out at 80000 ms; failure notifications reject and emit `task:outdialFailed` or `task:campaignPreview*Failed` |
777
+ | ContactMerged and participant departure | `ContactMerged` removes the EP-DN child and publishes `task:merged`; `ParticipantLeftConference` is correlated to one task | ContactMerged and participant departure | Ambiguous related matches and events without correlation IDs are ignored |
778
+ | Owner change | `ContactOwnerChanged` or owner-changing `ContactUpdated` yields one `task:hydrate` | Owner change | Payloads that fail the owner-change protections (Contact owner change propagation) are ignored; recovery is limited to a complete promotion payload (TASK-R-010) |
779
+ | RTD transcript and suggestion routing | Transcript start or stop events go out on CC events; RTD frames are emitted on the owning task | RTD transcript routing | Parse errors and unknown tasks are logged and dropped; acknowledgement frames are not emitted; start or stop failures are logged |
780
+ | AI summary | Summary request resolves on the RTD summary frame | AI summary request | Disabled flags, POST failure, and the 15-second RTD deadline reject |
781
+
782
+ ### Incoming task
783
+
784
+ ```mermaid
785
+ sequenceDiagram
786
+ participant Backend
787
+ participant WS as Primary WebSocket
788
+ participant TM as TaskManager
789
+ participant TF as TaskFactory
790
+ participant Task
791
+ participant CC as ContactCenter
792
+ participant App as Application
793
+ Backend-->>WS: AgentContactReserved event
794
+ WS-->>TM: message event
795
+ TM->>TM: parse and prepare event context
796
+ alt task is new and media is supported
797
+ TM->>TF: createTask(data, dependencies)
798
+ TF-->>TM: Voice / WebRTC / Digital
799
+ TM->>Task: initialize and store
800
+ TM->>Task: send mapped TaskEvent
801
+ TM-->>CC: emit TASK_INCOMING
802
+ CC-->>App: task:incoming
803
+ opt a BROWSER telephony INCOMING_CALL arrives
804
+ TM->>TM: map call ID to current telephony task
805
+ TM->>Task: send TASK_INCOMING for call/task association
806
+ end
807
+ else unsupported media
808
+ TF-->>TM: throw Unknown media type
809
+ else invalid/unmapped event
810
+ TM->>TM: ignore without publishing a partial task
811
+ end
812
+ ```
813
+
814
+ ### Hold or resume
815
+
816
+ ```mermaid
817
+ sequenceDiagram
818
+ participant App
819
+ participant Voice
820
+ participant Actor as Task state-machine actor
821
+ participant Contact as routingContact
822
+ participant AQM as AqmReqs
823
+ participant WR as WebexRequest
824
+ participant WS as Primary WebSocket
825
+ App->>Voice: hold() or resume()
826
+ Voice->>Voice: derive main media resource and direction from actor state and media isHold
827
+ alt hold outside CONNECTED, or resume outside HELD and outside CONNECTED/CONFERENCING with main media on hold
828
+ Voice-->>App: throw before transport
829
+ else valid state
830
+ Voice->>Actor: HOLD_INITIATED or UNHOLD_INITIATED
831
+ Voice->>Contact: hold/unHold({interactionId, data: {mediaResourceId}})
832
+ Contact->>AQM: generated request with success/failure binds
833
+ AQM->>WR: authenticated HTTP request
834
+ WR-->>AQM: acknowledgement only
835
+ alt matching success notification
836
+ WS-->>AQM: AGENT_CONTACT_HELD/UNHELD
837
+ AQM-->>Voice: TaskResponse
838
+ Voice->>Actor: HOLD_SUCCESS or UNHOLD_SUCCESS
839
+ Voice-->>App: resolve
840
+ else matching failure, HTTP rejection, or timeout
841
+ WS-->>AQM: failure notification or no completion
842
+ Voice->>Actor: HOLD_FAILED or UNHOLD_FAILED
843
+ Voice-->>App: throw detailed error
844
+ end
845
+ end
846
+ ```
847
+
848
+ `Voice.holdResume()` (behind `hold()` and `resume()`) sends `HOLD_INITIATED` or `UNHOLD_INITIATED`
849
+ with the main media resource before calling `contact.hold` or `contact.unHold`, and sends
850
+ `HOLD_SUCCESS` or `UNHOLD_SUCCESS` with the same `mediaResourceId` after the AQM response. The
851
+ direction comes from the actor state and the main media `isHold` flag: `HELD` and `RESUME_INITIATING`
852
+ resume, and `CONNECTED` with media still on hold resumes on the first call. The guard then allows hold
853
+ only in `CONNECTED`, and resume only in `HELD` or in `CONNECTED` or `CONFERENCING` while the main media
854
+ is on hold; `RESUME_INITIATING` is rejected with `Cannot resume call in current state`.
855
+
856
+ ### Consult and transfer
857
+
858
+ ```mermaid
859
+ sequenceDiagram
860
+ participant App
861
+ participant Voice
862
+ participant Actor as Task state-machine actor
863
+ participant Contact as routingContact
864
+ participant WS as Primary WebSocket
865
+ App->>Voice: consult/transfer/conference operation
866
+ alt consult outside CONNECTED/HELD/CONFERENCING
867
+ Voice-->>App: throw Cannot initiate consult
868
+ else queue consult transfer before an agent accepts
869
+ Voice-->>App: throw No agent has accepted this queue consult yet
870
+ else valid request
871
+ Voice->>Actor: initiating event
872
+ Voice->>Contact: correlated AQM operation (queue consult: timeout disabled)
873
+ alt matching success notification
874
+ WS-->>Contact: consult/transfer/conference success
875
+ Contact-->>Voice: TaskResponse
876
+ Voice->>Actor: success event and updated call context
877
+ Voice-->>App: resolve
878
+ else failure/cancel/timeout
879
+ WS-->>Contact: failure or cancel notification
880
+ Voice->>Actor: matching failure/end event
881
+ Voice-->>App: throw while preserving stable main/consult context
882
+ end
883
+ end
884
+ ```
885
+
886
+ ### Participant Drop
887
+
888
+ ```mermaid
889
+ sequenceDiagram
890
+ participant App
891
+ participant Voice
892
+ participant Contact as routingContact
893
+ participant AQM as AqmReqs
894
+ participant Backend
895
+ participant WS as Primary WebSocket
896
+ participant TM as TaskManager/state machine
897
+ App->>Voice: dropConferenceParticipant({participantId})
898
+ alt participantId is invalid
899
+ Voice-->>App: reject before metrics, HTTP, or bind registration
900
+ else valid target
901
+ Voice->>Voice: select latest main interaction ID
902
+ Voice->>Contact: participant Drop request
903
+ Contact->>AQM: POST encoded path with empty body and sensitive-log redaction
904
+ AQM->>Backend: authenticated HTTP initiation
905
+ alt ParticipantLeftConference
906
+ Backend-->>WS: ParticipantLeftConference
907
+ WS-->>AQM: correlated success
908
+ AQM-->>Voice: TaskResponse
909
+ WS-->>TM: existing PARTICIPANT_LEAVE mapping updates roster/conference state
910
+ Voice-->>App: resolve
911
+ else ParticipantDropConferenceFailed, HTTP failure, or timeout
912
+ AQM-->>Voice: structured rejection
913
+ Voice-->>App: reject without participant data in logs/metrics
914
+ end
915
+ end
916
+ ```
917
+
918
+ ### Wrapup or end
919
+
920
+ ```mermaid
921
+ sequenceDiagram
922
+ participant App
923
+ participant Task
924
+ participant Contact as routingContact
925
+ participant WS as Primary WebSocket
926
+ participant Actor as Task state-machine actor
927
+ App->>Task: wrapup(payload) or end()
928
+ alt invalid wrapup payload or missing task data
929
+ Task-->>App: throw validation error
930
+ else valid request
931
+ Task->>Contact: wrapup/end({interactionId, data})
932
+ alt matching success notification
933
+ WS-->>Contact: wrapup/end success
934
+ Contact-->>Task: TaskResponse
935
+ WS-->>Actor: backend event selects WRAPPING_UP/COMPLETED/TERMINATED
936
+ Task-->>App: resolve
937
+ else failure, HTTP rejection, or timeout
938
+ Contact-->>Task: structured rejection
939
+ Task-->>App: throw detailed error
940
+ end
941
+ end
942
+ ```
943
+
944
+ `end()` sends the main interaction ID (`interaction.mainInteractionId || interactionId`) and settles on
945
+ `AgentWrapup`; `wrapup()` cancels auto wrap-up first, validates `auxCodeId` and `wrapUpReason`, and
946
+ settles on `AgentWrappedUp`.
947
+
948
+ ### Channel-specific accept
949
+
950
+ ```mermaid
951
+ sequenceDiagram
952
+ participant App
953
+ participant TF as TaskFactory
954
+ participant WebRTC
955
+ participant Digital
956
+ participant Calling as WebCallingService
957
+ participant Contact as routingContact
958
+ TF-->>App: WebRTC or Digital task
959
+ alt WebRTC accept
960
+ App->>WebRTC: accept()
961
+ WebRTC->>WebRTC: getUserMedia(audio)
962
+ WebRTC->>Calling: answerCall(localAudioStream, interactionId)
963
+ alt media/calling succeeds
964
+ WebRTC-->>App: resolve
965
+ else media/calling failure
966
+ WebRTC-->>App: throw detailed error
967
+ end
968
+ else Digital accept
969
+ App->>Digital: accept()
970
+ Digital->>Contact: accept({interactionId})
971
+ alt AQM success notification
972
+ Contact-->>Digital: TaskResponse
973
+ Digital-->>App: resolve
974
+ else failure or timeout
975
+ Digital-->>App: throw detailed error
976
+ end
977
+ end
978
+ ```
979
+
980
+ ### wxApp telephony
981
+
982
+ ```mermaid
983
+ sequenceDiagram
984
+ participant App
985
+ participant Voice
986
+ participant WX as AnswerCallOnWebexService
987
+ participant Contact as routingContact
988
+ App->>Voice: accept() / decline() / toggleMute() / transmitDtmf()
989
+ alt enableWxBetterTogether off or not a wxApp offer or call
990
+ Voice-->>App: throw Unsupported operation
991
+ else accept on a wxApp offer
992
+ Voice->>Voice: set accept in flight and answer pending
993
+ Voice->>WX: answerCall(callId, endpointId, lineOwnerId)
994
+ alt answer succeeds
995
+ Voice->>WX: getCallDetails to seed mute state (retry 3 x 50 ms while call ID unknown)
996
+ Voice-->>App: resolve
997
+ else answer fails or device details missing
998
+ Voice->>Voice: clear answer pending
999
+ Voice-->>App: throw mapped error
1000
+ end
1001
+ Voice->>Voice: clear accept in flight
1002
+ else decline on an inbound wxApp offer
1003
+ Voice->>WX: rejectCall(callId, lineOwnerId)
1004
+ Voice-->>App: resolve or throw mapped error
1005
+ else decline on a wxApp outdial offer
1006
+ Voice->>Contact: cancelTask({interactionId})
1007
+ Contact-->>Voice: ContactEnded or AgentContactEndFailed
1008
+ Voice-->>App: resolve TaskResponse or throw detailed error
1009
+ else mute or DTMF on an engaged wxApp call
1010
+ Voice->>WX: serialized mute or DTMF request
1011
+ Voice-->>App: resolve or throw mapped error
1012
+ end
1013
+ ```
1014
+
1015
+ ### Outdial and preview campaign
1016
+
1017
+ ```mermaid
1018
+ sequenceDiagram
1019
+ participant App
1020
+ participant CC as ContactCenter
1021
+ participant Dialer as aqmDialer
1022
+ participant WS as Primary WebSocket
1023
+ participant TM as TaskManager
1024
+ participant Task
1025
+ alt outdial
1026
+ App->>CC: startOutdial(destination, origin)
1027
+ CC->>Dialer: startOutdial({data})
1028
+ alt AgentOfferContact
1029
+ WS-->>Dialer: correlated success
1030
+ Dialer-->>CC: TaskResponse
1031
+ CC-->>App: resolve (not a Task)
1032
+ WS-->>TM: contact events create the outdial task
1033
+ TM-->>App: task:incoming
1034
+ else AgentOutboundFailed, HTTP failure, or timeout
1035
+ Dialer-->>CC: rejection
1036
+ CC-->>App: reject
1037
+ WS-->>TM: AgentOutboundFailed for an existing task
1038
+ TM->>Task: OUTBOUND_FAILED, emits task:outdialFailed
1039
+ end
1040
+ else preview reservation, accept, skip, or remove
1041
+ WS-->>TM: AgentOfferCampaignReservation
1042
+ TM->>Task: create task, emits task:campaignPreviewReservation
1043
+ App->>CC: accept, skip, or remove PreviewContact({interactionId, campaignId})
1044
+ alt skip or remove with its disable flag 'true'
1045
+ CC-->>App: throw before transport
1046
+ else request sent
1047
+ CC->>Dialer: preview request (accept timeout 80000 ms)
1048
+ alt success notification
1049
+ WS-->>Dialer: AgentContactAssigned (accept) or CampaignContactUpdated / ContactEnded
1050
+ Dialer-->>CC: TaskResponse
1051
+ CC-->>App: resolve
1052
+ WS-->>TM: assigned task re-keyed from reservationInteractionId, or task:campaignContactUpdated
1053
+ else CampaignPreview*Failed, HTTP failure, or timeout
1054
+ Dialer-->>CC: rejection
1055
+ CC-->>App: reject
1056
+ TM->>Task: emits task:campaignPreview*Failed
1057
+ end
1058
+ end
1059
+ end
1060
+ ```
1061
+
1062
+ `cc.startOutdial` and the three preview methods, with their metrics, are specified by the
1063
+ [package specification](../../../docs/README.md). This module owns the `aqmDialer` routes and binds, the
1064
+ reservation task creation and re-keying in TaskManager, and the preview fields
1065
+ (`campaignPreviewAutoAction`, `campaignPreviewOfferTimeout`, `campaignPreviewSkipDisabled`,
1066
+ `campaignPreviewRemoveDisabled`) that TaskManager carries forward on `CampaignContactUpdated`.
1067
+
1068
+ ### ContactMerged and participant departure
1069
+
1070
+ ```mermaid
1071
+ sequenceDiagram
1072
+ participant WS as Primary WebSocket
1073
+ participant TM as TaskManager
1074
+ participant Child as EP-DN child task
1075
+ participant Main as Main task
1076
+ participant CC as ContactCenter
1077
+ alt ContactMerged
1078
+ WS-->>TM: ContactMerged(childInteractionId)
1079
+ TM->>Child: remove from collection (dispose observers, cancel auto wrap-up)
1080
+ alt main task exists
1081
+ TM->>Main: update task data
1082
+ else main task missing
1083
+ TM->>Main: create, internal HYDRATE, then install listeners
1084
+ end
1085
+ TM-->>CC: task:merged
1086
+ else ParticipantLeftConference or AgentConsultEnded
1087
+ WS-->>TM: lifecycle event
1088
+ TM->>TM: exact key, reservation key, then one unique related task
1089
+ alt one task found
1090
+ TM->>TM: preserve confirmed owner and stamp wrapUpRequired
1091
+ TM->>Main: update data and send mapped event
1092
+ else none or ambiguous
1093
+ TM->>TM: ignore without logging participant data
1094
+ end
1095
+ end
1096
+ ```
1097
+
1098
+ ### Owner change
1099
+
1100
+ ```mermaid
1101
+ sequenceDiagram
1102
+ participant Backend
1103
+ participant WS as Primary WebSocket
1104
+ participant TM as TaskManager
1105
+ participant Task
1106
+ participant App as Widgets
1107
+ Backend->>Backend: choose new interaction.owner
1108
+ alt promoted Agent
1109
+ Backend-->>WS: ContactOwnerChanged
1110
+ WS-->>TM: message event
1111
+ alt exact task
1112
+ TM->>Task: CONTACT_OWNER_CHANGED
1113
+ else one eligible related task with a stable, unoccupied main key
1114
+ TM->>Task: re-key to main interaction, CONTACT_OWNER_CHANGED
1115
+ else no related task and a complete promotion payload
1116
+ TM->>Task: create, internal HYDRATE before listeners, CONTACT_OWNER_CHANGED
1117
+ else an owner-change protection fails
1118
+ TM->>TM: ignore
1119
+ end
1120
+ else other surviving Agent
1121
+ Backend-->>WS: ContactUpdated with a different owner
1122
+ WS-->>TM: message event
1123
+ alt task exists
1124
+ TM->>Task: CONTACT_OWNER_CHANGED
1125
+ else no task
1126
+ TM->>TM: ignore, no task created
1127
+ end
1128
+ end
1129
+ Task-->>App: one task:hydrate with the backend owner
1130
+ ```
1131
+
1132
+ ### RTD transcript routing
1133
+
1134
+ ```mermaid
1135
+ sequenceDiagram
1136
+ participant WS as Primary WebSocket
1137
+ participant TM as TaskManager
1138
+ participant AI as ApiAIAssistant
1139
+ participant RTD as RTD WebSocket
1140
+ participant Task
1141
+ WS-->>TM: AgentContactAssigned / AgentConsulting / AgentConsultConferenced
1142
+ opt realtimeTranscripts enabled
1143
+ TM->>AI: sendEvent GET_TRANSCRIPTS START
1144
+ alt send fails
1145
+ AI-->>TM: rejection
1146
+ TM->>TM: log only
1147
+ end
1148
+ end
1149
+ RTD-->>TM: REAL_TIME_TRANSCRIPTION or SUGGESTED_RESPONSE frame
1150
+ alt JSON valid and task found by conversationId
1151
+ TM->>Task: emit payload.type with payload.data
1152
+ else parse error, no task, or acknowledgement frame
1153
+ TM->>TM: log or ignore
1154
+ end
1155
+ WS-->>TM: AgentWrapup / AgentConsultEnded / ParticipantLeftConference
1156
+ opt realtimeTranscripts enabled
1157
+ TM->>AI: sendEvent GET_TRANSCRIPTS STOP
1158
+ end
1159
+ ```
1160
+
1161
+ ### AI summary request
1162
+
1163
+ ```mermaid
1164
+ sequenceDiagram
1165
+ participant App
1166
+ participant Task
1167
+ participant AI as ApiAIAssistant
1168
+ participant RTD as RTD WebSocket
1169
+ participant TM as TaskManager
1170
+ App->>Task: requestPostCallSummary() or requestMidCallSummary(action)
1171
+ alt organization or task flag disabled
1172
+ Task-->>App: reject *_SUMMARY_DISABLED
1173
+ else enabled
1174
+ Task->>AI: requestAndWaitForRtd(conversationId, event)
1175
+ AI->>AI: register pending request and POST event
1176
+ alt POST fails
1177
+ AI-->>Task: reject transport error
1178
+ Task-->>App: reject
1179
+ else RTD summary frame within 15 s
1180
+ RTD-->>TM: POST_CALL_SUMMARY or MID_CALL_SUMMARY
1181
+ TM->>AI: resolveFromRtdEvent(type, conversationId, data)
1182
+ AI-->>Task: AISummary
1183
+ Task-->>App: resolve AISummary
1184
+ else deadline passes
1185
+ AI-->>Task: reject *_SUMMARY_TIMEOUT
1186
+ Task-->>App: reject
1187
+ end
1188
+ end
1189
+ ```
1190
+
1191
+ ## Class and component relationships
1192
+
1193
+ The file catalog is in Structure and key files; this section records only the relationships and the
1194
+ facts the catalog does not state.
1195
+
1196
+ ```mermaid
1197
+ classDiagram
1198
+ class Task {
1199
+ <<abstract>>
1200
+ # contact
1201
+ # metricsManager
1202
+ + data: TaskData
1203
+ + webCallMap: Record~TaskId, CallId~
1204
+ + stateMachineService
1205
+ + state
1206
+ # currentUiControls: TaskUIControls
1207
+ # uiControlConfig: UIControlConfig
1208
+ + autoWrapup: AutoWrapup
1209
+ + aiSummaryCapabilities
1210
+ + accept() TaskResponse
1211
+ + transfer(payload) TaskResponse
1212
+ + end() TaskResponse
1213
+ + wrapup(payload) TaskResponse
1214
+ + updateTaskData(updatedData, shouldOverwrite) ITask
1215
+ + sendStateMachineEvent(event) void
1216
+ + hold() TaskResponse
1217
+ + resume() TaskResponse
1218
+ + holdResume() TaskResponse
1219
+ + consult(payload) TaskResponse
1220
+ + endConsult(payload) TaskResponse
1221
+ + consultTransfer(payload) TaskResponse
1222
+ + consultConference() TaskResponse
1223
+ + dropConferenceParticipant(payload) TaskResponse
1224
+ + exitConference() TaskResponse
1225
+ + transferConference() TaskResponse
1226
+ + switchCall() TaskResponse
1227
+ + pauseRecording() TaskResponse
1228
+ + resumeRecording(payload) TaskResponse
1229
+ + toggleMute(options) void
1230
+ + transmitDtmf(options) void
1231
+ + requestPostCallSummary() AISummary
1232
+ + requestMidCallSummary(action) AISummary
1233
+ + unregisterWebCallListeners() void
1234
+ + cancelAutoWrapupTimer() void
1235
+ }
1236
+
1237
+ class Voice {
1238
+ + accept() TaskResponse
1239
+ + decline() TaskResponse
1240
+ + hold() TaskResponse
1241
+ + resume() TaskResponse
1242
+ + holdResume() TaskResponse
1243
+ + pauseRecording() TaskResponse
1244
+ + resumeRecording(payload) TaskResponse
1245
+ + consult(payload) TaskResponse
1246
+ + endConsult(payload) TaskResponse
1247
+ + transfer(payload) TaskResponse
1248
+ + consultConference() TaskResponse
1249
+ + dropConferenceParticipant(payload) TaskResponse
1250
+ + exitConference() TaskResponse
1251
+ + transferConference() TaskResponse
1252
+ + switchCall() TaskResponse
1253
+ + toggleMute(options) void
1254
+ + transmitDtmf(options) void
1255
+ }
1256
+
1257
+ class WebRTC {
1258
+ - localAudioStream: LocalMicrophoneStream
1259
+ - webCallingService: WebCallingService
1260
+ + accept() TaskResponse
1261
+ + decline() TaskResponse
1262
+ + toggleMute() void
1263
+ + unregisterWebCallListeners() void
1264
+ }
1265
+
1266
+ class Digital {
1267
+ + accept() TaskResponse
1268
+ + updateTaskData(newData, shouldOverwrite) IDigital
1269
+ }
1270
+
1271
+ class TaskFactory {
1272
+ + createTask(contact, webCallingService, data, configFlags, wrapupData, agentId, agentName, answerCallOnWebexService, apiAIAssistant) Task
1273
+ }
1274
+
1275
+ class TaskManager {
1276
+ - taskCollection: Record~TaskId, ITask~
1277
+ + getTaskManager(apiAIAssistant, contact, webCallingService, webSocketManager, rtdWebSocketManager) TaskManager
1278
+ + handleRealtimeWebsocketEvent(event) void
1279
+ + getTask(taskId) ITask
1280
+ + getAllTasks() Record~TaskId, ITask~
1281
+ }
1282
+
1283
+ Task <|-- Voice
1284
+ Voice <|-- WebRTC
1285
+ Task <|-- Digital
1286
+
1287
+ TaskFactory ..> Task : creates
1288
+ TaskFactory ..> Voice : creates
1289
+ TaskFactory ..> WebRTC : creates
1290
+ TaskFactory ..> Digital : creates
1291
+ TaskManager ..> TaskFactory : uses
1292
+ TaskManager o-- Task : owns
1293
+ ```
1294
+
1295
+ - **`Task` (base)**: Holds task data, emits SDK events, and provides default (unsupported) implementations for call control APIs. Every base method other than `accept` (abstract), `transfer`, `end`, `wrapup`, `updateTaskData`, `sendStateMachineEvent`, `cancelAutoWrapupTimer`, `unregisterWebCallListeners` (no-op plus log), the AI summary methods, `setFeatureEnablement`, `clearFeatureEnablement`, and the no-op wxApp hooks `setEnableWxBetterTogether` and `applyWxAppMuteStateFromSync` throws `Unsupported operation` through `unsupportedMethodError`. The `uiControls` getter includes ordered, action-specific `consultTransferDestinations` computed from Task profile configuration and live interaction data, and `aiSummaryCapabilities` starts with both flags false.
1296
+ - **`Voice`**: Adds hold/resume and consult-related capabilities for telephony tasks. Provides `hold()` and `resume()` that delegate to `holdResume()`.
1297
+ - **`WebRTC`**: Overrides `accept()`, `decline()`, and `toggleMute()` for WebRTC calls and hooks media events: emits `TASK_EVENTS.TASK_MEDIA` on remote media (`CALL_EVENT_KEYS.REMOTE_MEDIA`) and overrides `unregisterWebCallListeners()`.
1298
+ - **`Digital`**: Implements `accept` and refreshes digital task data/UI controls by overriding `updateTaskData()`.
1299
+ - `TaskManager` owns every Task through `taskCollection` and builds them only through `TaskFactory`.
1300
+
1301
+ Helper functions for task state analysis:
1302
+
1303
+ ```typescript
1304
+ // TaskUtils.ts
1305
+
1306
+ // Check if participant is in main interaction
1307
+ isParticipantInMainInteraction(task, agentId);
1308
+
1309
+ // Check if conference is in progress
1310
+ getIsConferenceInProgress(taskData);
1311
+
1312
+ // Check if agent is primary
1313
+ isPrimary(task, agentId);
1314
+
1315
+ // Check if secondary EPDN agent
1316
+ isSecondaryEpDnAgent(interaction);
1317
+ ```
1318
+
1319
+ ## Use cases and flows
1320
+
1321
+ | Use case | Actor or caller | Primary steps and outcome | Failure or boundary behavior | Evidence |
1322
+ | -------- | --------------- | ------------------------- | ---------------------------- | -------- |
1323
+ | `UC-001` | Backend and TaskManager | Incoming task creation: TaskManager maps a backend offer/reservation, TaskFactory creates a supported Voice/WebRTC/Digital task, and ContactCenter emits the typed incoming event. | Unsupported media throws; unmapped events are ignored | `src/services/task/TaskManager.ts`, `src/services/task/TaskFactory.ts`, `test/unit/spec/services/task/TaskManager.ts` |
1324
+ | `UC-002` | Host application | Accept/hold/resume: the Task or Voice method delegates the remote operation and sends the matching typed event to its actor (TASK-R-002). | Invalid state rejects before transport; AQM failure sends the failure event | `src/services/task/Task.ts`, `src/services/task/voice/Voice.ts`, `test/unit/spec/services/task/voice/Voice.ts` |
1325
+ | `UC-003` | Host application | Consult/transfer/conference: Voice coordinates contact routing with initiating/stable actor states and emits the corresponding complete `TASK_EVENTS` contract. | Failure notifications drive failure events; queue consult transfer needs an accepting agent | `src/services/task/voice/Voice.ts`, `src/services/task/types.ts`, `test/unit/spec/services/task/voice/Voice.ts` |
1326
+ | `UC-004` | Host application and backend | Wrapup/end: backend end/wrapup notifications drive WRAPPING_UP and final COMPLETED/TERMINATED outcomes without collapsing them into one result. | Missing wrap-up fields reject locally | `src/services/task/Task.ts`, `test/unit/spec/services/task/Task.ts` |
1327
+ | `UC-005` | Host application on a wxApp, BROWSER, or digital login | Receives the channel-specific task TaskFactory selected (TASK-R-001) and calls the same `ITask` methods | Methods the channel does not support throw `Unsupported operation` | `src/services/task/TaskFactory.ts`, `test/unit/spec/services/task/TaskFactory.ts` |
1328
+ | `UC-006` | Backend and surviving agents | Primary-Agent promotion reaches every surviving agent as one `task:hydrate` | Payloads that fail the owner-change protections are ignored | `src/services/task/TaskManager.ts`, `test/unit/spec/services/task/TaskManager.ts` |
1329
+ | `UC-007` | Host application | Requests a post-call or mid-call summary and reports the agent's response | Disabled flags, POST failure, or the RTD deadline reject | `src/services/task/Task.ts`, `test/unit/spec/services/task/Task.ts` |
1330
+
1331
+ > **Host-application example:** This consumer callback performs task operations without logging raw interaction data.
1332
+
1333
+ ```typescript
1334
+ // Listen for incoming tasks
1335
+ cc.on('task:incoming', async (task) => {
1336
+ // Accept the task
1337
+ await task.accept();
1338
+
1339
+ // Task operations
1340
+ await task.hold();
1341
+ await task.resume();
1342
+ await task.end();
1343
+ await task.wrapup({
1344
+ wrapUpReason: 'Resolved',
1345
+ auxCodeId: 'wrapup-code',
1346
+ });
1347
+ });
1348
+ ```
1349
+
1350
+ > **Host-application example:** `updateWrapupStatus` is a consumer-owned UI callback, not SDK package logging.
1351
+
1352
+ ```typescript
1353
+ task.on('task:wrappedup', () => {
1354
+ updateWrapupStatus('completed');
1355
+ });
1356
+ ```
1357
+
1358
+ ### Cross-boundary use-case flow
1359
+
1360
+ | Boundary | Transport and ordering | Compatibility | Timeout, retry, and recovery |
1361
+ | -------- | ---------------------- | ------------- | ---------------------------- |
1362
+ | WCC API gateway, through `contact.ts` and `dialer.ts` (`UC-001` to `UC-004`) | HTTP initiation through AqmReqs and WebexRequest; completion is the matching `RoutingMessage` notification on the primary WebSocket (contract `wxcc-api-gateway`, `wxcc-websocket-notifications`) | Routes and bind event names in Protocol and wire format | `TIMEOUT_REQ` 20000 ms by default, 80000 ms for preview accept, none for queue consult; no retry here |
1363
+ | Primary Contact Center WebSocket | Messages processed in arrival order by one listener; keepalives dropped | Payloads normalized by `normalizeTaskData` before mapping | Unparsable messages are logged and dropped; a reconnect replays state through `AgentContact` (HYDRATE), which recreates missing tasks |
1364
+ | RTD WebSocket (`UC-007`) | Separate socket registered by `src/cc.ts` when an AI or wellness feature is enabled | Frame types `FEATURE_ENABLEMENT`, `POST_CALL_SUMMARY`, `MID_CALL_SUMMARY`, `MID_CALL_SUMMARY_RESPONSE_SUBSEQUENT_AGENT`, `REAL_TIME_TRANSCRIPTION`, `SUGGESTED_RESPONSE` | 15-second summary deadline; early frames are buffered |
1365
+ | Webex Calling (BROWSER login) | `LINE_EVENTS.INCOMING_CALL` maps the call to the current non-preview telephony task; `CALL_EVENT_KEYS.REMOTE_MEDIA` emits `task:media` (contract `webex-calling-sdk`) | — | Calling errors reject `WebRTC` methods; cleanup calls `cleanUpCall()` |
1366
+ | Webex App telephony (wxApp) | `AnswerCallOnWebexService` REST calls for accept, reject, mute, DTMF, and call details; mute state also arrives through Mercury sync (contract `webex-internal-mercury`) | wxApp participant `deviceType: wxApp` and `deviceCallId` | Mute sync retries up to 3 times at 50 ms while the call ID is unknown; call-not-found is silent |
1367
+
1368
+ ## Client state model
1369
+
1370
+ | State or slice | Owner | Initial state | Transition triggers | Reset or persistence boundary |
1371
+ | -------------- | ----- | ------------- | ------------------- | ----------------------------- |
1372
+ | `taskCollection` | TaskManager | Empty | Created on `AgentContactReserved`, `AgentContact` (missing task), `AgentOfferCampaignReservation`, `ContactMerged`, recoverable `ContactOwnerChanged`; re-keyed by reservation ID and main-interaction updates | Removed on cleanup per `handleTaskCleanup` and on terminal `cleanupResources`; memory only |
1373
+ | `receivingSummaryBuffer`, `pendingFeatureEnablement` | TaskManager | Empty | RTD frames for a task that is missing or not yet answered | Delivery, task removal, `clearAISummaryState()` |
1374
+ | `Task.data` | Each task | The creating payload | Every pipeline `updateTaskData` and actor `syncTaskDataFromEvent` | Lives with the task |
1375
+ | Actor snapshot and `state` | Each task | `IDLE` | `sendStateMachineEvent` and Voice initiating events | Final states are defined by the state machine sub-module |
1376
+ | `uiControls` | Each task | `getDefaultUIControls()` | Actor snapshot or data change | Recomputed, never persisted |
1377
+ | `aiSummaryCapabilities` | Each task | Both false | `setFeatureEnablement` | `clearFeatureEnablement` on removal or session cleanup |
1378
+ | `autoWrapup` | Each task | Undefined | `setupAutoWrapupTimer` | `wrapup()`, `cancelAutoWrapupTimer()`, removal |
1379
+ | wxApp flags (`wxAppAnswerPending`, `wxAppAcceptInFlight`, `wxAppMuted`) | Each Voice task | False | wxApp accept, reject, mute, and Mercury sync | Lives with the task |
1380
+
1381
+ ## Business rules and invariants
1382
+
1383
+ | ID | Invariant | WHY | Enforcement source | Test evidence |
1384
+ | -- | --------- | --- | ------------------ | ------------- |
1385
+ | `INV-001` | Task event names come from `TASK_EVENTS`; actor transition names come from `TaskEvent`, and callers must not substitute raw strings. | Typed constants keep the event contract and the transition contract in one place each | `src/services/task/types.ts`, `src/services/task/Task.ts` | `test/unit/spec/services/task/Task.ts` |
1386
+ | `INV-002` | Task owns no credentials or authentication policy; contact/dialer factories delegate authenticated requests through AqmReqs and Core/WebexRequest. | TASK-R-006 | `src/services/task/contact.ts`, `src/services/task/dialer.ts` | `test/unit/spec/services/task/contact.ts` |
1387
+ | `INV-003` | 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. | TASK-R-007 | `src/cc.ts` | None found (TASK-R-007 gap) |
1388
+ | `INV-004` | One Task object per interaction: TaskManager never replaces an existing task with a new one; aliases of one object are deduplicated and removed together. | TASK-R-004, TASK-R-010 | `src/services/task/TaskManager.ts` | `test/unit/spec/services/task/TaskManager.ts` |
1389
+ | `INV-005` | The SDK never elects a conference owner; owner changes come only from backend payloads. | TASK-R-010 | `src/services/task/TaskManager.ts` | `test/unit/spec/services/task/TaskManager.ts` |
1390
+ | `INV-006` | `wrapUpRequired` is stamped once at ingress for the four wrap-up events, before data update and mapping. | TASK-R-011 | `src/services/task/TaskManager.ts` | `test/unit/spec/services/task/TaskManager.ts` |
1391
+
1392
+ ## Concurrency and reactive flow
1393
+
1394
+ - Execution model: one JavaScript event loop; call-control methods are async, WebSocket listeners are
1395
+ synchronous handlers.
1396
+ - Ordering guarantees: 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.
1397
+ - Idempotency and retry: nothing here retries a remote operation. A second identical method call sends
1398
+ a second request; the actor state guards in Voice (`Cannot hold call in current state`) reject only
1399
+ calls the current state forbids. wxApp mute toggles and DTMF sends are serialized on per-task
1400
+ promise tails.
1401
+ - Shared-state protection: TaskManager is the only writer of `taskCollection`; each task is the only
1402
+ writer of its `data` and actor; the internal hydrate of a recovered or merge-created task precedes
1403
+ listener installation (TASK-R-010, Participant departure and merge).
1404
+ - Blocking restrictions: metrics and transcript events are fire-and-forget; summary content is never
1405
+ logged.
1406
+
1407
+ ## State machine
1408
+
1409
+ 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.
1410
+
1411
+ States, transitions, guards, rejected transitions, and the CC-event to `TaskEvent` mapping are specified
1412
+ in the [state machine specification](../state-machine/docs/README.md) (contract
1413
+ `contact-center-task-state-machine`) and are not restated here.
1414
+
1415
+ This module's side of the contract:
1416
+
1417
+ - `Task.initializeStateMachine()` creates and starts the actor with this module's action overrides
1418
+ (Task creation and state machine initialization).
1419
+ - TaskManager sends the mapped event for each backend notification and updates task data even when no
1420
+ event is mapped (TaskManager lifecycle orchestration).
1421
+ - Voice sends initiating, success, and failure events around its own remote calls (hold, consult,
1422
+ conference, exit, transfer conference, switch call).
1423
+ - Entering a final state runs `cleanupResources`, which emits `task:cleanup` with
1424
+ `removeFromCollection: true`; TaskManager then cleans up calling resources and removes the task.
1425
+
1426
+ ## Protocol and wire format
1427
+
1428
+ 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.
1429
+
1430
+ | Message or frame | Version | Producer or serializer | Consumer or parser | Compatibility and ordering rule |
1431
+ | ---------------- | ------- | ---------------------- | ------------------ | ------------------------------- |
1432
+ | `POST /v1/tasks/{id}/accept`, `/hold`, `/unhold`, `/record/pause`, `/record/resume`, `/consult`, `/consult/accept`, `/consult/end`, `/transfer`, `/consult/transfer`, `/end`, `/wrapup`, `/cancelCtq`, `/consult/conference`, `/conference/exit`, `/conference/transfer` | — | `src/services/task/contact.ts` | WCC API gateway | `cancelTask` reuses `/end` and settles on `ContactEnded`; `blindTransfer` and `vteamTransfer` share `/transfer` |
1433
+ | `POST /v1/tasks/{id}/conference/participants/{encodeURIComponent(participantId)}/drop` with `{}` | — | `src/services/task/contact.ts` | WCC API gateway | `redactSensitiveLogs: true`; success `ParticipantLeftConference`, failure `ParticipantDropConferenceFailed` |
1434
+ | `POST /v1/tasks/` (outdial) | — | `src/services/task/dialer.ts` | WCC API gateway | Success `AgentOfferContact`, failure `AgentOutboundFailed` |
1435
+ | `POST /v1/dialer/campaign/{encodeURIComponent(campaignId)}/preview-task/{interactionId}/accept`, `/skip`, `/remove` | — | `src/services/task/dialer.ts` | WCC API gateway | Accept times out at 80000 ms and settles on `AgentContactAssigned` matched by `reservationInteractionId` or `ContactEnded`; skip and remove settle on `CampaignContactUpdated` or `ContactEnded` |
1436
+ | `RoutingMessage` notifications (`data.type` from `CC_EVENTS`) | — | Contact Center backend | `TaskManager.parseWebSocketMessage`, AqmReqs binds | Known string booleans are coerced; unknown types are ignored |
1437
+ | RTD frames (`type`, `data.data`) | — | AI Assistant backend | `TaskManager.handleRealtimeWebsocketEvent` | Routed by `conversationId` or `interactionId` |
1438
+ | AI summary CTI events (`GET_POST_CALL_SUMMARY`, `GET_MID_CALL_CONSULT_SUMMARY`, `GET_MID_CALL_TRANSFER_SUMMARY`, and the three `*_SUMMARY_RESPONSE` events) | — | `src/services/task/Task.ts` through `ApiAIAssistant.sendEvent` | AI Assistant backend | `conversationId` is `interaction.mainInteractionId` or `interactionId`; `clientType` `WxCC` |
1439
+
1440
+ ## Caller-visible failure modes
1441
+
1442
+ | Condition | Signal or result | Caller behavior | Retry or recovery | Evidence |
1443
+ | --------- | ---------------- | --------------- | ----------------- | -------- |
1444
+ | Method not supported by the task's channel or login (for example `hold` on Digital, `accept` on a non-wxApp Voice task) | `Error` with message `Unsupported operation:` followed by the method name | Check `task.uiControls` before calling | None | `src/services/task/Task.ts`, `src/services/task/voice/Voice.ts` |
1445
+ | AQM failure notification, HTTP rejection, or timeout | Detailed error from `getErrorDetails` (Participant Drop rethrows the original error); matching failure actor event for Voice operations | Inspect structured details, preserve tracking id, and retry only when the operation is safe | Never synthesize success | `src/services/task/Task.ts`, `src/services/task/voice/Voice.ts` |
1446
+ | Hold, resume, consult, or exit conference in a state that forbids it | `Error` with message `Cannot hold call in current state:` followed by the state, and similar messages | Follow `task.uiControls` | Retry after the state changes | `src/services/task/voice/Voice.ts` |
1447
+ | `wrapup` without `auxCodeId` or `wrapUpReason` | `Error('AuxCodeId is required')` or `Error('WrapUpReason is required')` | Supply both | — | `src/services/task/Task.ts` |
1448
+ | `dropConferenceParticipant` without a non-empty string `participantId` | `Error('participantId must be a non-empty string')` before any telemetry | Supply the backend participant ID | — | `src/services/task/voice/Voice.ts` |
1449
+ | Queue consult transfer before an agent accepts | `Error('No agent has accepted this queue consult yet')` | Wait for the consult to be accepted | — | `src/services/task/voice/Voice.ts` |
1450
+ | Summary disabled or deadline passed | Error whose `data.errorCode` is `POST_CALL_SUMMARY_DISABLED`, `MID_CALL_SUMMARY_DISABLED`, `POST_CALL_SUMMARY_TIMEOUT`, or `MID_CALL_SUMMARY_TIMEOUT` | Hide or retry the summary action | Retry is a new request (see Pitfalls and constraints for overlapping requests) | `src/services/task/Task.ts`, `src/services/task/TaskUtils.ts` |
1451
+ | Unsupported media type in a backend payload | `Error` with message `Unknown media type:` followed by the media type, thrown inside the WebSocket listener and not caught by TaskManager; no task is published | None (backend data) | — | `src/services/task/TaskFactory.ts` |
1452
+ | Skip or remove on a preview contact whose disable flag is `'true'` | `Error('Skip action is disabled for this campaign preview contact')` or the remove equivalent | Hide the control | — | `src/cc.ts` |
1453
+
1454
+ > **Host-application example:** `showTransferFailure` represents consumer-owned error presentation. SDK package implementation must use `LoggerProxy` and avoid logging raw runtime values.
1455
+
1456
+ ```typescript
1457
+ try {
1458
+ await task.transfer({
1459
+ to: 'queue-123',
1460
+ destinationType: 'queue',
1461
+ });
1462
+ } catch (error) {
1463
+ showTransferFailure(error);
1464
+ }
1465
+ ```
1466
+
1467
+ Troubleshooting:
1468
+
1469
+ - `task:incoming` not received. **Cause**: Agent not available or TaskManager not initialized
1470
+
1471
+ **Solution**:
1472
+
1473
+ 1. Ensure `cc.register()` completed
1474
+ 2. Ensure `cc.stationLogin()` completed
1475
+ 3. Ensure agent state is Available
1476
+
1477
+ - Task operations fail. **Cause**: Task state doesn't allow operation
1478
+
1479
+ **Solution**: Check task state before operation:
1480
+
1481
+ ```typescript
1482
+ if (task.uiControls.main.hold.isEnabled) {
1483
+ await task.hold();
1484
+ }
1485
+
1486
+ // During a consult, use the consult-leg controls instead.
1487
+ if (task.uiControls.consult.hold.isEnabled) {
1488
+ // Render or enable the consult-leg hold action.
1489
+ }
1490
+ ```
1491
+
1492
+ - WebRTC call not connecting. **Cause**: Call not mapped to task
1493
+
1494
+ **Solution**: Ensure BROWSER login and mercury connected:
1495
+
1496
+ ```typescript
1497
+ await webex.internal.mercury.connect();
1498
+ await cc.stationLogin({ loginOption: 'BROWSER', ... });
1499
+ ```
1500
+
1501
+ ## Pitfalls and constraints
1502
+
1503
+ - AQM HTTP acknowledgement never completes a task operation; success/failure binds or timeout settle the promise and must stay aligned with actor events.
1504
+ - 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.
1505
+ - `TaskManager.getTaskManager` returns the first instance forever; arguments passed on later calls are
1506
+ ignored, so tests and re-registration must reuse the same collaborators.
1507
+ - Do not build consumer logic that waits for the declared-but-never-emitted events in the Task events
1508
+ table.
1509
+ - `sendPostCallSummaryResponse` and `sendMidCallSummaryResponse` do not check that an `ApiAIAssistant`
1510
+ was injected; without one they reject with a `TypeError` tracked as `AI_SUMMARY_INVALID_RESPONSE_PAYLOAD`.
1511
+ - Two overlapping summary requests of the same type for one conversation share one pending
1512
+ `ApiAIAssistant` entry: the second replaces the first and clears its timer, so the first promise never
1513
+ settles. Wait for a request to settle before sending another.
1514
+ - `cc.startOutdial()` resolves with the AQM `AgentOfferContact` response; the outdial Task arrives later
1515
+ through `task:incoming` (TASK-R-005).
1516
+
1517
+ ## Module-specific rules
1518
+
1519
+ - Do: send initiating and success/failure events to the task actor around remote Voice operations.
1520
+ - Do not: create a generic task for unsupported media or treat `startOutdial()` as returning an ITask.
1521
+ - Do not: derive hold/resume completion from the HTTP response.
1522
+ - Do: correlate owner changes and main-interaction events only through the existing exact-then-unique
1523
+ related lookup, and keep recovery narrow (TASK-R-010).
1524
+ - Do: stamp `wrapUpRequired` only in `prepareEventContext` (and Voice `exitConference` for its HTTP
1525
+ path), never in the mapper (TASK-R-011).
1526
+ - Do not: log summary content, participant IDs on Participant Drop, or raw interaction payloads; use
1527
+ `LoggerProxy` with `module` and `method` context.
1528
+
1529
+ ## Key design trade-off
1530
+
1531
+ | Chosen trade-off | Preserved invariant or benefit | Cost or limitation | Decision evidence |
1532
+ | ---------------- | ------------------------------ | ------------------ | ----------------- |
1533
+ | A shared Task base preserves a stable API while media-specific subclasses and a separate state engine enforce capability differences. | Every channel exposes the same `ITask` methods and events, and transition rules live in one engine | Unsupported methods fail at runtime (`Unsupported operation`) rather than at compile time | `src/services/task/Task.ts`, `src/services/task/TaskFactory.ts` |
1534
+ | Backend-authoritative owner change with narrow local recovery | No client elects a successor; no duplicate tasks | A desynchronized client whose payload lacks main-leg proof stays without the task until normal events arrive | `src/services/task/TaskManager.ts` |
1535
+ | Remote operations settle on WebSocket notifications, not HTTP | Actor state matches backend state | Every operation depends on notification delivery and the AQM timeout | `src/services/task/contact.ts` |
1536
+
1537
+ ## Verification
1538
+
1539
+ 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.
1540
+
1541
+ | Requirement or invariant | Test level | Positive evidence | Negative or boundary evidence | Gap |
1542
+ | ------------------------ | ---------- | ----------------- | ----------------------------- | --- |
1543
+ | `TASK-R-001` | Unit (partial) | `test/unit/spec/services/task/TaskFactory.ts` creation cases | None found | No case asserts the `Unknown media type` throw |
1544
+ | `TASK-R-002` | Unit | `test/unit/spec/services/task/Task.ts`, `test/unit/spec/services/task/voice/Voice.ts` | `test/unit/spec/services/task/Task.ts` unsupported-method cases | The `Cannot hold call` and `Cannot resume call` state guards are not asserted |
1545
+ | `TASK-R-003`, `INV-001` | Unit | `test/unit/spec/services/task/Task.ts`, `test/unit/spec/services/task/state-machine/TaskStateMachine.ts` | `test/unit/spec/services/task/Task.ts` failure scenarios | Keep event-catalog parity checks synchronized with `TASK_EVENTS` |
1546
+ | `TASK-R-004`, `INV-004` | Unit | `test/unit/spec/services/task/TaskManager.ts` | `test/unit/spec/services/task/TaskManager.ts` alias-deduplication and distinct-canonical-key cases | None |
1547
+ | `TASK-R-005` | Unit | `test/unit/spec/services/task/TaskFactory.ts`, `test/unit/spec/services/task/dialer.ts` | None found | None |
1548
+ | `TASK-R-006`, `INV-002` | Unit | `test/unit/spec/services/task/contact.ts`, `test/unit/spec/services/core/WebexRequest.ts` | None found | Authentication ownership is verified across routing/Core boundaries |
1549
+ | `TASK-R-007`, `INV-003` | Unit | `test/unit/spec/cc.ts`, `test/unit/spec/services/task/dialer.ts` | `test/unit/spec/services/task/dialer.ts` network, server, and timeout cases | Add direct tests proving disabled skip/remove flags throw before dialer invocation |
1550
+ | `TASK-R-008` | Unit | `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` | `test/unit/spec/services/task/voice/Voice.ts` invalid-payload and failure cases, `test/unit/spec/services/task/Task.ts` unsupported case | None |
1551
+ | `TASK-R-009` | Unit | `test/unit/spec/cc.ts`, `test/unit/spec/services/task/TaskFactory.ts`, `test/unit/spec/services/task/state-machine/uiControlsComputer.ts` | None found | None |
1552
+ | `TASK-R-010`, `INV-005` | Unit | `test/unit/spec/services/task/TaskManager.ts` (Contact owner propagation), `test/unit/spec/services/task/Task.ts` | `test/unit/spec/services/task/TaskManager.ts` consult-only, ambiguous, and distinct-canonical-key cases | None |
1553
+ | `TASK-R-011`, `INV-006` | Unit | `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` | `test/unit/spec/services/task/TaskManager.ts` remaining-agent stamping cases | None |
1554
+ | `TASK-R-012` | Unit | `test/unit/spec/services/task/Task.ts` stale media and participants case | `test/unit/spec/services/task/Task.ts` partial-update case | `normalizeTaskData` has no dedicated suite |
1555
+ | `TASK-R-013` | Unit | `test/unit/spec/services/task/Task.ts` (Task AI summary APIs), `test/unit/spec/services/ApiAiAssistant.ts` | `test/unit/spec/services/task/Task.ts` disabled and timeout cases | None |
1556
+ | `TASK-R-014` | Unit | `test/unit/spec/services/task/TaskManager.ts` | `test/unit/spec/services/task/TaskManager.ts` case dropping a receiving summary held for a ringing task | No expiry bounds the pending maps |
1557
+
1558
+ The focused TaskManager tests cover owner-changing versus data-only
1559
+ `ContactUpdated`, exact and child-keyed correlation, collection-key and
1560
+ `mainCall` media-key payloads, stale incoming promotion evidence, consult-only
1561
+ and ambiguous ignore cases, narrow missing-task recovery, listener/alias safety,
1562
+ later `AgentContact` and `ContactMerged` reuse, exact-child/main-task collision
1563
+ protection, and both owner-change/participant-left orders (the Contact owner propagation block of
1564
+ `test/unit/spec/services/task/TaskManager.ts`).
1565
+
1566
+ Unit tests run with `yarn workspace @webex/contact-center test:unit` from the workspace root. On 2026-11-16 jest ran 191 tests in `TaskManager.ts`, 105 in `Task.ts`, 92 in
1567
+ `voice/Voice.ts`, and 6 in `TaskFactory.ts`, all passing. Coverage measurement and independent
1568
+ validation are pending. A module specification is complete only when its public surface, invariants,
1569
+ failure modes, and test evidence agree with the implementation.