use std::{ collections::BTreeMap, env, error::Error, fs, path::{Path, PathBuf}, }; use desktop_protocol::{ ClientCapabilities, ConnectionProfile, ConnectionSlot, DiagnosticBundle, FileTransferPlan, GatewayEvent, RawProtocolEnvelope, ServerCapabilities, ToolProposal, ToolResult, }; use schemars::{JsonSchema, schema_for}; use serde_json::Value; fn main() -> Result<(), Box> { let write = env::args().any(|arg| arg == "--write"); let output_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../docs/protocol/v1/schemas"); let schemas = generated_schemas()?; if write { fs::create_dir_all(&output_dir)?; for (name, schema) in schemas { let path = output_dir.join(name); fs::write( path, format!("{}\n", serde_json::to_string_pretty(&schema)?), )?; } return Ok(()); } let mut failures = Vec::new(); for (name, expected) in schemas { let path = output_dir.join(name); match read_json(&path) { Ok(actual) if actual == expected => {} Ok(_) => failures.push(format!("{} is stale", path.display())), Err(error) => failures.push(format!("{}: {error}", path.display())), } } if failures.is_empty() { Ok(()) } else { Err(format!( "protocol schema check failed; run with --write:\n{}", failures.join("\n") ) .into()) } } fn generated_schemas() -> Result, serde_json::Error> { let mut output = BTreeMap::new(); insert::(&mut output, "connection-profile.schema.json")?; insert::(&mut output, "connection-slot.schema.json")?; insert::(&mut output, "server-capabilities.schema.json")?; insert::(&mut output, "client-capabilities.schema.json")?; insert::(&mut output, "protocol-envelope.schema.json")?; insert::(&mut output, "gateway-event.schema.json")?; insert::(&mut output, "tool-proposal.schema.json")?; insert::(&mut output, "tool-result.schema.json")?; insert::(&mut output, "diagnostic-bundle.schema.json")?; insert::(&mut output, "file-transfer-plan.schema.json")?; Ok(output) } fn insert( output: &mut BTreeMap<&'static str, Value>, name: &'static str, ) -> Result<(), serde_json::Error> { output.insert(name, serde_json::to_value(schema_for!(T))?); Ok(()) } fn read_json(path: &Path) -> Result> { Ok(serde_json::from_str(&fs::read_to_string(path)?)?) }