Skip to main content

byob_protocol/
version.rs

1//! Version negotiation and capabilities.
2//!
3//! A client opens with [`crate::ClientMsg::Hello`] carrying [`PROTOCOL_MAJOR`],
4//! [`PROTOCOL_MINOR`] and its [`client_caps`]; the engine answers with
5//! [`crate::ServerMsg::Welcome`] (its own version and caps) before anything else.
6//!
7//! Compatibility rules:
8//! - **Major** must match. It is bumped only for changes an older peer can't survive
9//!   (a renamed or removed field, a changed meaning). A client with another major gets one
10//!   error notice and nothing else.
11//! - **Minor** is informational: everything a minor adds is optional on the wire (serde
12//!   defaults, skipped when empty) or behind a cap.
13//! - **Caps** are feature strings. A feature that needs both sides to understand it is used
14//!   only when both list its cap ([`shared`]). Unknown caps are ignored.
15//! - Enums that grow decode unknown values into a fallback (`#[serde(other)]`), and a
16//!   client skips a [`crate::ServerMsg`] it doesn't know ([`crate::ServerMsg::Unknown`]),
17//!   so additions don't need a major bump.
18
19use serde::{Deserialize, Serialize};
20use serde_json::Value;
21
22/// Bumped on a change an older peer can't survive (see the module docs).
23pub const PROTOCOL_MAJOR: u32 = 13;
24/// Bumped on additive changes; peers with the same major but another minor still talk.
25pub const PROTOCOL_MINOR: u32 = 18;
26// Minors: 1 — `Artifact::content_type` (open artifact types; `kind` stays for 13.0 clients);
27// 2 — `PluginInfo::backend` (plugin backend processes); 3 — render sites: `PluginInfo::views`,
28// `View::owner`, `OpenView`/`CloseView`/`ViewEvent`, `LiveView` (cap `view_sites`); 4 — bundled
29// plugins: `PluginScope::Bundled` (cap `bundled_scope`), `PluginInfo::{locked, renderers, starters}`;
30// 5 — web surfaces: `WebCall`/`WebReply`/`WebPush`, `ViewDecl::html`, step views `byob.mcp_app`
31// and `byob.web` (cap `web_bridge`).
32// 6 — `Site::Artifact` and `view:<id>` renderers (an artifact's body is a plugin's live view),
33// the `grid` tree node and `Event::grid`.
34// 7 — `PluginInfo::superseded_by` (manifest `provides`: one of two plugins offering the same
35// thing is used) and native plugin backends (no wire change).
36// 8 — question cards: `Ask::choice` and `ClientMsg::AnswerQuestion` (the `ask_user` tool).
37// 9 — model profiles: `GetProfiles`, `CreateProfile`, `UpdateProfile`, `DeleteProfile`,
38// `DuplicateProfile`, `SetRole`, `TestProfile`, `SetLevelProfile`, `ServerMsg::Profiles`/
39// `ProfileTested` (cap `profiles`), `Layer::profile`, `ChatEndpoint::profile`,
40// `EndpointInfo::slots`.
41// 10 — subagent models: `Layer::subagent_profile`, `Effective::subagent_profile`,
42// `Delegation::profile`.
43// 11 — the layout: `ClientMsg::SetLayout`, `ServerMsg::Layout` (cap `layout`).
44// 12 — looks: `ClientMsg::ReportLook`, `ServerMsg::SetLook` (cap `look`).
45// 13 — going back: `ClientMsg::Rewind` (cap `rewind`).
46// 14 — HTML apps on the internet: `Artifact::network`, `ClientMsg::SetArtifactNetwork` (cap
47// `artifact_network`); `LookReport::notes`.
48// 15 — screenshots: `ServerMsg::Capture`, `ClientMsg::Captured` (cap `capture`).
49// 16 — chats without a project: `ClientMsg::NewUnattachedChat`, `ClientMsg::ChatToProject`
50// (cap `unattached`).
51// 17 — archived chats: `ClientMsg::ArchiveChat`, `ChatSummary::archived_at` (cap `archive`);
52// the Library: `ClientMsg::ListLibrary`, `ServerMsg::Library` (cap `library`); plugin logos:
53// `PluginInfo::logo`, `ClientMsg::GetPluginLogo` (cap `plugin_logos`).
54// 18 — projects beyond one folder: `WorkspaceSummary::{folders, goal}`,
55// `CreateWorkspace::folders`, `ClientMsg::SetWorkspaceFolders` (cap `project_folders`).
56
57/// Cap: the engine takes [`crate::ClientMsg::Rewind`] (and the client offers it).
58pub const CAP_REWIND: &str = "rewind";
59
60/// Cap: the engine takes [`crate::ClientMsg::SetArtifactNetwork`] (and the client offers it).
61pub const CAP_ARTIFACT_NETWORK: &str = "artifact_network";
62
63/// Cap: the engine takes [`crate::ClientMsg::NewUnattachedChat`] and
64/// [`crate::ClientMsg::ChatToProject`] (and the client offers them).
65pub const CAP_UNATTACHED: &str = "unattached";
66
67/// Cap (17+): the engine takes [`crate::ClientMsg::ArchiveChat`] and fills
68/// [`crate::ChatSummary::archived_at`].
69pub const CAP_ARCHIVE: &str = "archive";
70
71/// Cap (17+): the engine answers [`crate::ClientMsg::ListLibrary`] with every chat's artifacts.
72pub const CAP_LIBRARY: &str = "library";
73
74/// Cap (17+): plugins say when they have a logo, and the engine serves it
75/// ([`crate::ClientMsg::GetPluginLogo`]).
76pub const CAP_PLUGIN_LOGOS: &str = "plugin_logos";
77
78/// Cap: the peer handles [`crate::ClientMsg::Plugin`] / [`crate::ServerMsg::Plugin`].
79pub const CAP_PLUGIN_CHANNEL: &str = "plugin_channel";
80/// Cap: the peer understands [`crate::View`]s on steps (renders known kinds, shows the
81/// fallback of the others). Part of major 13, listed so later view sites can be negotiated
82/// the same way.
83pub const CAP_VIEWS: &str = "views";
84
85/// Cap: the engine keeps projects' other folders ([`crate::ClientMsg::SetWorkspaceFolders`],
86/// `CreateWorkspace::folders`), and the client offers them.
87pub const CAP_PROJECT_FOLDERS: &str = "project_folders";
88
89/// Cap: the client decodes [`crate::PluginScope::Bundled`]. Clients without it get bundled
90/// plugins as `global` (their origin already says `bundled`).
91pub const CAP_BUNDLED_SCOPE: &str = "bundled_scope";
92
93/// Most caps one side may list.
94pub const MAX_CAPS: usize = 64;
95/// Longest cap.
96pub const MAX_CAP_CHARS: usize = 64;
97
98/// The caps this build's clients announce.
99pub fn client_caps() -> Vec<String> {
100    vec![
101        CAP_VIEWS.to_owned(),
102        CAP_PLUGIN_CHANNEL.to_owned(),
103        crate::sites::CAP_VIEW_SITES.to_owned(),
104        CAP_BUNDLED_SCOPE.to_owned(),
105        crate::web::CAP_WEB_BRIDGE.to_owned(),
106        crate::profiles::CAP_PROFILES.to_owned(),
107        crate::layout::CAP_LAYOUT.to_owned(),
108        crate::look::CAP_LOOK.to_owned(),
109        crate::look::CAP_CAPTURE.to_owned(),
110        CAP_REWIND.to_owned(),
111        CAP_ARTIFACT_NETWORK.to_owned(),
112        CAP_UNATTACHED.to_owned(),
113        CAP_ARCHIVE.to_owned(),
114        CAP_PROJECT_FOLDERS.to_owned(),
115        CAP_LIBRARY.to_owned(),
116        CAP_PLUGIN_LOGOS.to_owned(),
117    ]
118}
119
120/// The caps this build's engine announces.
121pub fn engine_caps() -> Vec<String> {
122    vec![
123        CAP_VIEWS.to_owned(),
124        CAP_PLUGIN_CHANNEL.to_owned(),
125        crate::sites::CAP_VIEW_SITES.to_owned(),
126        CAP_BUNDLED_SCOPE.to_owned(),
127        crate::web::CAP_WEB_BRIDGE.to_owned(),
128        crate::profiles::CAP_PROFILES.to_owned(),
129        crate::layout::CAP_LAYOUT.to_owned(),
130        crate::look::CAP_LOOK.to_owned(),
131        crate::look::CAP_CAPTURE.to_owned(),
132        CAP_REWIND.to_owned(),
133        CAP_ARTIFACT_NETWORK.to_owned(),
134        CAP_UNATTACHED.to_owned(),
135        CAP_ARCHIVE.to_owned(),
136        CAP_PROJECT_FOLDERS.to_owned(),
137        CAP_LIBRARY.to_owned(),
138        CAP_PLUGIN_LOGOS.to_owned(),
139    ]
140}
141
142/// Both sides list `cap`.
143pub fn shared(ours: &[String], theirs: &[String], cap: &str) -> bool {
144    ours.iter().any(|c| c == cap) && theirs.iter().any(|c| c == cap)
145}
146
147/// A cap is ASCII lowercase letters, digits, `_`, `.`, `-` (e.g. `plugin_channel`,
148/// `view.byob.plugin_card`).
149pub fn cap_ok(cap: &str) -> bool {
150    (1..=MAX_CAP_CHARS).contains(&cap.len()) && cap.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || matches!(b, b'_' | b'.' | b'-'))
151}
152
153/// Check a peer's caps list.
154pub fn check_caps(caps: &[String]) -> Result<(), String> {
155    if caps.len() > MAX_CAPS {
156        return Err(format!("too many caps (at most {MAX_CAPS})"));
157    }
158    match caps.iter().find(|c| !cap_ok(c)) {
159        Some(bad) => Err(format!("bad cap {:?}", bad.chars().take(MAX_CAP_CHARS).collect::<String>())),
160        None => Ok(()),
161    }
162}
163
164/// Largest plugin channel message (its JSON).
165pub const MAX_PLUGIN_MSG_BYTES: usize = 256 * 1024;
166
167/// A plugin channel message ([`crate::ClientMsg::Plugin`] / [`crate::ServerMsg::Plugin`]):
168/// plugin ids are plugin ids (`[a-z0-9-]`), the message any JSON up to
169/// [`MAX_PLUGIN_MSG_BYTES`].
170pub fn check_plugin_msg(plugin: &str, msg: &Value) -> Result<(), String> {
171    if !byob_types::config::plugin_id_ok(plugin) {
172        return Err(format!("{:?} isn't a plugin id", plugin.chars().take(60).collect::<String>()));
173    }
174    let size = serde_json::to_string(msg).map_or(usize::MAX, |s| s.len());
175    if size > MAX_PLUGIN_MSG_BYTES {
176        return Err(format!("plugin message too large ({size} bytes, at most {MAX_PLUGIN_MSG_BYTES})"));
177    }
178    Ok(())
179}
180
181/// The engine's side of the handshake ([`crate::ServerMsg::Welcome`]).
182#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
183pub struct Welcome {
184    pub protocol: u32,
185    #[serde(default)]
186    pub minor: u32,
187    #[serde(default)]
188    pub caps: Vec<String>,
189}
190
191impl Welcome {
192    /// This build's engine.
193    pub fn current() -> Self {
194        Self { protocol: PROTOCOL_MAJOR, minor: PROTOCOL_MINOR, caps: engine_caps() }
195    }
196}
197
198#[cfg(test)]
199mod tests {
200    use super::*;
201
202    #[test]
203    fn caps_are_shared_only_when_both_list_them() {
204        let a = vec!["views".to_owned(), "plugin_channel".to_owned()];
205        let b = vec!["views".to_owned(), "something_new".to_owned()];
206        assert!(shared(&a, &b, CAP_VIEWS));
207        assert!(!shared(&a, &b, CAP_PLUGIN_CHANNEL));
208        assert!(!shared(&a, &b, "something_new"));
209        assert!(check_caps(&a).is_ok() && check_caps(&client_caps()).is_ok() && check_caps(&engine_caps()).is_ok());
210        assert!(check_caps(&["Bad Cap".to_owned()]).is_err());
211        assert!(check_caps(&vec!["x".to_owned(); MAX_CAPS + 1]).is_err());
212        assert!(check_caps(&["x".repeat(MAX_CAP_CHARS + 1)]).is_err());
213    }
214
215    #[test]
216    fn plugin_messages_are_capped() {
217        assert!(check_plugin_msg("sheets", &serde_json::json!({"op": "get"})).is_ok());
218        assert!(check_plugin_msg("../x", &Value::Null).is_err());
219        assert!(check_plugin_msg("sheets", &Value::String("x".repeat(MAX_PLUGIN_MSG_BYTES))).is_err());
220    }
221}