-
Notifications
You must be signed in to change notification settings - Fork 62
Expand file tree
/
Copy pathConversation.swift
More file actions
575 lines (479 loc) · 20.6 KB
/
Copy pathConversation.swift
File metadata and controls
575 lines (479 loc) · 20.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
import Combine
import Foundation
import LiveKit
// swiftlint:disable file_length type_body_length
/// A single-use conversation session, created by and owned by `ConversationClient`.
///
/// Manages the lifecycle of one conversation: network layer
/// (`WebRTCConnectionManager`|`WebSocketConnectionManager`), protocol parser
/// (`EventParser`), and audio device setup.
@MainActor
final class Conversation: ObservableObject {
// MARK: - State
@Published var state: ConversationState = .idle
@Published var chatHistory: [any ChatHistoryItem] = []
@Published var agentState: AgentState = .listening
private var chatHistoryReconciler = ChatHistoryReconciler()
/// Stream of client tool calls that need to be executed by the app
@Published var pendingToolCalls: [ClientToolCallEvent] = []
/// Conversation metadata including conversation ID, received when the conversation is initialized
@Published var conversationMetadata: ConversationMetadataEvent?
/// MCP tool calls from the agent
@Published var mcpToolCalls: [MCPToolCallEvent] = []
/// Current MCP connection status for all integrations
@Published var mcpConnectionStatus: MCPConnectionStatusEvent?
/// Pending mute state to apply after connection completes.
/// Allows setting mute state during connection phase.
private var pendingMuteState: Bool?
/// Audio device management
private var audioManager: ConversationAudioManager?
/// Externally registered audio observers. Kept attached across track swaps.
let agentObserverRegistry = AudioObserverRegistry()
let micObserverRegistry = AudioObserverRegistry()
/// Agent state manager for event-based state tracking
var agentStateManager: AgentStateManager?
/// Forward a signal to the event-based state manager, or fall back to directly setting `agentState`.
func applyStateSignal(_ signal: AgentStateSignal, fallback: AgentState) {
if let manager = agentStateManager {
manager.processSignal(signal)
} else {
agentState = fallback
}
}
func handleRemoteSpeakingUpdate(isSpeaking: Bool) {
if let manager = agentStateManager {
manager.processSignal(isSpeaking ? .agentStartedSpeaking : .agentStoppedSpeaking)
} else if isSpeaking {
speakingTimer?.cancel()
agentState = .speaking
} else {
scheduleBackToListening(delay: 1.0)
}
}
/// Internal logger, accessible from nonisolated contexts.
nonisolated let logger: any Logging
/// Context for logging (e.g. agentId)
private var activeContext: [String: String]?
/// Internal LiveKit tracks used to attach ``ConversationAudioObserver``s.
var inputTrack: (any AudioTrackProtocol)? {
activeWebRTCConnectionManager?.inputTrack
}
var agentAudioTrack: (any AudioTrackProtocol)? {
activeWebRTCConnectionManager?.agentAudioTrack
}
// MARK: - Init
init(
dependencyProvider: any ConversationDependencyProvider,
config: ConversationConfig = .init(),
callbacks: ConversationCallbacks = .init(),
initialMicMuted: Bool = false
) {
self.dependencyProvider = dependencyProvider
self.config = config
self.callbacks = callbacks
pendingMuteState = initialMicMuted
logger = dependencyProvider.logger
setupAudioManager()
}
private func setupAudioManager() {
guard !config.conversationOverrides.textOnly else { return }
audioManager = ConversationAudioManager(logger: logger)
}
private func setupAgentStateManager() {
guard let configuration = config.agentStateConfiguration else { return }
let manager = AgentStateManager(configuration: configuration)
manager.onStateChange = { [weak self] state in
self?.agentState = state
self?.callbacks.onAgentStateChange?(state)
}
agentStateManager = manager
}
// MARK: - API
/// Start a conversation using authentication configuration.
func start(auth: ConversationCredentials) async throws -> ConversationStartResult {
guard state == .idle else {
throw ConversationError.alreadyStarted
}
let result: ConversationStartResult = if config.conversationOverrides.textOnly {
try await startTextOnlyConversation(auth: auth)
} else {
try await startVoiceConversation(auth: auth)
}
guard !Task.isCancelled, state.isConnecting else {
await activeConnectionManager?.disconnect()
throw CancellationError()
}
state = .connected(result.callInfo)
callbacks.onAgentReady?()
return result
}
private func startVoiceConversation(
auth: ConversationCredentials
) async throws -> ConversationStartResult {
let webRTCConnectionManager = dependencyProvider.webRTCConnectionManager
prepareConversationStart(
auth: auth,
connectionManager: webRTCConnectionManager
)
webRTCConnectionManager.onRemoteSpeakingChanged = { [weak self] isSpeaking in
Task { @MainActor in
self?.handleRemoteSpeakingUpdate(isSpeaking: isSpeaking)
}
}
webRTCConnectionManager.onTracksChanged = { [weak self] in
Task { @MainActor in
self?.refreshAudioObservers()
}
}
await audioManager?.configure(with: config, callbacks: callbacks)
if let pendingMuteState {
audioManager?.softwareMuteProcessor?.setMuted(pendingMuteState)
}
let result: ConversationStartResult
do {
result = try await webRTCConnectionManager.connect(
auth: auth,
config: config,
onStartupStateChange: { [weak self] stage in
self?.updateStartupStage(stage)
}
)
} catch let error as ConversationError {
await handleStartupFailure(error, disconnecting: webRTCConnectionManager)
throw error
} catch is CancellationError {
await handleStartupCancellation(disconnecting: webRTCConnectionManager)
throw CancellationError()
}
if let pendingMute = pendingMuteState {
pendingMuteState = nil
do {
if let softwareMuteProcessor = audioManager?.softwareMuteProcessor {
softwareMuteProcessor.setMuted(pendingMute)
} else {
try await webRTCConnectionManager.setMicrophoneMuted(pendingMute)
}
} catch {
logger.warning("Failed to apply pending mute state", context: ["error": "\(error)"])
}
}
refreshAudioObservers()
return result
}
// MARK: - Audio observers
/// Register an observer for the agent's decoded output audio.
func addAgentAudioObserver(_ observer: any ConversationAudioObserver) {
guard !isTearingDown else { return }
agentObserverRegistry.add(observer)
}
/// Unregister a previously added agent audio observer.
func removeAgentAudioObserver(_ observer: any ConversationAudioObserver) {
agentObserverRegistry.remove(observer)
}
/// Register an observer for the local microphone input audio.
func addMicAudioObserver(_ observer: any ConversationAudioObserver) {
guard !isTearingDown else { return }
micObserverRegistry.add(observer)
}
/// Unregister a previously added mic audio observer.
func removeMicAudioObserver(_ observer: any ConversationAudioObserver) {
micObserverRegistry.remove(observer)
}
/// Reconcile registered observers with the currently available tracks.
func refreshAudioObservers() {
guard !isTearingDown else { return }
agentObserverRegistry.attach(to: agentAudioTrack)
micObserverRegistry.attach(to: inputTrack)
}
private func startTextOnlyConversation(
auth: ConversationCredentials
) async throws -> ConversationStartResult {
let connectionManager = dependencyProvider.webSocketConnectionManager
prepareConversationStart(
auth: auth,
connectionManager: connectionManager
)
do {
return try await connectionManager.connect(
auth: auth,
config: config,
onStartupStateChange: { [weak self] stage in
self?.updateStartupStage(stage)
}
)
} catch let error as ConversationError {
await handleStartupFailure(error, disconnecting: connectionManager)
throw error
} catch is CancellationError {
await handleStartupCancellation(disconnecting: connectionManager)
throw CancellationError()
}
}
/// End and clean up.
/// Can be called during connection phase to cancel, or during connected conversation to end.
func endConversation(reason: EndReason = .userEnded) async {
if state == .idle {
state = .ended(reason: reason)
tearDownActiveSession()
return
}
guard state.isConnected || state.isConnecting,
let connectionManager = activeConnectionManager
else { return }
state = .ended(reason: reason)
tearDownActiveSession()
await connectionManager.disconnect()
callbacks.onDisconnect?(reason)
}
/// Send a text message to the agent.
func sendMessage(_ text: String) async throws {
guard state.isConnected else {
throw ConversationError.notConnected
}
let event = OutgoingEvent.userMessage(UserMessageEvent(text: text))
try await publish(event)
updateChatHistory { $0.appendUserMessage(text) }
}
/// Mute or unmute the local microphone.
func setMicMuted(_ muted: Bool) async throws {
if let softwareMuteProcessor = audioManager?.softwareMuteProcessor {
softwareMuteProcessor.setMuted(muted)
if state.isConnecting {
pendingMuteState = muted
}
return
}
try await setHardwareMicMuted(muted)
}
func setHardwareMicMuted(_ muted: Bool) async throws {
if state.isConnected {
guard let webRTCConnectionManager = activeWebRTCConnectionManager else {
throw ConversationError.notConnected
}
do {
try await webRTCConnectionManager.setMicrophoneMuted(muted)
pendingMuteState = nil
} catch WebRTCConnectionManagerError.roomUnavailable {
throw ConversationError.notConnected
} catch {
throw ConversationError.microphoneToggleFailed(error)
}
} else if state == .idle || state.isConnecting {
pendingMuteState = muted
}
}
/// Interrupt the agent while speaking.
func interruptAgent() async throws {
guard state.isConnected else { throw ConversationError.notConnected }
let event = OutgoingEvent.userActivity
try await publish(event)
}
/// Contextual update to agent (system prompt-ish).
func updateContext(_ context: String) async throws {
guard state.isConnected else { throw ConversationError.notConnected }
let event = OutgoingEvent.contextualUpdate(ContextualUpdateEvent(text: context))
try await publish(event)
}
/// Send feedback (like/dislike) for an event/message id.
func sendFeedback(_ score: FeedbackEvent.Score, eventId: Int) async throws {
guard state.isConnected else {
throw ConversationError.notConnected
}
let event = OutgoingEvent.feedback(FeedbackEvent(score: score, eventId: eventId))
try await publish(event)
}
/// Approve or reject an MCP tool call request from the agent.
/// - Parameters:
/// - toolCallId: The tool call identifier from `MCPToolCallEvent`.
/// - isApproved: Pass `true` to approve, `false` to reject.
func sendMCPToolApproval(toolCallId: String, isApproved: Bool) async throws {
guard state.isConnected else { throw ConversationError.notConnected }
let approval = MCPToolApprovalResultEvent(toolCallId: toolCallId, isApproved: isApproved)
try await publish(.mcpToolApprovalResult(approval))
}
/// Send the result of a client tool call back to the agent.
func sendToolResult(_ result: ClientToolResultEvent) async throws {
guard state.isConnected else { throw ConversationError.notConnected }
try await publish(.clientToolResult(result))
pendingToolCalls.removeAll { $0.toolCallId == result.toolCallId }
}
/// Mark a tool call as completed without sending a result (for tools that don't expect responses).
func markToolCallCompleted(_ toolCallId: String) {
pendingToolCalls.removeAll { $0.toolCallId == toolCallId }
}
// MARK: - Private
private let dependencyProvider: any ConversationDependencyProvider
private var activeConnectionManager: (any ConnectionManaging)?
private var activeWebRTCConnectionManager: (any WebRTCConnectionManaging)? {
activeConnectionManager as? any WebRTCConnectionManaging
}
let config: ConversationConfig
let callbacks: ConversationCallbacks
var speakingTimer: Task<Void, Never>?
private var isTearingDown = false
private func updateStartupStage(_ stage: ConversationStartupState) {
guard state.isConnecting, state != .connecting(stage) else { return }
state = .connecting(stage)
}
/// Common preparation shared by voice and text-only startup paths.
private func prepareConversationStart(
auth: ConversationCredentials,
connectionManager: any ConnectionManaging
) {
state = .connecting(.preparing)
activeConnectionManager = connectionManager
activeContext = ["agentId": auth.agentId]
let mode = config.conversationOverrides.textOnly ? "text-only" : "voice"
logger.info("Starting \(mode) conversation", context: activeContext)
setupAgentStateManager()
let connectionManagerID = ObjectIdentifier(connectionManager)
connectionManager.onEventReceived = { [weak self] event in
Task { @MainActor [weak self] in
await self?.handleIncomingEvent(event, from: connectionManagerID)
}
}
connectionManager.onDisconnected = { [weak self] in
guard let self else { return }
await endConversation(reason: .remoteDisconnected)
}
}
private func handleIncomingEvent(_ event: IncomingEvent, from connectionManagerID: ObjectIdentifier) async {
guard let activeConnectionManager,
ObjectIdentifier(activeConnectionManager) == connectionManagerID,
state.isConnecting || state.isConnected
else {
return
}
await handleIncomingEvent(event)
}
private func handleStartupFailure(
_ error: ConversationError,
disconnecting connectionManager: any ConnectionManaging
) async {
cleanupTransientResources()
await connectionManager.disconnect()
// End/supersede may have already moved us out of connecting; don't
// overwrite `.ended` or fire shared `onError` for a discarded session.
guard state.isConnecting else { return }
state = .error(error)
callbacks.onError?(error)
}
private func handleStartupCancellation(disconnecting connectionManager: any ConnectionManaging) async {
if state.isConnecting {
state = .ended(reason: .userEnded)
tearDownActiveSession()
}
await connectionManager.disconnect()
}
/// Tear down operational state when an active session ends.
/// Preserves user-visible display state (history, MCP activity, conversation
/// metadata) so `ConversationClient` can keep the completed transcript visible.
private func tearDownActiveSession() {
cleanupTransientResources()
pendingToolCalls.removeAll()
}
private func cleanupTransientResources() {
isTearingDown = true
speakingTimer?.cancel()
speakingTimer = nil
pendingMuteState = nil
agentState = .listening
agentObserverRegistry.reset()
micObserverRegistry.reset()
audioManager?.cleanup()
agentStateManager = nil
}
private func scheduleBackToListening(delay: TimeInterval = 0.5) {
speakingTimer?.cancel()
speakingTimer = Task {
do {
try await Task.sleep(nanoseconds: UInt64(delay * 1_000_000_000))
self.agentState = .listening
} catch {
// Task was cancelled, do nothing
}
}
}
func publish(_ event: OutgoingEvent) async throws {
guard let connectionManager = activeConnectionManager else {
throw ConversationError.notConnected
}
try await connectionManager.send(event: event)
}
// MARK: - Event Handling
// swiftlint:disable:next cyclomatic_complexity function_body_length
func handleIncomingEvent(_ event: IncomingEvent) async {
switch event {
case let .userTranscript(e):
updateChatHistory { $0.receive(e) }
agentStateManager?.processSignal(.userTranscript)
callbacks.onUserTranscript?(e.transcript, e.eventId)
case let .agentResponse(e):
updateChatHistory { $0.receive(e) }
agentStateManager?.processSignal(.agentResponse)
callbacks.onAgentResponse?(e.response, e.eventId)
case let .agentResponseCorrection(correction):
updateChatHistory { $0.receive(correction) }
callbacks.onAgentResponseCorrection?(
correction.originalAgentResponse,
correction.correctedAgentResponse,
correction.eventId
)
case let .agentResponseMetadata(metadata):
callbacks.onAgentResponseMetadata?(
metadata.metadataData,
metadata.eventId
)
case let .agentChatResponsePart(e):
updateChatHistory { $0.receive(e) }
case let .audio(audioEvent):
if let alignment = audioEvent.alignment {
callbacks.onAudioAlignment?(alignment)
}
case let .interruption(interruptionEvent):
speakingTimer?.cancel()
applyStateSignal(.interruption, fallback: .listening)
callbacks.onInterruption?(interruptionEvent.eventId)
case let .conversationMetadata(metadata):
conversationMetadata = metadata
callbacks.onConversationMetadata?(metadata)
case let .ping(p):
let pong = OutgoingEvent.pong(PongEvent(eventId: p.eventId))
try? await publish(pong)
case let .clientToolCall(toolCall):
callbacks.onClientToolCall?(toolCall)
pendingToolCalls.append(toolCall)
case let .vadScore(vad):
agentStateManager?.processSignal(.vadScore(vad.vadScore))
callbacks.onVadScore?(vad.vadScore)
case let .agentToolResponse(toolResponse):
updateChatHistory { $0.receive(toolResponse) }
applyStateSignal(.agentToolResponse, fallback: .listening)
if toolResponse.toolName == "end_call" {
await endConversation()
}
callbacks.onAgentToolResponse?(toolResponse)
case let .agentToolRequest(toolRequest):
applyStateSignal(.agentToolRequest, fallback: .thinking)
callbacks.onAgentToolRequest?(toolRequest)
case let .tentativeUserTranscript(transcript):
updateChatHistory { $0.receive(transcript) }
case let .mcpToolCall(toolCall):
if let index = mcpToolCalls.firstIndex(where: { $0.toolCallId == toolCall.toolCallId }) {
mcpToolCalls[index] = toolCall
} else {
mcpToolCalls.append(toolCall)
}
case let .mcpConnectionStatus(status):
mcpConnectionStatus = status
case let .error(errorEvent):
logger.error("Received error event from server: code=\(errorEvent.code), message=\(errorEvent.message ?? "none")")
callbacks.onError?(.serverError(errorEvent))
}
}
private func updateChatHistory(_ update: (inout ChatHistoryReconciler) -> Void) {
update(&chatHistoryReconciler)
chatHistory = chatHistoryReconciler.items
}
}
// swiftlint:enable file_length type_body_length