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 = 24;
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// 19 — routines: `ClientMsg::{SaveRoutine, DeleteRoutine, RunRoutine, SetRoutineEnabled,
57// ListRoutineRuns}`, `ServerMsg::{Routines, RoutineRuns, RoutineEvent}` (cap `routines`),
58// `ChatSummary::origin`, `EngineState::routines_active`.
59// 20 — keep running in the background: `EngineState::keep_running`, `ClientMsg::SetKeepRunning`
60// (sent only to an engine whose state has it).
61// 21 — pausing routines: `EngineState::routines_paused`, `ClientMsg::PauseRoutines` (sent only
62// to an engine whose state has it).
63// 22 — a tool's own card words: `Ask::card` (`CardWords`: the preview is complete, a plain
64// access line, button labels).
65// 23 — My phone: `ClientMsg::{PairPhone, CancelPairing, UnpairPhone, TestPhone}`,
66// `ServerMsg::Phone` (cap `phone`).
67// 24 — steering a running reply: `ClientMsg::Steer`, `QueuedMessage::steer` (engine cap `steer`).
68
69/// Cap: the engine takes [`crate::ClientMsg::Rewind`] (and the client offers it).
70pub const CAP_REWIND: &str = "rewind";
71
72/// Cap: the engine takes [`crate::ClientMsg::SetArtifactNetwork`] (and the client offers it).
73pub const CAP_ARTIFACT_NETWORK: &str = "artifact_network";
74
75/// Cap: the engine takes [`crate::ClientMsg::NewUnattachedChat`] and
76/// [`crate::ClientMsg::ChatToProject`] (and the client offers them).
77pub const CAP_UNATTACHED: &str = "unattached";
78
79/// Cap (17+): the engine takes [`crate::ClientMsg::ArchiveChat`] and fills
80/// [`crate::ChatSummary::archived_at`].
81pub const CAP_ARCHIVE: &str = "archive";
82
83/// Cap (17+): the engine answers [`crate::ClientMsg::ListLibrary`] with every chat's artifacts.
84pub const CAP_LIBRARY: &str = "library";
85
86/// Cap (17+): plugins say when they have a logo, and the engine serves it
87/// ([`crate::ClientMsg::GetPluginLogo`]).
88pub const CAP_PLUGIN_LOGOS: &str = "plugin_logos";
89
90/// Cap: the peer handles [`crate::ClientMsg::Plugin`] / [`crate::ServerMsg::Plugin`].
91pub const CAP_PLUGIN_CHANNEL: &str = "plugin_channel";
92/// Cap: the peer understands [`crate::View`]s on steps (renders known kinds, shows the
93/// fallback of the others). Part of major 13, listed so later view sites can be negotiated
94/// the same way.
95pub const CAP_VIEWS: &str = "views";
96
97/// Cap: the engine keeps projects' other folders ([`crate::ClientMsg::SetWorkspaceFolders`],
98/// `CreateWorkspace::folders`), and the client offers them.
99pub const CAP_PROJECT_FOLDERS: &str = "project_folders";
100
101/// Cap: the client decodes [`crate::PluginScope::Bundled`]. Clients without it get bundled
102/// plugins as `global` (their origin already says `bundled`).
103pub const CAP_BUNDLED_SCOPE: &str = "bundled_scope";
104
105/// Most caps one side may list.
106pub const MAX_CAPS: usize = 64;
107/// Longest cap.
108pub const MAX_CAP_CHARS: usize = 64;
109
110/// The caps this build's clients announce.
111pub fn client_caps() -> Vec<String> {
112 vec![
113 CAP_VIEWS.to_owned(),
114 CAP_PLUGIN_CHANNEL.to_owned(),
115 crate::sites::CAP_VIEW_SITES.to_owned(),
116 CAP_BUNDLED_SCOPE.to_owned(),
117 crate::web::CAP_WEB_BRIDGE.to_owned(),
118 crate::profiles::CAP_PROFILES.to_owned(),
119 crate::layout::CAP_LAYOUT.to_owned(),
120 crate::look::CAP_LOOK.to_owned(),
121 crate::look::CAP_CAPTURE.to_owned(),
122 CAP_REWIND.to_owned(),
123 CAP_ARTIFACT_NETWORK.to_owned(),
124 CAP_UNATTACHED.to_owned(),
125 CAP_ARCHIVE.to_owned(),
126 CAP_PROJECT_FOLDERS.to_owned(),
127 CAP_LIBRARY.to_owned(),
128 CAP_PLUGIN_LOGOS.to_owned(),
129 crate::routines::CAP_ROUTINES.to_owned(),
130 crate::phone::CAP_PHONE.to_owned(),
131 crate::queue::CAP_STEER.to_owned(),
132 ]
133}
134
135/// The caps this build's engine announces.
136pub fn engine_caps() -> Vec<String> {
137 vec![
138 CAP_VIEWS.to_owned(),
139 CAP_PLUGIN_CHANNEL.to_owned(),
140 crate::sites::CAP_VIEW_SITES.to_owned(),
141 CAP_BUNDLED_SCOPE.to_owned(),
142 crate::web::CAP_WEB_BRIDGE.to_owned(),
143 crate::profiles::CAP_PROFILES.to_owned(),
144 crate::layout::CAP_LAYOUT.to_owned(),
145 crate::look::CAP_LOOK.to_owned(),
146 crate::look::CAP_CAPTURE.to_owned(),
147 CAP_REWIND.to_owned(),
148 CAP_ARTIFACT_NETWORK.to_owned(),
149 CAP_UNATTACHED.to_owned(),
150 CAP_ARCHIVE.to_owned(),
151 CAP_PROJECT_FOLDERS.to_owned(),
152 CAP_LIBRARY.to_owned(),
153 CAP_PLUGIN_LOGOS.to_owned(),
154 crate::routines::CAP_ROUTINES.to_owned(),
155 crate::phone::CAP_PHONE.to_owned(),
156 crate::queue::CAP_STEER.to_owned(),
157 ]
158}
159
160/// Both sides list `cap`.
161pub fn shared(ours: &[String], theirs: &[String], cap: &str) -> bool {
162 ours.iter().any(|c| c == cap) && theirs.iter().any(|c| c == cap)
163}
164
165/// A cap is ASCII lowercase letters, digits, `_`, `.`, `-` (e.g. `plugin_channel`,
166/// `view.byob.plugin_card`).
167pub fn cap_ok(cap: &str) -> bool {
168 (1..=MAX_CAP_CHARS).contains(&cap.len()) && cap.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || matches!(b, b'_' | b'.' | b'-'))
169}
170
171/// Check a peer's caps list.
172pub fn check_caps(caps: &[String]) -> Result<(), String> {
173 if caps.len() > MAX_CAPS {
174 return Err(format!("too many caps (at most {MAX_CAPS})"));
175 }
176 match caps.iter().find(|c| !cap_ok(c)) {
177 Some(bad) => Err(format!("bad cap {:?}", bad.chars().take(MAX_CAP_CHARS).collect::<String>())),
178 None => Ok(()),
179 }
180}
181
182/// Largest plugin channel message (its JSON).
183pub const MAX_PLUGIN_MSG_BYTES: usize = 256 * 1024;
184
185/// A plugin channel message ([`crate::ClientMsg::Plugin`] / [`crate::ServerMsg::Plugin`]):
186/// plugin ids are plugin ids (`[a-z0-9-]`), the message any JSON up to
187/// [`MAX_PLUGIN_MSG_BYTES`].
188pub fn check_plugin_msg(plugin: &str, msg: &Value) -> Result<(), String> {
189 if !byob_types::config::plugin_id_ok(plugin) {
190 return Err(format!("{:?} isn't a plugin id", plugin.chars().take(60).collect::<String>()));
191 }
192 let size = serde_json::to_string(msg).map_or(usize::MAX, |s| s.len());
193 if size > MAX_PLUGIN_MSG_BYTES {
194 return Err(format!("plugin message too large ({size} bytes, at most {MAX_PLUGIN_MSG_BYTES})"));
195 }
196 Ok(())
197}
198
199/// The engine's side of the handshake ([`crate::ServerMsg::Welcome`]).
200#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
201pub struct Welcome {
202 pub protocol: u32,
203 #[serde(default)]
204 pub minor: u32,
205 #[serde(default)]
206 pub caps: Vec<String>,
207}
208
209impl Welcome {
210 /// This build's engine.
211 pub fn current() -> Self {
212 Self { protocol: PROTOCOL_MAJOR, minor: PROTOCOL_MINOR, caps: engine_caps() }
213 }
214}
215
216#[cfg(test)]
217mod tests {
218 use super::*;
219
220 #[test]
221 fn caps_are_shared_only_when_both_list_them() {
222 let a = vec!["views".to_owned(), "plugin_channel".to_owned()];
223 let b = vec!["views".to_owned(), "something_new".to_owned()];
224 assert!(shared(&a, &b, CAP_VIEWS));
225 assert!(!shared(&a, &b, CAP_PLUGIN_CHANNEL));
226 assert!(!shared(&a, &b, "something_new"));
227 assert!(check_caps(&a).is_ok() && check_caps(&client_caps()).is_ok() && check_caps(&engine_caps()).is_ok());
228 assert!(check_caps(&["Bad Cap".to_owned()]).is_err());
229 assert!(check_caps(&vec!["x".to_owned(); MAX_CAPS + 1]).is_err());
230 assert!(check_caps(&["x".repeat(MAX_CAP_CHARS + 1)]).is_err());
231 }
232
233 #[test]
234 fn plugin_messages_are_capped() {
235 assert!(check_plugin_msg("sheets", &serde_json::json!({"op": "get"})).is_ok());
236 assert!(check_plugin_msg("../x", &Value::Null).is_err());
237 assert!(check_plugin_msg("sheets", &Value::String("x".repeat(MAX_PLUGIN_MSG_BYTES))).is_err());
238 }
239}