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