#![cfg_attr(not(test), deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable))]
pub mod artifact;
pub mod delegation;
pub mod media;
pub mod usage;
use serde::{Deserialize, Serialize};
pub use artifact::{Artifact, ArtifactKind, ArtifactRef, ArtifactVersion};
pub use delegation::{Delegation, DelegationState, DelegationUpdate};
pub use media::{MediaContent, MediaKind, MediaRef};
pub use usage::{ChatUsage, Compaction};
pub const PROTOCOL_VERSION: u32 = 7;
pub const MAX_FRAME_BYTES: usize = 4 * 1024 * 1024;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ClientMsg {
Hello {
protocol: u32,
client: String,
},
SetInference {
base_url: String,
model: String,
api_key: Option<String>,
},
SendMessage {
text: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
attachments: Vec<String>,
},
Cancel,
Approve {
step: u64,
answer: ApprovalAnswer,
},
Undo {
entry: u64,
},
ListChats {
after: Option<ChatCursor>,
limit: u32,
},
NewChat,
OpenChat {
id: String,
},
RenameChat {
id: String,
title: String,
},
DeleteChat {
id: String,
},
PinChat {
id: String,
pinned: bool,
},
Upload {
upload: u64,
name: String,
size: u64,
offset: u64,
data: String,
done: bool,
},
GetMedia {
path: String,
},
GetArtifact {
id: String,
version: u32,
},
Compact {
#[serde(default, skip_serializing_if = "Option::is_none")]
focus: Option<String>,
},
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ServerMsg {
State(EngineState),
Notice { level: NoticeLevel, text: String },
Transcript { entries: Vec<Entry> },
EntryAdded(Entry),
EntryDelta { id: u64, content: String, reasoning: String },
EntryFinished { id: u64, error: Option<String>, stats: Option<TurnStats> },
StepUpdated { entry: u64, step: Step },
EntryUndo { id: u64, undoable: bool, undone: bool },
Chats { pinned: Vec<ChatSummary>, recent: Vec<ChatSummary>, after: Option<ChatCursor>, next: Option<ChatCursor> },
ChatUpdated(ChatSummary),
ChatDeleted { id: String },
ChatOpened { chat: Option<ChatSummary> },
Uploaded { upload: u64, attachment: Option<MediaRef>, error: Option<String> },
Media { path: String, content: MediaContent },
Artifacts { chat: Option<String>, artifacts: Vec<Artifact> },
ArtifactUpdated(Artifact),
ArtifactFile { id: String, version: u32, data: Option<String>, error: Option<String> },
Usage(ChatUsage),
Compactions { chat: Option<String>, items: Vec<Compaction> },
Compacted(Compaction),
Delegation { entry: u64, step: u64, update: DelegationUpdate },
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ChatSummary {
pub id: String,
pub title: String,
pub updated_at: i64,
pub pinned_at: Option<i64>,
#[serde(default)]
pub busy: bool,
}
impl ChatSummary {
pub fn cursor(&self) -> ChatCursor {
ChatCursor { updated_at: self.updated_at, id: self.id.clone() }
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ChatCursor {
pub updated_at: i64,
pub id: String,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum EntryRole {
User,
Assistant,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Entry {
pub id: u64,
pub role: EntryRole,
pub content: String,
pub reasoning: String,
pub done: bool,
pub error: Option<String>,
pub stats: Option<TurnStats>,
#[serde(default)]
pub steps: Vec<Step>,
#[serde(default)]
pub undoable: bool,
#[serde(default)]
pub undone: bool,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub attachments: Vec<MediaRef>,
}
impl Entry {
pub fn append(&mut self, content: &str, reasoning: &str) {
self.content.push_str(content);
self.reasoning.push_str(reasoning);
}
pub fn upsert_step(&mut self, step: Step) {
match self.steps.iter_mut().find(|s| s.id == step.id) {
Some(existing) => *existing = step,
None => self.steps.push(step),
}
}
pub fn pending_approvals(&self) -> impl Iterator<Item = &Step> {
self.steps.iter().flat_map(|s| std::iter::once(s).chain(s.delegation.iter().flat_map(|d| d.steps.iter()))).filter(|s| s.status == StepStatus::Waiting)
}
pub fn apply_delegation(&mut self, step: u64, update: &DelegationUpdate) {
if let Some(d) = self.steps.iter_mut().find(|s| s.id == step).and_then(|s| s.delegation.as_deref_mut()) {
d.apply(update);
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ToolAccess {
Read,
Write,
Network,
Execute,
}
impl ToolAccess {
pub fn label(self) -> &'static str {
match self {
Self::Read => "read",
Self::Write => "write",
Self::Network => "network",
Self::Execute => "execute",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum StepStatus {
Running,
Waiting,
Done,
Failed,
Denied,
}
impl StepStatus {
pub fn finished(self) -> bool {
matches!(self, Self::Done | Self::Failed | Self::Denied)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ApprovalAnswer {
Allow,
Always,
Deny,
AlwaysEverywhere,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum FileChange {
Created { path: String },
Modified { path: String },
Deleted { path: String },
Moved { from: String, to: String },
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Step {
pub id: u64,
pub tool: String,
pub title: String,
pub access: ToolAccess,
pub status: StepStatus,
pub detail: String,
#[serde(default)]
pub changes: Vec<FileChange>,
#[serde(default)]
pub at: usize,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub media: Vec<MediaRef>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub preview: Option<Preview>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub artifacts: Vec<ArtifactRef>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub delegation: Option<Box<Delegation>>,
}
pub const MAX_PREVIEW_LINES: usize = 40;
pub const MAX_PREVIEW_LINE_CHARS: usize = 300;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum Preview {
Write {
path: String,
bytes: u64,
replaces: bool,
lines: Vec<DiffLine>,
#[serde(default)]
more: usize,
},
Move {
moves: Vec<(String, String)>,
#[serde(default)]
more: usize,
},
Delete { path: String, what: String },
Args {
fields: Vec<(String, String)>,
#[serde(default, skip_serializing_if = "Option::is_none")]
code: Option<String>,
#[serde(default)]
more: usize,
},
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DiffLine {
pub kind: LineKind,
pub text: String,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum LineKind {
Same,
Added,
Removed,
Skipped,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
pub struct TurnStats {
pub prompt_tokens: u64,
pub completion_tokens: u64,
pub elapsed_ms: u64,
#[serde(default)]
pub model_calls: u64,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum NoticeLevel {
Info,
Error,
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct EngineState {
pub version: String,
pub inference_base_url: String,
pub inference_model: String,
pub has_api_key: bool,
pub endpoint: Option<String>,
pub busy: bool,
#[serde(default)]
pub endpoint_info: Option<EndpointInfo>,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ToolsMode {
Native,
Prompt,
#[default]
Unknown,
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct EndpointInfo {
#[serde(default)]
pub probing: bool,
#[serde(default)]
pub server: String,
#[serde(default)]
pub context_tokens: Option<u64>,
#[serde(default)]
pub tools: ToolsMode,
#[serde(default)]
pub vision: Option<bool>,
}
impl EndpointInfo {
pub fn summary(&self) -> String {
if self.probing {
return "checking endpoint…".into();
}
let mut parts = Vec::new();
if !self.server.is_empty() {
parts.push(self.server.clone());
}
if let Some(n) = self.context_tokens {
parts.push(if n >= 1000 { format!("{}k ctx", n / 1000) } else { format!("{n} ctx") });
}
parts.push(
match self.tools {
ToolsMode::Native => "native tools",
ToolsMode::Prompt => "prompt tools",
ToolsMode::Unknown => "tools untested",
}
.into(),
);
if self.vision == Some(true) {
parts.push("vision".into());
}
parts.join(" · ")
}
}
impl ClientMsg {
pub fn to_json(&self) -> String {
serde_json::to_string(self).unwrap_or_default()
}
pub fn from_json(text: &str) -> Result<Self, String> {
if text.len() > MAX_FRAME_BYTES {
return Err(format!("frame too large ({} bytes)", text.len()));
}
serde_json::from_str(text).map_err(|e| e.to_string())
}
}
impl ServerMsg {
pub fn to_json(&self) -> String {
serde_json::to_string(self).unwrap_or_default()
}
pub fn from_json(text: &str) -> Result<Self, String> {
if text.len() > MAX_FRAME_BYTES {
return Err(format!("frame too large ({} bytes)", text.len()));
}
serde_json::from_str(text).map_err(|e| e.to_string())
}
}
pub trait Connection {
fn send(&mut self, msg: ClientMsg);
fn try_recv(&mut self) -> Option<ServerMsg>;
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn client_msg_round_trips() {
let m = ClientMsg::Hello { protocol: PROTOCOL_VERSION, client: "test".into() };
assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m);
}
#[test]
fn wire_format_is_tagged() {
let json = ServerMsg::Notice { level: NoticeLevel::Info, text: "hi".into() }.to_json();
assert_eq!(json, r#"{"type":"notice","level":"info","text":"hi"}"#);
}
#[test]
fn rejects_garbage_and_oversized_frames() {
assert!(ClientMsg::from_json("{not json").is_err());
assert!(ClientMsg::from_json(&" ".repeat(MAX_FRAME_BYTES + 1)).is_err());
}
#[test]
fn approve_wire_format() {
let m = ClientMsg::Approve { step: 7, answer: ApprovalAnswer::Always };
assert_eq!(m.to_json(), r#"{"type":"approve","step":7,"answer":"always"}"#);
assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m);
}
fn step(id: u64, status: StepStatus) -> Step {
Step {
id,
tool: "t".into(),
title: "T".into(),
access: ToolAccess::Write,
status,
detail: String::new(),
changes: vec![],
at: 0,
preview: None,
media: vec![],
artifacts: vec![],
delegation: None,
}
}
#[test]
fn delegations_stream_into_their_step_and_round_trip() {
let mut parent = step(1, StepStatus::Running);
parent.delegation = Some(Box::new(Delegation { agent: "explorer".into(), task: "count lines".into(), ..Default::default() }));
let mut e = Entry {
id: 9,
role: EntryRole::Assistant,
content: String::new(),
reasoning: String::new(),
done: false,
error: None,
stats: None,
steps: vec![parent],
undoable: false,
undone: false,
attachments: vec![],
};
let updates = [
DelegationUpdate::Status { state: DelegationState::Running, prompt_tokens: 0, completion_tokens: 0, error: None },
DelegationUpdate::Delta { content: "Reading".into(), reasoning: "hm".into() },
DelegationUpdate::Step(step(2, StepStatus::Waiting)),
DelegationUpdate::Delta { content: " a.txt".into(), reasoning: String::new() },
];
for u in &updates {
let msg = ServerMsg::Delegation { entry: 9, step: 1, update: u.clone() };
assert_eq!(ServerMsg::from_json(&msg.to_json()).unwrap(), msg);
e.apply_delegation(1, u);
}
e.apply_delegation(77, &updates[1]);
let d = e.steps[0].delegation.as_deref().unwrap();
assert_eq!((d.content.as_str(), d.reasoning.as_str(), d.state), ("Reading a.txt", "hm", DelegationState::Running));
assert_eq!(d.status_line(), "explorer · 1 tool · waiting for approval");
assert_eq!(e.pending_approvals().map(|s| s.id).collect::<Vec<_>>(), vec![2]);
e.apply_delegation(1, &DelegationUpdate::Step(step(2, StepStatus::Done)));
e.apply_delegation(1, &DelegationUpdate::Status { state: DelegationState::Done, prompt_tokens: 50, completion_tokens: 5, error: None });
assert_eq!(e.steps[0].delegation.as_deref().unwrap().status_line(), "explorer · 1 tool · done");
assert_eq!(e.pending_approvals().count(), 0);
let msg = ServerMsg::StepUpdated { entry: 9, step: e.steps[0].clone() };
assert_eq!(ServerMsg::from_json(&msg.to_json()).unwrap(), msg);
let json = r#"{"id":1,"tool":"t","title":"T","access":"read","status":"done","detail":""}"#;
assert!(serde_json::from_str::<Step>(json).unwrap().delegation.is_none());
}
#[test]
fn steps_upsert_and_round_trip() {
let mut e = Entry {
id: 1,
role: EntryRole::Assistant,
content: String::new(),
reasoning: String::new(),
done: false,
error: None,
stats: None,
steps: vec![],
undoable: false,
undone: false,
attachments: vec![],
};
e.upsert_step(step(3, StepStatus::Running));
e.upsert_step(step(4, StepStatus::Waiting));
e.upsert_step(step(3, StepStatus::Done));
assert_eq!(e.steps.len(), 2);
assert_eq!(e.steps[0].status, StepStatus::Done);
assert_eq!(e.pending_approvals().map(|s| s.id).collect::<Vec<_>>(), vec![4]);
let mut s = step(5, StepStatus::Done);
s.changes = vec![FileChange::Moved { from: "a".into(), to: "b".into() }];
let msg = ServerMsg::StepUpdated { entry: 1, step: s };
assert_eq!(ServerMsg::from_json(&msg.to_json()).unwrap(), msg);
}
#[test]
fn entry_without_steps_still_parses() {
let json = r#"{"id":1,"role":"user","content":"hi","reasoning":"","done":true,"error":null,"stats":null}"#;
let e: Entry = serde_json::from_str(json).unwrap();
assert!(e.steps.is_empty());
}
#[test]
fn undo_and_preview_wire_format() {
let m = ClientMsg::Undo { entry: 4 };
assert_eq!(m.to_json(), r#"{"type":"undo","entry":4}"#);
assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m);
let mut s = step(1, StepStatus::Waiting);
s.preview =
Some(Preview::Write { path: "a.md".into(), bytes: 3, replaces: true, lines: vec![DiffLine { kind: LineKind::Added, text: "hi".into() }], more: 0 });
let msg = ServerMsg::StepUpdated { entry: 1, step: s };
assert_eq!(ServerMsg::from_json(&msg.to_json()).unwrap(), msg);
let msg = ServerMsg::EntryUndo { id: 1, undoable: false, undone: true };
assert_eq!(ServerMsg::from_json(&msg.to_json()).unwrap(), msg);
}
#[test]
fn chat_messages_round_trip() {
let summary = ChatSummary { id: "c1".into(), title: "Plans".into(), updated_at: 5, pinned_at: None, busy: true };
for m in [
ServerMsg::Chats { pinned: vec![], recent: vec![summary.clone()], after: None, next: Some(summary.cursor()) },
ServerMsg::ChatUpdated(summary.clone()),
ServerMsg::ChatOpened { chat: Some(summary) },
ServerMsg::ChatDeleted { id: "c1".into() },
] {
assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
}
let m = ClientMsg::ListChats { after: Some(ChatCursor { updated_at: 1, id: "x".into() }), limit: 50 };
assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m);
assert_eq!(ClientMsg::NewChat.to_json(), r#"{"type":"new_chat"}"#);
}
#[test]
fn endpoint_info_is_optional_and_summarised() {
let old = r#"{"version":"0","inference_base_url":"u","inference_model":"m","has_api_key":false,"endpoint":null,"busy":false}"#;
assert_eq!(serde_json::from_str::<EngineState>(old).unwrap().endpoint_info, None);
let info = EndpointInfo { probing: false, server: "llama.cpp".into(), context_tokens: Some(262_144), tools: ToolsMode::Native, vision: Some(true) };
assert_eq!(info.summary(), "llama.cpp · 262k ctx · native tools · vision");
assert_eq!(EndpointInfo { probing: true, ..info }.summary(), "checking endpoint…");
assert_eq!(EndpointInfo::default().summary(), "tools untested");
}
#[test]
fn media_messages_round_trip() {
let msgs = vec![
ClientMsg::SendMessage { text: "chart it".into(), attachments: vec!["uploads/sales.csv".into()] },
ClientMsg::Upload { upload: 1, name: "a.csv".into(), size: 3, offset: 0, data: media::encode(b"a,b"), done: true },
ClientMsg::GetMedia { path: "charts/x.chart.json".into() },
];
for m in msgs {
assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m);
}
let spec = byob_types::chart::validate(&serde_json::json!({"type": "bar", "x": "m", "series": ["v"], "data": [{"m": "a", "v": 1}]})).unwrap();
let msgs = vec![
ServerMsg::Uploaded { upload: 1, attachment: Some(MediaRef::new("uploads/a.csv", 3)), error: None },
ServerMsg::Media { path: "c.chart.json".into(), content: MediaContent::Chart { spec } },
ServerMsg::Media { path: "p.png".into(), content: MediaContent::Image { mime: "image/png".into(), data: "AA==".into() } },
ServerMsg::Media { path: "p.png".into(), content: MediaContent::Error { message: "gone".into() } },
];
for m in msgs {
assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
}
let mut s = step(1, StepStatus::Done);
s.media = vec![MediaRef::new("charts/x.chart.json", 10)];
let m = ServerMsg::StepUpdated { entry: 1, step: s };
assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
}
#[test]
fn artifact_messages_round_trip() {
let v = ArtifactVersion { n: 2, path: ".byob/artifacts/calc/v2.html".into(), created_at: 1, note: "blue button".into(), size: 10 };
let a = Artifact { id: "calc".into(), kind: ArtifactKind::Html, title: "Calc".into(), filename: "calc.html".into(), versions: vec![v] };
let msgs = vec![
ServerMsg::Artifacts { chat: Some("c1".into()), artifacts: vec![a.clone()] },
ServerMsg::Artifacts { chat: None, artifacts: vec![] },
ServerMsg::ArtifactUpdated(a),
ServerMsg::ArtifactFile { id: "calc".into(), version: 2, data: Some(media::encode(b"<p>")), error: None },
ServerMsg::ArtifactFile { id: "calc".into(), version: 9, data: None, error: Some("no such version".into()) },
];
for m in msgs {
assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
}
let m = ClientMsg::GetArtifact { id: "calc".into(), version: 2 };
assert_eq!(m.to_json(), r#"{"type":"get_artifact","id":"calc","version":2}"#);
assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m);
let mut s = step(1, StepStatus::Done);
s.artifacts = vec![ArtifactRef { id: "calc".into(), version: 2 }];
let m = ServerMsg::StepUpdated { entry: 1, step: s };
assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
let json = r#"{"id":1,"tool":"t","title":"T","access":"read","status":"done","detail":""}"#;
assert!(serde_json::from_str::<Step>(json).unwrap().artifacts.is_empty());
}
#[test]
fn older_send_message_without_attachments_parses() {
let m = ClientMsg::from_json(r#"{"type":"send_message","text":"hi"}"#).unwrap();
assert_eq!(m, ClientMsg::SendMessage { text: "hi".into(), attachments: vec![] });
assert_eq!(m.to_json(), r#"{"type":"send_message","text":"hi"}"#);
}
#[test]
fn compaction_messages_round_trip() {
let c = Compaction {
id: 1,
after_entry: 7,
tokens_before: 182_000,
tokens_after: 9_000,
summary: "## Goals".into(),
manual: true,
focus: Some("CSV".into()),
created_at: 5,
};
let u = ChatUsage { chat: "c1".into(), context_used: 34_000, context_window: 262_144, compact_at: 209_715, model_calls: 3, ..Default::default() };
for m in [ServerMsg::Usage(u), ServerMsg::Compactions { chat: Some("c1".into()), items: vec![c.clone()] }, ServerMsg::Compacted(c)] {
assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
}
assert_eq!(ClientMsg::Compact { focus: None }.to_json(), r#"{"type":"compact"}"#);
let m = ClientMsg::from_json(r#"{"type":"compact","focus":"keep the CSV"}"#).unwrap();
assert_eq!(m, ClientMsg::Compact { focus: Some("keep the CSV".into()) });
let s: TurnStats = serde_json::from_str(r#"{"prompt_tokens":1,"completion_tokens":2,"elapsed_ms":3}"#).unwrap();
assert_eq!(s.model_calls, 0);
}
#[test]
fn state_never_carries_api_key() {
let json = serde_json::to_string(&EngineState::default()).unwrap();
assert!(!json.contains("\"api_key\""));
}
}