| 1 | use agent_client_protocol_schema::v1 as acp; |
| 2 | use serde::Serialize; |
| 3 | use serde::de::DeserializeOwned; |
| 4 | use serde_json::Value; |
| 5 | use std::collections::{BTreeSet, HashMap}; |
| 6 | |
| 7 | #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] |
| 8 | pub enum Side { |
| 9 | Client, |
| 10 | Agent, |
| 11 | } |
| 12 | |
| 13 | impl Side { |
| 14 | fn name(self) -> &'static str { |
| 15 | match self { |
| 16 | Side::Client => "client", |
| 17 | Side::Agent => "agent", |
| 18 | } |
| 19 | } |
| 20 | fn peer(self) -> Side { |
| 21 | match self { |
| 22 | Side::Client => Side::Agent, |
| 23 | Side::Agent => Side::Client, |
| 24 | } |
| 25 | } |
| 26 | } |
| 27 | |
| 28 | pub struct Allowed { |
| 29 | pub side: Side, |
| 30 | pub frame: &'static str, |
| 31 | pub problem: &'static str, |
| 32 | pub reason: &'static str, |
| 33 | } |
| 34 | |
| 35 | pub struct Conformance { |
| 36 | checked: Vec<Side>, |
| 37 | pending: HashMap<(Side, String), String>, |
| 38 | findings: BTreeSet<(Side, String, String)>, |
| 39 | frames: usize, |
| 40 | } |
| 41 | |
| 42 | fn check<T: DeserializeOwned + Serialize>(value: &Value) -> Vec<String> { |
| 43 | let typed: T = match serde_json::from_value(value.clone()) { |
| 44 | Ok(typed) => typed, |
| 45 | Err(error) => { |
| 46 | let text = error.to_string(); |
| 47 | let text = text.split(" at line ").next().unwrap_or(&text); |
| 48 | return vec![format!("not a valid {}: {text}", short_type::<T>())]; |
| 49 | } |
| 50 | }; |
| 51 | let back = match serde_json::to_value(&typed) { |
| 52 | Ok(back) => back, |
| 53 | Err(error) => return vec![format!("does not re-serialize: {error}")], |
| 54 | }; |
| 55 | let mut problems = Vec::new(); |
| 56 | diff("", value, &back, &mut problems); |
| 57 | problems |
| 58 | } |
| 59 | |
| 60 | fn short_type<T>() -> &'static str { |
| 61 | let name = std::any::type_name::<T>(); |
| 62 | name.rsplit("::").next().unwrap_or(name) |
| 63 | } |
| 64 | |
| 65 | fn skipped_default(key: &str, value: &Value) -> bool { |
| 66 | match value { |
| 67 | Value::Null => true, |
| 68 | Value::Array(items) => items.is_empty(), |
| 69 | Value::Object(map) => key == "env" && map.is_empty(), |
| 70 | Value::String(text) => matches!( |
| 71 | (key, text.as_str()), |
| 72 | ("kind", "other") | ("status", "pending") |
| 73 | ), |
| 74 | _ => false, |
| 75 | } |
| 76 | } |
| 77 | |
| 78 | fn diff(path: &str, ours: &Value, official: &Value, problems: &mut Vec<String>) { |
| 79 | match (ours, official) { |
| 80 | (Value::Object(ours), Value::Object(official)) => { |
| 81 | for (key, value) in ours { |
| 82 | if key == "_meta" { |
| 83 | continue; |
| 84 | } |
| 85 | let at = format!("{path}.{key}"); |
| 86 | match official.get(key) { |
| 87 | Some(back) => diff(&at, value, back, problems), |
| 88 | None if skipped_default(key, value) => {} |
| 89 | None => problems.push(format!("field `{at}` is not in the official type")), |
| 90 | } |
| 91 | } |
| 92 | } |
| 93 | (Value::Array(ours), Value::Array(official)) if ours.len() == official.len() => { |
| 94 | for (value, back) in ours.iter().zip(official) { |
| 95 | diff(&format!("{path}[]"), value, back, problems); |
| 96 | } |
| 97 | } |
| 98 | (Value::Number(a), Value::Number(b)) if a.as_f64() == b.as_f64() => {} |
| 99 | _ if ours == official => {} |
| 100 | _ => problems.push(format!( |
| 101 | "value at `{}` reads back as {official} instead of {ours}", |
| 102 | if path.is_empty() { "." } else { path } |
| 103 | )), |
| 104 | } |
| 105 | } |
| 106 | |
| 107 | fn request_params(side: Side, method: &str, params: &Value) -> Option<Vec<String>> { |
| 108 | Some(match (side, method) { |
| 109 | (Side::Client, "initialize") => check::<acp::InitializeRequest>(params), |
| 110 | (Side::Client, "authenticate") => check::<acp::AuthenticateRequest>(params), |
| 111 | (Side::Client, "session/new") => check::<acp::NewSessionRequest>(params), |
| 112 | (Side::Client, "session/load") => check::<acp::LoadSessionRequest>(params), |
| 113 | (Side::Client, "session/resume") => check::<acp::ResumeSessionRequest>(params), |
| 114 | (Side::Client, "session/list") => check::<acp::ListSessionsRequest>(params), |
| 115 | (Side::Client, "session/close") => check::<acp::CloseSessionRequest>(params), |
| 116 | (Side::Client, "session/delete") => check::<acp::DeleteSessionRequest>(params), |
| 117 | (Side::Client, "session/set_mode") => check::<acp::SetSessionModeRequest>(params), |
| 118 | (Side::Client, "session/set_config_option") => { |
| 119 | check::<acp::SetSessionConfigOptionRequest>(params) |
| 120 | } |
| 121 | (Side::Client, "session/prompt") => check::<acp::PromptRequest>(params), |
| 122 | (Side::Agent, "session/request_permission") => { |
| 123 | check::<acp::RequestPermissionRequest>(params) |
| 124 | } |
| 125 | (Side::Agent, "fs/read_text_file") => check::<acp::ReadTextFileRequest>(params), |
| 126 | (Side::Agent, "fs/write_text_file") => check::<acp::WriteTextFileRequest>(params), |
| 127 | (Side::Agent, "terminal/create") => check::<acp::CreateTerminalRequest>(params), |
| 128 | (Side::Agent, "terminal/output") => check::<acp::TerminalOutputRequest>(params), |
| 129 | (Side::Agent, "terminal/release") => check::<acp::ReleaseTerminalRequest>(params), |
| 130 | (Side::Agent, "terminal/wait_for_exit") => check::<acp::WaitForTerminalExitRequest>(params), |
| 131 | (Side::Agent, "terminal/kill") => check::<acp::KillTerminalRequest>(params), |
| 132 | (Side::Agent, "elicitation/create") => check::<acp::CreateElicitationRequest>(params), |
| 133 | _ => return None, |
| 134 | }) |
| 135 | } |
| 136 | |
| 137 | fn response_result(method: &str, result: &Value) -> Option<Vec<String>> { |
| 138 | Some(match method { |
| 139 | "initialize" => check::<acp::InitializeResponse>(result), |
| 140 | "authenticate" => check::<acp::AuthenticateResponse>(result), |
| 141 | "session/new" => check::<acp::NewSessionResponse>(result), |
| 142 | "session/load" => check::<acp::LoadSessionResponse>(result), |
| 143 | "session/resume" => check::<acp::ResumeSessionResponse>(result), |
| 144 | "session/list" => check::<acp::ListSessionsResponse>(result), |
| 145 | "session/close" => check::<acp::CloseSessionResponse>(result), |
| 146 | "session/delete" => check::<acp::DeleteSessionResponse>(result), |
| 147 | "session/set_mode" => check::<acp::SetSessionModeResponse>(result), |
| 148 | "session/set_config_option" => check::<acp::SetSessionConfigOptionResponse>(result), |
| 149 | "session/prompt" => check::<acp::PromptResponse>(result), |
| 150 | "session/request_permission" => check::<acp::RequestPermissionResponse>(result), |
| 151 | "fs/read_text_file" => check::<acp::ReadTextFileResponse>(result), |
| 152 | "fs/write_text_file" => check::<acp::WriteTextFileResponse>(result), |
| 153 | "terminal/create" => check::<acp::CreateTerminalResponse>(result), |
| 154 | "terminal/output" => check::<acp::TerminalOutputResponse>(result), |
| 155 | "terminal/release" => check::<acp::ReleaseTerminalResponse>(result), |
| 156 | "terminal/wait_for_exit" => check::<acp::WaitForTerminalExitResponse>(result), |
| 157 | "terminal/kill" => check::<acp::KillTerminalResponse>(result), |
| 158 | "elicitation/create" => check::<acp::CreateElicitationResponse>(result), |
| 159 | _ => return None, |
| 160 | }) |
| 161 | } |
| 162 | |
| 163 | fn notification_params(side: Side, method: &str, params: &Value) -> Option<Vec<String>> { |
| 164 | Some(match (side, method) { |
| 165 | (_, "$/cancel_request") => check::<acp::CancelRequestNotification>(params), |
| 166 | (Side::Client, "session/cancel") => check::<acp::CancelNotification>(params), |
| 167 | (Side::Agent, "session/update") => check::<acp::SessionNotification>(params), |
| 168 | (Side::Agent, "elicitation/complete") => { |
| 169 | check::<acp::CompleteElicitationNotification>(params) |
| 170 | } |
| 171 | _ => return None, |
| 172 | }) |
| 173 | } |
| 174 | |
| 175 | fn envelope(frame: &Value, allowed: &[&str]) -> Vec<String> { |
| 176 | let mut problems = Vec::new(); |
| 177 | if frame.get("jsonrpc").and_then(Value::as_str) != Some("2.0") { |
| 178 | problems.push("envelope lacks `jsonrpc: \"2.0\"`".to_string()); |
| 179 | } |
| 180 | if let Some(map) = frame.as_object() { |
| 181 | for key in map.keys() { |
| 182 | if !allowed.contains(&key.as_str()) && key != "jsonrpc" { |
| 183 | problems.push(format!("envelope carries `{key}`")); |
| 184 | } |
| 185 | } |
| 186 | } |
| 187 | problems |
| 188 | } |
| 189 | |
| 190 | impl Conformance { |
| 191 | pub fn checking(sides: &[Side]) -> Self { |
| 192 | Self { |
| 193 | checked: sides.to_vec(), |
| 194 | pending: HashMap::new(), |
| 195 | findings: BTreeSet::new(), |
| 196 | frames: 0, |
| 197 | } |
| 198 | } |
| 199 | |
| 200 | pub fn observe(&mut self, side: Side, frame: &Value) { |
| 201 | self.frames += 1; |
| 202 | let method = frame.get("method").and_then(Value::as_str); |
| 203 | let id = frame.get("id"); |
| 204 | let params = frame.get("params").cloned().unwrap_or(Value::Null); |
| 205 | let (label, mut problems) = match (method, id) { |
| 206 | (Some(method), Some(id)) => { |
| 207 | self.pending |
| 208 | .insert((side, id.to_string()), method.to_string()); |
| 209 | let mut problems = envelope(frame, &["id", "method", "params"]); |
| 210 | match request_params(side, method, ¶ms) { |
| 211 | Some(found) => problems.extend(found), |
| 212 | None if method.starts_with('_') => {} |
| 213 | None => problems.push(format!( |
| 214 | "`{method}` is not a {} request in official v1", |
| 215 | side.name() |
| 216 | )), |
| 217 | } |
| 218 | (format!("{method} request"), problems) |
| 219 | } |
| 220 | (Some(method), None) => { |
| 221 | let mut problems = envelope(frame, &["method", "params"]); |
| 222 | match notification_params(side, method, ¶ms) { |
| 223 | Some(found) => problems.extend(found), |
| 224 | None if method.starts_with('_') => {} |
| 225 | None => problems.push(format!( |
| 226 | "`{method}` is not a {} notification in official v1", |
| 227 | side.name() |
| 228 | )), |
| 229 | } |
| 230 | (format!("{method} notification"), problems) |
| 231 | } |
| 232 | (None, Some(id)) => { |
| 233 | let answered = self.pending.remove(&(side.peer(), id.to_string())); |
| 234 | let label = match &answered { |
| 235 | Some(method) => format!("{method} response"), |
| 236 | None => "response".to_string(), |
| 237 | }; |
| 238 | let mut problems = Vec::new(); |
| 239 | if let Some(error) = frame.get("error") { |
| 240 | problems.extend(envelope(frame, &["id", "error"])); |
| 241 | problems.extend(check::<acp::Error>(error)); |
| 242 | } else if let Some(result) = frame.get("result") { |
| 243 | problems.extend(envelope(frame, &["id", "result"])); |
| 244 | if let Some(found) = answered |
| 245 | .as_deref() |
| 246 | .and_then(|method| response_result(method, result)) |
| 247 | { |
| 248 | problems.extend(found); |
| 249 | } |
| 250 | } else { |
| 251 | problems.push("response has neither result nor error".to_string()); |
| 252 | } |
| 253 | if answered.is_none() { |
| 254 | problems.push(format!("answers no outstanding request (id {id})")); |
| 255 | } |
| 256 | (label, problems) |
| 257 | } |
| 258 | (None, None) => ( |
| 259 | "frame".to_string(), |
| 260 | vec!["neither a request, a notification nor a response".to_string()], |
| 261 | ), |
| 262 | }; |
| 263 | let label = match frame |
| 264 | .pointer("/params/update/sessionUpdate") |
| 265 | .and_then(Value::as_str) |
| 266 | { |
| 267 | Some(kind) => format!("{label} ({kind})"), |
| 268 | None => label, |
| 269 | }; |
| 270 | if self.checked.contains(&side) { |
| 271 | for problem in problems.drain(..) { |
| 272 | self.findings.insert((side, label.clone(), problem)); |
| 273 | } |
| 274 | } |
| 275 | } |
| 276 | |
| 277 | pub fn assert_only(&self, allowed: &[Allowed]) { |
| 278 | assert!(self.frames > 0, "no frames were observed"); |
| 279 | let mut used = vec![false; allowed.len()]; |
| 280 | let mut unexpected = Vec::new(); |
| 281 | for (side, frame, problem) in &self.findings { |
| 282 | match allowed.iter().position(|entry| { |
| 283 | entry.side == *side && entry.frame == frame && problem.contains(entry.problem) |
| 284 | }) { |
| 285 | Some(index) => used[index] = true, |
| 286 | None => unexpected.push(format!("{} {frame}: {problem}", side.name())), |
| 287 | } |
| 288 | } |
| 289 | let stale: Vec<_> = allowed |
| 290 | .iter() |
| 291 | .zip(&used) |
| 292 | .filter(|(_, used)| !**used) |
| 293 | .map(|(entry, _)| { |
| 294 | format!( |
| 295 | "{} {}: {} ({})", |
| 296 | entry.side.name(), |
| 297 | entry.frame, |
| 298 | entry.problem, |
| 299 | entry.reason |
| 300 | ) |
| 301 | }) |
| 302 | .collect(); |
| 303 | assert!( |
| 304 | unexpected.is_empty() && stale.is_empty(), |
| 305 | "ACP frames differ from the official v1 schema.\nnew deviations:\n {}\nallowlisted deviations no longer seen (remove them):\n {}", |
| 306 | unexpected.join("\n "), |
| 307 | stale.join("\n ") |
| 308 | ); |
| 309 | } |
| 310 | |
| 311 | pub fn frames(&self) -> usize { |
| 312 | self.frames |
| 313 | } |
| 314 | } |
| 315 |