Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions AEPBrandConcierge.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
24037AE02EF364B000FF4031 /* CitationMarker.swift in Sources */ = {isa = PBXBuildFile; fileRef = 24037AC72EF364B000FF4031 /* CitationMarker.swift */; };
24037AE12EF364B000FF4031 /* ConciergeError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 24037AD12EF364B000FF4031 /* ConciergeError.swift */; };
24037AE22EF364B000FF4031 /* ConversationResponse.swift in Sources */ = {isa = PBXBuildFile; fileRef = 24037AD42EF364B000FF4031 /* ConversationResponse.swift */; };
C5F4EAFBB41CC4351E3AB9D5 /* VoicePayload.swift in Sources */ = {isa = PBXBuildFile; fileRef = 14D5B019AE7B2AEA4B6032C3 /* VoicePayload.swift */; };
24037AE32EF364B000FF4031 /* MessageTemplate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 24037AC92EF364B000FF4031 /* MessageTemplate.swift */; };
24037AE42EF364B000FF4031 /* WelcomePromptSuggestion.swift in Sources */ = {isa = PBXBuildFile; fileRef = 24037ACC2EF364B000FF4031 /* WelcomePromptSuggestion.swift */; };
24037AE92EF364D800FF4031 /* ConciergeOverlayManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 24037AE62EF364D800FF4031 /* ConciergeOverlayManager.swift */; };
Expand Down Expand Up @@ -289,6 +290,7 @@
24037AD22EF364B000FF4031 /* ConversationHandle.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ConversationHandle.swift; sourceTree = "<group>"; };
24037AD32EF364B000FF4031 /* ConversationPayload.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ConversationPayload.swift; sourceTree = "<group>"; };
24037AD42EF364B000FF4031 /* ConversationResponse.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ConversationResponse.swift; sourceTree = "<group>"; };
14D5B019AE7B2AEA4B6032C3 /* VoicePayload.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = VoicePayload.swift; sourceTree = "<group>"; };
24037AD52EF364B000FF4031 /* Source.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Source.swift; sourceTree = "<group>"; };
24037AE52EF364D800FF4031 /* ConciergeHostingController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ConciergeHostingController.swift; sourceTree = "<group>"; };
24037AE62EF364D800FF4031 /* ConciergeOverlayManager.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ConciergeOverlayManager.swift; sourceTree = "<group>"; };
Expand Down Expand Up @@ -562,6 +564,7 @@
0F1601712FADD63D0032EFD0 /* LinkHint.swift */,
24037AD32EF364B000FF4031 /* ConversationPayload.swift */,
24037AD42EF364B000FF4031 /* ConversationResponse.swift */,
14D5B019AE7B2AEA4B6032C3 /* VoicePayload.swift */,
24037AD52EF364B000FF4031 /* Source.swift */,
);
path = Network;
Expand Down Expand Up @@ -1312,6 +1315,7 @@
0F1601752FAF7FA80032EFD0 /* MessageFeedbackView.swift in Sources */,
4C29834B2F870A430057C927 /* ConciergeChatSession.swift in Sources */,
24037AE22EF364B000FF4031 /* ConversationResponse.swift in Sources */,
C5F4EAFBB41CC4351E3AB9D5 /* VoicePayload.swift in Sources */,
24037AE32EF364B000FF4031 /* MessageTemplate.swift in Sources */,
24037AE42EF364B000FF4031 /* WelcomePromptSuggestion.swift in Sources */,
4C3A65E12E5E989E00EEEF3B /* MarkdownBlockView.swift in Sources */,
Expand Down
11 changes: 11 additions & 0 deletions AEPBrandConcierge/Sources/Core/ConciergeConstants.swift
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,12 @@ public enum ConciergeConstants {
static let PAYLOAD = "payload"
static let TOKEN = "token"
}

/// Keys for the `query.conversation.voice` marker of a voice bootstrap. See `Values.VoiceBootstrap` for the `action` value.
enum VoiceBootstrap {
static let VOICE = "voice"
static let ACTION = "action"
}
}

enum Values {
Expand All @@ -203,6 +209,11 @@ public enum ConciergeConstants {
enum AuthData {
static let TYPE_AUTH = "auth"
}

enum VoiceBootstrap {
/// `query.conversation.voice.action` value requesting voice session credentials.
static let ACTION_START = "start"
}
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@ public struct ConversationResponse: Codable {
public let linkHints: [LinkHint]?
public let state: String?
public let feedback: ConversationFeedbackInfo?
/// Present only on a voice-bootstrap turn; carries the voice session credentials. Optional, so
/// text-turn responses (which omit this key) decode unchanged. Internal: the voice wire format
/// belongs to the service and is not part of the public API.
let voice: VoicePayload?
}

/// Feedback metadata returned with an agent response.
Expand Down
40 changes: 40 additions & 0 deletions AEPBrandConcierge/Sources/Models/Network/VoicePayload.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
/*
Copyright 2026 Adobe. All rights reserved.
This file is licensed to you under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under
the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
OF ANY KIND, either express or implied. See the License for the specific language
governing permissions and limitations under the License.
*/

import Foundation

/// The `response.voice` object carried on a `ConversationResponse` for a voice-bootstrap turn.
/// Mirrors the service's wire format, so it stays internal; callers receive `VoiceSessionBootstrap`.
///
/// Decodes only the fields the client consumes. Other `type` values (e.g. `"done"`) decode without
/// error and are ignored by callers that only act on `livekit_session`.
struct VoicePayload: Codable {
/// The kind of voice payload. `SessionType.livekitSession` is the only value the client acts on.
let type: String
/// Real-time media server URL; present on a `livekit_session` payload.
let livekitUrl: String?
/// Access token for the real-time media session; present on a `livekit_session` payload.
let token: String?

/// Known `type` discriminator values.
enum SessionType {
/// A resolved session carrying `livekitUrl` and `token`.
static let livekitSession = "livekit_session"
}
}

/// Connection credentials resolved from a successful voice bootstrap: the validated, non-optional
/// form of the fields carried on `VoicePayload`, under transport-neutral names.
struct VoiceSessionBootstrap: Equatable {
let url: String
let token: String
}
149 changes: 130 additions & 19 deletions AEPBrandConcierge/Sources/Services/ConciergeChatService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,73 @@ class ConciergeChatService: NSObject {
}
}

// MARK: - Voice Bootstrap

/// Requests voice session credentials with a `voice: { action: "start" }` conversation event on the
/// regular conversations endpoint (with the region, like a chat turn). `onBootstrap` fires at most once, for the first `response.voice` of type
/// `livekit_session` carrying both `livekitUrl` and `token`. `onComplete` has the same semantics
/// as in `streamChat`: an error on failure, `nil` when the stream closes. A stream that closes
/// without a session payload completes with `nil`; callers treat that as a failed bootstrap.
///
/// `token` is resolved by the caller, as for `streamChat`, and sent where a chat turn sends it;
/// pass `nil` to send the bootstrap without one. The service doesn't pass it to the agent during
/// voice yet.
///
/// `xdmFields` is the held XDM context snapshot. The service keeps the bootstrap's `xdm` for the
/// voice session and sends it with every voice turn, so later context updates don't reach a
/// running voice session. Pass `sessionID` from the same `resolveSessionID()` call as the snapshot.
///
/// Shares the per-request streaming state with `streamChat`, so callers must not run a bootstrap
/// and a chat turn on the same instance at the same time.
func bootstrapVoiceSession(token: String?,
xdmFields: [String: Any]? = nil,
sessionID: String? = nil,
onBootstrap: @escaping (VoiceSessionBootstrap) -> Void,
onComplete: @escaping (ConciergeError?) -> Void) {
do {
let url = try createUrl(sessionID: sessionID)

var didBootstrap = false
onChunkHandler = { payload in
guard !didBootstrap,
let voice = payload.response?.voice,
voice.type == VoicePayload.SessionType.livekitSession,
let livekitUrl = voice.livekitUrl,
let token = voice.token else {
return
}
didBootstrap = true
onBootstrap(VoiceSessionBootstrap(url: livekitUrl, token: token))
}
onCompleteHandler = onComplete

let payload = try createVoiceBootstrapPayload(token: token, xdmFields: xdmFields)

var request = URLRequest(url: url)
request.httpMethod = ConciergeConstants.HTTPMethods.POST
request.httpBody = payload
request.setValue(ConciergeConstants.ContentTypes.APPLICATION_JSON, forHTTPHeaderField: ConciergeConstants.HeaderFields.CONTENT_TYPE)
request.setValue(ConciergeConstants.AcceptTypes.TEXT_EVENT_STREAM, forHTTPHeaderField: ConciergeConstants.HeaderFields.ACCEPT)
request.timeoutInterval = ConciergeConstants.Request.READ_TIMEOUT

dataTask = session.dataTask(with: request)
// The request body is not logged, as for chat: it carries the app's auth token.
Log.debug(label: LOG_TAG, "Sending voice bootstrap request to Concierge Service: \(url)")

SessionManager.shared.refreshSessionActivity()

dataTask?.resume()
} catch {
// Same reasoning as `streamChat`: a prior task's delegate callback must not reach these handlers.
onChunkHandler = nil
onCompleteHandler = nil

let conciergeError = (error as? ConciergeError) ?? .unknown
Log.warning(label: LOG_TAG, conciergeError.localizedDescription)
onComplete(conciergeError)
}
}

// MARK: - Feedback reporting

/// Builds and sends a feedback request. `token` is resolved by the caller and attached to the
Expand Down Expand Up @@ -157,6 +224,8 @@ class ConciergeChatService: NSObject {
// MARK: - Private Methods

/// Creates the URL for a request to the Concierge Service.
/// - Parameters:
/// - sessionID: The backend session ID to send; defaults to the configuration's current session.
/// - Note: Internal visibility for testing
func createUrl(sessionID: String? = nil) throws -> URL {
// TODO: Remove prior to release
Expand All @@ -182,12 +251,12 @@ class ConciergeChatService: NSObject {
queryItems.append(URLQueryItem(name: ConciergeConstants.Request.Keys.CONVERSATION_ID, value: conversationId))
}

var region = ""
var servicePath = serviceName
if let configRegion = configuration.region, !configRegion.isEmpty {
region = "/\(configRegion)"
servicePath += "/\(configRegion)"
}
var urlComponents = URLComponents(string: "\(ConciergeConstants.Request.HTTPS)\(endpoint)\(serviceName)\(region)\(conversationsApiName)")

var urlComponents = URLComponents(string: "\(ConciergeConstants.Request.HTTPS)\(endpoint)\(servicePath)\(conversationsApiName)")
urlComponents?.queryItems = queryItems

guard let url = urlComponents?.url else {
Expand All @@ -212,25 +281,72 @@ class ConciergeChatService: NSObject {
/// - Returns: JSON data for the request body
/// - Note: Internal visibility for testing
func createChatPayload(query: String, token: String? = nil, extraXDMFields: [String: Any]? = nil) throws -> Data {
// ECID here is only the readiness gate; the full identityMap is forwarded below
guard configuration.ecid != nil else { throw ConciergeError.invalidEcid("Unable to create concierge request payload. ECID is nil.") }
guard !configuration.surfaces.isEmpty else { throw ConciergeError.invalidSurfaces("Unable to create concierge request payload. No surfaces were provided.") }
try requireConversationPrerequisites()

let consentState = ConsentState(configValue: configuration.consentCollectValue).payloadValue
var conversation: [String: Any] = [
ConciergeConstants.Request.Keys.SURFACES: USE_TEMPS ? [TEMP_surface] : configuration.surfaces,
ConciergeConstants.Request.Keys.MESSAGE: query
]
if let dataPart = Self.authDataPart(for: token) {
conversation[ConciergeConstants.Request.Keys.AuthData.DATA] = dataPart
}

// Forward identityMap verbatim; falls back to an ECID-only map
let identityMapPayload: [String: Any] = USE_TEMPS
? [ConciergeConstants.Request.Keys.ECID: [[ConciergeConstants.Request.Keys.ID: TEMP_ecid]]]
: configuration.identityMapPayload
let payload = makeConversationEventPayload(conversation: conversation, extraXDMFields: extraXDMFields)

guard let jsonData = try? JSONSerialization.data(withJSONObject: payload) else {
throw ConciergeError.invalidData("Unable to create JSON payload for request to Brand Concierge chat service.")
}
return jsonData
}

/// Creates the JSON payload for a voice-bootstrap request. Same envelope as `createChatPayload`
/// (surfaces, identity map, consent, and the auth token in `data`), but `conversation` carries the
/// `voice: { action: "start" }` marker instead of `message`. The service rejects `voice` together
/// with `message`.
/// - Parameters:
/// - token: The app-supplied auth token, or `nil`/blank to omit the `data` part.
/// - xdmFields: The held XDM context, merged into `xdm` as in a chat turn. The SDK's
/// `identityMap` wins on collision.
/// - Returns: JSON data for the request body.
/// - Note: Internal visibility for testing.
func createVoiceBootstrapPayload(token: String? = nil, xdmFields: [String: Any]? = nil) throws -> Data {
try requireConversationPrerequisites()

var conversation: [String: Any] = [
ConciergeConstants.Request.Keys.SURFACES: USE_TEMPS ? [TEMP_surface] : configuration.surfaces,
ConciergeConstants.Request.Keys.MESSAGE: query
ConciergeConstants.Request.Keys.VoiceBootstrap.VOICE: [
ConciergeConstants.Request.Keys.VoiceBootstrap.ACTION: ConciergeConstants.Request.Values.VoiceBootstrap.ACTION_START
]
]
if let dataPart = Self.authDataPart(for: token) {
conversation[ConciergeConstants.Request.Keys.AuthData.DATA] = dataPart
}

let payload = makeConversationEventPayload(conversation: conversation, extraXDMFields: xdmFields)

guard let jsonData = try? JSONSerialization.data(withJSONObject: payload) else {
throw ConciergeError.invalidData("Unable to create JSON payload for Brand Concierge voice bootstrap request.")
}
return jsonData
}

/// Throws if the configuration cannot yet produce a conversation request.
private func requireConversationPrerequisites() throws {
// ECID here is only the readiness gate; the full identityMap is forwarded in the payload
guard configuration.ecid != nil else { throw ConciergeError.invalidEcid("Unable to create concierge request payload. ECID is nil.") }
guard !configuration.surfaces.isEmpty else { throw ConciergeError.invalidSurfaces("Unable to create concierge request payload. No surfaces were provided.") }
}

/// Wraps a `conversation` object in the single-event envelope (xdm identity map and consent
/// meta) shared by chat-turn and voice-bootstrap requests.
private func makeConversationEventPayload(conversation: [String: Any], extraXDMFields: [String: Any]? = nil) -> [String: Any] {
let consentState = ConsentState(configValue: configuration.consentCollectValue).payloadValue

// Forward identityMap verbatim; falls back to an ECID-only map
let identityMapPayload: [String: Any] = USE_TEMPS
? [ConciergeConstants.Request.Keys.ECID: [[ConciergeConstants.Request.Keys.ID: TEMP_ecid]]]
: configuration.identityMapPayload

var xdm: [String: Any] = [
ConciergeConstants.Request.Keys.IDENTITY_MAP: identityMapPayload
]
Expand All @@ -240,7 +356,7 @@ class ConciergeChatService: NSObject {
xdm.merge(extraXDMFields) { current, _ in current }
}

let payload: [String: Any] = [
return [
ConciergeConstants.Request.Keys.EVENTS: [
[
ConciergeConstants.Request.Keys.QUERY: [
Expand All @@ -255,11 +371,6 @@ class ConciergeChatService: NSObject {
]
]
]

guard let jsonData = try? JSONSerialization.data(withJSONObject: payload) else {
throw ConciergeError.invalidData("Unable to create JSON payload for request to Brand Concierge chat service.")
}
return jsonData
}

/// Creates the JSON payload for a feedback request.
Expand Down
Loading
Loading