Skip to main content

byob_protocol/
lib.rs

1//! The wire protocol between byob clients (desktop window, browser tab) and the engine.
2//!
3//! Every client, including the in-process desktop window, talks to the engine only through
4//! these messages, so the desktop and web UIs can never drift apart. Messages travel as JSON
5//! text frames over a WebSocket, or through channels when in-process.
6#![cfg_attr(not(test), deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable))]
7
8pub mod artifact;
9pub mod connect;
10pub mod delegation;
11pub mod env;
12pub mod media;
13pub mod plugins;
14pub mod queue;
15pub mod usage;
16pub mod workspace;
17
18use serde::{Deserialize, Serialize};
19
20pub use artifact::{Artifact, ArtifactKind, ArtifactRef, ArtifactVersion};
21pub use connect::{Detected, InferenceTest, Link, PRESETS, Preset, Problem};
22pub use delegation::{Delegation, DelegationState, DelegationUpdate};
23pub use env::{ContainerEnv, EnvAction, EnvSupport, WorkspaceEnv};
24pub use media::{MediaContent, MediaKind, MediaRef};
25pub use plugins::{
26    Extensions, PluginAction, PluginCard, PluginInfo, PluginLoadError, PluginOrigin, PluginScope, PluginSetting, PluginTest, ServerInfo, ServerState,
27    SlashItem, SlashKind,
28};
29pub use queue::{ChatQueue, QueuePause, QueuedMessage};
30pub use usage::{ChatUsage, Compaction};
31pub use workspace::{ChatEndpoint, ConfigScope, ConfigView, FolderList, NewFolder, WorkspaceSummary};
32
33/// Bumped on any incompatible change to [`ClientMsg`] / [`ServerMsg`].
34pub const PROTOCOL_VERSION: u32 = 12;
35
36/// Hard cap on a single incoming frame, so a hostile peer can't make us allocate unboundedly.
37pub const MAX_FRAME_BYTES: usize = 4 * 1024 * 1024;
38
39/// Client -> engine.
40#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
41#[serde(tag = "type", rename_all = "snake_case")]
42pub enum ClientMsg {
43    /// First message on every connection.
44    Hello {
45        protocol: u32,
46        client: String,
47    },
48    /// Point the engine at a different inference endpoint (saved, then checked). `api_key`:
49    /// `None` keeps the stored key if the server (scheme, host, port) is unchanged and drops
50    /// it otherwise; `Some("")` removes it.
51    SetInference {
52        base_url: String,
53        model: String,
54        api_key: Option<String>,
55    },
56    /// Try an endpoint without switching to it; answered with [`ServerMsg::InferenceTested`].
57    /// `api_key` as for [`ClientMsg::SetInference`].
58    TestInference {
59        base_url: String,
60        model: String,
61        #[serde(default, skip_serializing_if = "Option::is_none")]
62        api_key: Option<String>,
63    },
64    /// Look again for inference servers on this machine's usual ports
65    /// ([`EngineState::detected`]).
66    DetectEndpoints,
67    /// Run the last message of the chat in view again, after its reply failed before
68    /// producing anything (e.g. the server was down). The failed reply is removed.
69    Retry,
70    /// Send a user message and start a turn; while a reply runs in the chat, queue it
71    /// instead (see [`queue`]). `attachments` are paths the engine returned in
72    /// [`ServerMsg::Uploaded`].
73    SendMessage {
74        text: String,
75        #[serde(default, skip_serializing_if = "Vec::is_empty")]
76        attachments: Vec<String>,
77    },
78    /// Stop the running turn. Pending approvals are denied; the chat's queue pauses.
79    Cancel,
80    /// Take queued message `id` out of the queue of the chat in view.
81    Unqueue {
82        id: u64,
83    },
84    /// Replace the text and attachments of queued message `id` (in place). Empty text and no
85    /// attachments removes it.
86    EditQueued {
87        id: u64,
88        text: String,
89        #[serde(default, skip_serializing_if = "Vec::is_empty")]
90        attachments: Vec<String>,
91    },
92    /// Move queued message `id` to position `to` (0 = next; past the end = last).
93    MoveQueued {
94        id: u64,
95        to: u32,
96    },
97    /// Run queued message `id` next, now: stop the running turn (if any) and resume the queue.
98    SendQueuedNow {
99        id: u64,
100    },
101    /// Let a paused queue go on (starts the next message if the chat is free).
102    ResumeQueue,
103    /// Answer a pending approval (a [`Step`] with status [`StepStatus::Waiting`]). Any
104    /// client may answer; the first answer wins and later ones are ignored.
105    Approve {
106        step: u64,
107        answer: ApprovalAnswer,
108    },
109    /// Reverse the file changes of assistant entry `entry` (see [`Entry::undoable`]). The
110    /// engine refuses, changing nothing, if any of those files changed since.
111    Undo {
112        entry: u64,
113    },
114    /// Ask for a page of the chat list (answered with [`ServerMsg::Chats`]). `after` is the
115    /// previous page's `next`; `None` asks for the first page (pinned chats included).
116    ListChats {
117        after: Option<ChatCursor>,
118        limit: u32,
119    },
120    /// Start a new, empty chat in this client, in workspace `workspace` (default: the
121    /// workspace of the chat in view, else the default one). The chat is created when the
122    /// first message is sent; until then this client sees an empty transcript.
123    NewChat {
124        #[serde(default, skip_serializing_if = "Option::is_none")]
125        workspace: Option<String>,
126    },
127    /// Look at another chat. Only this client switches; a turn running elsewhere goes on.
128    OpenChat {
129        id: String,
130    },
131    RenameChat {
132        id: String,
133        title: String,
134    },
135    /// Delete a chat and its messages. Refused while a reply is running in it.
136    DeleteChat {
137        id: String,
138    },
139    PinChat {
140        id: String,
141        pinned: bool,
142    },
143    /// One chunk of a file the user attaches. `upload` is chosen by the client (unique per
144    /// connection); chunks arrive in order, `offset` is where `data` (base64, at most
145    /// [`media::UPLOAD_CHUNK_BYTES`] raw) starts; `size` is the whole file's size. The engine
146    /// answers the last chunk (`done`) or the first problem with [`ServerMsg::Uploaded`].
147    Upload {
148        upload: u64,
149        name: String,
150        size: u64,
151        offset: u64,
152        data: String,
153        done: bool,
154    },
155    /// Ask for the content of a [`MediaRef`] in the transcript; answered with [`ServerMsg::Media`].
156    GetMedia {
157        path: String,
158    },
159    /// Ask for the bytes of version `version` of artifact `id` in the chat this client looks
160    /// at; answered with [`ServerMsg::ArtifactFile`].
161    GetArtifact {
162        id: String,
163        version: u32,
164    },
165    /// Summarise the conversation in view now, so later requests start from the summary
166    /// (also typed as `/compact [focus]`). `focus` says what the summary must keep.
167    Compact {
168        #[serde(default, skip_serializing_if = "Option::is_none")]
169        focus: Option<String>,
170    },
171    /// Ask for the environment state of workspace `workspace` (default: the chat in view's),
172    /// after applying `action` if given; answered with [`ServerMsg::WorkspaceEnv`].
173    WorkspaceEnv {
174        #[serde(default, skip_serializing_if = "Option::is_none")]
175        action: Option<EnvAction>,
176        #[serde(default, skip_serializing_if = "Option::is_none")]
177        workspace: Option<String>,
178    },
179    /// Make a workspace: a name, a folder on the engine's machine, its own settings
180    /// (validated for the workspace level). Answered with [`ServerMsg::WorkspaceCreated`];
181    /// on success this client starts a new chat in it.
182    CreateWorkspace {
183        name: String,
184        folder: NewFolder,
185        #[serde(default)]
186        config: workspace::Layer,
187    },
188    RenameWorkspace {
189        id: String,
190        name: String,
191    },
192    /// Remove a workspace from byob with its chats; the folder and its files stay. `clean`
193    /// also deletes what byob keeps for it elsewhere (installed packages, its container).
194    RemoveWorkspace {
195        id: String,
196        #[serde(default)]
197        clean: bool,
198    },
199    /// Ask for one level's settings; answered with [`ServerMsg::Config`].
200    GetConfig {
201        scope: ConfigScope,
202    },
203    /// Replace one level's own settings (`None` fields inherit). `api_key` as for
204    /// [`ClientMsg::SetInference`], for a level with its own URL. Answered with
205    /// [`ServerMsg::Config`].
206    SetConfig {
207        scope: ConfigScope,
208        layer: workspace::Layer,
209        #[serde(default, skip_serializing_if = "Option::is_none")]
210        api_key: Option<String>,
211    },
212    /// List the subfolders of `path` on the engine's machine (default: the home folder);
213    /// answered with [`ServerMsg::Folders`].
214    ListFolders {
215        #[serde(default, skip_serializing_if = "Option::is_none")]
216        path: Option<String>,
217    },
218    /// Is Docker/Podman reachable? Answered with [`ServerMsg::ContainersChecked`].
219    CheckContainers,
220    /// Ask for the plugins of the chat in view; answered with [`ServerMsg::Extensions`].
221    GetExtensions,
222    /// Turn plugin `plugin` on (`Some(true)`) or off (`Some(false)`) at one level of the
223    /// layered settings, or forget that level's switch (`None`: inherit). Applies from the
224    /// next turn. Answered with [`ServerMsg::Extensions`].
225    SetPluginEnabled {
226        scope: ConfigScope,
227        plugin: String,
228        enabled: Option<bool>,
229    },
230    /// Set (or clear, `None`) a setting the plugin declares. Secret settings go to
231    /// secrets.json, the others to settings.json; values are never sent back, only whether
232    /// each is set ([`PluginSetting::set`]).
233    SetPluginSetting {
234        plugin: String,
235        key: String,
236        value: Option<String>,
237    },
238    /// Keep plugin `plugin` of the chat in view (its scratch copy, or whichever copy the chat
239    /// uses) in the chat's workspace or everywhere, as `new_id` if given. The user asked, so
240    /// there is no approval card.
241    KeepPlugin {
242        plugin: String,
243        scope: PluginScope,
244        #[serde(default, skip_serializing_if = "Option::is_none")]
245        new_id: Option<String>,
246    },
247    /// Delete the copy of plugin `plugin` in `scope` (the chat in view's scratch folder, its
248    /// workspace's `.byob/plugins`, or the global plugins folder).
249    RemovePlugin {
250        plugin: String,
251        scope: PluginScope,
252    },
253    /// Read the plugin folders of the chat in view again now.
254    ReloadPlugins,
255    /// Let the plugins that came with workspace `workspace`'s folder run their tools and
256    /// servers (`trust: true`), or keep them to skills and prompt lines without asking again
257    /// (`false`). `plugins` empty: all of them.
258    TrustPlugins {
259        workspace: String,
260        #[serde(default)]
261        plugins: Vec<String>,
262        trust: bool,
263    },
264}
265
266/// Engine -> client(s).
267#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
268#[serde(tag = "type", rename_all = "snake_case")]
269pub enum ServerMsg {
270    /// Full engine state; sent on connect and whenever it changes.
271    State(EngineState),
272    /// A human-readable message for the user (errors, warnings).
273    Notice { level: NoticeLevel, text: String },
274    /// The whole conversation; sent on connect.
275    Transcript { entries: Vec<Entry> },
276    /// A new entry was appended.
277    EntryAdded(Entry),
278    /// Streamed text appended to an entry.
279    EntryDelta { id: u64, content: String, reasoning: String },
280    /// An entry finished streaming.
281    EntryFinished { id: u64, error: Option<String>, stats: Option<TurnStats> },
282    /// A tool step of entry `entry` was added or changed (replace by `step.id`).
283    StepUpdated { entry: u64, step: Step },
284    /// Whether entry `id`'s file changes can be undone, or have been.
285    EntryUndo { id: u64, undoable: bool, undone: bool },
286    /// A page of the chat list. With `after: None` it replaces the client's list (pinned
287    /// chats are in `pinned`); otherwise `recent` continues the list after `after`.
288    Chats { pinned: Vec<ChatSummary>, recent: Vec<ChatSummary>, after: Option<ChatCursor>, next: Option<ChatCursor> },
289    /// A chat was created or changed (title, pin, activity, busy). Sent to every client.
290    ChatUpdated(ChatSummary),
291    /// A chat was deleted. Sent to every client.
292    ChatDeleted { id: String },
293    /// This client now looks at `chat` (`None`: a new chat, not sent yet), which is in
294    /// workspace `workspace`. The chat's [`ServerMsg::Transcript`] follows; entry messages
295    /// only arrive for the chat in view.
296    ChatOpened {
297        chat: Option<ChatSummary>,
298        #[serde(default)]
299        workspace: Option<String>,
300    },
301    /// An upload finished (`attachment`) or failed (`error`). Only sent to the uploader.
302    Uploaded { upload: u64, attachment: Option<MediaRef>, error: Option<String> },
303    /// Answer to [`ClientMsg::GetMedia`].
304    Media { path: String, content: MediaContent },
305    /// Every artifact of the chat this client looks at (`chat`, `None` for a new chat).
306    /// Sent after [`ServerMsg::Transcript`]; replaces the client's list.
307    Artifacts { chat: Option<String>, artifacts: Vec<Artifact> },
308    /// An artifact of the chat in view was created or got a new version.
309    ArtifactUpdated(Artifact),
310    /// Answer to [`ClientMsg::GetArtifact`]: the file, base64 (see [`media::encode`]), or why not.
311    ArtifactFile { id: String, version: u32, data: Option<String>, error: Option<String> },
312    /// Context usage of the chat in view; sent after the transcript and whenever it changes.
313    Usage(ChatUsage),
314    /// Every compaction of the chat in view, oldest first (`chat`, `None` for a new chat).
315    /// Sent after [`ServerMsg::Transcript`] (before `Artifacts`); replaces the client's list.
316    Compactions { chat: Option<String>, items: Vec<Compaction> },
317    /// The chat in view was just compacted.
318    Compacted(Compaction),
319    /// The subagent run of step `step` (in entry `entry`) changed.
320    Delegation { entry: u64, step: u64, update: DelegationUpdate },
321    /// Answer to [`ClientMsg::TestInference`].
322    InferenceTested(InferenceTest),
323    /// Answer to [`ClientMsg::WorkspaceEnv`]: the environment of a workspace.
324    WorkspaceEnv(WorkspaceEnv),
325    /// Every workspace, most recently active first; sent on connect and whenever one is
326    /// added, renamed, removed or changes its chat count. `current` is where new chats go
327    /// by default; `root` is where fresh workspace folders are created.
328    Workspaces { items: Vec<WorkspaceSummary>, current: Option<String>, root: String, support: EnvSupport },
329    /// Answer to [`ClientMsg::GetConfig`] / [`ClientMsg::SetConfig`].
330    Config(Box<ConfigView>),
331    /// Answer to [`ClientMsg::ListFolders`].
332    Folders(FolderList),
333    /// Answer to [`ClientMsg::CheckContainers`].
334    ContainersChecked { ok: bool, message: String },
335    /// Answer to [`ClientMsg::CreateWorkspace`].
336    WorkspaceCreated { id: Option<String>, error: Option<String> },
337    /// The queue of the chat in view; sent after [`ServerMsg::Transcript`] and whenever it
338    /// changes.
339    Queue(ChatQueue),
340    /// The plugins of the chat in view; sent after [`ServerMsg::ChatOpened`], on
341    /// [`ClientMsg::GetExtensions`], and whenever they change.
342    Extensions(Box<Extensions>),
343}
344
345/// A chat as shown in the sidebar.
346#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
347pub struct ChatSummary {
348    pub id: String,
349    pub title: String,
350    /// Milliseconds since the Unix epoch of the last activity; the list is ordered by it.
351    pub updated_at: i64,
352    /// When it was pinned (ms since the epoch), if it is. Pinned chats list first.
353    pub pinned_at: Option<i64>,
354    /// A reply is running in this chat.
355    #[serde(default)]
356    pub busy: bool,
357    /// The workspace it belongs to.
358    #[serde(default, skip_serializing_if = "Option::is_none")]
359    pub workspace: Option<String>,
360}
361
362impl ChatSummary {
363    pub fn cursor(&self) -> ChatCursor {
364        ChatCursor { updated_at: self.updated_at, id: self.id.clone() }
365    }
366}
367
368/// Position in the recent-first chat list, for paging.
369#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
370pub struct ChatCursor {
371    pub updated_at: i64,
372    pub id: String,
373}
374
375#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
376#[serde(rename_all = "snake_case")]
377pub enum EntryRole {
378    User,
379    Assistant,
380}
381
382/// One message in the conversation as shown to users.
383#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
384pub struct Entry {
385    pub id: u64,
386    pub role: EntryRole,
387    pub content: String,
388    pub reasoning: String,
389    /// False while the reply is still streaming.
390    pub done: bool,
391    pub error: Option<String>,
392    pub stats: Option<TurnStats>,
393    /// Tool calls made while producing this reply, in order. Part of the transcript so a
394    /// client that connects late sees them and can answer pending approvals.
395    #[serde(default)]
396    pub steps: Vec<Step>,
397    /// Every file change of this reply can be reversed with [`ClientMsg::Undo`].
398    #[serde(default)]
399    pub undoable: bool,
400    /// The reply's file changes were undone.
401    #[serde(default)]
402    pub undone: bool,
403    /// Files the user attached to this message.
404    #[serde(default, skip_serializing_if = "Vec::is_empty")]
405    pub attachments: Vec<MediaRef>,
406}
407
408impl Entry {
409    /// Apply a [`ServerMsg::EntryDelta`].
410    pub fn append(&mut self, content: &str, reasoning: &str) {
411        self.content.push_str(content);
412        self.reasoning.push_str(reasoning);
413    }
414
415    /// Apply a [`ServerMsg::StepUpdated`]: replace the step with the same id, or append it.
416    pub fn upsert_step(&mut self, step: Step) {
417        match self.steps.iter_mut().find(|s| s.id == step.id) {
418            Some(existing) => *existing = step,
419            None => self.steps.push(step),
420        }
421    }
422
423    /// Steps waiting for a user's approval, subagents' steps included.
424    pub fn pending_approvals(&self) -> impl Iterator<Item = &Step> {
425        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)
426    }
427
428    /// Apply a [`ServerMsg::Delegation`] to step `step`'s subagent run.
429    pub fn apply_delegation(&mut self, step: u64, update: &DelegationUpdate) {
430        if let Some(d) = self.steps.iter_mut().find(|s| s.id == step).and_then(|s| s.delegation.as_deref_mut()) {
431            d.apply(update);
432        }
433    }
434}
435
436/// How dangerous a tool call is; drives the permission gate. Mirrors `byob_tools::Access`.
437#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
438#[serde(rename_all = "snake_case")]
439pub enum ToolAccess {
440    Read,
441    Write,
442    Network,
443    Execute,
444}
445
446impl ToolAccess {
447    pub fn label(self) -> &'static str {
448        match self {
449            Self::Read => "read",
450            Self::Write => "write",
451            Self::Network => "network",
452            Self::Execute => "execute",
453        }
454    }
455}
456
457#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
458#[serde(rename_all = "snake_case")]
459pub enum StepStatus {
460    Running,
461    /// An approval request: blocked until a client sends [`ClientMsg::Approve`].
462    Waiting,
463    Done,
464    /// The tool ran (or could not run) and reported an error.
465    Failed,
466    /// The user (or the policy) said no, or the turn was stopped while waiting.
467    Denied,
468}
469
470impl StepStatus {
471    pub fn finished(self) -> bool {
472        matches!(self, Self::Done | Self::Failed | Self::Denied)
473    }
474}
475
476/// A user's answer to an approval request.
477#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
478#[serde(rename_all = "snake_case")]
479pub enum ApprovalAnswer {
480    Allow,
481    /// Allow, and stop asking about this tool in this chat (remembered across restarts).
482    Always,
483    Deny,
484    /// Allow, and stop asking about this tool in every chat.
485    AlwaysEverywhere,
486}
487
488/// A file-system effect of a tool call. Paths are for display (workspace-relative when possible).
489#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
490#[serde(tag = "kind", rename_all = "snake_case")]
491pub enum FileChange {
492    Created { path: String },
493    Modified { path: String },
494    Deleted { path: String },
495    Moved { from: String, to: String },
496}
497
498/// One tool call inside an assistant reply.
499#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
500pub struct Step {
501    /// Unique within the engine; also the approval id.
502    pub id: u64,
503    /// Tool name, e.g. `read_file`.
504    pub tool: String,
505    /// Short human title, e.g. "Read notes.md".
506    pub title: String,
507    pub access: ToolAccess,
508    pub status: StepStatus,
509    /// Short detail: the arguments while running or waiting, then a result excerpt or reason.
510    pub detail: String,
511    #[serde(default)]
512    pub changes: Vec<FileChange>,
513    /// Byte offset into the entry's `content` when the step started, for interleaving.
514    #[serde(default)]
515    pub at: usize,
516    /// Charts and images this call made, shown inline.
517    #[serde(default, skip_serializing_if = "Vec::is_empty")]
518    pub media: Vec<MediaRef>,
519    /// What the call will do, readable, for the approval card and the expanded row.
520    #[serde(default, skip_serializing_if = "Option::is_none")]
521    pub preview: Option<Preview>,
522    /// Artifact versions this call made, shown as cards where it happened.
523    #[serde(default, skip_serializing_if = "Vec::is_empty")]
524    pub artifacts: Vec<ArtifactRef>,
525    /// The subagent run of a `delegate` step: its live transcript.
526    #[serde(default, skip_serializing_if = "Option::is_none")]
527    pub delegation: Option<Box<Delegation>>,
528    /// Set when the approval card isn't an ordinary tool call: a question a tool asks while
529    /// it runs, or a call a person must confirm every time. Such cards offer only Allow
530    /// and Deny.
531    #[serde(default, skip_serializing_if = "Option::is_none")]
532    pub ask: Option<Box<Ask>>,
533    /// The step made, changed, kept or removed a plugin: show a plugin card. Set on the
534    /// finished step, and stored with it (a transcript loaded from storage has it too).
535    #[serde(default, skip_serializing_if = "Option::is_none")]
536    pub plugin: Option<Box<PluginCard>>,
537}
538
539/// The special part of an approval card (see [`Step::ask`]).
540#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
541pub struct Ask {
542    /// What saying yes means.
543    #[serde(default)]
544    pub text: String,
545    /// Shown prominently, e.g. that it installs system-wide.
546    #[serde(default, skip_serializing_if = "Option::is_none")]
547    pub warning: Option<String>,
548    /// Only a person can allow it: no policy, grant or `--auto-approve` does.
549    #[serde(default)]
550    pub always: bool,
551}
552
553/// Most lines in a [`Preview`]'s line lists.
554pub const MAX_PREVIEW_LINES: usize = 40;
555/// Most characters in one preview line or value.
556pub const MAX_PREVIEW_LINE_CHARS: usize = 300;
557
558/// A readable account of a tool call, built from its (untrusted, bounded) arguments.
559#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
560#[serde(tag = "kind", rename_all = "snake_case")]
561pub enum Preview {
562    /// Create or replace a file. `lines` is the start of the new content, or for a
563    /// replacement a compact line diff against the current file.
564    Write {
565        path: String,
566        bytes: u64,
567        /// The file exists and will be replaced.
568        replaces: bool,
569        lines: Vec<DiffLine>,
570        /// Lines (or changes) not shown.
571        #[serde(default)]
572        more: usize,
573    },
574    /// Move or rename: `(from, to)` pairs.
575    Move {
576        moves: Vec<(String, String)>,
577        #[serde(default)]
578        more: usize,
579    },
580    /// Move something to the trash; `what` describes it, e.g. "file, 2.1 KB".
581    Delete { path: String, what: String },
582    /// Any other tool: its key arguments. `code` is command/script text, shown monospaced.
583    Args {
584        fields: Vec<(String, String)>,
585        #[serde(default, skip_serializing_if = "Option::is_none")]
586        code: Option<String>,
587        #[serde(default)]
588        more: usize,
589    },
590}
591
592/// One line of a preview's content or diff.
593#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
594pub struct DiffLine {
595    pub kind: LineKind,
596    pub text: String,
597}
598
599#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
600#[serde(rename_all = "snake_case")]
601pub enum LineKind {
602    /// Unchanged (or, for a new file, plain content).
603    Same,
604    Added,
605    Removed,
606    /// Unchanged lines left out; `text` says how many.
607    Skipped,
608}
609
610#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
611pub struct TurnStats {
612    pub prompt_tokens: u64,
613    pub completion_tokens: u64,
614    pub elapsed_ms: u64,
615    /// Model requests the reply took (tool rounds and compactions included).
616    #[serde(default)]
617    pub model_calls: u64,
618}
619
620#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
621#[serde(rename_all = "snake_case")]
622pub enum NoticeLevel {
623    Info,
624    Error,
625}
626
627/// What clients may know about the engine. Secrets (API keys) never leave the engine.
628#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
629pub struct EngineState {
630    pub version: String,
631    pub inference_base_url: String,
632    pub inference_model: String,
633    pub has_api_key: bool,
634    /// Resolved `chat/completions` URL, if the base URL is valid.
635    pub endpoint: Option<String>,
636    /// A turn is running in the chat this client is looking at.
637    pub busy: bool,
638    /// What the engine knows about the inference endpoint (from its capability probe).
639    #[serde(default)]
640    pub endpoint_info: Option<EndpointInfo>,
641    /// Whether the current endpoint answers.
642    #[serde(default)]
643    pub link: Link,
644    /// An endpoint has worked before (saved in settings.json): returning users skip the
645    /// welcome screen.
646    #[serde(default)]
647    pub onboarded: bool,
648    /// Inference servers found on this machine's usual ports.
649    #[serde(default)]
650    pub detected: Vec<Detected>,
651    /// The engine is looking for them.
652    #[serde(default)]
653    pub detecting: bool,
654    /// The chat in view uses another endpoint than the one above (its workspace's or its
655    /// own); `None`: it uses the global one.
656    #[serde(default, skip_serializing_if = "Option::is_none")]
657    pub chat_endpoint: Option<ChatEndpoint>,
658}
659
660/// How turns pass tools to the model.
661#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
662#[serde(rename_all = "snake_case")]
663pub enum ToolsMode {
664    /// The server's structured `tools` / `tool_calls`.
665    Native,
666    /// Tools described in the system prompt; calls parsed from the reply text.
667    Prompt,
668    /// Not known yet: native first, switching to prompt mode if the server rejects tools.
669    #[default]
670    Unknown,
671}
672
673/// Capability summary of the inference endpoint, for a small header detail.
674#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
675pub struct EndpointInfo {
676    /// The probe is still running.
677    #[serde(default)]
678    pub probing: bool,
679    /// Server software, e.g. "llama.cpp", "vLLM", "Ollama"; empty if unknown.
680    #[serde(default)]
681    pub server: String,
682    /// Context window in tokens, if the server reports it.
683    #[serde(default)]
684    pub context_tokens: Option<u64>,
685    #[serde(default)]
686    pub tools: ToolsMode,
687    /// Takes image input: `Some(true)` yes, `Some(false)` no, `None` unknown.
688    #[serde(default)]
689    pub vision: Option<bool>,
690}
691
692impl EndpointInfo {
693    /// One short line, e.g. "llama.cpp · 262k ctx · native tools · vision".
694    pub fn summary(&self) -> String {
695        if self.probing {
696            return "checking endpoint…".into();
697        }
698        let mut parts = Vec::new();
699        if !self.server.is_empty() {
700            parts.push(self.server.clone());
701        }
702        if let Some(n) = self.context_tokens {
703            parts.push(if n >= 1000 { format!("{}k ctx", n / 1000) } else { format!("{n} ctx") });
704        }
705        parts.push(
706            match self.tools {
707                ToolsMode::Native => "native tools",
708                ToolsMode::Prompt => "prompt tools",
709                ToolsMode::Unknown => "tools untested",
710            }
711            .into(),
712        );
713        if self.vision == Some(true) {
714            parts.push("vision".into());
715        }
716        parts.join(" · ")
717    }
718}
719
720impl ClientMsg {
721    pub fn to_json(&self) -> String {
722        serde_json::to_string(self).unwrap_or_default()
723    }
724
725    /// Parse an untrusted frame.
726    pub fn from_json(text: &str) -> Result<Self, String> {
727        if text.len() > MAX_FRAME_BYTES {
728            return Err(format!("frame too large ({} bytes)", text.len()));
729        }
730        serde_json::from_str(text).map_err(|e| e.to_string())
731    }
732}
733
734impl ServerMsg {
735    pub fn to_json(&self) -> String {
736        serde_json::to_string(self).unwrap_or_default()
737    }
738
739    /// Parse an untrusted frame.
740    pub fn from_json(text: &str) -> Result<Self, String> {
741        if text.len() > MAX_FRAME_BYTES {
742            return Err(format!("frame too large ({} bytes)", text.len()));
743        }
744        serde_json::from_str(text).map_err(|e| e.to_string())
745    }
746}
747
748/// A client's link to an engine, in-process or over a WebSocket. Never blocks.
749pub trait Connection {
750    fn send(&mut self, msg: ClientMsg);
751    /// Next pending message, if any. Called every UI frame.
752    fn try_recv(&mut self) -> Option<ServerMsg>;
753}
754
755#[cfg(test)]
756mod tests {
757    use super::*;
758
759    #[test]
760    fn client_msg_round_trips() {
761        let m = ClientMsg::Hello { protocol: PROTOCOL_VERSION, client: "test".into() };
762        assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m);
763    }
764
765    #[test]
766    fn wire_format_is_tagged() {
767        let json = ServerMsg::Notice { level: NoticeLevel::Info, text: "hi".into() }.to_json();
768        assert_eq!(json, r#"{"type":"notice","level":"info","text":"hi"}"#);
769    }
770
771    #[test]
772    fn rejects_garbage_and_oversized_frames() {
773        assert!(ClientMsg::from_json("{not json").is_err());
774        assert!(ClientMsg::from_json(&" ".repeat(MAX_FRAME_BYTES + 1)).is_err());
775    }
776
777    #[test]
778    fn approve_wire_format() {
779        let m = ClientMsg::Approve { step: 7, answer: ApprovalAnswer::Always };
780        assert_eq!(m.to_json(), r#"{"type":"approve","step":7,"answer":"always"}"#);
781        assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m);
782    }
783
784    fn step(id: u64, status: StepStatus) -> Step {
785        Step {
786            id,
787            tool: "t".into(),
788            title: "T".into(),
789            access: ToolAccess::Write,
790            status,
791            detail: String::new(),
792            changes: vec![],
793            at: 0,
794            preview: None,
795            media: vec![],
796            artifacts: vec![],
797            delegation: None,
798            ask: None,
799            plugin: None,
800        }
801    }
802
803    #[test]
804    fn delegations_stream_into_their_step_and_round_trip() {
805        let mut parent = step(1, StepStatus::Running);
806        parent.delegation = Some(Box::new(Delegation { agent: "explorer".into(), task: "count lines".into(), ..Default::default() }));
807        let mut e = Entry {
808            id: 9,
809            role: EntryRole::Assistant,
810            content: String::new(),
811            reasoning: String::new(),
812            done: false,
813            error: None,
814            stats: None,
815            steps: vec![parent],
816            undoable: false,
817            undone: false,
818            attachments: vec![],
819        };
820        let updates = [
821            DelegationUpdate::Status { state: DelegationState::Running, prompt_tokens: 0, completion_tokens: 0, error: None },
822            DelegationUpdate::Delta { content: "Reading".into(), reasoning: "hm".into() },
823            DelegationUpdate::Step(Box::new(step(2, StepStatus::Waiting))),
824            DelegationUpdate::Delta { content: " a.txt".into(), reasoning: String::new() },
825        ];
826        for u in &updates {
827            let msg = ServerMsg::Delegation { entry: 9, step: 1, update: u.clone() };
828            assert_eq!(ServerMsg::from_json(&msg.to_json()).unwrap(), msg);
829            e.apply_delegation(1, u);
830        }
831        // An unknown step is ignored.
832        e.apply_delegation(77, &updates[1]);
833        let d = e.steps[0].delegation.as_deref().unwrap();
834        assert_eq!((d.content.as_str(), d.reasoning.as_str(), d.state), ("Reading a.txt", "hm", DelegationState::Running));
835        assert_eq!(d.status_line(), "explorer · 1 tool · waiting for approval");
836        // A child's approval card counts as pending in the entry.
837        assert_eq!(e.pending_approvals().map(|s| s.id).collect::<Vec<_>>(), vec![2]);
838        e.apply_delegation(1, &DelegationUpdate::Step(Box::new(step(2, StepStatus::Done))));
839        e.apply_delegation(1, &DelegationUpdate::Status { state: DelegationState::Done, prompt_tokens: 50, completion_tokens: 5, error: None });
840        assert_eq!(e.steps[0].delegation.as_deref().unwrap().status_line(), "explorer · 1 tool · done");
841        assert_eq!(e.pending_approvals().count(), 0);
842        let msg = ServerMsg::StepUpdated { entry: 9, step: e.steps[0].clone() };
843        assert_eq!(ServerMsg::from_json(&msg.to_json()).unwrap(), msg);
844        // Steps from an older engine have no delegation.
845        let json = r#"{"id":1,"tool":"t","title":"T","access":"read","status":"done","detail":""}"#;
846        assert!(serde_json::from_str::<Step>(json).unwrap().delegation.is_none());
847    }
848
849    #[test]
850    fn steps_upsert_and_round_trip() {
851        let mut e = Entry {
852            id: 1,
853            role: EntryRole::Assistant,
854            content: String::new(),
855            reasoning: String::new(),
856            done: false,
857            error: None,
858            stats: None,
859            steps: vec![],
860            undoable: false,
861            undone: false,
862            attachments: vec![],
863        };
864        e.upsert_step(step(3, StepStatus::Running));
865        e.upsert_step(step(4, StepStatus::Waiting));
866        e.upsert_step(step(3, StepStatus::Done));
867        assert_eq!(e.steps.len(), 2);
868        assert_eq!(e.steps[0].status, StepStatus::Done);
869        assert_eq!(e.pending_approvals().map(|s| s.id).collect::<Vec<_>>(), vec![4]);
870        let mut s = step(5, StepStatus::Done);
871        s.changes = vec![FileChange::Moved { from: "a".into(), to: "b".into() }];
872        let msg = ServerMsg::StepUpdated { entry: 1, step: s };
873        assert_eq!(ServerMsg::from_json(&msg.to_json()).unwrap(), msg);
874    }
875
876    #[test]
877    fn entry_without_steps_still_parses() {
878        let json = r#"{"id":1,"role":"user","content":"hi","reasoning":"","done":true,"error":null,"stats":null}"#;
879        let e: Entry = serde_json::from_str(json).unwrap();
880        assert!(e.steps.is_empty());
881    }
882
883    #[test]
884    fn undo_and_preview_wire_format() {
885        let m = ClientMsg::Undo { entry: 4 };
886        assert_eq!(m.to_json(), r#"{"type":"undo","entry":4}"#);
887        assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m);
888        let mut s = step(1, StepStatus::Waiting);
889        s.preview =
890            Some(Preview::Write { path: "a.md".into(), bytes: 3, replaces: true, lines: vec![DiffLine { kind: LineKind::Added, text: "hi".into() }], more: 0 });
891        let msg = ServerMsg::StepUpdated { entry: 1, step: s };
892        assert_eq!(ServerMsg::from_json(&msg.to_json()).unwrap(), msg);
893        let msg = ServerMsg::EntryUndo { id: 1, undoable: false, undone: true };
894        assert_eq!(ServerMsg::from_json(&msg.to_json()).unwrap(), msg);
895    }
896
897    #[test]
898    fn chat_messages_round_trip() {
899        let summary = ChatSummary { id: "c1".into(), title: "Plans".into(), updated_at: 5, pinned_at: None, busy: true, workspace: Some("w1".into()) };
900        for m in [
901            ServerMsg::Chats { pinned: vec![], recent: vec![summary.clone()], after: None, next: Some(summary.cursor()) },
902            ServerMsg::ChatUpdated(summary.clone()),
903            ServerMsg::ChatOpened { chat: Some(summary), workspace: None },
904            ServerMsg::ChatDeleted { id: "c1".into() },
905        ] {
906            assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
907        }
908        let m = ClientMsg::ListChats { after: Some(ChatCursor { updated_at: 1, id: "x".into() }), limit: 50 };
909        assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m);
910        assert_eq!(ClientMsg::NewChat { workspace: None }.to_json(), r#"{"type":"new_chat"}"#);
911    }
912
913    #[test]
914    fn endpoint_info_is_optional_and_summarised() {
915        let old = r#"{"version":"0","inference_base_url":"u","inference_model":"m","has_api_key":false,"endpoint":null,"busy":false}"#;
916        assert_eq!(serde_json::from_str::<EngineState>(old).unwrap().endpoint_info, None);
917        let info = EndpointInfo { probing: false, server: "llama.cpp".into(), context_tokens: Some(262_144), tools: ToolsMode::Native, vision: Some(true) };
918        assert_eq!(info.summary(), "llama.cpp · 262k ctx · native tools · vision");
919        assert_eq!(EndpointInfo { probing: true, ..info }.summary(), "checking endpoint…");
920        assert_eq!(EndpointInfo::default().summary(), "tools untested");
921    }
922
923    #[test]
924    fn media_messages_round_trip() {
925        let msgs = vec![
926            ClientMsg::SendMessage { text: "chart it".into(), attachments: vec!["uploads/sales.csv".into()] },
927            ClientMsg::Upload { upload: 1, name: "a.csv".into(), size: 3, offset: 0, data: media::encode(b"a,b"), done: true },
928            ClientMsg::GetMedia { path: "charts/x.chart.json".into() },
929        ];
930        for m in msgs {
931            assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m);
932        }
933        let spec = byob_types::chart::validate(&serde_json::json!({"type": "bar", "x": "m", "series": ["v"], "data": [{"m": "a", "v": 1}]})).unwrap();
934        let msgs = vec![
935            ServerMsg::Uploaded { upload: 1, attachment: Some(MediaRef::new("uploads/a.csv", 3)), error: None },
936            ServerMsg::Media { path: "c.chart.json".into(), content: MediaContent::Chart { spec } },
937            ServerMsg::Media { path: "p.png".into(), content: MediaContent::Image { mime: "image/png".into(), data: "AA==".into() } },
938            ServerMsg::Media { path: "p.png".into(), content: MediaContent::Error { message: "gone".into() } },
939        ];
940        for m in msgs {
941            assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
942        }
943        let mut s = step(1, StepStatus::Done);
944        s.media = vec![MediaRef::new("charts/x.chart.json", 10)];
945        let m = ServerMsg::StepUpdated { entry: 1, step: s };
946        assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
947    }
948
949    #[test]
950    fn artifact_messages_round_trip() {
951        let v = ArtifactVersion { n: 2, path: ".byob/artifacts/calc/v2.html".into(), created_at: 1, note: "blue button".into(), size: 10 };
952        let a = Artifact { id: "calc".into(), kind: ArtifactKind::Html, title: "Calc".into(), filename: "calc.html".into(), versions: vec![v] };
953        let msgs = vec![
954            ServerMsg::Artifacts { chat: Some("c1".into()), artifacts: vec![a.clone()] },
955            ServerMsg::Artifacts { chat: None, artifacts: vec![] },
956            ServerMsg::ArtifactUpdated(a),
957            ServerMsg::ArtifactFile { id: "calc".into(), version: 2, data: Some(media::encode(b"<p>")), error: None },
958            ServerMsg::ArtifactFile { id: "calc".into(), version: 9, data: None, error: Some("no such version".into()) },
959        ];
960        for m in msgs {
961            assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
962        }
963        let m = ClientMsg::GetArtifact { id: "calc".into(), version: 2 };
964        assert_eq!(m.to_json(), r#"{"type":"get_artifact","id":"calc","version":2}"#);
965        assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m);
966        let mut s = step(1, StepStatus::Done);
967        s.artifacts = vec![ArtifactRef { id: "calc".into(), version: 2 }];
968        let m = ServerMsg::StepUpdated { entry: 1, step: s };
969        assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
970        // A step from an older engine has no artifacts.
971        let json = r#"{"id":1,"tool":"t","title":"T","access":"read","status":"done","detail":""}"#;
972        assert!(serde_json::from_str::<Step>(json).unwrap().artifacts.is_empty());
973    }
974
975    #[test]
976    fn older_send_message_without_attachments_parses() {
977        let m = ClientMsg::from_json(r#"{"type":"send_message","text":"hi"}"#).unwrap();
978        assert_eq!(m, ClientMsg::SendMessage { text: "hi".into(), attachments: vec![] });
979        assert_eq!(m.to_json(), r#"{"type":"send_message","text":"hi"}"#);
980    }
981
982    #[test]
983    fn compaction_messages_round_trip() {
984        let c = Compaction {
985            id: 1,
986            after_entry: 7,
987            tokens_before: 182_000,
988            tokens_after: 9_000,
989            summary: "## Goals".into(),
990            manual: true,
991            focus: Some("CSV".into()),
992            created_at: 5,
993        };
994        let u = ChatUsage { chat: "c1".into(), context_used: 34_000, context_window: 262_144, compact_at: 209_715, model_calls: 3, ..Default::default() };
995        for m in [ServerMsg::Usage(u), ServerMsg::Compactions { chat: Some("c1".into()), items: vec![c.clone()] }, ServerMsg::Compacted(c)] {
996            assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
997        }
998        assert_eq!(ClientMsg::Compact { focus: None }.to_json(), r#"{"type":"compact"}"#);
999        let m = ClientMsg::from_json(r#"{"type":"compact","focus":"keep the CSV"}"#).unwrap();
1000        assert_eq!(m, ClientMsg::Compact { focus: Some("keep the CSV".into()) });
1001        // Stats from an older engine have no call count.
1002        let s: TurnStats = serde_json::from_str(r#"{"prompt_tokens":1,"completion_tokens":2,"elapsed_ms":3}"#).unwrap();
1003        assert_eq!(s.model_calls, 0);
1004    }
1005
1006    #[test]
1007    fn connection_messages_round_trip() {
1008        for m in [
1009            ClientMsg::TestInference { base_url: "http://127.0.0.1:11434/v1".into(), model: "qwen3".into(), api_key: None },
1010            ClientMsg::TestInference { base_url: "https://api.openai.com/v1".into(), model: "m".into(), api_key: Some("sk".into()) },
1011            ClientMsg::DetectEndpoints,
1012            ClientMsg::Retry,
1013        ] {
1014            assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m);
1015        }
1016        assert_eq!(ClientMsg::Retry.to_json(), r#"{"type":"retry"}"#);
1017        let t = InferenceTest { base_url: "u".into(), model: "m".into(), ok: false, problem: Some(Problem::Unauthorized), detail: "x".into(), models: vec![] };
1018        let m = ServerMsg::InferenceTested(t);
1019        assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
1020        let state = EngineState {
1021            link: Link::failed("could not reach u: refused"),
1022            onboarded: true,
1023            detected: vec![Detected { preset: "ollama".into(), base_url: "http://127.0.0.1:11434/v1".into(), models: vec!["qwen3".into()] }],
1024            ..Default::default()
1025        };
1026        let m = ServerMsg::State(state);
1027        assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
1028        // State from an older engine: link unknown, not onboarded.
1029        let old = r#"{"version":"0","inference_base_url":"u","inference_model":"m","has_api_key":false,"endpoint":null,"busy":false}"#;
1030        let s = serde_json::from_str::<EngineState>(old).unwrap();
1031        assert_eq!((s.link, s.onboarded, s.detected.len()), (Link::Unknown, false, 0));
1032    }
1033
1034    #[test]
1035    fn state_never_carries_api_key() {
1036        let json = serde_json::to_string(&EngineState::default()).unwrap();
1037        assert!(!json.contains("\"api_key\""));
1038    }
1039}