| 1 | use serde_json::{Value, json}; |
| 2 | use session::{NestedApp, Request, Scope, Session, SignalrExchange}; |
| 3 | use uuid::Uuid; |
| 4 | |
| 5 | use crate::error::{Error, Result}; |
| 6 | |
| 7 | const CHATHUB_URL: &str = "https://substrate.office.com/m365Copilot/Chathub"; |
| 8 | const SYDNEY_RESOURCE: &str = "https://substrate.office.com/sydney"; |
| 9 | const SYDNEY_SCOPE: &str = "sydney.readwrite"; |
| 10 | const COPILOT_APP: NestedApp = NestedApp { |
| 11 | client_id: "c0ab8ce9-e9a0-42e7-b064-33d422df41f1", |
| 12 | redirect_uri: "brk-multihub://m365copilotapp.svc.cloud.microsoft", |
| 13 | broker_redirect_uri: "https://teams.cloud.microsoft/v2/authv2", |
| 14 | }; |
| 15 | const HOST_PARAMETERS: &str = "source=%22officeweb%22&product=Office&agentHost=Bizchat.FullScreen&licenseType=Premium&isEdu=false&agent=work&scenario=officeweb"; |
| 16 | const HANDSHAKE: &str = r#"{"protocol":"json","version":1}"#; |
| 17 | const INVOCATION: u8 = 4; |
| 18 | const COMPLETION: u8 = 2; |
| 19 | const CLOSE: u8 = 7; |
| 20 | const ANSWER_TIMEOUT_MS: u64 = 55_000; |
| 21 | const SOURCE: &str = "teamshub"; |
| 22 | const CITATION_OPEN: char = '\u{e200}'; |
| 23 | const CITATION_CLOSE: char = '\u{e201}'; |
| 24 | const INLINE_TAGS: [&str; 6] = ["Person", "TeamsMessage", "File", "Event", "Email", "Chat"]; |
| 25 | |
| 26 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 27 | pub struct CopilotAsk { |
| 28 | pub user_id: String, |
| 29 | pub tenant_id: String, |
| 30 | pub chat_id: String, |
| 31 | pub prompt: String, |
| 32 | pub locale: String, |
| 33 | pub utc_offset_hours: i32, |
| 34 | } |
| 35 | |
| 36 | pub struct Copilot { |
| 37 | session: Session, |
| 38 | } |
| 39 | |
| 40 | impl Copilot { |
| 41 | pub fn new(session: &Session) -> Self { |
| 42 | Copilot { |
| 43 | session: session.clone(), |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | pub async fn ask(&self, ask: &CopilotAsk) -> Result<String> { |
| 48 | let session_id = Uuid::new_v4().to_string(); |
| 49 | let request_id = Uuid::new_v4().simple().to_string(); |
| 50 | let request = Request::signalr( |
| 51 | chathub_url(ask, &session_id, &request_id), |
| 52 | SignalrExchange { |
| 53 | handshake: HANDSHAKE.to_owned(), |
| 54 | invocations: vec![invocation(ask, &session_id, &request_id).to_string()], |
| 55 | done_types: vec![COMPLETION, CLOSE], |
| 56 | timeout_ms: ANSWER_TIMEOUT_MS, |
| 57 | }, |
| 58 | ); |
| 59 | let response = self |
| 60 | .session |
| 61 | .send( |
| 62 | request, |
| 63 | &Scope::new(SYDNEY_RESOURCE, SYDNEY_SCOPE).for_nested_app(COPILOT_APP), |
| 64 | ) |
| 65 | .await?; |
| 66 | answer_of(&response.body) |
| 67 | } |
| 68 | } |
| 69 | |
| 70 | fn chathub_url(ask: &CopilotAsk, session_id: &str, request_id: &str) -> String { |
| 71 | let route = format!("{}@{}", ask.user_id, ask.tenant_id); |
| 72 | format!( |
| 73 | "{CHATHUB_URL}/{route}?chatsessionid={request_id}&XRoutingParameterSessionKey={user}&clientrequestid={request_id}&X-SessionId={session_id}&ConversationId={conversation}&{HOST_PARAMETERS}", |
| 74 | user = ask.user_id, |
| 75 | conversation = Uuid::new_v4(), |
| 76 | ) |
| 77 | } |
| 78 | |
| 79 | pub fn invocation(ask: &CopilotAsk, session_id: &str, request_id: &str) -> Value { |
| 80 | json!({ |
| 81 | "type": INVOCATION, |
| 82 | "invocationId": "0", |
| 83 | "target": "chat", |
| 84 | "arguments": [{ |
| 85 | "source": SOURCE, |
| 86 | "clientCorrelationId": request_id, |
| 87 | "sessionId": session_id, |
| 88 | "optionsSets": ["enterprise_flux_work", "rich_responses"], |
| 89 | "streamingMode": "ConciseWithPadding", |
| 90 | "allowedMessageTypes": ["Chat", "Disengaged", "Progress", "EndOfRequest"], |
| 91 | "requestId": request_id, |
| 92 | "traceId": request_id, |
| 93 | "isStartOfSession": true, |
| 94 | "clientInfo": { |
| 95 | "clientPlatform": "web", |
| 96 | "clientAppName": "Teams", |
| 97 | "clientEntrypoint": "ChatPanel", |
| 98 | "clientSessionId": session_id, |
| 99 | "ProductCategory": "Chat", |
| 100 | "clientAppType": "Web", |
| 101 | "productEntryPoint": "ChatPanel", |
| 102 | }, |
| 103 | "message": { |
| 104 | "author": "user", |
| 105 | "inputMethod": "Keyboard", |
| 106 | "text": ask.prompt, |
| 107 | "requestId": request_id, |
| 108 | "locale": ask.locale, |
| 109 | "locationInfo": {"timeZoneOffset": ask.utc_offset_hours}, |
| 110 | "messageType": "Chat", |
| 111 | "experienceType": "Default", |
| 112 | "messageAnnotations": [{ |
| 113 | "id": ask.chat_id, |
| 114 | "text": ask.chat_id, |
| 115 | "messageAnnotationAppContext": "Teams", |
| 116 | "messageAnnotationSource": "ClientAnnotated", |
| 117 | "messageAnnotationMetadata": {"@type": "Chat", "annotationType": "Chat"}, |
| 118 | "messageAnnotationType": "Chat", |
| 119 | }], |
| 120 | }, |
| 121 | }], |
| 122 | }) |
| 123 | } |
| 124 | |
| 125 | pub fn answer_of(received: &Value) -> Result<String> { |
| 126 | let messages = received.as_array().map(Vec::as_slice).unwrap_or_default(); |
| 127 | let completion = messages |
| 128 | .iter() |
| 129 | .find(|message| message["type"].as_u64() == Some(u64::from(COMPLETION))) |
| 130 | .ok_or_else(|| Error::UnexpectedAnswer(close_reason(messages)))?; |
| 131 | let item = &completion["item"]; |
| 132 | let answer = item["messages"] |
| 133 | .as_array() |
| 134 | .into_iter() |
| 135 | .flatten() |
| 136 | .filter(|message| message["author"] == "bot") |
| 137 | .filter(|message| message["messageType"].is_null() || message["messageType"] == "Chat") |
| 138 | .filter_map(|message| message["text"].as_str()) |
| 139 | .next_back() |
| 140 | .map(clean_answer) |
| 141 | .filter(|text| !text.is_empty()); |
| 142 | answer.ok_or_else(|| { |
| 143 | let reason = item["result"]["message"] |
| 144 | .as_str() |
| 145 | .or_else(|| item["result"]["value"].as_str()) |
| 146 | .unwrap_or("Copilot gave no answer"); |
| 147 | Error::UnexpectedAnswer(reason.to_owned()) |
| 148 | }) |
| 149 | } |
| 150 | |
| 151 | fn close_reason(messages: &[Value]) -> String { |
| 152 | messages |
| 153 | .iter() |
| 154 | .find_map(|message| message["error"].as_str()) |
| 155 | .unwrap_or("Copilot did not answer") |
| 156 | .to_owned() |
| 157 | } |
| 158 | |
| 159 | pub fn clean_answer(text: &str) -> String { |
| 160 | let mut cleaned = String::with_capacity(text.len()); |
| 161 | let mut in_citation = false; |
| 162 | for character in text.chars() { |
| 163 | match character { |
| 164 | CITATION_OPEN => in_citation = true, |
| 165 | CITATION_CLOSE => in_citation = false, |
| 166 | _ if !in_citation => cleaned.push(character), |
| 167 | _ => {} |
| 168 | } |
| 169 | } |
| 170 | for tag in INLINE_TAGS { |
| 171 | cleaned = cleaned |
| 172 | .replace(&format!("<{tag}>"), "") |
| 173 | .replace(&format!("</{tag}>"), ""); |
| 174 | } |
| 175 | cleaned.trim().to_owned() |
| 176 | } |
| 177 | |
| 178 | #[cfg(test)] |
| 179 | mod tests { |
| 180 | use super::*; |
| 181 | |
| 182 | fn ask() -> CopilotAsk { |
| 183 | CopilotAsk { |
| 184 | user_id: "user-1".into(), |
| 185 | tenant_id: "tenant-1".into(), |
| 186 | chat_id: "19:chat@thread.v2".into(), |
| 187 | prompt: "Summarize this chat".into(), |
| 188 | locale: "en-us".into(), |
| 189 | utc_offset_hours: 1, |
| 190 | } |
| 191 | } |
| 192 | |
| 193 | #[test] |
| 194 | fn the_chat_rides_along_as_a_message_annotation() { |
| 195 | let body = invocation(&ask(), "session-1", "request-1"); |
| 196 | let message = &body["arguments"][0]["message"]; |
| 197 | assert_eq!(body["target"], "chat"); |
| 198 | assert_eq!(message["text"], "Summarize this chat"); |
| 199 | assert_eq!(message["messageAnnotations"][0]["id"], "19:chat@thread.v2"); |
| 200 | assert_eq!( |
| 201 | message["messageAnnotations"][0]["messageAnnotationType"], |
| 202 | "Chat" |
| 203 | ); |
| 204 | } |
| 205 | |
| 206 | #[test] |
| 207 | fn the_url_routes_to_the_user_in_the_tenant() { |
| 208 | let url = chathub_url(&ask(), "session-1", "request-1"); |
| 209 | assert!( |
| 210 | url.starts_with("https://substrate.office.com/m365Copilot/Chathub/user-1@tenant-1?") |
| 211 | ); |
| 212 | assert!(url.contains("X-SessionId=session-1")); |
| 213 | } |
| 214 | |
| 215 | #[test] |
| 216 | fn the_last_bot_chat_message_is_the_answer() { |
| 217 | let received = json!([ |
| 218 | {"type": 1, "target": "update", "arguments": [{"messages": [{"text": "Digging in", "author": "bot", "messageType": "Progress"}]}]}, |
| 219 | {"type": 2, "invocationId": "0", "item": {"messages": [ |
| 220 | {"text": "Summarize this chat", "author": "user"}, |
| 221 | {"text": "Working", "author": "bot", "messageType": "Progress"}, |
| 222 | {"text": "### Chat summary\n\n- <Person>Ada</Person> shipped it. \u{e200}cite\u{e202}turn1search1\u{e201}", "author": "bot"} |
| 223 | ], "result": {"value": "Success"}}} |
| 224 | ]); |
| 225 | assert_eq!( |
| 226 | answer_of(&received).unwrap(), |
| 227 | "### Chat summary\n\n- Ada shipped it." |
| 228 | ); |
| 229 | } |
| 230 | |
| 231 | #[test] |
| 232 | fn a_refusal_carries_the_service_reason() { |
| 233 | let received = json!([ |
| 234 | {"type": 2, "item": {"messages": [{"text": "Hi", "author": "user"}], "result": {"value": "Throttled", "message": "Too many requests"}}} |
| 235 | ]); |
| 236 | assert_eq!( |
| 237 | answer_of(&received).unwrap_err().to_string(), |
| 238 | "unexpected service answer: Too many requests" |
| 239 | ); |
| 240 | } |
| 241 | |
| 242 | #[test] |
| 243 | fn a_closed_hub_reports_its_error() { |
| 244 | let received = json!([{"type": 7, "error": "Unauthorized"}]); |
| 245 | assert_eq!( |
| 246 | answer_of(&received).unwrap_err().to_string(), |
| 247 | "unexpected service answer: Unauthorized" |
| 248 | ); |
| 249 | } |
| 250 | } |