BlueGit

ict rusty-teams

Files

rusty-teams / crates / chatsvc / src / compose_copilot.rs

compose_copilot.rs

compose_copilot.rs 13.2 KiB Download Raw
1use base64::Engine as _;
2use serde_json::{Value, json};
3use session::{AugloopExchange, AugloopStage, Request, Scope, Session};
4use uuid::Uuid;
5
6use crate::error::{Error, Result};
7
8const AUGLOOP_URL: &str = "wss://augloop.office.com/";
9const AUGLOOP_RESOURCE: &str = "https://augloop.office.com/v2";
10const AUGLOOP_SCOPE: &str = ".default";
11const TOKEN_PLACEHOLDER: &str = "@@augloop-token@@";
12const DONE_MARKER: &str = "\"isCompleted\":true";
13const ANSWER_TIMEOUT_MS: u64 = 55_000;
14const KEEPALIVE_MS: u64 = 30_000;
15const RUNTIME_VERSION: &str = "2.37.2676";
16const DOCUMENT_ID: &str = "doc";
17const INIT_MESSAGE_ID: &str = "c1";
18const SEED_MESSAGE_ID: &str = "c2";
19const ANNOTATION_TYPE: &str = "AugLoop_TeamsCopilot_TeamsCopilotComposeRewriteStreamingAnnotation";
20const SIGNAL_TYPE: &str = "AugLoop_TeamsCopilot_TeamsCopilotComposeRewriteSignal";
21const 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
23const DEFAULT_TONE: &str = "default";
24const PROOFREAD_TONE: &str = "PROOFREAD_SCENARIO";
25const MEDIUM_LENGTH: &str = "medium";
26
27#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28pub enum Adjustment {
29 Concise,
30 Longer,
31 Casual,
32 Professional,
33 Confident,
34 Enthusiastic,
35}
36
37impl 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)]
61pub enum ComposeAction {
62 Rewrite,
63 Proofread,
64 Adjust(Adjustment),
65 Custom(String),
66}
67
68impl 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)]
99pub 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
108pub struct ComposeCopilot {
109 session: Session,
110}
111
112impl 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
129fn correlation_vector() -> String {
130 base64::engine::general_purpose::STANDARD_NO_PAD.encode(Uuid::new_v4().as_bytes())
131}
132
133fn header(type_name: &str, base_types: &[&str]) -> Value {
134 json!({"T_": type_name, "B_": base_types})
135}
136
137pub 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
217fn add_operation_header() -> Value {
218 header(
219 "AugLoop_Core_AddOperation",
220 &["AugLoop_Core_OperationWithSiblingContext", "AugLoop_Core_Operation"],
221 )
222}
223
224pub fn signal(rewrite: &ComposeRewrite) -> Value {
225 let mut body = json!({
226 "userText": rewrite.user_html,
227 "tone": rewrite.action.tone(),
228 "length": rewrite.action.length(),
229 "requestContext": {
230 "threadId": rewrite.thread_id,
231 "contextType": "Chat",
232 "tenantId": rewrite.tenant_id,
233 },
234 "streamResponse": true,
235 "H_": header(SIGNAL_TYPE, &["AugLoop_TeamsCopilot_TeamsCopilotBaseSignal", "AugLoop_Signals_Signal"]),
236 });
237 if let ComposeAction::Custom(prompt) = &rewrite.action {
238 body["customPrompt"] = json!(prompt);
239 }
240 json!({
241 "cv": correlation_vector(),
242 "seq": 1,
243 "ops": [{
244 "parentPath": [
245 "session",
246 DOCUMENT_ID,
247 format!("teams_compose_copilot_streaming_{}", Uuid::new_v4()),
248 Uuid::new_v4().to_string(),
249 ],
250 "items": [{"id": Uuid::new_v4().to_string(), "body": body, "contextId": "C1"}],
251 "H_": add_operation_header(),
252 }],
253 "H_": header("AugLoop_Session_Protocol_SyncMessage", &["AugLoop_Session_Protocol_Message"]),
254 "messageId": "c5",
255 })
256}
257
258fn annotation_bodies(received: &Value) -> impl Iterator<Item = &Value> {
259 received
260 .as_array()
261 .into_iter()
262 .flatten()
263 .filter(|message| message["annotationType"] == ANNOTATION_TYPE)
264 .flat_map(|message| message["ops"].as_array().into_iter().flatten())
265 .flat_map(|operation| operation["items"].as_array().into_iter().flatten())
266 .map(|item| &item["body"])
267}
268
269pub fn answer_of(received: &Value) -> Result<String> {
270 let completed = annotation_bodies(received).find(|body| body["isCompleted"] == true);
271 let Some(body) = completed else {
272 return Err(Error::UnexpectedAnswer(failure_reason(received)));
273 };
274 if body["status"].as_i64().unwrap_or(0) != 0 {
275 return Err(Error::UnexpectedAnswer(format!("Copilot status {}", body["status"])));
276 }
277 body["answer"]
278 .as_str()
279 .map(str::trim)
280 .filter(|answer| !answer.is_empty())
281 .map(str::to_owned)
282 .ok_or_else(|| Error::UnexpectedAnswer("Copilot gave no answer".to_owned()))
283}
284
285fn failure_reason(received: &Value) -> String {
286 received
287 .as_array()
288 .into_iter()
289 .flatten()
290 .find_map(|message| message["error"].as_str().map(str::to_owned))
291 .unwrap_or_else(|| "Copilot did not answer".to_owned())
292}
293
294#[cfg(test)]
295mod tests {
296 use super::*;
297
298 fn rewrite() -> ComposeRewrite {
299 ComposeRewrite {
300 tenant_id: "tenant-1".into(),
301 thread_id: "19:chat@thread.v2".into(),
302 user_html: "<p>hallo</p>".into(),
303 action: ComposeAction::Rewrite,
304 ui_language: "en-gb".into(),
305 time_zone: "Europe/Berlin".into(),
306 }
307 }
308
309 #[test]
310 fn stages_init_then_seed_with_token_then_signal() {
311 let exchange = exchange(&rewrite(), "session-1");
312 assert_eq!(exchange.stages.len(), 3);
313 assert_eq!(exchange.stages[0].await_message_id.as_deref(), Some("c1"));
314 let init: Value = serde_json::from_str(&exchange.stages[0].send[0]).unwrap();
315 assert_eq!(init["clientMetadata"]["sessionId"], "session-1");
316 let token: Value = serde_json::from_str(&exchange.stages[1].send[2]).unwrap();
317 assert_eq!(token["authToken"], TOKEN_PLACEHOLDER);
318 let signal: Value = serde_json::from_str(&exchange.stages[2].send[0]).unwrap();
319 let body = &signal["ops"][0]["items"][0]["body"];
320 assert_eq!(body["userText"], "<p>hallo</p>");
321 assert_eq!(body["requestContext"]["threadId"], "19:chat@thread.v2");
322 assert_eq!((body["tone"].as_str(), body["length"].as_str()), (Some("default"), Some("medium")));
323 assert!(body.get("customPrompt").is_none());
324 }
325
326 #[test]
327 fn actions_send_the_tone_and_length_teams_sends() {
328 let sent = |action: ComposeAction| {
329 let body = signal(&ComposeRewrite { action, ..rewrite() })["ops"][0]["items"][0]["body"].clone();
330 (body["tone"].as_str().unwrap().to_owned(), body["length"].as_str().unwrap().to_owned(), body.get("customPrompt").cloned())
331 };
332 assert_eq!(sent(ComposeAction::Proofread), ("PROOFREAD_SCENARIO".into(), "medium".into(), None));
333 assert_eq!(sent(ComposeAction::Adjust(Adjustment::Concise)), ("default".into(), "short".into(), None));
334 assert_eq!(sent(ComposeAction::Adjust(Adjustment::Longer)), ("default".into(), "long".into(), None));
335 assert_eq!(sent(ComposeAction::Adjust(Adjustment::Confident)), ("confident".into(), "medium".into(), None));
336 assert_eq!(
337 sent(ComposeAction::Custom("as a haiku".into())),
338 ("default".into(), "medium".into(), Some(json!("as a haiku")))
339 );
340 }
341
342 #[test]
343 fn the_completed_annotation_carries_the_answer() {
344 let part = |body: Value| json!({"annotationType": ANNOTATION_TYPE, "ops": [{"items": [{"body": body}]}]});
345 let received = json!([
346 {"messageId": "c1"},
347 part(json!({"answerPart": "<p>Hallo", "isCompleted": false})),
348 part(json!({"status": 0, "answerPart": "", "answer": "<p>Hallo zusammen</p>", "isCompleted": true})),
349 ]);
350 assert_eq!(answer_of(&received).unwrap(), "<p>Hallo zusammen</p>");
351 }
352
353 #[test]
354 fn a_missing_answer_reports_the_socket_error() {
355 let received = json!([{"messageId": "c1", "error": "Unauthorized"}]);
356 assert_eq!(
357 answer_of(&received).unwrap_err().to_string(),
358 "unexpected service answer: Unauthorized"
359 );
360 }
361}