| 1 | use base64::Engine as _; |
| 2 | use serde_json::{Value, json}; |
| 3 | use session::{AugloopExchange, AugloopStage, Request, Scope, Session}; |
| 4 | use uuid::Uuid; |
| 5 | |
| 6 | use crate::error::{Error, Result}; |
| 7 | |
| 8 | const AUGLOOP_URL: &str = "wss://augloop.office.com/"; |
| 9 | const AUGLOOP_RESOURCE: &str = "https://augloop.office.com/v2"; |
| 10 | const AUGLOOP_SCOPE: &str = ".default"; |
| 11 | const TOKEN_PLACEHOLDER: &str = "@@augloop-token@@"; |
| 12 | const DONE_MARKER: &str = "\"isCompleted\":true"; |
| 13 | const ANSWER_TIMEOUT_MS: u64 = 55_000; |
| 14 | const KEEPALIVE_MS: u64 = 30_000; |
| 15 | const RUNTIME_VERSION: &str = "2.37.2676"; |
| 16 | const DOCUMENT_ID: &str = "doc"; |
| 17 | const INIT_MESSAGE_ID: &str = "c1"; |
| 18 | const SEED_MESSAGE_ID: &str = "c2"; |
| 19 | const ANNOTATION_TYPE: &str = "AugLoop_TeamsCopilot_TeamsCopilotComposeRewriteStreamingAnnotation"; |
| 20 | const SIGNAL_TYPE: &str = "AugLoop_TeamsCopilot_TeamsCopilotComposeRewriteSignal"; |
| 21 | const FLIGHTS: &str = "Microsoft.Teams.Augloop.EnableSendSubstrateEvents:true;Microsoft.Teams.Augloop.AllowPartialResults:true;Microsoft.Teams.Augloop.DefaultModelOverride:GPT41_ShortCo_0414;Microsoft.Teams.Augloop.FLIGHT_OMNI_MIGRATION:true;Microsoft.Teams.Augloop.EnableCopilotOrTeamsPremiumLicenseAggregation:true;Microsoft.Teams.Augloop.RingInfo:general;Microsoft.Teams.Augloop.EnableTeamsAuthSvcLicensingChecks:true;_acceptsClaimsChallengeMessages;_acceptsSeedingStatusChangeMessages"; |
| 22 | |
| 23 | const DEFAULT_TONE: &str = "default"; |
| 24 | const PROOFREAD_TONE: &str = "PROOFREAD_SCENARIO"; |
| 25 | const MEDIUM_LENGTH: &str = "medium"; |
| 26 | |
| 27 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 28 | pub enum Adjustment { |
| 29 | Concise, |
| 30 | Longer, |
| 31 | Casual, |
| 32 | Professional, |
| 33 | Confident, |
| 34 | Enthusiastic, |
| 35 | } |
| 36 | |
| 37 | impl Adjustment { |
| 38 | pub const ALL: [Adjustment; 6] = [ |
| 39 | Adjustment::Concise, |
| 40 | Adjustment::Longer, |
| 41 | Adjustment::Casual, |
| 42 | Adjustment::Professional, |
| 43 | Adjustment::Confident, |
| 44 | Adjustment::Enthusiastic, |
| 45 | ]; |
| 46 | |
| 47 | pub fn label(self) -> &'static str { |
| 48 | match self { |
| 49 | Adjustment::Concise => "Concise", |
| 50 | Adjustment::Longer => "Longer", |
| 51 | Adjustment::Casual => "Casual", |
| 52 | Adjustment::Professional => "Professional", |
| 53 | Adjustment::Confident => "Confident", |
| 54 | Adjustment::Enthusiastic => "Enthusiastic", |
| 55 | } |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | /// The "Write with Copilot" choices with the tone and length Teams sends for each. |
| 60 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 61 | pub enum ComposeAction { |
| 62 | Rewrite, |
| 63 | Proofread, |
| 64 | Adjust(Adjustment), |
| 65 | Custom(String), |
| 66 | } |
| 67 | |
| 68 | impl ComposeAction { |
| 69 | pub fn tone(&self) -> &'static str { |
| 70 | match self { |
| 71 | ComposeAction::Proofread => PROOFREAD_TONE, |
| 72 | ComposeAction::Adjust(Adjustment::Casual) => "casual", |
| 73 | ComposeAction::Adjust(Adjustment::Professional) => "professional", |
| 74 | ComposeAction::Adjust(Adjustment::Confident) => "confident", |
| 75 | ComposeAction::Adjust(Adjustment::Enthusiastic) => "enthusiastic", |
| 76 | _ => DEFAULT_TONE, |
| 77 | } |
| 78 | } |
| 79 | |
| 80 | pub fn length(&self) -> &'static str { |
| 81 | match self { |
| 82 | ComposeAction::Adjust(Adjustment::Concise) => "short", |
| 83 | ComposeAction::Adjust(Adjustment::Longer) => "long", |
| 84 | _ => MEDIUM_LENGTH, |
| 85 | } |
| 86 | } |
| 87 | |
| 88 | pub fn label(&self) -> &str { |
| 89 | match self { |
| 90 | ComposeAction::Rewrite => "Rewrite", |
| 91 | ComposeAction::Proofread => "Proofread", |
| 92 | ComposeAction::Adjust(adjustment) => adjustment.label(), |
| 93 | ComposeAction::Custom(prompt) => prompt, |
| 94 | } |
| 95 | } |
| 96 | } |
| 97 | |
| 98 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 99 | pub struct ComposeRewrite { |
| 100 | pub tenant_id: String, |
| 101 | pub thread_id: String, |
| 102 | pub user_html: String, |
| 103 | pub action: ComposeAction, |
| 104 | pub ui_language: String, |
| 105 | pub time_zone: String, |
| 106 | } |
| 107 | |
| 108 | pub struct ComposeCopilot { |
| 109 | session: Session, |
| 110 | } |
| 111 | |
| 112 | impl ComposeCopilot { |
| 113 | pub fn new(session: &Session) -> Self { |
| 114 | ComposeCopilot { |
| 115 | session: session.clone(), |
| 116 | } |
| 117 | } |
| 118 | |
| 119 | pub async fn rewrite(&self, rewrite: &ComposeRewrite) -> Result<String> { |
| 120 | let request = Request::augloop(AUGLOOP_URL, exchange(rewrite, &Uuid::new_v4().to_string())); |
| 121 | let response = self |
| 122 | .session |
| 123 | .send(request, &Scope::new(AUGLOOP_RESOURCE, AUGLOOP_SCOPE)) |
| 124 | .await?; |
| 125 | answer_of(&response.body) |
| 126 | } |
| 127 | } |
| 128 | |
| 129 | fn correlation_vector() -> String { |
| 130 | base64::engine::general_purpose::STANDARD_NO_PAD.encode(Uuid::new_v4().as_bytes()) |
| 131 | } |
| 132 | |
| 133 | fn header(type_name: &str, base_types: &[&str]) -> Value { |
| 134 | json!({"T_": type_name, "B_": base_types}) |
| 135 | } |
| 136 | |
| 137 | pub fn exchange(rewrite: &ComposeRewrite, session_id: &str) -> AugloopExchange { |
| 138 | let vector = correlation_vector(); |
| 139 | let init = json!({ |
| 140 | "protocolVersion": 2, |
| 141 | "clientMetadata": { |
| 142 | "appName": "Teams", |
| 143 | "appPlatform": "Web", |
| 144 | "uiLanguage": rewrite.ui_language, |
| 145 | "flights": FLIGHTS, |
| 146 | "releaseAudienceGroup": "Production", |
| 147 | "releaseChannel": "general", |
| 148 | "sessionId": session_id, |
| 149 | "runtimeVersion": RUNTIME_VERSION, |
| 150 | "docSessionId": Uuid::new_v4().to_string(), |
| 151 | "userSystemTimezone": rewrite.time_zone, |
| 152 | }, |
| 153 | "extensionConfigs": [], |
| 154 | "returnWorkflowInputTypes": true, |
| 155 | "enableRemoteExecutionNotification": false, |
| 156 | "createBlobStorageContainer": false, |
| 157 | "H_": header("AugLoop_Session_Protocol_SessionInitMessage", &["AugLoop_Session_Protocol_Message"]), |
| 158 | "cv": format!("{vector}.1"), |
| 159 | "messageId": INIT_MESSAGE_ID, |
| 160 | }); |
| 161 | let seed = json!({ |
| 162 | "cv": correlation_vector(), |
| 163 | "seq": 0, |
| 164 | "ops": [{ |
| 165 | "parentPath": ["session"], |
| 166 | "items": [{"id": DOCUMENT_ID, "body": { |
| 167 | "isReadonly": false, |
| 168 | "H_": header("AugLoop_Core_Document", &["AugLoop_Core_TileGroup"]), |
| 169 | }}], |
| 170 | "H_": add_operation_header(), |
| 171 | }], |
| 172 | "groupId": "Seed", |
| 173 | "groupSize": 1, |
| 174 | "groupComplete": true, |
| 175 | "H_": header("AugLoop_Session_Protocol_SyncMessage", &["AugLoop_Session_Protocol_Message"]), |
| 176 | "messageId": SEED_MESSAGE_ID, |
| 177 | }); |
| 178 | let activation = json!({ |
| 179 | "annotationType": ANNOTATION_TYPE, |
| 180 | "token": format!("{ANNOTATION_TYPE}-0"), |
| 181 | "ignoreExistingAnnotations": false, |
| 182 | "returnAnnotationDoesNotExist": true, |
| 183 | "sendApologies": false, |
| 184 | "H_": header("AugLoop_Session_Protocol_AnnotationActivationMessage", &["AugLoop_Session_Protocol_Message"]), |
| 185 | "cv": format!("{vector}.2"), |
| 186 | "messageId": "c3", |
| 187 | }); |
| 188 | let token = json!({ |
| 189 | "authToken": TOKEN_PLACEHOLDER, |
| 190 | "version": 1, |
| 191 | "H_": header("AugLoop_Session_Protocol_TokenProvisionMessage", &["AugLoop_Session_Protocol_Message"]), |
| 192 | "cv": format!("{vector}.3"), |
| 193 | "messageId": "c4", |
| 194 | }); |
| 195 | AugloopExchange { |
| 196 | stages: vec![ |
| 197 | AugloopStage { |
| 198 | send: vec![init.to_string()], |
| 199 | await_message_id: Some(INIT_MESSAGE_ID.to_owned()), |
| 200 | }, |
| 201 | AugloopStage { |
| 202 | send: vec![seed.to_string(), activation.to_string(), token.to_string()], |
| 203 | await_message_id: Some(SEED_MESSAGE_ID.to_owned()), |
| 204 | }, |
| 205 | AugloopStage { |
| 206 | send: vec![signal(rewrite).to_string()], |
| 207 | await_message_id: None, |
| 208 | }, |
| 209 | ], |
| 210 | placeholder: TOKEN_PLACEHOLDER.to_owned(), |
| 211 | done_marker: DONE_MARKER.to_owned(), |
| 212 | timeout_ms: ANSWER_TIMEOUT_MS, |
| 213 | keepalive_ms: KEEPALIVE_MS, |
| 214 | } |
| 215 | } |
| 216 | |
| 217 | fn add_operation_header() -> Value { |
| 218 | header( |
| 219 | "AugLoop_Core_AddOperation", |
| 220 | &[ |
| 221 | "AugLoop_Core_OperationWithSiblingContext", |
| 222 | "AugLoop_Core_Operation", |
| 223 | ], |
| 224 | ) |
| 225 | } |
| 226 | |
| 227 | pub fn signal(rewrite: &ComposeRewrite) -> Value { |
| 228 | let mut body = json!({ |
| 229 | "userText": rewrite.user_html, |
| 230 | "tone": rewrite.action.tone(), |
| 231 | "length": rewrite.action.length(), |
| 232 | "requestContext": { |
| 233 | "threadId": rewrite.thread_id, |
| 234 | "contextType": "Chat", |
| 235 | "tenantId": rewrite.tenant_id, |
| 236 | }, |
| 237 | "streamResponse": true, |
| 238 | "H_": header(SIGNAL_TYPE, &["AugLoop_TeamsCopilot_TeamsCopilotBaseSignal", "AugLoop_Signals_Signal"]), |
| 239 | }); |
| 240 | if let ComposeAction::Custom(prompt) = &rewrite.action { |
| 241 | body["customPrompt"] = json!(prompt); |
| 242 | } |
| 243 | json!({ |
| 244 | "cv": correlation_vector(), |
| 245 | "seq": 1, |
| 246 | "ops": [{ |
| 247 | "parentPath": [ |
| 248 | "session", |
| 249 | DOCUMENT_ID, |
| 250 | format!("teams_compose_copilot_streaming_{}", Uuid::new_v4()), |
| 251 | Uuid::new_v4().to_string(), |
| 252 | ], |
| 253 | "items": [{"id": Uuid::new_v4().to_string(), "body": body, "contextId": "C1"}], |
| 254 | "H_": add_operation_header(), |
| 255 | }], |
| 256 | "H_": header("AugLoop_Session_Protocol_SyncMessage", &["AugLoop_Session_Protocol_Message"]), |
| 257 | "messageId": "c5", |
| 258 | }) |
| 259 | } |
| 260 | |
| 261 | fn annotation_bodies(received: &Value) -> impl Iterator<Item = &Value> { |
| 262 | received |
| 263 | .as_array() |
| 264 | .into_iter() |
| 265 | .flatten() |
| 266 | .filter(|message| message["annotationType"] == ANNOTATION_TYPE) |
| 267 | .flat_map(|message| message["ops"].as_array().into_iter().flatten()) |
| 268 | .flat_map(|operation| operation["items"].as_array().into_iter().flatten()) |
| 269 | .map(|item| &item["body"]) |
| 270 | } |
| 271 | |
| 272 | pub fn answer_of(received: &Value) -> Result<String> { |
| 273 | let completed = annotation_bodies(received).find(|body| body["isCompleted"] == true); |
| 274 | let Some(body) = completed else { |
| 275 | return Err(Error::UnexpectedAnswer(failure_reason(received))); |
| 276 | }; |
| 277 | if body["status"].as_i64().unwrap_or(0) != 0 { |
| 278 | return Err(Error::UnexpectedAnswer(format!( |
| 279 | "Copilot status {}", |
| 280 | body["status"] |
| 281 | ))); |
| 282 | } |
| 283 | body["answer"] |
| 284 | .as_str() |
| 285 | .map(str::trim) |
| 286 | .filter(|answer| !answer.is_empty()) |
| 287 | .map(str::to_owned) |
| 288 | .ok_or_else(|| Error::UnexpectedAnswer("Copilot gave no answer".to_owned())) |
| 289 | } |
| 290 | |
| 291 | fn failure_reason(received: &Value) -> String { |
| 292 | received |
| 293 | .as_array() |
| 294 | .into_iter() |
| 295 | .flatten() |
| 296 | .find_map(|message| message["error"].as_str().map(str::to_owned)) |
| 297 | .unwrap_or_else(|| "Copilot did not answer".to_owned()) |
| 298 | } |
| 299 | |
| 300 | #[cfg(test)] |
| 301 | mod tests { |
| 302 | use super::*; |
| 303 | |
| 304 | fn rewrite() -> ComposeRewrite { |
| 305 | ComposeRewrite { |
| 306 | tenant_id: "tenant-1".into(), |
| 307 | thread_id: "19:chat@thread.v2".into(), |
| 308 | user_html: "<p>hallo</p>".into(), |
| 309 | action: ComposeAction::Rewrite, |
| 310 | ui_language: "en-gb".into(), |
| 311 | time_zone: "Europe/Berlin".into(), |
| 312 | } |
| 313 | } |
| 314 | |
| 315 | #[test] |
| 316 | fn stages_init_then_seed_with_token_then_signal() { |
| 317 | let exchange = exchange(&rewrite(), "session-1"); |
| 318 | assert_eq!(exchange.stages.len(), 3); |
| 319 | assert_eq!(exchange.stages[0].await_message_id.as_deref(), Some("c1")); |
| 320 | let init: Value = serde_json::from_str(&exchange.stages[0].send[0]).unwrap(); |
| 321 | assert_eq!(init["clientMetadata"]["sessionId"], "session-1"); |
| 322 | let token: Value = serde_json::from_str(&exchange.stages[1].send[2]).unwrap(); |
| 323 | assert_eq!(token["authToken"], TOKEN_PLACEHOLDER); |
| 324 | let signal: Value = serde_json::from_str(&exchange.stages[2].send[0]).unwrap(); |
| 325 | let body = &signal["ops"][0]["items"][0]["body"]; |
| 326 | assert_eq!(body["userText"], "<p>hallo</p>"); |
| 327 | assert_eq!(body["requestContext"]["threadId"], "19:chat@thread.v2"); |
| 328 | assert_eq!( |
| 329 | (body["tone"].as_str(), body["length"].as_str()), |
| 330 | (Some("default"), Some("medium")) |
| 331 | ); |
| 332 | assert!(body.get("customPrompt").is_none()); |
| 333 | } |
| 334 | |
| 335 | #[test] |
| 336 | fn actions_send_the_tone_and_length_teams_sends() { |
| 337 | let sent = |action: ComposeAction| { |
| 338 | let body = signal(&ComposeRewrite { |
| 339 | action, |
| 340 | ..rewrite() |
| 341 | })["ops"][0]["items"][0]["body"] |
| 342 | .clone(); |
| 343 | ( |
| 344 | body["tone"].as_str().unwrap().to_owned(), |
| 345 | body["length"].as_str().unwrap().to_owned(), |
| 346 | body.get("customPrompt").cloned(), |
| 347 | ) |
| 348 | }; |
| 349 | assert_eq!( |
| 350 | sent(ComposeAction::Proofread), |
| 351 | ("PROOFREAD_SCENARIO".into(), "medium".into(), None) |
| 352 | ); |
| 353 | assert_eq!( |
| 354 | sent(ComposeAction::Adjust(Adjustment::Concise)), |
| 355 | ("default".into(), "short".into(), None) |
| 356 | ); |
| 357 | assert_eq!( |
| 358 | sent(ComposeAction::Adjust(Adjustment::Longer)), |
| 359 | ("default".into(), "long".into(), None) |
| 360 | ); |
| 361 | assert_eq!( |
| 362 | sent(ComposeAction::Adjust(Adjustment::Confident)), |
| 363 | ("confident".into(), "medium".into(), None) |
| 364 | ); |
| 365 | assert_eq!( |
| 366 | sent(ComposeAction::Custom("as a haiku".into())), |
| 367 | ("default".into(), "medium".into(), Some(json!("as a haiku"))) |
| 368 | ); |
| 369 | } |
| 370 | |
| 371 | #[test] |
| 372 | fn the_completed_annotation_carries_the_answer() { |
| 373 | let part = |body: Value| json!({"annotationType": ANNOTATION_TYPE, "ops": [{"items": [{"body": body}]}]}); |
| 374 | let received = json!([ |
| 375 | {"messageId": "c1"}, |
| 376 | part(json!({"answerPart": "<p>Hallo", "isCompleted": false})), |
| 377 | part(json!({"status": 0, "answerPart": "", "answer": "<p>Hallo zusammen</p>", "isCompleted": true})), |
| 378 | ]); |
| 379 | assert_eq!(answer_of(&received).unwrap(), "<p>Hallo zusammen</p>"); |
| 380 | } |
| 381 | |
| 382 | #[test] |
| 383 | fn a_missing_answer_reports_the_socket_error() { |
| 384 | let received = json!([{"messageId": "c1", "error": "Unauthorized"}]); |
| 385 | assert_eq!( |
| 386 | answer_of(&received).unwrap_err().to_string(), |
| 387 | "unexpected service answer: Unauthorized" |
| 388 | ); |
| 389 | } |
| 390 | } |